"use client";

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

export type HistBin = { label: string; value: number };

type HistogramProps = {
  bins: HistBin[];
  width?: number;
  height?: number;
  className?: string;
};

const M = { top: 16, right: 18, bottom: 36, left: 44 };

/** Histogram — contiguous bars (no gap) growing scaleY from the baseline, staggered. */
export function Histogram({ bins, width = 600, height = 360, className }: HistogramProps) {
  const max = Math.max(...bins.map((b) => b.value), 1);
  const sy = linearScale([0, max], [height - M.bottom, M.top]);
  const baseY = height - M.bottom;
  const plotW = width - M.left - M.right;
  const bw = plotW / bins.length;
  const ticks = niceTicks(0, max, 4);

  return (
    <ChartFrame width={width} height={height} label="Histograma" className={className}>
      {({ inView, reduce }) => (
        <>
          {ticks.map((t) => (
            <g key={t}>
              <line x1={M.left} x2={width - M.right} y1={sy(t)} y2={sy(t)} stroke="var(--ink-100)" />
              <text x={M.left - 8} y={sy(t)} textAnchor="end" dominantBaseline="middle" fontSize={11} fill="var(--ink-400)">{t}</text>
            </g>
          ))}
          {bins.map((b, i) => {
            const x = M.left + i * bw;
            const y = sy(b.value);
            const h = baseY - y;
            return (
              <g key={b.label}>
                <motion.rect
                  x={x + 1}
                  y={y}
                  width={bw - 2}
                  height={h}
                  fill="var(--accent-400)"
                  stroke="var(--accent-500)"
                  strokeWidth={1}
                  initial={reduce ? false : { scaleY: 0 }}
                  animate={inView ? { scaleY: 1 } : { scaleY: 0 }}
                  transition={{ duration: 0.7, delay: 0.1 + i * 0.06, ease: [0.77, 0, 0.175, 1] }}
                  style={{ transformOrigin: `${x + bw / 2}px ${baseY}px` }}
                />
                <text x={x + bw / 2} y={baseY + 16} textAnchor="middle" fontSize={10} fill="var(--ink-500)">{b.label}</text>
              </g>
            );
          })}
        </>
      )}
    </ChartFrame>
  );
}
