"use client";

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

export type PieSlice = { label: string; value: number };

type PieChartProps = {
  data: PieSlice[];
  /** 0 = pie, >0 = donut (fraction of radius). Default 0. */
  innerRatio?: number;
  size?: number;
  className?: string;
};

/**
 * PieChart — SVG sectors that sweep open one after another (angle 0 → target),
 * staggered around the circle. Set `innerRatio` > 0 for a donut.
 */
export function PieChart({ data, innerRatio = 0, size = 320, className }: PieChartProps) {
  const total = data.reduce((a, d) => a + d.value, 0) || 1;
  const cx = size / 2;
  const cy = size / 2;
  const rOuter = size / 2 - 6;
  const rInner = rOuter * innerRatio;

  const slices = data.map((d, i) => {
    const before = data.slice(0, i).reduce((a, x) => a + x.value, 0);
    const start = (before / total) * Math.PI * 2;
    const end = ((before + d.value) / total) * Math.PI * 2;
    return { ...d, start, end, color: catColor(i), pct: Math.round((d.value / total) * 100) };
  });

  return (
    <ChartFrame width={size} height={size} label="Gráfica circular" className={className} amount={0.4}>
      {({ inView, reduce }) => (
        <>
          {slices.map((s, i) => {
            const mid = (s.start + s.end) / 2;
            const lr = (rOuter + rInner) / 2 || rOuter * 0.62;
            const lx = cx + Math.cos(mid - Math.PI / 2) * lr;
            const ly = cy + Math.sin(mid - Math.PI / 2) * lr;
            return (
              <g key={s.label}>
                <motion.path
                  d={sectorPath(cx, cy, rOuter, rInner, s.start, s.end)}
                  fill={s.color}
                  stroke="var(--paper)"
                  strokeWidth={2}
                  initial={reduce ? false : { opacity: 0, scale: 0.6 }}
                  animate={inView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0.6 }}
                  transition={{ duration: 0.5, delay: 0.1 + i * 0.12, ease: [0.22, 1, 0.36, 1] }}
                  style={{ transformOrigin: `${cx}px ${cy}px` }}
                />
                {s.pct >= 8 && (
                  <motion.text
                    x={lx}
                    y={ly}
                    textAnchor="middle"
                    dominantBaseline="middle"
                    fontSize={13}
                    fontWeight={800}
                    fill="var(--ink-900)"
                    initial={{ opacity: 0 }}
                    animate={inView ? { opacity: 1 } : { opacity: 0 }}
                    transition={{ duration: 0.3, delay: 0.1 + i * 0.12 + 0.4 }}
                  >
                    {s.pct}%
                  </motion.text>
                )}
              </g>
            );
          })}
        </>
      )}
    </ChartFrame>
  );
}
