const { useState, useLayoutEffect, useRef, useEffect } = React;
const cx = (...a) => a.filter(Boolean).join(' ');

const TV_COLORS = { g5: '#f2617a', e8s: '#14b8a6', sny: '#5b8def', tcl: '#f59e0b' };
const ACCENTS = [
  { name: '蓝', hex: '#0A84FF', rgb: '10, 132, 255' },
  { name: '青绿', hex: '#0FB5AE', rgb: '15, 181, 174' },
  { name: '紫', hex: '#8B5CF6', rgb: '139, 92, 246' },
  { name: '橙', hex: '#FF9F0A', rgb: '255, 159, 10' },
  { name: '洋红', hex: '#FF375F', rgb: '255, 55, 95' },
];

/* ---------- primitives ---------- */
function Seg({ options, value, onChange, block, sm }) {
  const ref = useRef(null);
  const [st, setSt] = useState({ opacity: 0 });
  useLayoutEffect(() => {
    const c = ref.current; if (!c) return;
    const on = c.querySelector('[data-on="1"]');
    if (on) setSt({ width: on.offsetWidth, transform: `translateX(${on.offsetLeft}px)`, opacity: 1 });
  }, [value, options]);
  return (
    <div className={cx('seg', block && 'block', sm && 'sm')} ref={ref} role="group">
      <span className="thumb" style={st} aria-hidden="true"></span>
      {options.map((o) => {
        const val = typeof o === 'string' ? o : o.value;
        const lab = typeof o === 'string' ? o : o.label;
        const on = val === value;
        return (
          <button key={val} type="button" data-on={on ? '1' : '0'} className={on ? 'on' : ''} onClick={() => onChange(val)}>
            {lab}
          </button>
        );
      })}
    </div>
  );
}

function Btn({ v = 'glass', size, icon, iconR, block, children, ...rest }) {
  const isz = size === 'lg' ? 20 : size === 'sm' ? 16 : 18;
  return (
    <button className={cx('btn', v, size, block && 'block', !children && 'icon')} {...rest}>
      {icon && <Icon name={icon} size={isz} />}
      {children}
      {iconR && <Icon name={iconR} size={isz} />}
    </button>
  );
}

function SHead({ icon, tone = 'blue', title, right }) {
  return (
    <div className="shead">
      {icon && <span className={cx('sicn', tone)}><Icon name={icon} size={17} /></span>}
      <span className="stitle">{title}</span>
      {right && <span className="right">{right}</span>}
    </div>
  );
}

/* ---------- radar ---------- */
function Radar({ ids, size = 268 }) {
  const c = size / 2, R = size / 2 - 40, keys = ATTR_KEYS, n = keys.length;
  const ang = (i) => -Math.PI / 2 + (i * 2 * Math.PI) / n;
  const pt = (i, r) => [c + Math.cos(ang(i)) * r, c + Math.sin(ang(i)) * r];
  const ringPoly = (f) => keys.map((_, i) => pt(i, R * f).join(',')).join(' ');
  const tvs = TVS.filter((t) => ids.includes(t.id));
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="radar">
      {[0.25, 0.5, 0.75, 1].map((f) => (
        <polygon key={f} points={ringPoly(f)} fill="none" stroke="var(--hair)" strokeWidth="1" />
      ))}
      {keys.map((k, i) => {
        const [x, y] = pt(i, R);
        return <line key={k} x1={c} y1={c} x2={x} y2={y} stroke="var(--hair)" strokeWidth="1" />;
      })}
      {tvs.map((t) => {
        const poly = keys.map((k, i) => pt(i, (R * (t.attrs[k] || 0)) / 100).join(',')).join(' ');
        return (
          <polygon key={t.id} points={poly} fill={TV_COLORS[t.id]} fillOpacity="0.14"
            stroke={TV_COLORS[t.id]} strokeWidth="2" strokeLinejoin="round" />
        );
      })}
      {keys.map((k, i) => {
        const [x, y] = pt(i, R + 16);
        return (
          <text key={k} x={x} y={y} className="radar-lbl" textAnchor="middle" dominantBaseline="middle">{k}</text>
        );
      })}
    </svg>
  );
}

/* ---------- compare screen ---------- */
function scoreTV(tv, scene) {
  let s = 0; for (const k in scene.w) s += scene.w[k] * (tv.attrs[k] || 0);
  return s;
}
function topReasons(tv, scene) {
  return Object.keys(scene.w)
    .map((k) => ({ k, c: scene.w[k] * (tv.attrs[k] || 0) }))
    .sort((a, b) => b.c - a.c).slice(0, 3).map((x) => x.k);
}
function bestId(metric, ids) {
  if (!metric.better) return null;
  let best = null, bv = null;
  ids.forEach((id) => {
    const v = metric.vals[id];
    if (typeof v !== 'number') return;
    if (bv === null || (metric.better === 'hi' ? v > bv : v < bv)) { bv = v; best = id; }
  });
  return best;
}

function CompareScreen() {
  const [sel, setSel] = useState(['g5', 'e8s', 'sny']);
  const [dim, setDim] = useState('pic');
  const [sc, setSc] = useState('living');
  const scene = SCENES.find((s) => s.key === sc);
  const dimObj = DIMS.find((d) => d.key === dim);
  const selTvs = TVS.filter((t) => sel.includes(t.id));

  const toggle = (id) => setSel((p) => (p.includes(id) ? (p.length > 2 ? p.filter((x) => x !== id) : p) : [...p, id]));

  const ranked = [...selTvs].map((t) => ({ t, s: scoreTV(t, scene) })).sort((a, b) => b.s - a.s);
  const winner = ranked[0];
  const maxScore = Math.max(...ranked.map((r) => r.s), 1);

  return (
    <div className="page">
      <div className="phead">
        <div className="ptitles">
          <div className="ptitle">电视对比看板</div>
          <div className="psub">勾选候选机型 · 按你家的场景推荐 · 实测数据逐行高亮最优</div>
        </div>
        <div className="actions">
          <Btn v="glass" icon="download">导出对比</Btn>
          <Btn v="pri" icon="plus">加入清单</Btn>
        </div>
      </div>

      {/* 机型选择 */}
      <div className="tvtog">
        {TVS.map((t) => {
          const on = sel.includes(t.id);
          return (
            <button key={t.id} className={cx('tvchip', on && 'on')} onClick={() => toggle(t.id)}>
              <span className="tvdot" style={{ background: TV_COLORS[t.id], opacity: on ? 1 : 0.35 }}></span>
              <span className="tvchip-txt">
                <b>{t.name}</b>
                <small>{t.panel} · {t.size}″ · {t.price}</small>
              </span>
              <span className="tvchip-x">{on ? <Icon name="check" size={15} /> : <Icon name="plus" size={15} />}</span>
            </button>
          );
        })}
      </div>

      <div className="split cmp-split">
        <div className="stack">
          <div className="chartcard">
            <div className="chart-head">
              <span className="chart-title">综合能力雷达</span>
              <span className="legend">
                {selTvs.map((t) => (
                  <span key={t.id}><i style={{ background: TV_COLORS[t.id] }}></i>{t.brand}</span>
                ))}
              </span>
            </div>
            <div className="radar-wrap"><Radar ids={sel} /></div>
          </div>

          <div className="card pad">
            <SHead icon="sliders" title="按场景推荐" />
            <Seg block options={SCENES.map((s) => ({ value: s.key, label: s.label }))} value={sc} onChange={setSc} />
            <div className="scene-blurb">{scene.blurb}</div>
            <div className="rcard hero verdict">
              <div className="vk">首选 · {scene.label}</div>
              <div className="vn">{winner.t.name}</div>
              <div className="vwhy">
                {topReasons(winner.t, scene).map((r) => <span key={r} className="vchip">{r}优</span>)}
              </div>
            </div>
            <div className="ranklist">
              {ranked.map((r, i) => (
                <div className="rankrow" key={r.t.id}>
                  <span className="rank-i">{i + 1}</span>
                  <span className="rank-n">{r.t.name}</span>
                  <span className="rank-bar"><i style={{ width: `${(r.s / maxScore) * 100}%`, background: TV_COLORS[r.t.id] }}></i></span>
                  <span className="rank-s tnum">{Math.round(r.s)}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card pad">
          <div className="cmp-top">
            <Seg options={DIMS.map((d) => ({ value: d.key, label: d.label }))} value={dim} onChange={setDim} />
            <span className="cmp-hint">绿色 = 该行最优</span>
          </div>
          <div className="tbl-wrap">
            <table className="gtable cmp-table">
              <thead>
                <tr>
                  <th>指标</th>
                  {selTvs.map((t) => (
                    <th key={t.id} className="num">
                      <span className="cmp-h"><i style={{ background: TV_COLORS[t.id] }}></i>{t.name}</span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {dimObj.metrics.map((m) => {
                  const best = bestId(m, sel);
                  return (
                    <tr key={m.name}>
                      <td className="lead">{m.name} {m.unit && <span className="mu">{m.unit}</span>}</td>
                      {selTvs.map((t) => {
                        const v = m.vals[t.id];
                        const isBest = best === t.id;
                        let inner;
                        if (v === '✓') inner = <span className="ck ok"><Icon name="check" size={14} /></span>;
                        else if (v === '—') inner = <span className="ck no">—</span>;
                        else inner = v;
                        return (
                          <td key={t.id} className={cx('num', isBest && 'cmp-best')}>
                            {inner}{isBest && <span className="best-dot"></span>}
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- data screen ---------- */
const TIER = {
  done: { label: '已测', tone: 'ok', bar: 'var(--green)' },
  todo: { label: '可实测·待补', tone: 'acc', bar: 'var(--accent)' },
  ext: { label: '需外部', tone: 'mut', bar: 'var(--ink-4)' },
};
function DataScreen() {
  const [f, setF] = useState('all');
  const counts = { done: 0, todo: 0, ext: 0 };
  DATA_ITEMS.forEach((i) => counts[i.tier]++);
  const maxN = Math.max(...DATA_ITEMS.map((i) => i.n));
  const rows = DATA_ITEMS.filter((i) => f === 'all' || i.tier === f).slice().sort((a, b) => b.n - a.n);
  const tiles = [
    { k: 'done', v: counts.done, label: '已测 · 评测已产出', tone: 'ok' },
    { k: 'todo', v: counts.todo, label: '可实测 · 待补', tone: 'acc' },
    { k: 'ext', v: counts.ext, label: '需外部 · 采集/众包/定义', tone: 'mut' },
  ];
  return (
    <div className="page">
      <div className="phead">
        <div className="ptitles">
          <div className="ptitle">原始数据清单</div>
          <div className="psub">65 个工具去重后 55 项 · 按“能不能自己测”分三桶</div>
        </div>
      </div>
      <div className="rgrid tri">
        {tiles.map((t) => (
          <div key={t.k} className={cx('rcard bkt', t.tone)}>
            <div className="rk"><span className={cx('bkt-dot', t.tone)}></span>{t.label}</div>
            <div className="rv">{t.v}</div>
          </div>
        ))}
      </div>
      <div className="cmp-top" style={{ marginTop: 20 }}>
        <Seg options={[{ value: 'all', label: '全部 ' + DATA_ITEMS.length }, { value: 'done', label: '已测 ' + counts.done }, { value: 'todo', label: '可实测 ' + counts.todo }, { value: 'ext', label: '需外部 ' + counts.ext }]} value={f} onChange={setF} />
      </div>
      <div className="card" style={{ marginTop: 12, padding: '18px 8px 10px' }}>
        <div className="tbl-wrap">
          <table className="gtable">
            <thead>
              <tr><th style={{ paddingLeft: 22 }}>数据项</th><th style={{ width: 220 }}>被工具依赖</th><th style={{ width: 140 }}>归属</th></tr>
            </thead>
            <tbody>
              {rows.map((it) => {
                const t = TIER[it.tier];
                return (
                  <tr key={it.name}>
                    <td className="lead" style={{ paddingLeft: 22, whiteSpace: 'normal' }}>
                      <span className={cx('bkt-dot', t.tone)} style={{ marginRight: 9 }}></span>{it.name}
                    </td>
                    <td>
                      <span className="deprow">
                        <span className="depbar"><i style={{ width: `${(it.n / maxN) * 100}%`, background: t.bar }}></i></span>
                        <span className="depn tnum">{it.n}</span>
                      </span>
                    </td>
                    <td><span className={cx('tag', t.tone)}>{it.src || t.label}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* ---------- tools screen ---------- */
function ToolsScreen() {
  const backN = TOOLS_BACK.reduce((s, b) => s + b.tools.length, 0);
  return (
    <div className="page">
      <div className="phead">
        <div className="ptitles">
          <div className="ptitle">工具库</div>
          <div className="psub">AI Agent 后台调用 {backN} · 用户前台交互 {TOOLS_FRONT.length}</div>
        </div>
      </div>

      <SHead icon="scan" tone="blue" title="前台 · 用户交互" right={<span className="cnt-pill">{TOOLS_FRONT.length}</span>} />
      <div className="dgrid front-grid">
        {TOOLS_FRONT.map((t) => (
          <div className="dcard" key={t.n}>
            <div className="dtop">
              <span className="dtile purple"><Icon name={t.icon} size={26} /></span>
              <div><div className="dname">{t.n}</div></div>
            </div>
            <div className="front-act">{t.act}</div>
            <div className="front-ret">
              <span className="ret-lbl">回传 →</span>
              <span className="chips">{t.ret.map((r) => <span key={r} className="chip ret">{r}</span>)}</span>
            </div>
          </div>
        ))}
      </div>

      <div style={{ height: 28 }}></div>
      <SHead icon="layers" tone="purple" title="后台 · Agent 调用" right={<span className="cnt-pill">{backN}</span>} />
      <div className="back-wrap">
        {TOOLS_BACK.map((b) => (
          <div className="card pad back-fam" key={b.t}>
            <div className="fam-head">
              <span className="fam-t">{b.t}</span>
              <span className="fam-d">{b.d}</span>
              <span className="cnt-pill">{b.tools.length}</span>
            </div>
            <div className="chips">{b.tools.map((x) => <span key={x} className="chip flat">{x}</span>)}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- soon ---------- */
function SoonScreen() {
  return (
    <div className="page">
      <div className="soon">
        <span className="ei"><Icon name="broadcast" size={40} /></span>
        <div className="big">AI 选购助手</div>
        <div>对话式入口：你问，Agent 调用后台工具、回结果卡片。<br />（本原型聚焦「对比看板」样板，此处为占位）</div>
      </div>
    </div>
  );
}

/* ---------- app shell ---------- */
const NAV = [
  { cap: '工作台', items: [
    { id: 'agent', label: 'AI 选购助手', icon: 'broadcast' },
    { id: 'compare', label: '对比看板', icon: 'crosshair' },
  ] },
  { cap: '资料库', items: [
    { id: 'data', label: '数据清单', icon: 'database', badge: '55' },
    { id: 'tools', label: '工具库', icon: 'layers', badge: '65' },
  ] },
];
const CRUMB = { agent: 'AI 选购助手', compare: '对比看板', data: '数据清单', tools: '工具库' };

const SCREENS = ['agent', 'compare', 'data', 'tools'];
function App() {
  const initScreen = location.hash.slice(1);
  const [screen, setScreenRaw] = useState(SCREENS.includes(initScreen) ? initScreen : 'compare');
  const setScreen = (id) => { setScreenRaw(id); if (history.replaceState) history.replaceState(null, '', '#' + id); };
  const [theme, setTheme] = useState(new URLSearchParams(location.search).get('theme') === 'light' ? 'light' : 'dark');
  const [accent, setAccent] = useState(ACCENTS[0]);

  useEffect(() => {
    const h = document.documentElement;
    h.setAttribute('data-theme', theme);
    h.style.setProperty('--accent', accent.hex);
    h.style.setProperty('--accent-rgb', accent.rgb);
    h.style.setProperty('--accent-2', `color-mix(in srgb, ${accent.hex} 74%, #fff)`);
    h.style.setProperty('--on-accent', '#fff');
  }, [theme, accent]);

  return (
    <div className="win">
      <div className="mesh" aria-hidden="true"><span className="b b1"></span><span className="b b2"></span><span className="b b3"></span><span className="b b4"></span></div>

      <div className="tb">
        <span className="brand-mini">
          <span className="bmark2"><Icon name="tv" size={19} /></span>
          <span className="bname">电视<b>一站</b></span>
        </span>
        <div className="tb-mid"><span className="crumb">{CRUMB[screen]}</span></div>
        <div className="tb-right">
          <div className="acc-sws">
            {ACCENTS.map((a) => (
              <button key={a.hex} className={cx('acc-sw', a.hex === accent.hex && 'on')} style={{ background: a.hex }} onClick={() => setAccent(a)} aria-label={a.name}></button>
            ))}
          </div>
          <button className={cx('tb-icn')} onClick={() => setTheme((t) => (t === 'dark' ? 'light' : 'dark'))} aria-label="切换主题">
            <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={18} />
          </button>
          <span className="tb-online"><span className="dot"></span>实验室在线</span>
        </div>
      </div>

      <div className="body">
        <aside className="side">
          <div className="brand">
            <span className="bmark2 big"><Icon name="tv" size={22} /></span>
            <span className="bname" style={{ marginLeft: 11, fontSize: 18 }}>电视<b>一站</b></span>
          </div>
          <nav className="nav">
            {NAV.map((g) => (
              <React.Fragment key={g.cap}>
                <div className="scap">{g.cap}</div>
                {g.items.map((it) => (
                  <button key={it.id} className={cx('nitem', screen === it.id && 'on')} onClick={() => setScreen(it.id)}>
                    <span className="nico"><Icon name={it.icon} size={18} /></span>
                    <span className="nlbl">{it.label}</span>
                    {it.badge && <span className="nbadge">{it.badge}</span>}
                  </button>
                ))}
              </React.Fragment>
            ))}
          </nav>
          <div className="side-foot">
            <div className="conncard">
              <span className="cdot"></span>
              <span className="ctxt"><div className="cname">c0lor 测评实验室</div><div className="cstat">Liquid Glass · {theme === 'dark' ? '深色' : '浅色'}</div></span>
            </div>
          </div>
        </aside>

        <main className="content">
          <div className="cscroll scroll">
            <div className="cinner">
              {screen === 'compare' && <CompareScreen />}
              {screen === 'data' && <DataScreen />}
              {screen === 'tools' && <ToolsScreen />}
              {screen === 'agent' && <SoonScreen />}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
