import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";

function seriesFrom(histogram, fallbackKey = "intensity") {
  if (Array.isArray(histogram)) return histogram;
  return histogram?.[fallbackKey] || histogram?.intensity || [];
}

function toChartData(original, processed) {
  const originalSeries = seriesFrom(original);
  const processedSeries = seriesFrom(processed);
  const r = processed?.r || [];
  const g = processed?.g || [];
  const b = processed?.b || [];
  return Array.from({ length: 256 }, (_, level) => ({
    level,
    original: originalSeries?.[level] ?? 0,
    processed: processedSeries?.[level] ?? 0,
    r: r[level] ?? 0,
    g: g[level] ?? 0,
    b: b[level] ?? 0
  }));
}

export default function HistogramPanel({ original, processed }) {
  const data = toChartData(original, processed);
  return (
    <section className="border-t border-zinc-800 bg-zinc-950 px-4 py-3">
      <div className="mb-3 flex items-center justify-between">
        <h2 className="text-sm font-semibold text-zinc-100">Histogram Analytics</h2>
        <div className="flex gap-3 text-xs text-zinc-400">
          <span className="text-cyan-300">Original</span>
          <span className="text-emerald-300">Active</span>
        </div>
      </div>
      <div className="h-40">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={data} margin={{ left: 0, right: 8, top: 8, bottom: 0 }}>
            <CartesianGrid stroke="#27272a" strokeDasharray="3 3" />
            <XAxis dataKey="level" stroke="#71717a" tick={{ fontSize: 10 }} interval={63} />
            <YAxis stroke="#71717a" tick={{ fontSize: 10 }} width={44} />
            <Tooltip contentStyle={{ background: "#18181b", border: "1px solid #3f3f46", color: "#f4f4f5" }} />
            <Area type="monotone" dataKey="original" stroke="#67e8f9" fill="#0891b2" fillOpacity={0.22} dot={false} />
            <Area type="monotone" dataKey="processed" stroke="#6ee7b7" fill="#059669" fillOpacity={0.24} dot={false} />
            <Area type="monotone" dataKey="r" stroke="#f87171" fill="#ef4444" fillOpacity={0.08} dot={false} />
            <Area type="monotone" dataKey="g" stroke="#4ade80" fill="#22c55e" fillOpacity={0.08} dot={false} />
            <Area type="monotone" dataKey="b" stroke="#60a5fa" fill="#3b82f6" fillOpacity={0.08} dot={false} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </section>
  );
}
