// Radar chart + score bar components

function Radar({ data, size = 320, fill = 'var(--k-accent)', compareData = null, compareFill = 'var(--k-indigo)' }) {
  const cx = size / 2, cy = size / 2;
  const r = size / 2 - 40;
  const n = data.length;
  const angle = (i) => (Math.PI * 2 * i) / n - Math.PI / 2;
  const pt = (v, i) => [cx + Math.cos(angle(i)) * r * (v / 100), cy + Math.sin(angle(i)) * r * (v / 100)];
  const poly = (arr) => arr.map((d, i) => pt(d.value, i).join(',')).join(' ');
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      {[20, 40, 60, 80, 100].map(lv => (
        <polygon key={lv} points={data.map((_, i) => {
          const [x, y] = [cx + Math.cos(angle(i)) * r * (lv / 100), cy + Math.sin(angle(i)) * r * (lv / 100)];
          return `${x},${y}`;
        }).join(' ')} fill="none" stroke="var(--k-line)" strokeWidth={lv === 100 ? 1 : 0.6} />
      ))}
      {data.map((_, i) => {
        const [x, y] = [cx + Math.cos(angle(i)) * r, cy + Math.sin(angle(i)) * r];
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="var(--k-line)" strokeWidth={0.6} />;
      })}
      {compareData && (
        <polygon points={poly(compareData)} fill={compareFill} fillOpacity="0.12" stroke={compareFill} strokeWidth="1.5" strokeDasharray="3 3" />
      )}
      <polygon points={poly(data)} fill={fill} fillOpacity="0.18" stroke={fill} strokeWidth="1.8" />
      {data.map((d, i) => {
        const [x, y] = pt(d.value, i);
        const a = angle(i);
        const dotR = r * d.value / 100;
        const labelR = Math.min(Math.max(dotR + 11, 16), r - 6);
        const lx = cx + Math.cos(a) * labelR;
        const ly = cy + Math.sin(a) * labelR;
        return (
          <g key={i}>
            <circle cx={x} cy={y} r={3.5} fill={fill} />
            <text x={lx} y={ly} textAnchor="middle" dominantBaseline="middle"
              fontSize="9" fill={fill} fontFamily="var(--k-mono)" fontWeight="700">{d.value}</text>
          </g>
        );
      })}
      {data.map((d, i) => {
        const lx = cx + Math.cos(angle(i)) * (r + 22);
        const ly = cy + Math.sin(angle(i)) * (r + 22);
        return <text key={i} x={lx} y={ly} textAnchor="middle" dominantBaseline="middle"
          fontSize="10" fill="var(--k-ink-3)" fontFamily="var(--k-sans)">{d.short}</text>;
      })}
    </svg>
  );
}

function ScoreBar({ value, compare = null, height = 6 }) {
  return (
    <div style={{ position: 'relative', height, background: 'var(--k-bg-3)', borderRadius: height / 2, overflow: 'visible' }}>
      <div style={{ position: 'absolute', inset: 0, width: `${value}%`, background: 'var(--k-accent)', borderRadius: height / 2 }} />
      {compare !== null && (
        <div style={{ position: 'absolute', top: -3, left: `${compare}%`, transform: 'translateX(-50%)', width: 2, height: height + 6, background: 'var(--k-indigo)' }} />
      )}
    </div>
  );
}

Object.assign(window, { Radar, ScoreBar });
