// Notes — personal/team scratchpads, decisions, drafts.
// Card grid layout (like Skills). Click a card to open the editor in a focused overlay.

const NotesPage = ({ onNav }) => {
  const [notesData, setNotesData] = React.useState(NOTES);
  const [openId, setOpenId] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [filter, setFilter] = React.useState('all'); // all | pinned | mine | shared
  const [tagFilter, setTagFilter] = React.useState(null);
  const [sort, setSort] = React.useState('updated');

  const allTags = React.useMemo(() => {
    const t = {};
    notesData.forEach(n => n.tags.forEach(x => t[x] = (t[x]||0)+1));
    return Object.entries(t).sort((a,b) => b[1]-a[1]);
  }, [notesData]);

  const filtered = notesData.filter(n => {
    if (filter === 'mine' && n.shared) return false;
    if (filter === 'shared' && !n.shared) return false;
    if (filter === 'pinned' && !n.pinned) return false;
    if (tagFilter && !n.tags.includes(tagFilter)) return false;
    if (search && !(n.title + ' ' + n.body + ' ' + n.tags.join(' ')).toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const sorted = [...filtered].sort((a,b) => {
    if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
    if (sort === 'title') return a.title.localeCompare(b.title);
    return 0;
  });

  const updateNote = (id, patch) => {
    setNotesData(d => d.map(n => n.id === id ? { ...n, ...patch, updated: 'now' } : n));
  };
  const togglePin = (id) => setNotesData(d => d.map(n => n.id === id ? { ...n, pinned: !n.pinned } : n));
  const deleteNote = (id) => {
    setNotesData(d => d.filter(n => n.id !== id));
    if (openId === id) setOpenId(null);
  };
  const newNote = () => {
    const id = 'n-' + String(notesData.length + 1).padStart(3, '0');
    const note = { id, title: 'Untitled', body: '', updated: 'now', pinned: false, tags: [], shared: false, author: 'XM' };
    setNotesData(d => [note, ...d]);
    setOpenId(id);
  };

  const openNote = notesData.find(n => n.id === openId);

  return (
    <div className="fade-in" style={{display:'flex',flexDirection:'column',height:'100%',minHeight:0}}>
      <div className="page-head">
        <div>
          <div className="page-title">Notes</div>
          <div className="page-sub">{notesData.length} notes · personal scratchpad and team drafts</div>
        </div>
        <span className="spacer" />
        <button className="ibtn bordered" onClick={newNote}>
          <Icon name="plus" size={13} /> New note
        </button>
      </div>

      {/* Toolbar */}
      <div className="notes-toolbar">
        <div className="notes-toolbar-search">
          <Icon name="search" size={13} />
          <input
            placeholder="Search notes…"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          {search && (
            <button onClick={() => setSearch('')} className="notes-clear-btn">
              <Icon name="close" size={11} />
            </button>
          )}
        </div>

        <div className="notes-filter-chips">
          {[
            {id:'all', label:'All', n: notesData.length},
            {id:'pinned', label:'Pinned', n: notesData.filter(n=>n.pinned).length, icon:'bookmark'},
            {id:'mine', label:'Private', n: notesData.filter(n=>!n.shared).length, icon:'lock'},
            {id:'shared', label:'Shared', n: notesData.filter(n=>n.shared).length, icon:'users'},
          ].map(t => (
            <button key={t.id}
              className={`notes-chip ${filter===t.id?'on':''}`}
              onClick={() => setFilter(t.id)}>
              {t.icon && <Icon name={t.icon} size={11} />}
              {t.label}
              <span className="mono notes-chip-count">{t.n}</span>
            </button>
          ))}
        </div>

        <span className="spacer" />

        <button className="ibtn bordered notes-sort"
          onClick={() => setSort(s => s === 'updated' ? 'title' : 'updated')}>
          <Icon name="filter" size={12} />
          {sort === 'updated' ? 'Recent' : 'A → Z'}
        </button>
      </div>

      {/* Tag rail */}
      {allTags.length > 0 && (
        <div className="notes-tagrail">
          <span className="notes-tagrail-label">Tags</span>
          <button className={`notes-tag-flat ${!tagFilter?'on':''}`} onClick={() => setTagFilter(null)}>
            All
          </button>
          {allTags.map(([t, n]) => (
            <button key={t}
              className={`notes-tag-flat ${tagFilter===t?'on':''}`}
              onClick={() => setTagFilter(tagFilter === t ? null : t)}>
              <Icon name="tag" size={10} /> {t}
              <span className="mono notes-chip-count">{n}</span>
            </button>
          ))}
        </div>
      )}

      {/* Card grid */}
      <div className="notes-grid-wrap">
        <div className="notes-grid">
          {sorted.map(n => (
            <NoteCard key={n.id} note={n}
              onOpen={() => setOpenId(n.id)}
              onTogglePin={() => togglePin(n.id)}
            />
          ))}
          {sorted.length === 0 && (
            <div className="notes-empty">
              <Icon name="file" size={28} />
              <div style={{fontSize:14,fontWeight:500,marginTop:10}}>No notes match</div>
              <div style={{fontSize:12,color:'var(--fg-3)',marginTop:4}}>Try clearing the filter or search.</div>
            </div>
          )}
        </div>
      </div>

      {/* Editor overlay */}
      {openNote && (
        <NoteOverlay
          note={openNote}
          onClose={() => setOpenId(null)}
          onChange={patch => updateNote(openNote.id, patch)}
          onTogglePin={() => togglePin(openNote.id)}
          onDelete={() => deleteNote(openNote.id)}
          allTagNames={allTags.map(t => t[0])}
        />
      )}
    </div>
  );
};

// ----- Card -----
const NoteCard = ({ note, onOpen, onTogglePin }) => {
  const preview = (note.body || '')
    .replace(/^#+\s*/gm, '')
    .replace(/\*\*(.+?)\*\*/g, '$1')
    .replace(/\*(.+?)\*/g, '$1')
    .replace(/`(.+?)`/g, '$1')
    .replace(/^- /gm, '· ')
    .trim();

  return (
    <div className={`note-card ${note.pinned ? 'pinned' : ''}`} onClick={onOpen}>
      {note.pinned && <span className="note-card-pinmark"><Icon name="bookmark" size={11} /></span>}

      <div className="note-card-head">
        <div className="note-card-title">{note.title || 'Untitled'}</div>
        <button className="note-card-pinbtn"
          onClick={(e) => { e.stopPropagation(); onTogglePin(); }}
          title={note.pinned ? 'Unpin' : 'Pin'}>
          <Icon name="bookmark" size={13} />
        </button>
      </div>

      <div className="note-card-preview">{preview || <span style={{color:'var(--fg-3)',fontStyle:'italic'}}>Empty note</span>}</div>

      {note.tags.length > 0 && (
        <div className="note-card-tags">
          {note.tags.slice(0,4).map(t => (
            <span key={t} className="note-tag-pill">{t}</span>
          ))}
          {note.tags.length > 4 && <span className="note-tag-pill more">+{note.tags.length-4}</span>}
        </div>
      )}

      <div className="note-card-foot">
        {note.shared
          ? <span className="note-share-pill shared"><Icon name="users" size={10} /> Shared</span>
          : <span className="note-share-pill private"><Icon name="lock" size={10} /> Private</span>}
        <span className="spacer" />
        <span className="mono note-card-time">{note.updated}</span>
        <span className="avatar" style={{width:18,height:18,fontSize:9}}>{note.author}</span>
      </div>
    </div>
  );
};

// ----- Overlay editor -----
const NoteOverlay = ({ note, onClose, onChange, onTogglePin, onDelete, allTagNames }) => {
  const [mode, setMode] = React.useState('preview');
  const [tagInput, setTagInput] = React.useState('');
  const [showTagPick, setShowTagPick] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const addTag = (t) => {
    const tag = t.trim().toLowerCase();
    if (!tag || note.tags.includes(tag)) return;
    onChange({ tags: [...note.tags, tag] });
    setTagInput('');
  };
  const removeTag = (t) => onChange({ tags: note.tags.filter(x => x !== t) });

  return (
    <div className="note-overlay-scrim" onClick={onClose}>
      <div className="note-overlay" onClick={e => e.stopPropagation()}>
        {/* Topbar */}
        <div className="note-overlay-topbar">
          <button className="ibtn bordered" onClick={onClose}>
            <Icon name="chevLeft" size={13} /> Close
          </button>
          <span className="mono" style={{fontSize:11,color:'var(--fg-3)'}}>{note.id}</span>
          <span className="dot-sep">·</span>
          <span style={{fontSize:11,color:'var(--fg-3)'}}>Updated {note.updated} ago</span>
          <span className="spacer" />
          <button className={`ibtn ${note.pinned?'':'bordered'}`}
            onClick={onTogglePin}
            style={note.pinned ? {background:'var(--fg)',color:'var(--bg)'} : {}}>
            <Icon name="bookmark" size={12} /> {note.pinned ? 'Pinned' : 'Pin'}
          </button>
          <button className={`ibtn ${note.shared?'':'bordered'}`}
            onClick={() => onChange({ shared: !note.shared })}
            style={note.shared ? {background:'var(--fg)',color:'var(--bg)'} : {}}>
            <Icon name={note.shared?'users':'lock'} size={12} /> {note.shared ? 'Shared' : 'Private'}
          </button>
          <div className="note-mode-toggle">
            <button className={mode==='write'?'on':''} onClick={() => setMode('write')}>Write</button>
            <button className={mode==='preview'?'on':''} onClick={() => setMode('preview')}>Preview</button>
          </div>
          <button className="ibtn bordered" onClick={onDelete} title="Delete">
            <Icon name="trash" size={12} />
          </button>
        </div>

        {/* Body scroll */}
        <div className="note-overlay-body">
          <div className="note-overlay-inner">
            {/* Title */}
            <input
              className="note-title-input"
              value={note.title}
              onChange={e => onChange({ title: e.target.value })}
              placeholder="Untitled"
              readOnly={mode === 'preview'}
            />

            {/* Tags */}
            <div className="note-tags-row">
              <Icon name="tag" size={11} className="note-tags-icon" />
              {note.tags.map(t => (
                <span key={t} className="note-tag-chip">
                  {t}
                  <button onClick={() => removeTag(t)} className="note-tag-x">
                    <Icon name="close" size={9} />
                  </button>
                </span>
              ))}
              <div style={{position:'relative'}}>
                <input
                  className="note-tag-input"
                  placeholder="Add tag…"
                  value={tagInput}
                  onChange={e => setTagInput(e.target.value)}
                  onFocus={() => setShowTagPick(true)}
                  onBlur={() => setTimeout(() => setShowTagPick(false), 150)}
                  onKeyDown={e => {
                    if (e.key === 'Enter') { e.preventDefault(); addTag(tagInput); }
                    if (e.key === 'Backspace' && !tagInput && note.tags.length) removeTag(note.tags[note.tags.length-1]);
                  }}
                />
                {showTagPick && allTagNames.filter(t => !note.tags.includes(t) && t.includes(tagInput.toLowerCase())).length > 0 && (
                  <div className="note-tag-suggest">
                    {allTagNames.filter(t => !note.tags.includes(t) && t.includes(tagInput.toLowerCase())).slice(0,6).map(t => (
                      <button key={t} className="note-tag-suggest-item" onMouseDown={() => addTag(t)}>
                        <Icon name="tag" size={10} /> {t}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* Body */}
            {mode === 'write' ? (
              <textarea
                className="note-body-input"
                value={note.body}
                onChange={e => onChange({ body: e.target.value })}
                placeholder="Start writing… Markdown supported."
                spellCheck={false}
                autoFocus
              />
            ) : (
              <div className="note-body-preview">
                <NoteMarkdown text={note.body} />
              </div>
            )}

            {/* Footer */}
            <div className="note-footer">
              <span><Icon name="check" size={11} /> Saved</span>
              <span className="dot-sep">·</span>
              <span>{(note.body || '').split(/\s+/).filter(Boolean).length} words</span>
              <span className="dot-sep">·</span>
              <span>{(note.body || '').length} characters</span>
              <span className="spacer" />
              <span style={{color:'var(--fg-3)'}}>Markdown · Esc to close</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// Lightweight markdown renderer.
const NoteMarkdown = ({ text }) => {
  if (!text) return <div style={{color:'var(--fg-3)',fontStyle:'italic'}}>Nothing to preview.</div>;

  const lines = text.split('\n');
  const out = [];
  let listBuf = null;
  const flushList = () => { if (listBuf) { out.push(<ul key={'ul-'+out.length} className="note-md-ul">{listBuf}</ul>); listBuf = null; } };
  const renderInline = (s) => {
    const parts = []; let i = 0, key = 0;
    while (i < s.length) {
      if (s.startsWith('**', i)) {
        const end = s.indexOf('**', i+2);
        if (end > -1) { parts.push(<strong key={key++}>{s.slice(i+2, end)}</strong>); i = end+2; continue; }
      }
      if (s[i] === '`') {
        const end = s.indexOf('`', i+1);
        if (end > -1) { parts.push(<code key={key++} className="note-md-code">{s.slice(i+1, end)}</code>); i = end+1; continue; }
      }
      if (s[i] === '*' && s[i+1] !== '*') {
        const end = s.indexOf('*', i+1);
        if (end > -1) { parts.push(<em key={key++}>{s.slice(i+1, end)}</em>); i = end+1; continue; }
      }
      let j = i; while (j < s.length && s[j] !== '*' && s[j] !== '`') j++;
      parts.push(s.slice(i, j)); i = j;
    }
    return parts;
  };
  lines.forEach((ln, idx) => {
    if (ln.startsWith('## ')) { flushList(); out.push(<h3 key={idx} className="note-md-h2">{renderInline(ln.slice(3))}</h3>); }
    else if (ln.startsWith('# ')) { flushList(); out.push(<h2 key={idx} className="note-md-h1">{renderInline(ln.slice(2))}</h2>); }
    else if (ln.startsWith('- ')) { if (!listBuf) listBuf = []; listBuf.push(<li key={idx}>{renderInline(ln.slice(2))}</li>); }
    else if (ln.trim() === '') { flushList(); out.push(<div key={idx} style={{height:8}} />); }
    else { flushList(); out.push(<p key={idx} className="note-md-p">{renderInline(ln)}</p>); }
  });
  flushList();
  return <div>{out}</div>;
};

Object.assign(window, { NotesPage });
