"use client";

import { motion } from "motion/react";
import { ChartFrame } from "./chart-frame";
import { treemapLayout, type TreemapItemIn } from "@/lib/layout";
import { seqRamp } from "@/lib/chart-utils";

type TreemapProps = {
  data: TreemapItemIn[];
  width?: number;
  height?: number;
  className?: string;
};

/** Treemap — rects (deterministic binary split) scale in from their own center, staggered by area. */
export function Treemap({ data, width = 640, height = 380, className }: TreemapProps) {
  const rects = treemapLayout(data, width, height);
  const max = Math.max(...data.map((d) => d.value), 1);

  return (
    <ChartFrame width={width} height={height} label="Treemap" className={className}>
      {({ inView, reduce }) => (
        <>
          {rects.map((r, i) => {
            const cx = r.x + r.w / 2;
            const cy = r.y + r.h / 2;
            const t = r.value / max;
            return (
              <g key={r.id}>
                <motion.rect
                  x={r.x + 1.5}
                  y={r.y + 1.5}
                  width={Math.max(r.w - 3, 0)}
                  height={Math.max(r.h - 3, 0)}
                  rx={4}
                  fill={seqRamp(0.25 + t * 0.6)}
                  initial={reduce ? false : { opacity: 0, scale: 0.7 }}
                  animate={inView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0.7 }}
                  transition={{ duration: 0.5, delay: 0.1 + i * 0.06, ease: [0.22, 1, 0.36, 1] }}
                  style={{ transformOrigin: `${cx}px ${cy}px` }}
                />
                {r.w > 70 && r.h > 34 && (
                  <motion.text
                    x={r.x + 12}
                    y={r.y + 24}
                    fontSize={13}
                    fontWeight={800}
                    fill={t > 0.6 ? "var(--ink-900)" : "var(--ink-800)"}
                    initial={{ opacity: 0 }}
                    animate={inView ? { opacity: 1 } : { opacity: 0 }}
                    transition={{ duration: 0.3, delay: 0.1 + i * 0.06 + 0.35 }}
                  >
                    {r.label ?? r.id}
                  </motion.text>
                )}
              </g>
            );
          })}
        </>
      )}
    </ChartFrame>
  );
}
