"use client";

import { motion } from "motion/react";
import { ChartFrame } from "@/components/charts/chart-frame";
import { sankeyLayout, type SankeyNodeIn, type SankeyLinkIn } from "@/lib/layout";
import { catColor } from "@/lib/chart-utils";

type SankeyProps = {
  columns: string[][];
  nodes: SankeyNodeIn[];
  links: SankeyLinkIn[];
  width?: number;
  height?: number;
  className?: string;
};

/** Sankey — flows whose width encodes value. Nodes fade in by column; links draw (pathLength) as strokes. */
export function Sankey({ columns, nodes, links, width = 720, height = 400, className }: SankeyProps) {
  const M = 12;
  const layout = sankeyLayout(columns, nodes, links, width - M * 2, height - M * 2);
  const lastCol = columns.length - 1;
  const colOf = new Map<string, number>();
  columns.forEach((col, ci) => col.forEach((id) => colOf.set(id, ci)));

  return (
    <ChartFrame width={width} height={height} label="Diagrama de Sankey" className={className}>
      {({ inView, reduce }) => (
        <g transform={`translate(${M},${M})`}>
          {layout.links.map((l, i) => (
            <motion.path
              key={i}
              d={l.path}
              fill="none"
              stroke={catColor(colOf.get(l.source) ?? 0)}
              strokeOpacity={0.4}
              strokeWidth={l.width}
              initial={reduce ? false : { pathLength: 0, opacity: 0 }}
              animate={inView ? { pathLength: 1, opacity: 1 } : { pathLength: 0, opacity: 0 }}
              transition={{ duration: 0.9, delay: 0.2 + (colOf.get(l.source) ?? 0) * 0.2, ease: [0.22, 1, 0.36, 1] }}
            />
          ))}
          {layout.nodes.map((n) => {
            const ci = colOf.get(n.id) ?? 0;
            const labelLeft = ci === lastCol;
            return (
              <motion.g
                key={n.id}
                initial={reduce ? false : { opacity: 0 }}
                animate={inView ? { opacity: 1 } : { opacity: 0 }}
                transition={{ duration: 0.4, delay: 0.1 + ci * 0.2 }}
              >
                <rect x={n.x} y={n.y} width={n.w} height={n.h} rx={2} fill={catColor(ci)} />
                <text
                  x={labelLeft ? n.x - 6 : n.x + n.w + 6}
                  y={n.y + n.h / 2}
                  textAnchor={labelLeft ? "end" : "start"}
                  dominantBaseline="middle"
                  fontSize={11}
                  fontWeight={700}
                  fill="var(--ink-700)"
                >
                  {n.label}
                </text>
              </motion.g>
            );
          })}
        </g>
      )}
    </ChartFrame>
  );
}
