"use client";

import { motion } from "motion/react";
import { ChartFrame } from "./chart-frame";
import { polygonPath, catColor, type Point } from "@/lib/chart-utils";

export type RadarSeries = { label: string; values: number[] };

type RadarChartProps = {
  axes: string[];
  series: RadarSeries[];
  max?: number;
  size?: number;
  className?: string;
};

/** RadarChart — grid rings + spokes draw, then each series polygon draws (pathLength) and fills. Multi-series via --cat-*. */
export function RadarChart({ axes, series, max, size = 380, className }: RadarChartProps) {
  const cx = size / 2;
  const cy = size / 2;
  const r = size / 2 - 44;
  const n = axes.length;
  const maxVal = max ?? Math.max(...series.flatMap((s) => s.values), 1);
  const angleAt = (i: number) => (i / n) * Math.PI * 2 - Math.PI / 2;
  const pointAt = (i: number, value: number): Point => {
    const rr = (value / maxVal) * r;
    return { x: cx + Math.cos(angleAt(i)) * rr, y: cy + Math.sin(angleAt(i)) * rr };
  };
  const rings = [0.25, 0.5, 0.75, 1];

  return (
    <ChartFrame width={size} height={size} label="Gráfica radar" className={className}>
      {({ inView, reduce }) => (
        <>
          {rings.map((f, ri) => (
            <polygon
              key={ri}
              points={axes.map((_, i) => {
                const p = pointAt(i, maxVal * f);
                return `${p.x},${p.y}`;
              }).join(" ")}
              fill="none"
              stroke="var(--ink-100)"
              strokeWidth={1}
            />
          ))}
          {axes.map((ax, i) => {
            const outer = pointAt(i, maxVal);
            const lp = pointAt(i, maxVal * 1.16);
            return (
              <g key={ax}>
                <line x1={cx} y1={cy} x2={outer.x} y2={outer.y} stroke="var(--ink-200)" strokeWidth={1} />
                <text x={lp.x} y={lp.y} textAnchor="middle" dominantBaseline="middle" fontSize={11} fill="var(--ink-600)">{ax}</text>
              </g>
            );
          })}
          {series.map((s, si) => {
            const pts = s.values.map((v, i) => pointAt(i, v));
            const color = catColor(si);
            return (
              <g key={s.label}>
                <motion.path
                  d={polygonPath(pts)}
                  fill={color}
                  fillOpacity={0.12}
                  stroke={color}
                  strokeWidth={2.5}
                  strokeLinejoin="round"
                  initial={reduce ? false : { pathLength: 0, opacity: 0 }}
                  animate={inView ? { pathLength: 1, opacity: 1 } : { pathLength: 0, opacity: 0 }}
                  transition={{ duration: 1, delay: 0.2 + si * 0.25, ease: [0.22, 1, 0.36, 1] }}
                />
                {pts.map((p, i) => (
                  <motion.circle
                    key={i} cx={p.x} cy={p.y} r={3.5} fill={color}
                    initial={{ opacity: 0, scale: 0 }}
                    animate={inView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0 }}
                    transition={{ duration: 0.3, delay: 0.2 + si * 0.25 + 0.9 + i * 0.04 }}
                    style={{ transformOrigin: `${p.x}px ${p.y}px` }}
                  />
                ))}
              </g>
            );
          })}
        </>
      )}
    </ChartFrame>
  );
}
