"use client";

import type { SeoSection } from "@/lib/audit/types";

interface Props {
  aiConversionAttribution: NonNullable<SeoSection["aiConversionAttribution"]>;
}

function engineLabel(raw: string): string {
  const map: Record<string, string> = {
    chatgpt: "ChatGPT", openai: "ChatGPT",
    perplexity: "Perplexity",
    claude: "Claude", anthropic: "Claude",
    gemini: "Gemini", bard: "Gemini",
    google_ai_overview: "Google AI Overview", google_ai: "Google AI Overview",
    copilot: "Copilot", bing: "Copilot",
    grok: "Grok", unknown: "Other",
  };
  return map[raw.toLowerCase()] ?? raw;
}

function urlPath(url: string): string {
  try {
    const p = new URL(url).pathname.replace(/\/$/, "") || "/";
    return p.length > 40 ? p.slice(0, 38) + "…" : p;
  } catch {
    return url.length > 40 ? url.slice(0, 38) + "…" : url;
  }
}

export function AIConversionGapChart({ aiConversionAttribution: ac }: Props) {
  const maxEngineCount = Math.max(...ac.topConvertingEngines.map((e) => e.count), 1);

  return (
    <div className="rounded-2xl bg-slate-900/60 border border-white/10 overflow-hidden">
      <div className="px-6 py-5 border-b border-white/10">
        <h3 className="text-sm font-semibold text-slate-100">AI Conversion Funnel</h3>
        <p className="text-xs text-slate-400 mt-0.5">AI referral volume, conversion rate, and top converting pages — last 30 days</p>
      </div>

      {/* Summary row */}
      <div className="grid grid-cols-3 divide-x divide-white/10 border-b border-white/10">
        <div className="px-5 py-4">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">AI referrals</p>
          <div className="text-3xl font-black tabular-nums text-white">{ac.totalAiReferrals30d.toLocaleString()}</div>
        </div>
        <div className="px-5 py-4">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">Conversions</p>
          <div className="text-3xl font-black tabular-nums text-emerald-400">{ac.totalAiConversions30d.toLocaleString()}</div>
        </div>
        <div className="px-5 py-4">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">Conversion rate</p>
          <div className="text-3xl font-black tabular-nums text-white">{ac.aiConversionRate.toFixed(1)}%</div>
        </div>
      </div>

      <div className="grid sm:grid-cols-2 divide-y sm:divide-y-0 sm:divide-x divide-white/10">
        {/* Engine breakdown */}
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">By engine</p>
          {ac.topConvertingEngines.length === 0 ? (
            <p className="text-xs text-slate-500">No engine data</p>
          ) : (
            <div className="space-y-3">
              {ac.topConvertingEngines.map((e) => {
                const pct = (e.count / maxEngineCount) * 100;
                return (
                  <div key={e.engine} className="flex items-center gap-2.5">
                    <span className="text-xs text-slate-300 w-24 shrink-0 truncate">{engineLabel(e.engine)}</span>
                    <div className="flex-1 bg-white/10 rounded-full h-1.5 overflow-hidden">
                      <div className="h-full rounded-full bg-indigo-400" style={{ width: `${pct.toFixed(1)}%` }} />
                    </div>
                    <span className="text-xs tabular-nums text-slate-400 w-8 text-right shrink-0">{e.count}</span>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Top converting pages */}
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">Top converting pages</p>
          {ac.topConvertingPages.length === 0 ? (
            <p className="text-xs text-slate-500">No conversions recorded yet</p>
          ) : (
            <table className="w-full text-xs">
              <thead>
                <tr className="text-slate-500">
                  <th className="text-left font-medium pb-2">Page</th>
                  <th className="text-right font-medium pb-2 pl-2">Visits</th>
                  <th className="text-right font-medium pb-2 pl-2">Conv.</th>
                </tr>
              </thead>
              <tbody>
                {ac.topConvertingPages.map((p, i) => (
                  <tr key={p.url} className={i < ac.topConvertingPages.length - 1 ? "border-b border-white/5" : ""}>
                    <td className="py-1.5 pr-2 font-mono text-[11px] text-slate-400" title={p.url}>{urlPath(p.url)}</td>
                    <td className="py-1.5 px-2 text-right tabular-nums text-slate-300">{p.aiVisits.toLocaleString()}</td>
                    <td className="py-1.5 pl-2 text-right tabular-nums text-emerald-400 font-semibold">{p.conversions}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}
