// Left sidebar: book + chapters + entries tree + add controls
function Sidebar({
  book, activeEntryId, onSelect, aiFocusEntryId,
  openChapters, setOpenChapters, onCollapse,
  onAddChapter, onAddEntry, newlyCreatedId,
}) {
  const [q, setQ] = React.useState('');
  const [addOpen, setAddOpen] = React.useState(false);
  const [chapterPicker, setChapterPicker] = React.useState(false);
  const addRef = React.useRef(null);

  React.useEffect(() => {
    const h = (e) => {
      if (addRef.current && !addRef.current.contains(e.target)) {
        setAddOpen(false); setChapterPicker(false);
      }
    };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  const toggleChapter = (id) => {
    setOpenChapters(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const ql = q.trim().toLowerCase();
  const match = (txt) => !ql || (txt || '').toLowerCase().includes(ql);

  return (
    <aside className="sidebar">
      <div className="sb-head">
        <div className="sb-book">
          <div className="sb-book-title">{book.title}</div>
          <div className="sb-book-sub">{book.subtitle}</div>
        </div>
        <button className="sb-collapse-btn" onClick={onCollapse} title="收起侧栏">
          <Icon.PanelLeft size={14} />
        </button>
      </div>
      <div className="sb-search">
        <div className="sb-search-box">
          <Icon.Search />
          <input
            placeholder="搜索条目…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
          {!q && <kbd>⌘K</kbd>}
        </div>
      </div>
      <div className="sb-tree">
        {book.chapters.map(ch => {
          const entries = ch.entries.filter(e =>
            match(e.title) || match(e.titleEn) || match(ch.title)
          );
          if (ql && entries.length === 0) return null;
          const isOpen = ql ? true : (openChapters[ch.id] ?? true);
          return (
            <div key={ch.id} className={`sb-chapter ${isOpen ? 'open' : ''}`}>
              <div className="sb-chapter-head" onClick={() => !ql && toggleChapter(ch.id)}>
                <span className="sb-caret"><Icon.Caret /></span>
                <span className="sb-chapter-title">{ch.title}</span>
                <button
                  className="sb-ch-add"
                  title="在此章新建条目"
                  onClick={(e) => { e.stopPropagation(); onAddEntry(ch.id); }}
                >
                  <Icon.Plus size={13} />
                </button>
                <span className="sb-count">{ch.entries.length}</span>
              </div>
              <div className="sb-entries">
                <div>
                  {entries.map(e => (
                    <div
                      key={e.id}
                      className={
                        'sb-entry' +
                        (e.id === activeEntryId ? ' active' : '') +
                        (e.id === aiFocusEntryId ? ' ai-focus' : '') +
                        (e.id === newlyCreatedId ? ' just-created' : '')
                      }
                      onClick={() => onSelect(e.id)}
                    >
                      <span className="sb-entry-title">{e.title}</span>
                      <span className="sb-entry-en">{e.titleEn}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="sb-foot" ref={addRef}>
        <button className="sb-add-btn" onClick={() => { setAddOpen(v => !v); setChapterPicker(false); }}>
          <Icon.Plus size={13} /> <span>新建</span>
        </button>
        {addOpen && !chapterPicker && (
          <div className="sb-add-menu">
            <button className="sb-add-item" onClick={() => { setAddOpen(false); onAddChapter(); }}>
              <span className="sb-add-ico">📖</span>
              <div>
                <div className="sb-add-t">新建章节</div>
                <div className="sb-add-s">在底部添加一个新章节</div>
              </div>
            </button>
            <button className="sb-add-item" onClick={() => setChapterPicker(true)}>
              <span className="sb-add-ico">📄</span>
              <div>
                <div className="sb-add-t">新建条目…</div>
                <div className="sb-add-s">选择章节，然后添加一条</div>
              </div>
            </button>
          </div>
        )}
        {addOpen && chapterPicker && (
          <div className="sb-add-menu">
            <div className="sb-add-hint">选择一个章节：</div>
            <div className="sb-picker">
              {book.chapters.map(ch => (
                <button
                  key={ch.id}
                  className="sb-add-item compact"
                  onClick={() => { setAddOpen(false); setChapterPicker(false); onAddEntry(ch.id); }}
                >
                  <span>{ch.title}</span>
                  <span className="sb-count" style={{marginLeft:'auto'}}>{ch.entries.length}</span>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </aside>
  );
}
window.Sidebar = Sidebar;
