"use client";

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

type HeatmapProps = {
  rows: string[];
  cols: string[];
  /** values[row][col]. */
  values: number[][];
  width?: number;
  height?: number;
  className?: string;
};

const M = { top: 24, right: 12, bottom: 12, left: 88 };

/** Heatmap — cells fade in along a diagonal cascade; color from the sequential ramp. */
export function Heatmap({ rows, cols, values, width = 600, height, className }: HeatmapProps) {
  const all = values.flat();
  const min = Math.min(...all);
  const max = Math.max(...all);
  const norm = (v: number) => (max === min ? 0.5 : (v - min) / (max - min));
  const cellW = (width - M.left - M.right) / cols.length;
  const cellH = 38;
  const h = height ?? M.top + M.bottom + rows.length * cellH;

  return (
    <ChartFrame width={width} height={h} label="Mapa de calor" className={className}>
      {({ inView, reduce }) => (
        <>
          {cols.map((c, ci) => (
            <text key={c} x={M.left + cellW * (ci + 0.5)} y={M.top - 8} textAnchor="middle" fontSize={11} fill="var(--ink-500)">{c}</text>
          ))}
          {rows.map((r, ri) => (
            <g key={r}>
              <text x={M.left - 10} y={M.top + cellH * (ri + 0.5)} textAnchor="end" dominantBaseline="middle" fontSize={11} fill="var(--ink-600)">{r}</text>
              {cols.map((_, ci) => {
                const v = values[ri]?.[ci] ?? 0;
                const t = norm(v);
                return (
                  <motion.rect
                    key={ci}
                    x={M.left + cellW * ci + 1}
                    y={M.top + cellH * ri + 1}
                    width={cellW - 2}
                    height={cellH - 2}
                    rx={2}
                    fill={seqRamp(t)}
                    initial={reduce ? false : { opacity: 0 }}
                    animate={inView ? { opacity: 1 } : { opacity: 0 }}
                    transition={{ duration: 0.4, delay: 0.1 + (ri + ci) * 0.05, ease: [0.22, 1, 0.36, 1] }}
                  />
                );
              })}
            </g>
          ))}
        </>
      )}
    </ChartFrame>
  );
}
