/* ========== Opening × CTA 棋盤 + 公式列表 ========== */

function FormulaView({ items, onSelect }) {
  const [hoverCell, setHoverCell] = useState(null);

  // 建立 opening x cta 矩陣（從 backfill 推算每個影片的 hook + 推測 CTA）
  // 由於資料中只有 hook_type 在 item.hook，CTA 需要從 patterns 反向查 vid_evidence
  const live = items.filter(i => i.b);

  // openings 與 ctas
  const openings = PATTERNS.proven_openings;
  const ctas = PATTERNS.proven_ctas;

  // 建立 lookup：vid -> opening / cta
  const vidOpening = {};
  openings.forEach(o => o.vid_evidence.forEach(v => { vidOpening[v] = o.code; }));
  const vidCta = {};
  ctas.forEach(c => c.vid_evidence.forEach(v => { vidCta[v] = c.code; }));

  // 建立矩陣
  const matrix = {};
  openings.forEach(o => {
    matrix[o.code] = {};
    ctas.forEach(c => { matrix[o.code][c.code] = []; });
  });
  live.forEach(it => {
    const oCode = vidOpening[it.vid] || it.hook;
    const cCode = vidCta[it.vid];
    if (oCode && cCode && matrix[oCode]?.[cCode]) {
      matrix[oCode][cCode].push(it);
    }
  });

  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(--ink-2)" bg="var(--bg-2)" border="var(--line)" size="md">Opening × CTA</Pill>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 340px', gap: 14 }}>
        <Card padding={0} title={<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="grid" size={14} /> 配對勝率</span>}>
          <div style={{ padding: 16, overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 4 }}>
              <thead>
                <tr>
                  <th style={{ padding: 8 }}></th>
                  {ctas.map(c => (
                    <th key={c.code} style={{ padding: 6, fontSize: 10.5, color: 'var(--ink-2)', fontFamily: 'var(--mono)', fontWeight: 500, textAlign: 'center' }}>
                      <div style={{ color: 'var(--kai-bright)', fontWeight: 600 }}>{c.code}</div>
                      <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>{c.name}</div>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {openings.map(o => (
                  <tr key={o.code}>
                    <th style={{ padding: 6, fontSize: 10.5, color: 'var(--ink-2)', fontFamily: 'var(--mono)', fontWeight: 500, textAlign: 'right' }}>
                      <div style={{ color: 'var(--kai-bright)', fontWeight: 600 }}>{o.code}</div>
                      <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{o.name}</div>
                    </th>
                    {ctas.map(c => {
                      const cell = matrix[o.code][c.code];
                      const n = cell.length;
                      const high = cell.filter(x => x.b.p === 'high').length;
                      const rate = n > 0 ? high / n : 0;
                      const intensity = n === 0 ? 0 : Math.max(0.15, rate);
                      return (
                        <td key={c.code}
                          onMouseEnter={() => setHoverCell({ o, c, items: cell, rate, n, high })}
                          onMouseLeave={() => setHoverCell(null)}
                          style={{
                            padding: 0, position: 'relative',
                            background: n === 0 ? 'var(--bg-2)' : `rgba(92, 216, 150, ${intensity * 0.7})`,
                            border: '1px solid var(--line)',
                            borderRadius: 6, height: 64, minWidth: 80,
                            cursor: n > 0 ? 'pointer' : 'default',
                            transition: 'transform 0.15s, box-shadow 0.15s',
                            transform: hoverCell?.o.code === o.code && hoverCell?.c.code === c.code ? 'scale(1.05)' : 'scale(1)',
                            boxShadow: hoverCell?.o.code === o.code && hoverCell?.c.code === c.code ? '0 4px 12px rgba(0,0,0,0.4)' : 'none',
                          }}>
                          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 2 }}>
                            <div className="mono" style={{ fontSize: 16, fontWeight: 700, color: n > 0 ? 'var(--ink-0)' : 'var(--ink-4)' }}>{n}</div>
                            {n > 0 && <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-1)' }}>{Math.round(rate * 100)}%</div>}
                          </div>
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, fontSize: 10.5, fontFamily: 'var(--mono)', color: 'var(--ink-3)' }}>
              <span>勝率：</span>
              {[0, 0.25, 0.5, 0.75, 1].map(v => (
                <div key={v} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <div style={{ width: 18, height: 14, background: `rgba(92, 216, 150, ${Math.max(0.15, v) * 0.7})`, border: '1px solid var(--line)' }} />
                  <span>{Math.round(v * 100)}%</span>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {hoverCell && hoverCell.n > 0 ? (
            <Card padding={14} title={<span><span className="mono" style={{ color: 'var(--kai-bright)' }}>{hoverCell.o.code}</span> + <span className="mono" style={{ color: 'var(--kai-bright)' }}>{hoverCell.c.code}</span></span>}>
              <div style={{ fontSize: 12, color: 'var(--ink-2)', marginBottom: 10 }}>
                {hoverCell.o.name} × {hoverCell.c.name}
              </div>
              <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
                <Pill color="var(--high)" bg="var(--high-tint)" size="md">{hoverCell.high}/{hoverCell.n} 高表現</Pill>
                <Pill color="var(--ink-1)" bg="var(--bg-3)" size="md">勝率 {Math.round(hoverCell.rate * 100)}%</Pill>
              </div>
              <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', fontFamily: 'var(--mono)', marginBottom: 6 }}>實證影片</div>
              {hoverCell.items.map(it => (
                <button key={it.id} onClick={() => onSelect(it.id)} style={{
                  display: 'flex', gap: 8, padding: '6px 8px', width: '100%', textAlign: 'left',
                  background: 'var(--bg-2)', borderRadius: 5, marginBottom: 4, alignItems: 'center',
                }}>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--kai-bright)' }}>{it.vid}</span>
                  <span style={{ fontSize: 11.5, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.title || it.topic}</span>
                  {it.b.p === 'high' && <span>🏆</span>}
                </button>
              ))}
            </Card>
          ) : (
            <Card padding={14}>
              <div style={{ fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>
                hover 任一格看實證影片。<br/>
                綠色越深 = 該配對歷史勝率越高。<br/>
                <strong style={{ color: 'var(--high)' }}>B2 + C4</strong>（好奇缺口 + 利益引導）是目前最強組合。
              </div>
            </Card>
          )}

          <Card title="證實公式" padding={0}>
            <div style={{ maxHeight: 380, overflowY: 'auto' }}>
              {PATTERNS.proven_formulas.slice(0, 6).map((f, i) => (
                <div key={i} style={{ padding: '10px 14px', borderBottom: '1px solid var(--line-faint)' }}>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-1)', lineHeight: 1.5, marginBottom: 6 }}>{f.formula}</div>
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', alignItems: 'center' }}>
                    {f.tags?.slice(0, 4).map(t => <Pill key={t} color="var(--kai-bright)" bg="var(--kai-tint)" size="xs">#{t}</Pill>)}
                    <div style={{ flex: 1 }} />
                    {f.vid_evidence.map(v => {
                      const found = items.find(i => i.vid === v);
                      return <button key={v} onClick={() => found && onSelect(found.id)} className="mono" style={{ fontSize: 9.5, color: 'var(--high)', padding: '2px 5px', background: 'var(--high-tint)', borderRadius: 3 }}>{v}</button>;
                    })}
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FormulaView });
