"use client";

import { useEffect, useState } from "react";
import { BarChart3 } from "lucide-react";

interface Benchmark { metric: string; value: number; sampleSize: number }

interface Props { industry: string; brandMetrics?: { ctr?: number; avgPosition?: number; conversionRate?: number } }

const LABELS: Record<string, string> = { avg_ctr: "CTR", avg_position: "Avg Position", monthly_conversions_per_brand: "Monthly Conversions" };
const FORMAT: Record<string, (v: number) => string> = { avg_ctr: (v) => `${v.toFixed(1)}%`, avg_position: (v) => v.toFixed(1), monthly_conversions_per_brand: (v) => v.toFixed(0) };

export default function BenchmarksPanel({ industry, brandMetrics }: Props) {
  const [benchmarks, setBenchmarks] = useState<Benchmark[]>([]);

  useEffect(() => {
    fetch(`/api/industry-intel/benchmarks?industry=${encodeURIComponent(industry)}`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setBenchmarks(d?.benchmarks ?? []))
      .catch(() => {});
  }, [industry]);

  if (benchmarks.length === 0) return null;

  const brandMap: Record<string, number | undefined> = { avg_ctr: brandMetrics?.ctr, avg_position: brandMetrics?.avgPosition, monthly_conversions_per_brand: brandMetrics?.conversionRate };
  const sample = benchmarks[0]?.sampleSize ?? 0;

  return (
    <div>
      <div className="flex items-center gap-2 mb-3"><BarChart3 className="w-4 h-4 text-brand-600" /><h2 className="text-xs font-bold uppercase tracking-widest text-slate-400">Industry Benchmarks</h2></div>
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="divide-y divide-slate-100">
          {benchmarks.map((b) => {
            const label = LABELS[b.metric] || b.metric;
            const fmt = FORMAT[b.metric] || ((v: number) => v.toFixed(1));
            const brandVal = brandMap[b.metric];
            const better = b.metric === "avg_position" ? (brandVal != null && brandVal < b.value) : (brandVal != null && brandVal > b.value);
            return (
              <div key={b.metric} className="px-5 py-3 flex items-center gap-4">
                <span className="text-xs font-semibold text-slate-700 w-32">{label}</span>
                {brandVal != null && (
                  <div className="flex items-center gap-2">
                    <span className={`text-sm font-bold tabular-nums ${better ? "text-green-600" : "text-red-500"}`}>You: {fmt(brandVal)}</span>
                    <span className="text-slate-300">|</span>
                  </div>
                )}
                <span className="text-sm text-slate-600 tabular-nums">Industry: {fmt(b.value)}</span>
                <div className="flex-1 h-2 bg-slate-100 rounded-full overflow-hidden">
                  {brandVal != null && (
                    <div className={`h-full rounded-full ${better ? "bg-green-500" : "bg-red-400"}`} style={{ width: `${Math.min(100, b.metric === "avg_position" ? (b.value / Math.max(brandVal, 1)) * 50 : (brandVal / Math.max(b.value, 1)) * 50)}%` }} />
                  )}
                </div>
              </div>
            );
          })}
        </div>
        <div className="px-5 py-2 bg-slate-50 border-t border-slate-100">
          <p className="text-[10px] text-slate-400">Based on {sample} brands in {industry}</p>
        </div>
      </div>
    </div>
  );
}
