/* ========== Skills + Todo + 影片抽屜 + Cmd-K ========== */

function SkillsView({ runCommand }) {
  const [running, setRunning] = useState(null);

  const tiers = { T0: '基礎', T1: '生成', T2: '進階' };
  const tierColors = { T0: 'var(--info)', T1: 'var(--kai-bright)', T2: 'var(--ruby)' };

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 6 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>Skills</h1>
        <Pill color="var(--ink-2)" bg="var(--bg-2)" border="var(--line)" size="md">{SKILLS.length} 個工具</Pill>
      </div>
      <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginBottom: 18 }}>點擊任一 Skill 直接執行。所有 Skill 都會根據 pipeline 與表現資料自動帶入上下文。</div>

      {Object.entries(tiers).map(([tier, tierLabel]) => (
        <div key={tier} style={{ marginBottom: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}>
            <Pill color={tierColors[tier]} bg={`${tierColors[tier]}1f`} border={`${tierColors[tier]}33`}>{tier} · {tierLabel}</Pill>
            <div style={{ flex: 1, height: 1, background: 'var(--line-faint)' }} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 10 }}>
            {SKILLS.filter(s => s.tier === tier).map(s => (
              <SkillCard key={s.name} skill={s} color={tierColors[tier]} running={running === s.name} onRun={() => {
                setRunning(s.name);
                runCommand(`skill: ${s.name}`);
                setTimeout(() => setRunning(null), 1500);
              }} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function SkillCard({ skill, color, running, onRun }) {
  const [hover, setHover] = useState(false);
  return (
    <div className="lift"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        padding: 14, background: 'var(--bg-1)',
        border: `1px solid ${hover ? color : 'var(--line)'}`,
        borderRadius: 9, position: 'relative', overflow: 'hidden',
        transition: 'border-color 0.15s',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <span className="mono" style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-0)' }}>{skill.name}</span>
        <div style={{ flex: 1 }} />
        <Pill color="var(--ink-3)" bg="var(--bg-3)" size="xs">{skill.uses}× 使用</Pill>
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 12, minHeight: 32 }}>{skill.desc}</div>
      <button onClick={onRun} disabled={running} style={{
        width: '100%', padding: '7px 0',
        background: running ? 'var(--bg-3)' : hover ? color : 'var(--bg-3)',
        color: running ? 'var(--ink-2)' : hover ? '#fff' : 'var(--ink-1)',
        borderRadius: 5, fontSize: 11.5, fontWeight: 600,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        transition: 'all 0.15s',
      }}>
        {running ? <><Icon name="cpu" size={12} /> 執行中…</> : <><Icon name="play" size={11} /> 執行</>}
      </button>
    </div>
  );
}

/* ===== 待辦頁 ===== */
function TodoView({ todos }) {
  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>待辦</h1>
        <Pill color="var(--low)" bg="var(--low-tint)" border="var(--low-glow)" size="md">{todos.filter(t => t.overdue).length} 逾期</Pill>
      </div>
      <Card padding={0}>
        {todos.map((t, i) => (
          <div key={i} style={{
            padding: '14px 16px',
            borderBottom: i < todos.length - 1 ? '1px solid var(--line-faint)' : 'none',
            display: 'flex', alignItems: 'flex-start', gap: 12,
          }}>
            <button style={{
              width: 18, height: 18, borderRadius: 5, flexShrink: 0,
              border: '1.5px solid var(--line-bright)', marginTop: 1,
            }} />
            <span style={{ fontSize: 16, flexShrink: 0 }}>{t.emoji}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, color: 'var(--ink-0)', marginBottom: 4 }}>{t.text}</div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 11, fontFamily: 'var(--mono)' }}>
                {t.routine ? (
                  <Pill color="var(--info)" bg="var(--info-glow)">每週例行</Pill>
                ) : (
                  <>
                    <span style={{ color: 'var(--ink-3)' }}>期限 {t.due}</span>
                    {t.overdue && <Pill color="var(--low)" bg="var(--low-tint)">逾期 {t.overdue} 天</Pill>}
                  </>
                )}
                {t.note && <span style={{ color: 'var(--ink-3)' }}>· {t.note}</span>}
              </div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

/* ========== 影片詳細抽屜 ========== */
function DetailDrawer({ items, current, onClose, onNav }) {
  const idx = items.findIndex(i => i.id === current);
  const it = items[idx];
  if (!it) return null;
  const prev = idx > 0 ? items[idx - 1] : null;
  const next = idx < items.length - 1 ? items[idx + 1] : null;

  useEffect(() => {
    const h = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowLeft' && prev) onNav(prev.id);
      else if (e.key === 'ArrowRight' && next) onNav(next.id);
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [current, prev, next]);

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100,
        animation: 'fade-in 0.2s var(--ease-out)',
      }} />
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(560px, 92vw)',
        background: 'var(--bg-1)', borderLeft: '1px solid var(--line)',
        zIndex: 101, display: 'flex', flexDirection: 'column',
        animation: 'slide-in-right 0.3s var(--ease-out)',
        boxShadow: '-8px 0 32px rgba(0,0,0,0.4)',
      }}>
        {/* 頂部 */}
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Pill color={stageColor(it.status)} bg={`${stageColor(it.status)}22`} size="md">{STAGE_LABELS[it.status]}</Pill>
          <span className="mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{it.id}</span>
          {it.vid && <><Icon name="arrow_right" size={11} color="var(--ink-3)" /><span className="mono" style={{ fontSize: 11, color: 'var(--kai-bright)' }}>{it.vid}</span></>}
          <div style={{ flex: 1 }} />
          <IconBtn icon="arrow_left" tip="上一則 (←)" onClick={() => prev && onNav(prev.id)} />
          <IconBtn icon="arrow_right" tip="下一則 (→)" onClick={() => next && onNav(next.id)} />
          <IconBtn icon="close" tip="關閉 (Esc)" onClick={onClose} />
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 20 }}>
          <h2 style={{ fontSize: 19, fontWeight: 700, lineHeight: 1.3, marginBottom: 8, letterSpacing: '-0.01em' }}>{it.title || it.topic}</h2>
          {it.publish && <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 14 }}>上線 {it.publish} · 距今 {it.age} 天</div>}
          {!it.publish && <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 14 }}>建立 {it.created} · {it.age} 天前</div>}

          {it.tags?.length > 0 && (
            <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginBottom: 16 }}>
              {it.tags.map(t => <Pill key={t} color="var(--kai-bright)" bg="var(--kai-tint)" size="md">#{t}</Pill>)}
            </div>
          )}

          {it.b && (
            <div style={{ marginBottom: 18 }}>
              <SectionTitle icon="trending_up">表現數據</SectionTitle>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <DetailMetric label="觀看" value={fmtNum(it.b.v)} />
                <DetailMetric label="表現" value={perfLabel(it.b.p)} />
                <DetailMetric label="3s 留存" value={fmtPct(it.b.r, 1)} good={it.b.r >= 70} bad={it.b.r < 55} />
                <DetailMetric label="完播" value={fmtPct(it.b.c, 1)} good={it.b.c >= 40} bad={it.b.c < 30} />
                <DetailMetric label="互動" value={fmtPct(it.b.e, 2)} good={it.b.e >= 1.5} bad={it.b.e < 1} />
                <DetailMetric label="路徑" value={it.b.path || '—'} />
              </div>
              {it.b.str?.length > 0 && (
                <div style={{ marginTop: 12, padding: 10, background: 'var(--high-tint)', borderRadius: 6, border: '1px solid var(--high-glow)' }}>
                  <div style={{ fontSize: 10.5, color: 'var(--high)', fontWeight: 600, marginBottom: 4, fontFamily: 'var(--mono)' }}>強項</div>
                  {it.b.str.map((s, i) => <div key={i} style={{ fontSize: 12, color: 'var(--ink-1)' }}>· {s}</div>)}
                </div>
              )}
              {it.b.wk?.length > 0 && (
                <div style={{ marginTop: 8, padding: 10, background: 'var(--low-tint)', borderRadius: 6, border: '1px solid var(--low-glow)' }}>
                  <div style={{ fontSize: 10.5, color: 'var(--low)', fontWeight: 600, marginBottom: 4, fontFamily: 'var(--mono)' }}>弱項</div>
                  {it.b.wk.map((s, i) => <div key={i} style={{ fontSize: 12, color: 'var(--ink-1)' }}>· {s}</div>)}
                </div>
              )}
              <AIReading item={it} />
            </div>
          )}

          <SectionTitle icon="file">流程資訊</SectionTitle>
          <KV label="主題" value={it.topic} />
          {it.script && <KV label="腳本檔" value={it.script} mono />}
          {it.skill && <KV label="使用 Skill" value={it.skill} mono />}
          {it.hook && <KV label="Hook 類型" value={it.hook} mono />}
          {it.notes && <KV label="筆記" value={it.notes} />}
          <KV label="建立日期" value={it.created} mono />
          {it.publish && <KV label="上線日期" value={it.publish} mono />}

          {!it.b && (it.status === 'inbox' || it.status === 'selected' || it.status === '待拍') && (
            <div style={{ marginTop: 16 }}>
              <SectionTitle icon="sparkle">AI 標題建議</SectionTitle>
              <AITitleCandidates
                idea={it}
                opening={[...PATTERNS.proven_openings].sort((a,b) => b.win_rate - a.win_rate)[0]}
                cta={[...PATTERNS.proven_ctas].sort((a,b) => b.win_rate - a.win_rate)[0]}
              />
            </div>
          )}
        </div>

        {/* 底部動作 */}
        <div style={{ padding: 14, borderTop: '1px solid var(--line)', display: 'flex', gap: 8 }}>
          <ActionBtn icon="play" label="生成腳本" />
          <ActionBtn icon="bolt" label="標題建議" />
          <ActionBtn icon="check" label="腳本驗證" />
        </div>
      </aside>
    </>
  );
}

function SectionTitle({ icon, children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 10, marginTop: 4 }}>
      <Icon name={icon} size={12} color="var(--kai-bright)" />
      <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-1)', textTransform: 'uppercase', letterSpacing: '0.06em', fontFamily: 'var(--mono)' }}>{children}</span>
    </div>
  );
}

function KV({ label, value, mono }) {
  return (
    <div style={{ display: 'flex', gap: 12, padding: '6px 0', borderBottom: '1px solid var(--line-faint)', fontSize: 12 }}>
      <div style={{ width: 84, color: 'var(--ink-3)', flexShrink: 0 }}>{label}</div>
      <div style={{ flex: 1, color: 'var(--ink-1)', fontFamily: mono ? 'var(--mono)' : 'inherit', wordBreak: 'break-all' }}>{value}</div>
    </div>
  );
}

function ActionBtn({ icon, label }) {
  return (
    <button className="lift" style={{
      flex: 1, padding: '8px 0', borderRadius: 6,
      background: 'var(--bg-3)', color: 'var(--ink-1)',
      fontSize: 11.5, fontWeight: 500,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      border: '1px solid var(--line)',
    }}>
      <Icon name={icon} size={12} />
      {label}
    </button>
  );
}

/* ========== Cmd-K Palette ========== */
function CmdK({ items, onClose, onSelect, switchView }) {
  const [q, setQ] = useState('');
  const [idx, setIdx] = useState(0);
  const inputRef = useRef(null);

  useEffect(() => { inputRef.current?.focus(); }, []);

  const results = useMemo(() => {
    const cmds = [
      { kind: 'view', label: '前往：今天', action: () => switchView('today'), icon: 'home' },
      { kind: 'view', label: '前往：Pipeline', action: () => switchView('pipeline'), icon: 'flow' },
      { kind: 'view', label: '前往：表現分析', action: () => switchView('performance'), icon: 'radar' },
      { kind: 'view', label: '前往：公式矩陣', action: () => switchView('formula'), icon: 'formula' },
      { kind: 'view', label: '前往：Skills', action: () => switchView('skills'), icon: 'bolt' },
      { kind: 'view', label: '前往：待辦', action: () => switchView('todo'), icon: 'todo' },
    ];
    const itemResults = items.slice(0, 30).map(it => ({
      kind: 'item', label: `${it.id}${it.vid ? ` · ${it.vid}` : ''} — ${it.title || it.topic}`,
      sub: STAGE_LABELS[it.status], action: () => onSelect(it.id), icon: 'file', meta: it,
    }));
    const all = [...cmds, ...itemResults];
    if (!q) return all.slice(0, 12);
    const lc = q.toLowerCase();
    return all.filter(r => r.label.toLowerCase().includes(lc)).slice(0, 12);
  }, [q, items]);

  useEffect(() => { setIdx(0); }, [q]);

  const handleKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setIdx(i => Math.min(results.length - 1, i + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setIdx(i => Math.max(0, i - 1)); }
    else if (e.key === 'Enter' && results[idx]) { results[idx].action(); onClose(); }
    else if (e.key === 'Escape') onClose();
  };

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(4px)', zIndex: 200, animation: 'fade-in 0.15s var(--ease-out)' }} />
      <div style={{
        position: 'fixed', top: '14vh', left: '50%', transform: 'translateX(-50%)',
        width: 'min(620px, 92vw)', maxHeight: '70vh',
        background: 'var(--bg-1)', border: '1px solid var(--line-strong)', borderRadius: 12, zIndex: 201,
        overflow: 'hidden', display: 'flex', flexDirection: 'column',
        boxShadow: '0 24px 60px rgba(0,0,0,0.5)',
        animation: 'slide-up 0.2s var(--ease-out)',
      }}>
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <Icon name="search" size={16} color="var(--ink-2)" />
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} onKeyDown={handleKey}
            placeholder="搜尋影片、靈感、指令…"
            style={{ flex: 1, fontSize: 14, color: 'var(--ink-0)', background: 'none' }} />
          <Pill color="var(--ink-3)" bg="var(--bg-3)" border="var(--line)">Esc</Pill>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 6 }}>
          {results.map((r, i) => (
            <button key={i}
              onClick={() => { r.action(); onClose(); }}
              onMouseEnter={() => setIdx(i)}
              style={{
                width: '100%', padding: '8px 12px', borderRadius: 6,
                display: 'flex', alignItems: 'center', gap: 10,
                background: i === idx ? 'var(--bg-3)' : 'transparent',
                color: 'var(--ink-1)', fontSize: 13, textAlign: 'left',
              }}>
              <Icon name={r.icon} size={14} color={i === idx ? 'var(--kai-bright)' : 'var(--ink-3)'} />
              <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.label}</span>
              {r.sub && <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{r.sub}</span>}
              {i === idx && <Icon name="arrow_right" size={12} color="var(--kai-bright)" />}
            </button>
          ))}
          {results.length === 0 && <div style={{ padding: 20, textAlign: 'center', color: 'var(--ink-3)', fontSize: 12 }}>沒有結果</div>}
        </div>
        <div style={{ padding: '8px 16px', borderTop: '1px solid var(--line-faint)', display: 'flex', gap: 14, fontSize: 10.5, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>
          <span>↑↓ 選擇</span><span>↵ 確認</span><span>Esc 關閉</span>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { SkillsView, TodoView, DetailDrawer, CmdK });
