import type { PlayerAttribute } from "../lib/playerProgress";

export function AttributeRadar({
  attributes,
  size = 220,
}: {
  attributes: PlayerAttribute[];
  size?: number;
}) {
  const center = size / 2;
  const radius = size * 0.36;
  const n = attributes.length;
  const start = -Math.PI / 2;
  const step = (Math.PI * 2) / n;

  const polar = (i: number, r: number) => {
    const a = start + i * step;
    return { x: center + r * Math.cos(a), y: center + r * Math.sin(a) };
  };

  const rings = [0.25, 0.5, 0.75, 1];
  const dataPoints = attributes
    .map((attr, i) => polar(i, radius * (attr.value / 100)))
    .map((p) => `${p.x},${p.y}`)
    .join(" ");

  return (
    <svg
      className="attr-radar-svg"
      width={size}
      height={size}
      viewBox={`0 0 ${size} ${size}`}
      role="img"
      aria-label="五維屬性雷達"
    >
      {rings.map((ring) => {
        const pts = attributes
          .map((_, i) => polar(i, radius * ring))
          .map((p) => `${p.x},${p.y}`)
          .join(" ");
        return (
          <polygon
            key={ring}
            points={pts}
            fill="none"
            stroke="color-mix(in srgb, var(--line) 70%, var(--gold) 20%)"
            strokeWidth={ring === 1 ? 1.5 : 1}
            opacity={ring === 1 ? 1 : 0.55}
          />
        );
      })}
      {attributes.map((_, i) => {
        const outer = polar(i, radius);
        const inner = polar(i, radius * 0.12);
        return (
          <line
            key={i}
            x1={inner.x}
            y1={inner.y}
            x2={outer.x}
            y2={outer.y}
            stroke="color-mix(in srgb, var(--line) 60%, transparent)"
            strokeWidth={1}
          />
        );
      })}
      <polygon
        points={dataPoints}
        fill="color-mix(in srgb, var(--gold) 28%, transparent)"
        stroke="var(--gold)"
        strokeWidth={2}
      />
      {attributes.map((attr, i) => {
        const p = polar(i, radius * 1.18);
        return (
          <text
            key={attr.id}
            x={p.x}
            y={p.y}
            textAnchor="middle"
            dominantBaseline="middle"
            className="attr-radar-label"
          >
            {attr.label}
          </text>
        );
      })}
    </svg>
  );
}