// Columns.jsx — 左栏(时间/地点轴)、中栏(笔记列表)、右栏(本子系列)
const { useState: useStateCol } = React;

// ---- 由笔记聚合时间树 / 地点树（区分已写入 vs 采集箱）----
function buildTimeTree(notes) {
  const years = {};
  notes.forEach(n => {
    if (!n.year) return;   // 只有地点、没有时间的采集（如口述地点）不进时间轴
    const y = years[n.year] = years[n.year] || { months: {}, total: 0, inbox: 0 };
    const m = y.months[n.month] = y.months[n.month] || { count: 0, inbox: 0 };
    if (n._inbox) { y.inbox++; m.inbox++; } else { y.total++; m.count++; }
  });
  return Object.keys(years).sort((a, b) => b - a).map(y => ({
    year: y, total: years[y].total, inbox: years[y].inbox,
    months: Object.keys(years[y].months).sort((a, b) => parseInt(b) - parseInt(a))
      .map(m => ({ month: m, count: years[y].months[m].count, inbox: years[y].months[m].inbox })),
  }));
}
function buildPlaceTree(notes) {
  const cities = {};
  notes.forEach(n => {
    if (!n.city) return;
    const c = cities[n.city] = cities[n.city] || { scenes: {}, total: 0, inbox: 0 };
    const s = c.scenes[n.scene] = c.scenes[n.scene] || { count: 0, inbox: 0 };
    if (n._inbox) { c.inbox++; s.inbox++; } else { c.total++; s.count++; }
  });
  return Object.keys(cities).map(c => ({
    city: c, total: cities[c].total, inbox: cities[c].inbox,
    scenes: Object.keys(cities[c].scenes).map(s => ({ scene: s, count: cities[c].scenes[s].count, inbox: cities[c].scenes[s].inbox })),
  }));
}

const SCENE_ICON = { '家': 'home', '咖啡馆': 'coffee', '旅途中': 'mapPin', '图书馆': 'book', '户外': 'globe', '办公室': 'layers' };

// ============ 左栏 ============
function LeftAxis({ axis, setAxis, allNotes, timeFilter, setTimeFilter, placeFilter, setPlaceFilter,
                    onOpenNote, onExpandMetro, selectedNote, stCity, setStCity, onOpenInbox }) {
  const [openY, setOpenY] = useStateCol(() => new Set(['2026', '2021']));
  const [openC, setOpenC] = useStateCol(() => new Set(['上海', '京都']));
  const timeTree = buildTimeTree(allNotes);
  const placeTree = buildPlaceTree(allNotes);

  const filterText = axis === 'time'
    ? (timeFilter.year ? timeFilter.year + (timeFilter.month ? ' · ' + timeFilter.month : '年') : null)
    : (placeFilter.city ? placeFilter.city + (placeFilter.scene ? ' · ' + placeFilter.scene : '') : null);

  function toggleY(y) { const s = new Set(openY); s.has(y) ? s.delete(y) : s.add(y); setOpenY(s); }
  function toggleC(c) { const s = new Set(openC); s.has(c) ? s.delete(c) : s.add(c); setOpenC(s); }

  return (
    <div className="colL">
      <div className="lefttab">
        <button className={axis === 'time' ? 'on' : ''} onClick={() => setAxis('time')}>
          <Icon name="clock" size={13} /> 时间
        </button>
        <button className={axis === 'place' ? 'on' : ''} onClick={() => setAxis('place')}>
          <Icon name="mapPin" size={13} /> 地点
        </button>
        <button className={axis === 'spacetime' ? 'on' : ''} onClick={() => setAxis('spacetime')}>
          <Icon name="route" size={13} /> 时空
        </button>
      </div>

      {axis === 'spacetime' ? (
        <SpacetimeColumn onOpenNote={onOpenNote} onExpand={onExpandMetro}
          selected={selectedNote} cityFilter={stCity} setCityFilter={setStCity} />
      ) : (<React.Fragment>
      {filterText && (
        <div className="filter-chip">
          <Icon name="filter" size={12} />
          <span>{filterText}</span>
          <span className="x" onClick={() => axis === 'time' ? setTimeFilter({}) : setPlaceFilter({})}>
            <Icon name="x" size={12} />
          </span>
        </div>
      )}

      <div className="tree">
        {axis === 'time' ? timeTree.map(y => (
          <div key={y.year}>
            <div className={'tnode' + (openY.has(y.year) ? ' open' : '') + (timeFilter.year === y.year && !timeFilter.month ? ' on' : '')}>
              <span onClick={() => toggleY(y.year)} style={{ display: 'inline-grid' }}>
                <Icon name="chevRight" size={12} className="tw" />
              </span>
              <span className="label" onClick={() => setTimeFilter(timeFilter.year === y.year && !timeFilter.month ? {} : { year: y.year })}>
                {y.year}
              </span>
              {y.total > 0 && <span className="badge">{y.total}</span>}
              {y.inbox > 0 && (
                <span className="badge ib" title="采集箱里待整理" onClick={e => { e.stopPropagation(); onOpenInbox && onOpenInbox(); }}>
                  <Icon name="download" size={9} /> {y.inbox}
                </span>
              )}
            </div>
            <div className="tchild-wrap" style={{ maxHeight: openY.has(y.year) ? y.months.length * 36 + 'px' : 0 }}>
              {y.months.map(m => (
                <div key={m.month}
                  className={'tchild' + (timeFilter.year === y.year && timeFilter.month === m.month ? ' on' : '')}
                  onClick={() => {
                    const same = timeFilter.year === y.year && timeFilter.month === m.month;
                    setTimeFilter(same ? {} : { year: y.year, month: m.month });
                  }}>
                  <span className="label">{m.month}</span>
                  {m.count > 0 && <span className="badge">{m.count}</span>}
                  {m.inbox > 0 && <span className="badge ib"><Icon name="download" size={9} /> {m.inbox}</span>}
                </div>
              ))}
            </div>
          </div>
        )) : placeTree.map(c => (
          <div key={c.city}>
            <div className={'tnode' + (openC.has(c.city) ? ' open' : '') + (placeFilter.city === c.city && !placeFilter.scene ? ' on' : '')}>
              <span onClick={() => toggleC(c.city)} style={{ display: 'inline-grid' }}>
                <Icon name="chevRight" size={12} className="tw" />
              </span>
              <Icon name="mapPin" size={13} className="placeicon" />
              <span className="label" onClick={() => setPlaceFilter(placeFilter.city === c.city && !placeFilter.scene ? {} : { city: c.city })}>
                {c.city}
              </span>
              {c.total > 0 && <span className="badge">{c.total}</span>}
              {c.inbox > 0 && (
                <span className="badge ib" title="采集箱里待整理" onClick={e => { e.stopPropagation(); onOpenInbox && onOpenInbox(); }}>
                  <Icon name="download" size={9} /> {c.inbox}
                </span>
              )}
            </div>
            <div className="tchild-wrap" style={{ maxHeight: openC.has(c.city) ? c.scenes.length * 36 + 'px' : 0 }}>
              {c.scenes.map(s => (
                <div key={s.scene}
                  className={'tchild' + (placeFilter.city === c.city && placeFilter.scene === s.scene ? ' on' : '')}
                  onClick={() => {
                    const same = placeFilter.city === c.city && placeFilter.scene === s.scene;
                    setPlaceFilter(same ? {} : { city: c.city, scene: s.scene });
                  }}>
                  <Icon name={SCENE_ICON[s.scene] || 'mapPin'} size={12} style={{ color: 'var(--ink-3)' }} />
                  <span className="label">{s.scene}</span>
                  <span className="badge">{s.count}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      </React.Fragment>)}
    </div>
  );
}

// ============ 标签 ============
function Tag({ kind, children, icon }) {
  return <span className={'tag ' + kind}>{icon && <Icon name={icon} size={10} />}{children}</span>;
}

// ============ 中栏：笔记列表 ============
function NoteList({ notes, allTags, tagFilter, setTagFilter, selected, onOpen, cardLayout }) {
  return (
    <div className="colM">
      <div className="tagbar">
        <button className={'tagpill' + (tagFilter === 'all' ? ' on' : '')} onClick={() => setTagFilter('all')}>全部</button>
        {allTags.map(t => (
          <button key={t} className={'tagpill' + (tagFilter === t ? ' on' : '')} onClick={() => setTagFilter(tagFilter === t ? 'all' : t)}>{t}</button>
        ))}
      </div>
      <div className="listscroll">
        <div className="list-meta">{notes.length} 则笔记{cardLayout === 'stream' ? ' · 时间流' : ''}</div>
        {notes.length === 0 ? (
          <div className="empty">
            <div className="seal">空</div>
            这里还什么都没有。<br/>你的笔记，会随阅读慢慢聚拢。
          </div>
        ) : (
          <div className="cards">
            {notes.map(n => (
              <div key={n.id} className={'card' + (selected === n.id ? ' on' : '')} onClick={() => onOpen(n.id)}>
                <div className="card-row1">
                  <div className="card-title">{n.title} <span className="en">{n.en}</span></div>
                  <div className="card-date">{n.date}</div>
                </div>
                <div className="card-prev">{n.preview}</div>
                <div className="card-tags">
                  <Tag kind="cat">{n.cat}</Tag>
                  {n.notes.map(t => <Tag key={t} kind="note">{t}</Tag>)}
                  {n.locs.map(t => <Tag key={t} kind="loc" icon="mapPin">{t}</Tag>)}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ============ 右栏：本子系列 ============
function NotebookRail({ notebooks, counts, active, onPick, iconStyle, onAdd }) {
  return (
    <div className="colR">
      <div className="colR-head">
        <span className="t">Notebooks<span className="cjk">本子</span></span>
      </div>
      <div className="nb-scroll">
        {notebooks.map(nb => (
          <div key={nb.id}
            className={'notebook' + (active === nb.id ? ' on' : '')}
            style={{ background: nb.bg, color: nb.fg }}
            onClick={() => onPick(active === nb.id ? null : nb.id)}>
            <div className="nb-top">
              <SealGlyph glyph={nb.glyph} size={26}
                color={iconStyle === 'line' ? 'transparent' : 'var(--flame)'}
                fg={nb.fg}
                variant={iconStyle === 'seal' ? 'seal' : iconStyle === 'stamp' ? 'stamp' : 'line'}
                lineIcon={nb.lineIcon}
                style={iconStyle === 'line' ? { color: nb.fg, border: '1px solid ' + nb.fg } : (iconStyle === 'stamp' ? { color: nb.fg, borderColor: nb.fg } : {})} />
              <span className="nb-count">{counts[nb.id] || 0}</span>
            </div>
            <div className="nb-name" style={{ marginTop: 10 }}>{nb.name}</div>
            <div className="nb-desc">{nb.desc}</div>
          </div>
        ))}
        <div className="nb-add" onClick={onAdd}>
          <Icon name="plus" size={15} /> 新建本子
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LeftAxis, NoteList, NotebookRail, Tag, SCENE_ICON });
