"use client";

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

export type ScatterSeries = { label: string; data: Point[] };

type ScatterPlotProps = {
  series: ScatterSeries[];
  width?: number;
  height?: number;
  className?: string;
};

const M = { top: 16, right: 18, bottom: 34, left: 44 };

/** ScatterPlot — points scale + fade in, staggered, over drawn axes. */
export function ScatterPlot({ series, width = 560, height = 380, className }: ScatterPlotProps) {
  const all = series.flatMap((s) => s.data);
  const xs = all.map((p) => p.x);
  const ys = all.map((p) => p.y);
  const sx = linearScale([Math.min(...xs), Math.max(...xs)], [M.left, width - M.right]);
  const sy = linearScale([Math.min(0, ...ys), Math.max(...ys)], [height - M.bottom, M.top]);
  const yticks = niceTicks(Math.min(0, ...ys), Math.max(...ys), 4);

  return (
    <ChartFrame width={width} height={height} label="Diagrama de dispersión" className={className}>
      {({ inView, reduce }) => (
        <>
          {yticks.map((t) => (
            <g key={t}>
              <line x1={M.left} x2={width - M.right} y1={sy(t)} y2={sy(t)} stroke="var(--ink-100)" />
              <text x={M.left - 8} y={sy(t)} textAnchor="end" dominantBaseline="middle" fontSize={11} fill="var(--ink-400)">{t}</text>
            </g>
          ))}
          <line x1={M.left} x2={M.left} y1={M.top} y2={height - M.bottom} stroke="var(--ink-200)" />
          {series.map((s, si) =>
            s.data.map((p, i) => {
              const cx = sx(p.x);
              const cy = sy(p.y);
              return (
                <motion.circle
                  key={`${si}-${i}`}
                  cx={cx}
                  cy={cy}
                  r={5}
                  fill={catColor(si)}
                  fillOpacity={0.85}
                  initial={reduce ? false : { opacity: 0, scale: 0 }}
                  animate={inView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0 }}
                  transition={{ duration: 0.4, delay: 0.1 + (si * s.data.length + i) * 0.02, ease: [0.22, 1, 0.36, 1] }}
                  style={{ transformOrigin: `${cx}px ${cy}px` }}
                />
              );
            }),
          )}
        </>
      )}
    </ChartFrame>
  );
}
