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,
    red: r[level] ?? 0,
    green: g[level] ?? 0,
    blue: b[level] ?? 0
  }));
}

function HistogramTooltip({ active, payload, label }) {
  if (!active || !payload?.length) return null;
  const values = Object.fromEntries(payload.map((item) => [item.dataKey, item.value]));
  const rows = [
    ["Original", values.original, "text-cyan-300"],
    ["Active", values.processed, "text-emerald-300"],
    ["R", values.red, "text-red-300"],
    ["G", values.green, "text-green-300"],
    ["B", values.blue, "text-blue-300"]
  ];
  return (
    <div className="border border-zinc-700 bg-zinc-900 px-3 py-2 text-xs shadow-xl">
      <div className="mb-1 font-semibold text-zinc-100">Level {label}</div>
      <div className="space-y-1">
        {rows.map(([name, value, className]) => (
          <div key={name} className="flex min-w-32 justify-between gap-4">
            <span className={className}>{name}</span>
            <span className="tabular-nums text-zinc-100">{Number(value ?? 0).toFixed(8)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

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 content={<HistogramTooltip />} />
            <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="red" stroke="#f87171" fill="#ef4444" fillOpacity={0.08} dot={false} />
            <Area type="monotone" dataKey="green" stroke="#4ade80" fill="#22c55e" fillOpacity={0.08} dot={false} />
            <Area type="monotone" dataKey="blue" stroke="#60a5fa" fill="#3b82f6" fillOpacity={0.08} dot={false} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </section>
  );
}
