/* ========== 表現雷達 ========== */

function PerformanceView({ items, onSelect }) {
  const live = items.filter(i => i.status === '已上線' && i.b);
  const [hover, setHover] = useState(null);
  const [axisX, setAxisX] = useState('r');
  const [axisY, setAxisY] = useState('c');

  const axes = {
    r: { label: '3秒留存', max: 100, threshold: 55, format: v => `${v.toFixed(0)}%` },
    c: { label: '完播率', max: 100, threshold: 40, format: v => `${v.toFixed(0)}%` },
    e: { label: '互動率', max: 4, threshold: 1.5, format: v => `${v.toFixed(2)}%` },
    v: { label: '觀看數', max: Math.max(...live.map(i => i.b.v || 0)), threshold: 0, format: v => fmtNum(v) },
  };

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18, flexWrap: 'wrap' }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>表現分析</h1>
        <Pill color="var(--ink-2)" bg="var(--bg-2)" border="var(--line)" size="md">{live.length} 支已上線</Pill>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 320px', gap: 14 }}>
        <Card title={
          <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="radar" size={14} />
            <span>{axes[axisX].label} × {axes[axisY].label}</span>
            <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>· hover 看詳細</span>
          </span>
        } padding={0}>
          <div style={{ padding: 14, borderBottom: '1px solid var(--line-faint)', display: 'flex', gap: 14, alignItems: 'center' }}>
            <AxisPicker label="X 軸" value={axisX} onChange={setAxisX} options={axes} />
            <AxisPicker label="Y 軸" value={axisY} onChange={setAxisY} options={axes} />
          </div>
          <Scatter items={live} axisX={axisX} axisY={axisY} axes={axes} hover={hover} setHover={setHover} onSelect={onSelect} />
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {hover ? <HoverDetail item={hover} /> : <DistroPanel items={live} />}
          <RiskPatterns items={live} onSelect={onSelect} />
        </div>
      </div>
    </div>
  );
}

function AxisPicker({ label, value, onChange, options }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase' }}>{label}</span>
      <div style={{ display: 'flex', gap: 2, padding: 2, background: 'var(--bg-2)', borderRadius: 5, border: '1px solid var(--line)' }}>
        {Object.entries(options).map(([k, o]) => (
          <button key={k} onClick={() => onChange(k)} style={{
            padding: '3px 8px', borderRadius: 3, fontSize: 11,
            background: value === k ? 'var(--bg-4)' : 'transparent',
            color: value === k ? 'var(--ink-0)' : 'var(--ink-2)',
          }}>{o.label}</button>
        ))}
      </div>
    </div>
  );
}

function Scatter({ items, axisX, axisY, axes, hover, setHover, onSelect }) {
  const W = 600, H = 360, P = 40;
  const xa = axes[axisX], ya = axes[axisY];
  const xMax = xa.max, yMax = ya.max;
  const xPos = v => P + ((v || 0) / xMax) * (W - 2 * P);
  const yPos = v => H - P - ((v || 0) / yMax) * (H - 2 * P);

  return (
    <div style={{ padding: 16, position: 'relative' }}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        {/* 網格 */}
        {[0.25, 0.5, 0.75].map(t => (
          <g key={t}>
            <line x1={P} x2={W - P} y1={P + t * (H - 2 * P)} y2={P + t * (H - 2 * P)} stroke="var(--line-faint)" strokeDasharray="2 4" />
            <line x1={P + t * (W - 2 * P)} x2={P + t * (W - 2 * P)} y1={P} y2={H - P} stroke="var(--line-faint)" strokeDasharray="2 4" />
          </g>
        ))}
        {/* 門檻線 */}
        {xa.threshold > 0 && (
          <line x1={xPos(xa.threshold)} x2={xPos(xa.threshold)} y1={P} y2={H - P} stroke="var(--warn)" strokeDasharray="3 3" opacity="0.4" />
        )}
        {ya.threshold > 0 && (
          <line x1={P} x2={W - P} y1={yPos(ya.threshold)} y2={yPos(ya.threshold)} stroke="var(--warn)" strokeDasharray="3 3" opacity="0.4" />
        )}
        {/* 軸 */}
        <line x1={P} x2={W - P} y1={H - P} y2={H - P} stroke="var(--line)" />
        <line x1={P} x2={P} y1={P} y2={H - P} stroke="var(--line)" />
        {/* 軸標籤 */}
        <text x={W / 2} y={H - 8} fill="var(--ink-3)" fontSize="10" textAnchor="middle" fontFamily="var(--mono)">{xa.label}</text>
        <text x={12} y={H / 2} fill="var(--ink-3)" fontSize="10" textAnchor="middle" fontFamily="var(--mono)" transform={`rotate(-90 12 ${H / 2})`}>{ya.label}</text>
        {/* 點 */}
        {items.map((it, i) => {
          const cx = xPos(it.b[axisX]);
          const cy = yPos(it.b[axisY]);
          const r = 4 + Math.min(8, (it.b.v || 0) / 100000);
          const c = perfColor(it.b.p);
          const isHover = hover?.id === it.id;
          return (
            <g key={it.id}
              onMouseEnter={() => setHover(it)}
              onMouseLeave={() => setHover(null)}
              onClick={() => onSelect(it.id)}
              style={{ cursor: 'pointer' }}
            >
              <circle cx={cx} cy={cy} r={r + 4} fill={c} opacity={isHover ? 0.3 : 0} style={{ transition: 'opacity 0.15s' }} />
              <circle cx={cx} cy={cy} r={r} fill={c} stroke="var(--bg-0)" strokeWidth="1.5" opacity={hover && !isHover ? 0.3 : 0.85}
                style={{ transition: 'opacity 0.15s, transform 0.15s', transformOrigin: `${cx}px ${cy}px`, transform: isHover ? 'scale(1.2)' : 'scale(1)' }} />
            </g>
          );
        })}
      </svg>
      <div style={{ display: 'flex', gap: 16, justifyContent: 'center', fontSize: 10.5, fontFamily: 'var(--mono)', color: 'var(--ink-3)', marginTop: 8 }}>
        <span><span style={{ color: 'var(--high)' }}>●</span> 高表現</span>
        <span><span style={{ color: 'var(--normal)' }}>●</span> Normal</span>
        <span><span style={{ color: 'var(--low)' }}>●</span> 啞彈</span>
        <span style={{ color: 'var(--warn)' }}>┄ 門檻</span>
        <span>圓圈大小 = 觀看數</span>
      </div>
    </div>
  );
}

function HoverDetail({ item }) {
  return (
    <Card padding={14}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
        <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{item.vid}</span>
        <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>·</span>
        <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{item.publish}</span>
        <div style={{ flex: 1 }} />
        <Pill color={perfColor(item.b.p)} bg={`${perfColor(item.b.p)}1f`} size="sm">{perfLabel(item.b.p)}</Pill>
      </div>
      <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 12 }}>{item.title || item.topic}</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <DetailMetric label="觀看" value={fmtNum(item.b.v)} />
        <DetailMetric label="3s 留存" value={fmtPct(item.b.r, 1)} good={item.b.r >= 70} bad={item.b.r < 55} />
        <DetailMetric label="完播率" value={fmtPct(item.b.c, 1)} good={item.b.c >= 40} bad={item.b.c < 30} />
        <DetailMetric label="互動率" value={fmtPct(item.b.e, 2)} good={item.b.e >= 1.5} bad={item.b.e < 1} />
      </div>
    </Card>
  );
}

function DetailMetric({ label, value, good, bad }) {
  const c = good ? 'var(--high)' : bad ? 'var(--low)' : 'var(--ink-0)';
  return (
    <div style={{ padding: 10, background: 'var(--bg-2)', borderRadius: 6 }}>
      <div style={{ fontSize: 9.5, color: 'var(--ink-3)', textTransform: 'uppercase', fontFamily: 'var(--mono)' }}>{label}</div>
      <div className="mono" style={{ fontSize: 17, fontWeight: 700, color: c, marginTop: 2 }}>{value}</div>
    </div>
  );
}

function DistroPanel({ items }) {
  const buckets = { high: 0, normal: 0, low: 0 };
  items.forEach(i => buckets[i.b.p] = (buckets[i.b.p] || 0) + 1);
  const total = items.length;
  return (
    <Card title="表現分布" padding={14}>
      {['high', 'normal', 'low'].map(k => {
        const c = perfColor(k);
        const v = buckets[k] || 0;
        const pct = (v / total) * 100;
        return (
          <div key={k} style={{ marginBottom: 10 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 4 }}>
              <span style={{ color: c }}>{perfLabel(k)}</span>
              <span className="mono" style={{ color: 'var(--ink-2)' }}>{v} 支 · {pct.toFixed(0)}%</span>
            </div>
            <Bar value={v} max={total} color={c} height={5} />
          </div>
        );
      })}
    </Card>
  );
}

function RiskPatterns({ items, onSelect }) {
  return (
    <Card title={<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="warn" size={13} color="var(--low)" /> 風險模式</span>} padding={0}>
      {PATTERNS.risk_patterns.map((p, i) => (
        <div key={i} style={{
          padding: '10px 14px',
          borderBottom: i < PATTERNS.risk_patterns.length - 1 ? '1px solid var(--line-faint)' : 'none',
          fontSize: 11.5,
        }}>
          <div style={{ color: 'var(--low)', fontWeight: 600, marginBottom: 4 }}>{p.pattern}</div>
          <div style={{ color: 'var(--ink-2)', fontSize: 11, lineHeight: 1.5, marginBottom: 4 }}>{p.description}</div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>留存 {p.avg_retention} · 完播 {p.avg_completion}</span>
            <div style={{ flex: 1 }} />
            {p.vid_evidence.map(v => (
              <button key={v} onClick={() => {
                const found = items.find(i => i.vid === v);
                if (found) onSelect(found.id);
              }} className="mono" style={{ fontSize: 10, color: 'var(--kai-bright)', padding: '2px 6px', background: 'var(--kai-tint)', borderRadius: 3 }}>{v}</button>
            ))}
          </div>
        </div>
      ))}
    </Card>
  );
}

Object.assign(window, { PerformanceView });
