// Reusable interactive radar/hexagon component.
const { useMemo, useState, useEffect, useRef } = React;

const AXES_DEFAULT = [
  { key: "negotiation", label: "Negotiation" },
  { key: "math",        label: "Math" },
  { key: "coding",      label: "Coding" },
  { key: "reasoning",   label: "Reasoning" },
  { key: "tool_use",    label: "Tool use" },
  { key: "communication", label: "Communication" },
];

function polar(cx, cy, r, angleDeg) {
  const a = (angleDeg - 90) * Math.PI / 180;
  return [cx + r * Math.cos(a), cy + r * Math.sin(a)];
}

function Hexagon({
  size = 520,
  axes = AXES_DEFAULT,
  scores = {},          // { key: 0..100 }
  compareScores = null, // optional second polygon
  accent = "var(--accent)",
  compareAccent = "var(--accent-2, #f59e0b)",
  showLabels = true,
  animateKey = 0,       // bump to retrigger anim
  onHoverAxis = () => {},
  highlight = null,
}) {
  const padding = showLabels ? 84 : 24;
  const cx = size / 2, cy = size / 2;
  const r  = size / 2 - padding;
  const rings = [0.2, 0.4, 0.6, 0.8, 1.0];
  const N = axes.length;

  const points = useMemo(() => axes.map((a, i) => {
    const angle = (360 / N) * i;
    const [x, y] = polar(cx, cy, r, angle);
    const [lx, ly] = polar(cx, cy, r + 36, angle);
    const [tx, ty] = polar(cx, cy, r + 56, angle);
    return { ...a, angle, x, y, lx, ly, tx, ty };
  }), [N, r, cx, cy, axes]);

  const polyFor = (s) =>
    points.map((p, i) => {
      const v = (s[p.key] ?? 0) / 100;
      const [x, y] = polar(cx, cy, r * v, p.angle);
      return `${x},${y}`;
    }).join(" ");

  const polyA = polyFor(scores);
  const polyB = compareScores ? polyFor(compareScores) : null;

  // re-mount polygon to retrigger CSS draw animation
  const animClass = `hex-poly hex-poly-anim-${animateKey % 1000}`;

  return (
    <svg
      width="100%"
      viewBox={`0 0 ${size} ${size}`}
      style={{ display: "block", overflow: "visible" }}
      aria-label="Capability radar"
    >
      <defs>
        <radialGradient id="hexGrad" cx="50%" cy="50%" r="50%">
          <stop offset="0%"   stopColor="var(--surface-2)" stopOpacity="0.6"/>
          <stop offset="100%" stopColor="var(--surface-2)" stopOpacity="0"/>
        </radialGradient>
        <pattern id="hexDots" width="6" height="6" patternUnits="userSpaceOnUse">
          <circle cx="1" cy="1" r="0.6" fill="var(--border)" />
        </pattern>
      </defs>

      {/* faint dot fill */}
      <polygon
        points={points.map(p => `${p.x},${p.y}`).join(" ")}
        fill="url(#hexDots)"
        opacity="0.5"
      />

      {/* concentric rings */}
      {rings.map((t, idx) => (
        <polygon
          key={idx}
          points={points.map(p => {
            const [x, y] = polar(cx, cy, r * t, p.angle);
            return `${x},${y}`;
          }).join(" ")}
          fill={idx === rings.length - 1 ? "url(#hexGrad)" : "none"}
          stroke="var(--border)"
          strokeWidth={idx === rings.length - 1 ? 1.25 : 1}
          strokeDasharray={idx === rings.length - 1 ? "0" : "2 4"}
        />
      ))}

      {/* spokes */}
      {points.map((p, i) => (
        <line key={i} x1={cx} y1={cy} x2={p.x} y2={p.y}
              stroke="var(--border)" strokeWidth="1" strokeDasharray="2 4"/>
      ))}

      {/* ring numeric labels */}
      {rings.map((t, idx) => {
        const [x, y] = polar(cx, cy, r * t, 0);
        return (
          <text key={idx} x={x + 6} y={y + 3}
                fill="var(--muted)" fontSize="10" fontFamily="var(--mono)">
            {Math.round(t * 100)}
          </text>
        );
      })}

      {/* compare polygon */}
      {polyB && (
        <polygon
          points={polyB}
          fill={compareAccent}
          fillOpacity="0.10"
          stroke={compareAccent}
          strokeWidth="1.5"
          strokeDasharray="4 3"
        />
      )}

      {/* main polygon */}
      <polygon
        key={animateKey}
        className={animClass}
        points={polyA}
        fill={accent}
        fillOpacity="0.18"
        stroke={accent}
        strokeWidth="2"
        style={{
          filter: `drop-shadow(0 0 12px color-mix(in oklab, ${accent} 35%, transparent))`,
        }}
      />

      {/* score nodes */}
      {points.map((p, i) => {
        const v = (scores[p.key] ?? 0) / 100;
        const [x, y] = polar(cx, cy, r * v, p.angle);
        const isH = highlight === p.key;
        return (
          <g key={`n-${i}`}>
            <circle cx={x} cy={y} r={isH ? 6 : 4}
                    fill="var(--bg)" stroke={accent} strokeWidth="2"/>
            {isH && (
              <circle cx={x} cy={y} r="12" fill="none"
                      stroke={accent} strokeOpacity="0.4" strokeWidth="1"/>
            )}
          </g>
        );
      })}

      {/* axis hover hit-area + labels */}
      {showLabels && points.map((p, i) => {
        const v = scores[p.key] ?? 0;
        const isH = highlight === p.key;
        return (
          <g key={`l-${i}`}
             onMouseEnter={() => onHoverAxis(p.key)}
             onMouseLeave={() => onHoverAxis(null)}
             style={{ cursor: "default" }}>
            <line x1={cx} y1={cy} x2={p.x} y2={p.y}
                  stroke="transparent" strokeWidth="22"/>
            <text
              x={p.lx} y={p.ly}
              textAnchor="middle"
              dominantBaseline="middle"
              fill={isH ? "var(--fg)" : "var(--muted)"}
              fontSize="11"
              fontFamily="var(--mono)"
              style={{ letterSpacing: "0.08em", textTransform: "uppercase" }}>
              {p.label}
            </text>
            <text
              x={p.tx} y={p.ty}
              textAnchor="middle"
              dominantBaseline="middle"
              fill={isH ? accent : "var(--fg)"}
              fontSize="14"
              fontFamily="var(--mono)"
              fontWeight="600">
              {v.toString().padStart(2, "0")}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

window.Hexagon = Hexagon;
window.AXES_DEFAULT = AXES_DEFAULT;
