"use client";

// Tier definitions match the canonical 5-bucket toxicity ladder in
// src/lib/services/backlink-toxicity.ts. Each `keys` array lists every
// label variant we accept so the chart works for current-format
// rows ("Healthy", "Low Risk"...) AND legacy AI-scored rows
// ("excellent", "good"...) without re-tagging the database.
const TIERS = [
  { keys: ["Healthy", "excellent", "good"],      label: "Healthy",       color: "bg-green-500" },
  { keys: ["Low Risk", "neutral"],                label: "Low Risk",      color: "bg-teal-500" },
  { keys: ["Moderate Risk"],                      label: "Moderate Risk", color: "bg-amber-400" },
  { keys: ["High Risk", "poor"],                  label: "High Risk",     color: "bg-orange-500" },
  { keys: ["Toxic", "toxic"],                     label: "Toxic",         color: "bg-red-500" },
];

export default function QualityChart({ distribution }: { distribution: Record<string, number> }) {
  // Sum each tier across all accepted label variants
  const counts = TIERS.map((t) => ({
    ...t,
    count: t.keys.reduce((sum, k) => sum + (distribution[k] ?? 0), 0),
  }));
  const max = Math.max(1, ...counts.map((c) => c.count));
  const total = counts.reduce((s, c) => s + c.count, 0);

  return (
    <div className="bg-white rounded-xl border border-slate-200 p-5">
      <h3 className="text-sm font-bold text-slate-800 mb-4">Quality Distribution</h3>
      <div className="space-y-2.5">
        {counts.map((t) => (
          <div key={t.label} className="flex items-center gap-3">
            <span className="text-xs text-slate-600 w-24 shrink-0">{t.label}</span>
            <div className="flex-1 h-5 bg-slate-100 rounded-full overflow-hidden">
              <div className={`h-full ${t.color} rounded-full transition-all`} style={{ width: `${(t.count / max) * 100}%` }} />
            </div>
            <span className="text-xs font-bold text-slate-700 w-10 text-right tabular-nums">{t.count}</span>
          </div>
        ))}
      </div>
      {total === 0 && (
        <p className="text-[10px] text-slate-400 mt-3 italic">
          No quality data yet — backlinks need a toxicity score from the next sync.
        </p>
      )}
    </div>
  );
}
