"use client";

import { motion } from "motion/react";
import { ChartFrame } from "@/components/charts/chart-frame";
import { treeLayout, type TreeNode } from "@/lib/layout";

type OrgChartProps = {
  root: TreeNode;
  width?: number;
  height?: number;
  className?: string;
};

const BOX_W = 132;
const BOX_H = 46;

/** OrgChart — tidy top-down tree. Boxes reveal level by level; elbow connectors draw with pathLength. */
export function OrgChart({ root, width = 720, height = 380, className }: OrgChartProps) {
  const { nodes, edges } = treeLayout(root, width, height);
  const depthDelay = (d: number) => 0.1 + d * 0.25;

  return (
    <ChartFrame width={width} height={height} label="Organigrama" className={className}>
      {({ inView, reduce }) => (
        <>
          {edges.map((e, i) => {
            const midY = (e.from.y + BOX_H / 2 + (e.to.y - BOX_H / 2)) / 2;
            const d = `M${e.from.x},${e.from.y + BOX_H / 2} V${midY} H${e.to.x} V${e.to.y - BOX_H / 2}`;
            return (
              <motion.path
                key={i}
                d={d}
                fill="none"
                stroke="var(--ink-300)"
                strokeWidth={1.5}
                initial={reduce ? false : { pathLength: 0 }}
                animate={inView ? { pathLength: 1 } : { pathLength: 0 }}
                transition={{ duration: 0.4, delay: depthDelay(nodes.find((n) => n.x === e.to.x && n.y === e.to.y)?.depth ?? 0) - 0.1, ease: [0.22, 1, 0.36, 1] }}
              />
            );
          })}
          {nodes.map((n) => (
            <motion.g
              key={n.id}
              initial={reduce ? false : { opacity: 0, y: 10 }}
              animate={inView ? { opacity: 1, y: 0 } : { opacity: 0, y: 10 }}
              transition={{ duration: 0.4, delay: depthDelay(n.depth), ease: [0.22, 1, 0.36, 1] }}
            >
              <rect
                x={n.x - BOX_W / 2}
                y={n.y - BOX_H / 2}
                width={BOX_W}
                height={BOX_H}
                rx={6}
                fill="var(--paper)"
                stroke={n.depth === 0 ? "var(--accent-500)" : "var(--ink-200)"}
                strokeWidth={n.depth === 0 ? 2 : 1}
              />
              <text x={n.x} y={n.y} textAnchor="middle" dominantBaseline="middle" fontSize={12} fontWeight={700} fill="var(--ink-900)">
                {n.label}
              </text>
            </motion.g>
          ))}
        </>
      )}
    </ChartFrame>
  );
}
