/* ========== 今天重點頁 ========== */

function TodayView({ items, todos, onSelect, switchView, runCommand }) {
  const stuck = items.filter(isStuck);
  const live = items.filter(i => i.status === '已上線' && i.b);
  const high = live.filter(i => i.b.p === 'high');
  const lowOrNormal = live.filter(i => i.b.p !== 'high');
  const inbox = items.filter(i => i.status === 'inbox');
  const ready = items.filter(i => i.status === '待拍');
  const overdue = todos.filter(t => t.overdue);

  // 表現摘要
  const totalViews = live.reduce((s, i) => s + (i.b.v || 0), 0);
  const avgRet = live.length ? live.reduce((s, i) => s + (i.b.r || 0), 0) / live.length : 0;
  const avgComp = live.length ? live.reduce((s, i) => s + (i.b.c || 0), 0) / live.length : 0;
  const winRate = live.length ? (high.length / live.length) : 0;

  const recent = [...live].sort((a, b) => (b.publish || '').localeCompare(a.publish || '')).slice(0, 3);

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 22 }}>
      {/* 歡迎條 + 今天的數字感 */}
      <div style={{ marginBottom: 18, animation: 'slide-up 0.4s var(--ease-out)' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 4 }}>
          <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em' }}>
            早安，<span style={{ color: 'var(--kai-bright)' }}>Kai</span>
          </h1>
          <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>
            {new Date().toLocaleDateString('zh-TW', { weekday: 'long', month: 'long', day: 'numeric' })}
          </span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', display: 'flex', gap: 18, flexWrap: 'wrap' }}>
          <span><strong style={{ color: 'var(--ink-1)' }}>{stuck.length}</strong> 件卡關</span>
          <span><strong style={{ color: 'var(--ink-1)' }}>{overdue.length}</strong> 件待辦逾期</span>
          <span><strong style={{ color: 'var(--ink-1)' }}>{ready.length}</strong> 支等待拍攝</span>
          <span><strong style={{ color: 'var(--ink-1)' }}>{inbox.length}</strong> 個靈感未篩選</span>
        </div>
      </div>

      {/* KPI 條：累計表現 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 18 }}>
        <KPI label="累計觀看" value={fmtNum(totalViews)} sub={`${live.length} 支已上線`} icon="eye" delay={0} />
        <KPI label="平均 3s 留存" value={fmtPct(avgRet, 1)} sub="門檻 55% / 高表現 70%" color={avgRet >= 55 ? 'var(--high)' : 'var(--warn)'} icon="trending_up" delay={0.05} />
        <KPI label="平均完播" value={fmtPct(avgComp, 1)} sub="門檻 40%" color={avgComp >= 40 ? 'var(--high)' : 'var(--warn)'} icon="target" delay={0.1} />
        <KPI label="高表現勝率" value={fmtPct(winRate * 100, 0)} sub={`${high.length} / ${live.length} 支`} color="var(--high)" icon="fire" delay={0.15} />
      </div>

      {/* 三大重點區 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(380px, 1fr))', gap: 14, marginBottom: 18 }}>
        {/* 卡關提醒 */}
        <Card
          title={
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="warn" size={14} color="var(--low)" />
              <span>卡關提醒</span>
              <Pill color="var(--low)" bg="var(--low-tint)" border="var(--low-glow)">{stuck.length}</Pill>
            </span>
          }
          accent="var(--low)"
          padding={0}
          action={<button onClick={() => switchView('pipeline')} style={{ fontSize: 11, color: 'var(--ink-2)', padding: '4px 8px' }}>看全部 →</button>}
        >
          <div style={{ maxHeight: 240, overflowY: 'auto' }}>
            {stuck.slice(0, 5).map((it, i) => (
              <StuckRow key={it.id} item={it} onClick={() => onSelect(it.id)} delay={i * 0.04} />
            ))}
            {stuck.length === 0 && (
              <div style={{ padding: 24, textAlign: 'center', color: 'var(--ink-3)', fontSize: 12 }}>沒有卡關 🎉</div>
            )}
          </div>
        </Card>

        {/* 逾期待辦 */}
        <Card
          title={
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="clock" size={14} color="var(--warn)" />
              <span>逾期待辦</span>
              <Pill color="var(--warn)" bg="var(--warn-glow)" border="var(--warn-glow)">{overdue.length}</Pill>
            </span>
          }
          accent="var(--warn)"
          padding={0}
          action={<button onClick={() => switchView('todo')} style={{ fontSize: 11, color: 'var(--ink-2)', padding: '4px 8px' }}>看全部 →</button>}
        >
          <div style={{ maxHeight: 240, overflowY: 'auto' }}>
            {overdue.map((t, i) => (
              <div key={i} style={{
                padding: '11px 14px',
                borderBottom: i < overdue.length - 1 ? '1px solid var(--line-faint)' : 'none',
                display: 'flex', alignItems: 'flex-start', gap: 10,
                animation: `slide-up 0.3s ${i * 0.04}s var(--ease-out) both`,
              }}>
                <span style={{ fontSize: 16, flexShrink: 0 }}>{t.emoji}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, color: 'var(--ink-1)', lineHeight: 1.45, marginBottom: 3 }}>{t.text}</div>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--low)', fontWeight: 600 }}>
                    逾期 {t.overdue} 天 · 期限 {t.due}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* 贏家公式提示 */}
        <Card
          title={
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="formula" size={14} color="var(--kai-bright)" />
              <span>贏家公式（已驗證）</span>
            </span>
          }
          accent="var(--kai-bright)"
          padding={0}
          action={<button onClick={() => switchView('formula')} style={{ fontSize: 11, color: 'var(--ink-2)', padding: '4px 8px' }}>展開矩陣 →</button>}
        >
          <div style={{ padding: 14 }}>
            {PATTERNS.proven_openings.slice(0, 3).map((p, i) => (
              <FormulaRow key={p.code} pattern={p} kind="開場" delay={i * 0.04} />
            ))}
            <div style={{ height: 1, background: 'var(--line-faint)', margin: '10px 0' }} />
            {PATTERNS.proven_ctas.slice(0, 2).map((p, i) => (
              <FormulaRow key={p.code} pattern={p} kind="CTA" delay={(i + 3) * 0.04} />
            ))}
          </div>
          <div style={{
            padding: '10px 14px',
            background: 'var(--bg-2)',
            borderTop: '1px solid var(--line-faint)',
            fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--ink-2)',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <Icon name="cpu" size={11} color="var(--kai-bright)" />
            下支腳本生成自動注入 · 依信心度調整
          </div>
        </Card>
      </div>

      {/* 最近上線 */}
      <Card
        title={<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="trending_up" size={14} /> 最近上線</span>}
        action={<button onClick={() => switchView('performance')} style={{ fontSize: 11, color: 'var(--ink-2)', padding: '4px 8px' }}>表現分析 →</button>}
        padding={0}
      >
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))' }}>
          {recent.map((it, i) => (
            <RecentVideoCard key={it.id} item={it} onClick={() => onSelect(it.id)} delay={i * 0.06} />
          ))}
        </div>
      </Card>
    </div>
  );
}

/* ===== KPI 卡片 ===== */
function KPI({ label, value, sub, color = 'var(--ink-0)', icon, delay = 0 }) {
  return (
    <div className="lift" style={{
      padding: 16,
      background: 'var(--bg-1)',
      border: '1px solid var(--line)',
      borderRadius: 10,
      animation: `slide-up 0.4s ${delay}s var(--ease-out) both`,
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: -10, right: -10,
        width: 60, height: 60, borderRadius: '50%',
        background: 'radial-gradient(circle, var(--kai-glow), transparent 70%)',
        opacity: 0.5, pointerEvents: 'none',
      }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        {icon && <Icon name={icon} size={13} color="var(--ink-3)" />}
        <span style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontFamily: 'var(--mono)' }}>{label}</span>
      </div>
      <div className="mono" style={{ fontSize: 28, fontWeight: 700, color, letterSpacing: '-0.02em', lineHeight: 1, marginBottom: 6 }}>{value}</div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{sub}</div>
    </div>
  );
}

/* ===== 卡關列 ===== */
function StuckRow({ item, onClick, delay }) {
  const limit = THRESHOLDS[item.status];
  const over = item.age - limit;
  return (
    <button
      onClick={onClick}
      style={{
        width: '100%', padding: '11px 14px',
        borderBottom: '1px solid var(--line-faint)',
        display: 'flex', alignItems: 'center', gap: 12,
        textAlign: 'left',
        transition: 'background 0.12s',
        animation: `slide-up 0.3s ${delay}s var(--ease-out) both`,
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0, gap: 2 }}>
        <Pill color={stageColor(item.status)} bg={`${stageColor(item.status)}1f`} size="xs">{STAGE_LABELS[item.status]}</Pill>
        <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>{item.id.replace('IDEA-', '')}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, color: 'var(--ink-0)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: 2 }}>
          {item.title || item.topic}
        </div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--low)' }}>
          ⏱ {item.age} 天（超過 {over} 天）
        </div>
      </div>
      <Icon name="chevron_right" size={14} color="var(--ink-3)" />
    </button>
  );
}

/* ===== 公式列 ===== */
function FormulaRow({ pattern, kind, delay }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0',
      animation: `slide-up 0.3s ${delay}s var(--ease-out) both`,
    }}>
      <Pill color="var(--kai-bright)" bg="var(--kai-tint)" border="var(--kai-glow)">{kind}·{pattern.code}</Pill>
      <span style={{ fontSize: 12, color: 'var(--ink-1)', flex: 1 }}>{pattern.name}</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
        <div style={{ width: 50, height: 5, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
          <div style={{ width: `${pattern.win_rate * 100}%`, height: '100%', background: 'var(--high)' }} />
        </div>
        <span className="mono" style={{ fontSize: 10.5, color: 'var(--high)', fontWeight: 600, width: 30, textAlign: 'right' }}>
          {Math.round(pattern.win_rate * 100)}%
        </span>
      </div>
    </div>
  );
}

/* ===== 最近上線卡 ===== */
function RecentVideoCard({ item, onClick, delay }) {
  const { b } = item;
  const perf = b?.p;
  return (
    <button
      onClick={onClick}
      style={{
        padding: 14, textAlign: 'left',
        borderRight: '1px solid var(--line-faint)',
        borderBottom: '1px solid var(--line-faint)',
        background: 'transparent',
        transition: 'background 0.12s',
        animation: `slide-up 0.4s ${delay}s var(--ease-out) both`,
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{item.vid}</span>
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>·</span>
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{item.publish}</span>
        <div style={{ flex: 1 }} />
        {perf === 'high' && <Pill color="var(--high)" bg="var(--high-tint)" border="var(--high-glow)">🏆</Pill>}
        {perf === 'low' && <Pill color="var(--low)" bg="var(--low-tint)" border="var(--low-glow)">啞彈</Pill>}
      </div>
      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-0)', marginBottom: 10, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {item.title || item.topic}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
        <MiniMetric label="觀看" value={fmtNum(b?.v)} />
        <MiniMetric label="留存" value={fmtPct(b?.r, 0)} good={b?.r >= 55} />
        <MiniMetric label="完播" value={fmtPct(b?.c, 0)} good={b?.c >= 40} />
      </div>
    </button>
  );
}

function MiniMetric({ label, value, good }) {
  return (
    <div>
      <div style={{ fontSize: 9.5, color: 'var(--ink-3)', textTransform: 'uppercase', fontFamily: 'var(--mono)' }}>{label}</div>
      <div className="mono" style={{ fontSize: 13, fontWeight: 600, color: good === true ? 'var(--high)' : good === false ? 'var(--low)' : 'var(--ink-0)' }}>{value}</div>
    </div>
  );
}

Object.assign(window, { TodayView, KPI, StuckRow, FormulaRow, RecentVideoCard, MiniMetric });
