"use client";

import { motion } from "motion/react";
import { ChartFrame } from "@/components/charts/chart-frame";
import { circleLayout } from "@/lib/layout";

export type GraphNode = { id: string; label?: string; group?: number };
export type GraphEdge = { source: string; target: string };

type NetworkGraphProps = {
  nodes: GraphNode[];
  edges: GraphEdge[];
  width?: number;
  height?: number;
  className?: string;
};

/** NetworkGraph — deterministic circular layout; edges draw (pathLength), nodes pop in. */
export function NetworkGraph({ nodes, edges, width = 520, height = 460, className }: NetworkGraphProps) {
  const cx = width / 2;
  const cy = height / 2;
  const pos = circleLayout(nodes.length, cx, cy, Math.min(width, height) / 2 - 56);
  const posOf = new Map(nodes.map((n, i) => [n.id, pos[i]]));

  return (
    <ChartFrame width={width} height={height} label="Grafo de red" className={className}>
      {({ inView, reduce }) => (
        <>
          {edges.map((e, i) => {
            const a = posOf.get(e.source);
            const b = posOf.get(e.target);
            if (!a || !b) return null;
            return (
              <motion.line
                key={i}
                x1={a.x} y1={a.y} x2={b.x} y2={b.y}
                stroke="var(--ink-200)"
                strokeWidth={1.5}
                initial={reduce ? false : { pathLength: 0, opacity: 0 }}
                animate={inView ? { pathLength: 1, opacity: 1 } : { pathLength: 0, opacity: 0 }}
                transition={{ duration: 0.6, delay: 0.1 + i * 0.03, ease: [0.22, 1, 0.36, 1] }}
              />
            );
          })}
          {nodes.map((n, i) => {
            const p = pos[i];
            return (
              <motion.g
                key={n.id}
                initial={reduce ? false : { opacity: 0, scale: 0 }}
                animate={inView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0 }}
                transition={{ duration: 0.4, delay: 0.4 + i * 0.05, ease: [0.22, 1, 0.36, 1] }}
                style={{ transformOrigin: `${p.x}px ${p.y}px` }}
              >
                <circle cx={p.x} cy={p.y} r={13} fill="var(--accent-500)" stroke="var(--ink-900)" strokeWidth={1.5} />
                {n.label && (
                  <text x={p.x} y={p.y - 22} textAnchor="middle" fontSize={11} fontWeight={700} fill="var(--ink-700)">
                    {n.label}
                  </text>
                )}
              </motion.g>
            );
          })}
        </>
      )}
    </ChartFrame>
  );
}
