// Top.jsx — 顶部本子横条 + 时空轴（左栏竖向时间轴 / 展开：线路图 + 数字地图）
const { useState: useStateTop } = React;

// ============ 本子横条（书架式 · 统一深色书脊）============
function NotebookRow({ notebooks, counts, active, onPick, onAdd, onNewNote }) {
  const activeNb = notebooks.find(nb => nb.id === active);
  return (
    <div className="nbrow">
      <span className="nbrow-label">本子</span>
      <div className="nbrow-shelf">
        {notebooks.map(nb => (
          <div key={nb.id} className={'spine-wrap' + (active === nb.id ? ' on' : '')}>
            <button
              className={'spine' + (active === nb.id ? ' on' : '')}
              onClick={() => onPick(active === nb.id ? null : nb.id)}>
              <span className="spine-edge"></span>
              <span className="spine-ico"><Icon name={nb.lineIcon} size={17} /></span>
              <span className="spine-name">{nb.name}</span>
              <span className="spine-count">{counts[nb.id] || 0}</span>
            </button>
          </div>
        ))}
        <button className="spine-add" onClick={onAdd}><Icon name="plus" size={14} /> 新建本子</button>
        {/* 选中一个本子后，在这里写新的一页 */}
        {activeNb && (
          <button className="spine-newnote" title={'在「' + activeNb.name + '」里写一页'}
            onClick={() => onNewNote && onNewNote(activeNb.id)}>
            <Icon name="pencil" size={13} /> 在「{activeNb.name}」新建一页
          </button>
        )}
      </div>
    </div>
  );
}

// ============ 时空轴 · 左栏（时间 × 地点合一 · 以现在为主轴 · 可伸缩）============
function SpacetimeColumn({ onOpenNote, onExpand, selected, cityFilter, setCityFilter }) {
  const [scale, setScale] = useStateTop(1);     // 时间疏密（伸缩）
  const asc = buildStations();
  const all = [...asc].reverse();                // 以现在为主轴 → 最新在上，向下走入过去
  const cities = [...new Set(asc.map(s => s.note.city))];
  const stations = cityFilter ? all.filter(s => s.note.city === cityFilter) : all;

  const gap = Math.round(4 * scale);
  let lastYear = null;
  return (
    <div className="stcol">
      <div className="stcol-head">
        <div>
          <div className="stcol-title">时空轴</div>
          <div className="stcol-sub">沿着时间与地点，回到那一刻</div>
        </div>
        <button className="stcol-expand" onClick={onExpand}><Icon name="globe" size={13} /> 地图</button>
      </div>

      <div className="stcol-cities">
        <button className={'stcity' + (!cityFilter ? ' on' : '')} onClick={() => setCityFilter(null)}>全部</button>
        {cities.map(c => (
          <button key={c} className={'stcity' + (cityFilter === c ? ' on' : '')}
            style={cityFilter === c ? { background: CITY_LINE[c], borderColor: CITY_LINE[c], color: '#fff' } : { color: CITY_LINE[c] }}
            onClick={() => setCityFilter(cityFilter === c ? null : c)}>{c}</button>
        ))}
      </div>

      {/* 伸缩控制：把时间轴拉疏 / 收密 */}
      <div className="stcol-zoom">
        <span className="zl">时间疏密</span>
        <div className="zbtns">
          <button onClick={() => setScale(s => Math.max(0.7, +(s - 0.35).toFixed(2)))} title="收密"><Icon name="minus" size={13} /></button>
          <span className="zbar"><i style={{ width: ((scale - 0.7) / (2.1 - 0.7) * 100) + '%' }} /></span>
          <button onClick={() => setScale(s => Math.min(2.1, +(s + 0.35).toFixed(2)))} title="拉疏"><Icon name="plus" size={13} /></button>
        </div>
      </div>

      <div className="stcol-scroll">
        <div className="stline" style={{ gap: gap + 'px' }}>
          {/* 现在 · 主轴锚点 */}
          {!cityFilter && (
            <button className="st-stop now" onClick={onExpand}>
              <span className="st-time">{NOW.date.slice(5)}<i>{NOW.time}</i></span>
              <span className="st-rail"><span className="st-dot now-dot"></span></span>
              <span className="st-body">
                <span className="st-name">现在</span>
                <span className="st-place" style={{ color: 'var(--flame)' }}>{NOW.city} · {NOW.scene}</span>
              </span>
            </button>
          )}
          {stations.map((st, i) => {
            const showYear = st.note.year !== lastYear;
            lastYear = st.note.year;
            const prevCity = i > 0 ? stations[i - 1].note.city : null;
            const transfer = prevCity && prevCity !== st.note.city;
            const place = st.note.city ? st.note.city + (st.note.scene ? ' · ' + st.note.scene : '') : '未记地点';
            return (
              <React.Fragment key={st.note.id}>
                {showYear && <div className="st-year">{st.note.year}</div>}
                <button className={'st-stop' + (selected === st.note.id ? ' on' : '')} onClick={() => onOpenNote(st.note.id)}>
                  <span className="st-time">{st.note.date.slice(5)}<i>{st.note.time}</i></span>
                  <span className="st-rail">
                    <span className={'st-dot' + (transfer ? ' transfer' : '')} style={{ color: st.line }}></span>
                  </span>
                  <span className="st-body">
                    <span className="st-name">{st.note.title}</span>
                    <span className="st-place" style={{ color: st.line }}>{place}</span>
                  </span>
                </button>
              </React.Fragment>
            );
          })}
          <div className="st-tail">更早的时空 · 向下滑</div>
        </div>
      </div>
    </div>
  );
}

// ============ 展开覆层：线路图 + 数字地图 ============
function MetroMap({ onClose, onOpenNote }) {
  const [view, setView] = useStateTop('route');   // route | map
  const stations = buildStations();
  const cities = [...new Set(stations.map(s => s.note.city))];

  return (
    <div className="metro" onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="metro-panel">
        <div className="metro-head">
          <div>
            <div className="metro-title">时空地图</div>
            <div className="metro-sub">你的旅程 · {stations.length} 站 · 跨越 {cities.length} 城 · 2021 — 2026</div>
          </div>
          <div className="metro-switch">
            <button className={view === 'route' ? 'on' : ''} onClick={() => setView('route')}><Icon name="route" size={13} /> 线路图</button>
            <button className={view === 'map' ? 'on' : ''} onClick={() => setView('map')}><Icon name="globe" size={13} /> 数字地图</button>
          </div>
          <button className="metro-close" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="metro-canvas">
          {view === 'route'
            ? <RouteDiagram stations={stations} cities={cities} onOpenNote={onOpenNote} />
            : <DigitalMap stations={stations} cities={cities} onOpenNote={onOpenNote} />}
        </div>

        <div className="metro-foot">
          <Icon name="route" size={13} />
          {view === 'route' ? '时间自上而下，城市分列成线 — 点任意一站，回到那个时空的笔记' : '按经纬度落点的数字地图 — 虚线是你走过的顺序'}
        </div>
      </div>
    </div>
  );
}

// —— 线路图：时间(行) × 城市(列) 地铁式 —— //
function RouteDiagram({ stations, cities, onOpenNote }) {
  const colX = {}; cities.forEach((c, i) => colX[c] = 150 + i * 150);
  const rowY = i => 70 + i * 74;
  const W = 150 + cities.length * 150 + 40;
  const H = rowY(stations.length - 1) + 60;
  const pos = stations.map((st, i) => ({ x: colX[st.note.city], y: rowY(i), st, i }));
  const segs = [];
  for (let i = 1; i < pos.length; i++) {
    const a = pos[i - 1], b = pos[i];
    segs.push({ a, b, color: b.st.line, transfer: a.st.note.city !== b.st.note.city });
  }
  let lastYear = null;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block', minWidth: W * 0.6 }}>
      {/* 时间轴竖线 */}
      <line x1="58" y1={rowY(0) - 14} x2="58" y2={rowY(stations.length - 1) + 14} stroke="var(--rule-2)" strokeWidth="1.5" />
      {/* 城市表头 */}
      {cities.map(c => (
        <g key={c}>
          <text x={colX[c]} y="32" textAnchor="middle" className="rd-city" fill={CITY_LINE[c]}>{c}</text>
          <line x1={colX[c]} y1="42" x2={colX[c]} y2={H - 30} stroke={CITY_LINE[c]} strokeWidth="1" opacity=".12" />
        </g>
      ))}
      {/* 连线 */}
      {segs.map((s, i) => (
        <line key={i} x1={s.a.x} y1={s.a.y} x2={s.b.x} y2={s.b.y}
          stroke={s.color} strokeWidth={s.transfer ? 3 : 6}
          strokeDasharray={s.transfer ? '3 7' : 'none'} strokeLinecap="round" opacity={s.transfer ? .75 : .92} />
      ))}
      {/* 站点 + 时间刻度 */}
      {pos.map(p => {
        const showYear = p.st.note.year !== lastYear; lastYear = p.st.note.year;
        return (
          <g key={p.st.note.id}>
            {showYear && <text x="20" y={p.y - 26} className="rd-year">{p.st.note.year}</text>}
            <line x1="52" y1={p.y} x2="64" y2={p.y} stroke="var(--rule-2)" strokeWidth="1.5" />
            <text x="48" y={p.y - 5} textAnchor="end" className="rd-date">{p.st.note.date.slice(5)}</text>
            <text x="48" y={p.y + 8} textAnchor="end" className="rd-time">{p.st.note.time}</text>
            <g className="rd-stop" onClick={() => onOpenNote(p.st.note.id)} style={{ cursor: 'pointer' }}>
              <circle cx={p.x} cy={p.y} r="8" fill="var(--white)" stroke={p.st.line} strokeWidth="3.5" />
              <text x={p.x + 16} y={p.y + 4.5} className="rd-note">{p.st.note.title}</text>
            </g>
          </g>
        );
      })}
    </svg>
  );
}

// —— 数字地图：东亚经纬度落点 —— //
function DigitalMap({ stations, cities, onOpenNote }) {
  const W = 760, H = 460;
  const lonMin = 110, lonMax = 140, latMin = 19, latMax = 38;
  const px = lon => 60 + (lon - lonMin) / (lonMax - lonMin) * (W - 120);
  const py = lat => 40 + (latMax - lat) / (latMax - latMin) * (H - 90);

  // 经纬网格
  const lonLines = []; for (let lo = 110; lo <= 140; lo += 5) lonLines.push(lo);
  const latLines = []; for (let la = 20; la <= 35; la += 5) latLines.push(la);

  // 城市落点（去重）
  const cityPos = {}; cities.forEach(c => { cityPos[c] = { x: px(CITY_GEO[c].lon), y: py(CITY_GEO[c].lat) }; });
  const counts = {}; stations.forEach(s => counts[s.note.city] = (counts[s.note.city] || 0) + 1);

  // 行程弧线（按时间顺序的城市变化）
  const path = [];
  let prev = null;
  stations.forEach(s => { if (s.note.city !== prev) { path.push(s.note.city); prev = s.note.city; } });
  const arcs = [];
  for (let i = 1; i < path.length; i++) {
    const a = cityPos[path[i - 1]], b = cityPos[path[i]];
    const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2 - Math.abs(b.x - a.x) * .18 - 14;
    arcs.push({ d: `M${a.x} ${a.y} Q${mx} ${my} ${b.x} ${b.y}`, color: CITY_LINE[path[i]] });
  }

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
      {/* 海面底 */}
      <rect x="0" y="0" width={W} height={H} fill="url(#sea)" />
      <defs>
        <radialGradient id="sea" cx="40%" cy="35%" r="80%">
          <stop offset="0%" stopColor="#EAF1F6" />
          <stop offset="100%" stopColor="#DDE7EC" />
        </radialGradient>
      </defs>
      {/* 简化东亚陆块（示意） */}
      <path d="M60 60 Q150 80 175 150 Q185 210 150 250 Q120 300 150 360 Q165 420 120 430 L60 430 Z"
        fill="#E7E0D0" opacity=".7" stroke="#D0C8B8" strokeWidth="1" />
      <path d="M250 300 Q300 280 320 320 Q330 360 295 380 Q260 395 250 360 Z"
        fill="#E7E0D0" opacity=".7" stroke="#D0C8B8" strokeWidth="1" />
      {/* 经纬网格 */}
      {lonLines.map(lo => (
        <g key={'lo' + lo}>
          <line x1={px(lo)} y1="30" x2={px(lo)} y2={H - 30} stroke="#9FB4C0" strokeWidth=".5" opacity=".5" strokeDasharray="2 4" />
          <text x={px(lo)} y={H - 14} textAnchor="middle" className="dm-grid">{lo}°E</text>
        </g>
      ))}
      {latLines.map(la => (
        <g key={'la' + la}>
          <line x1="48" y1={py(la)} x2={W - 30} y2={py(la)} stroke="#9FB4C0" strokeWidth=".5" opacity=".5" strokeDasharray="2 4" />
          <text x="20" y={py(la) + 3} className="dm-grid">{la}°N</text>
        </g>
      ))}
      {/* 行程弧线 */}
      {arcs.map((a, i) => (
        <path key={i} d={a.d} fill="none" stroke={a.color} strokeWidth="2" strokeDasharray="4 6" opacity=".75" />
      ))}
      {/* 城市落点 */}
      {cities.map(c => {
        const p = cityPos[c];
        return (
          <g key={c} className="dm-node" onClick={() => { const s = stations.find(s => s.note.city === c); onOpenNote(s.note.id); }} style={{ cursor: 'pointer' }}>
            <circle cx={p.x} cy={p.y} r={9 + counts[c] * 2} fill={CITY_LINE[c]} opacity=".16" />
            <circle cx={p.x} cy={p.y} r="6" fill="var(--white)" stroke={CITY_LINE[c]} strokeWidth="3" />
            <text x={p.x + 12} y={p.y - 6} className="dm-city" fill={CITY_LINE[c]}>{c}</text>
            <text x={p.x + 12} y={p.y + 8} className="dm-cnt">{counts[c]} 则</text>
          </g>
        );
      })}
      <text x={W - 24} y="26" textAnchor="end" className="dm-label">EAST ASIA · 数字时空图</text>
    </svg>
  );
}

Object.assign(window, { NotebookRow, SpacetimeColumn, MetroMap });
