/* ========== 主 App + Tweaks ========== */

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState(t.startPage || 'today');
  const [selected, setSelected] = useState(null);
  const [cmdK, setCmdK] = useState(false);
  const [now, setNow] = useState(() => new Date().toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit' }));
  const [activity, setActivity] = useState([
    { time: '09:42', text: 'pipeline 同步 Google Sheets 完成', kind: 'sync' },
    { time: '09:14', text: 'topic-researcher 抓到 3 則品牌輿情', kind: 'skill' },
    { time: '08:50', text: 'IDEA-026 標記為高表現（646k）', kind: 'high' },
  ]);

  // 時鐘
  useEffect(() => {
    const i = setInterval(() => setNow(new Date().toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit' })), 30000);
    return () => clearInterval(i);
  }, []);

  // 鍵盤快捷鍵
  useEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setCmdK(true);
      } else if (!cmdK && !selected && !e.metaKey && !e.ctrlKey && !e.altKey) {
        const map = { '1': 'today', '2': 'pipeline', '3': 'performance', '4': 'formula', '5': 'skills', '6': 'todo' };
        if (map[e.key] && document.activeElement?.tagName !== 'INPUT') setView(map[e.key]);
      }
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [cmdK, selected]);

  const runCommand = useCallback((cmd) => {
    const time = new Date().toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit' });
    setActivity(a => [{ time, text: cmd, kind: 'skill' }, ...a].slice(0, 8));
  }, []);

  const narrow = window.innerWidth < 1100;

  const accentMap = {
    kai: { bright: '#f59879', main: '#e88565', deep: '#c46647' },
    blue: { bright: '#7ab5ff', main: '#62a4ff', deep: '#3d7ad6' },
    green: { bright: '#7ee5a8', main: '#5cd896', deep: '#3aa86c' },
    ruby: { bright: '#ff8fbb', main: '#f06ea0', deep: '#c64a7a' },
  };

  useEffect(() => {
    const c = accentMap[t.accent] || accentMap.kai;
    document.documentElement.style.setProperty('--kai', c.main);
    document.documentElement.style.setProperty('--kai-bright', c.bright);
    document.documentElement.style.setProperty('--kai-deep', c.deep);
    document.documentElement.style.setProperty('--kai-glow', c.main + '2e');
    document.documentElement.style.setProperty('--kai-tint', c.main + '14');
    const baseSize = t.density === 'compact' ? 12.5 : t.density === 'spacious' ? 14.5 : 13.5;
    document.body.style.fontSize = baseSize + 'px';
  }, [t.accent, t.density]);

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
      <CommandBar
        now={now} view={view} setView={setView}
        openCmdK={() => setCmdK(true)}
        narrow={narrow}
      />

      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* 主視圖 */}
        <main style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
          {view === 'today' && <CommandRoom items={ITEMS} todos={TODOS} onSelect={setSelected} switchView={setView} />}
          {view === 'pipeline' && <PipelineView items={ITEMS} onSelect={setSelected} narrow={narrow} />}
          {view === 'performance' && <PerformanceView items={ITEMS} onSelect={setSelected} />}
          {view === 'formula' && <FormulaView items={ITEMS} onSelect={setSelected} />}
          {view === 'skills' && <SkillsView runCommand={runCommand} />}
          {view === 'todo' && <TodoView todos={TODOS} />}

          {/* 底部狀態欄 */}
          <footer style={{
            height: 26, flexShrink: 0,
            background: 'var(--bg-1)', borderTop: '1px solid var(--line)',
            display: 'flex', alignItems: 'center', padding: '0 14px', gap: 14,
            fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--ink-3)',
          }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <Dot color="var(--high)" pulse size={5} /> 已連線
            </span>
            <span>{ITEMS.length} 項目</span>
            <span>{ITEMS.filter(i => i.status === '已上線').length} 已上線</span>
            <span style={{ color: 'var(--low)' }}>{ITEMS.filter(isStuck).length} 卡關</span>
            <div style={{ flex: 1 }} />
            <span><Pill color="var(--ink-3)" bg="var(--bg-3)" border="var(--line)" size="xs">⌘K</Pill> 搜尋</span>
            <span><Pill color="var(--ink-3)" bg="var(--bg-3)" border="var(--line)" size="xs">1-6</Pill> 切換頁</span>
            <span>v{REPO.version} · {REPO.commit}</span>
          </footer>
        </main>

        {/* 右側：活動流 */}
        {t.showActivity && !narrow && (
          <aside style={{
            width: 260, flexShrink: 0,
            background: 'var(--bg-1)', borderLeft: '1px solid var(--line)',
            display: 'flex', flexDirection: 'column', overflow: 'hidden',
          }}>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="cpu" size={14} color="var(--kai-bright)" />
              <span style={{ fontSize: 12, fontWeight: 600 }}>系統活動</span>
              <Dot color="var(--high)" pulse size={5} />
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: '10px 14px' }}>
              {activity.map((a, i) => (
                <div key={i} style={{
                  padding: '8px 0',
                  borderBottom: i < activity.length - 1 ? '1px solid var(--line-faint)' : 'none',
                  animation: i === 0 ? 'slide-in-right 0.3s var(--ease-out)' : 'none',
                }}>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 3 }}>{a.time}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-1)', lineHeight: 1.4 }}>{a.text}</div>
                </div>
              ))}
            </div>

            <div style={{ padding: 12, borderTop: '1px solid var(--line)' }}>
              <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', fontFamily: 'var(--mono)', marginBottom: 8 }}>品牌輿情</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                  <Dot color="var(--high)" size={5} />
                  <span style={{ color: 'var(--high)' }}>正面 12</span>
                  <span style={{ color: 'var(--ink-3)' }}>·</span>
                  <Dot color="var(--low)" size={5} />
                  <span style={{ color: 'var(--low)' }}>負面 0</span>
                </div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>近 30 天 · Google 全網</div>
              </div>
            </div>
          </aside>
        )}
      </div>

      {/* 抽屜 */}
      {selected && <DetailDrawer items={ITEMS} current={selected} onClose={() => setSelected(null)} onNav={setSelected} />}
      {/* Cmd-K */}
      {cmdK && <CmdK items={ITEMS} onClose={() => setCmdK(false)} onSelect={(id) => { setSelected(id); setCmdK(false); }} switchView={setView} />}

      {/* Tweaks */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="外觀" />
        <TweakColor label="主題色" value={t.accent === 'kai' ? '#e88565' : t.accent === 'blue' ? '#62a4ff' : t.accent === 'green' ? '#5cd896' : '#f06ea0'}
          options={['#e88565', '#62a4ff', '#5cd896', '#f06ea0']}
          onChange={(v) => {
            const map = { '#e88565': 'kai', '#62a4ff': 'blue', '#5cd896': 'green', '#f06ea0': 'ruby' };
            setTweak('accent', map[v] || 'kai');
          }} />
        <TweakRadio label="密度" value={t.density}
          options={['compact', 'comfortable', 'spacious']}
          onChange={(v) => setTweak('density', v)} />
        <TweakSection label="行為" />
        <TweakSelect label="起始頁" value={t.startPage}
          options={['today', 'pipeline', 'performance', 'formula', 'skills', 'todo']}
          onChange={(v) => setTweak('startPage', v)} />
        <TweakToggle label="顯示活動側欄" value={t.showActivity}
          onChange={(v) => setTweak('showActivity', v)} />
      </TweaksPanel>
    </div>
  );
}

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