"use client";

import React from "react";

// Fixed categorical order from the validated reference palette (dataviz skill,
// references/palette.md) — never cycled or reassigned per-render, so the same category
// always gets the same color across a session.
export const CATEGORICAL_COLORS = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#4a3aa7", "#e34948"];

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

// A simple, dependency-free horizontal bar list: thin rounded track, filled bar, direct value
// label. Suited to comparing a handful of categories' magnitude (the job most reports need) —
// per the dataviz skill's form heuristic, magnitude-by-category is exactly a bar chart's job.
export function HorizontalBarChart({
  data, valueFormatter, labelWidthClass = "w-28",
}: {
  data: BarDatum[];
  valueFormatter?: (v: number) => string;
  labelWidthClass?: string;
}) {
  const max = Math.max(1, ...data.map(d => Math.abs(d.value)));
  const fmt = valueFormatter || ((v: number) => String(v));
  return (
    <div className="space-y-2.5">
      {data.map((d, i) => (
        <div key={d.label} className="flex items-center gap-3">
          <div className={labelWidthClass + " text-xs text-gray-600 truncate shrink-0"} title={d.label}>{d.label}</div>
          <div className="flex-1 h-3 rounded-full bg-gray-100 overflow-hidden">
            <div
              className="h-full rounded-full transition-all"
              style={{ width: `${Math.max(d.value > 0 ? 2 : 0, (Math.abs(d.value) / max) * 100)}%`, backgroundColor: CATEGORICAL_COLORS[i % CATEGORICAL_COLORS.length] }}
            />
          </div>
          <div className="w-24 text-xs text-gray-700 text-right shrink-0 tabular-nums">{fmt(d.value)}</div>
        </div>
      ))}
      {data.length === 0 && <div className="text-xs text-gray-400">No data to chart.</div>}
    </div>
  );
}
