"use client";

import type { PredictiveConversionScoring, ScoreBand } from "@/lib/audit/types";

interface Props {
  predictiveConversionScoring: PredictiveConversionScoring | null | undefined;
}

function urlPath(url: string): string {
  let path = url;
  try { path = new URL(url).pathname || "/"; } catch { /* keep original */ }
  return path.length > 50 ? path.slice(0, 49) + "…" : path;
}

const BAND_CONFIG: Record<ScoreBand, { label: string; color: string; bg: string; bar: string }> = {
  very_high: { label: "Very High",  color: "text-violet-700", bg: "bg-violet-50 border-violet-200",  bar: "bg-violet-500" },
  high:      { label: "High",       color: "text-emerald-700", bg: "bg-emerald-50 border-emerald-200", bar: "bg-emerald-500" },
  moderate:  { label: "Moderate",   color: "text-amber-700",   bg: "bg-amber-50 border-amber-200",    bar: "bg-amber-400" },
  low:       { label: "Low",        color: "text-slate-600",   bg: "bg-slate-50 border-slate-200",    bar: "bg-slate-300" },
  very_low:  { label: "Very Low",   color: "text-slate-400",   bg: "bg-slate-50 border-slate-100",    bar: "bg-slate-200" },
};

const BAND_ORDER: ScoreBand[] = ["very_high", "high", "moderate", "low", "very_low"];

function ScorePill({ score }: { score: number }) {
  const band = score >= 81 ? "very_high" : score >= 61 ? "high" : score >= 41 ? "moderate" : score >= 21 ? "low" : "very_low";
  const cfg = BAND_CONFIG[band];
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold border ${cfg.bg} ${cfg.color}`}>
      {score}/100
    </span>
  );
}

export function PredictiveConversionScoringSection({ predictiveConversionScoring: pcs }: Props) {
  if (!pcs) return null;

  const totalSessions = pcs.totalScoredSessions;
  const highIntentCount = pcs.scoreDistribution.high + pcs.scoreDistribution.very_high;

  return (
    <section id="audit-predictive-conversion-scoring" className="scroll-mt-20">
      <div className="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
        {/* Header */}
        <div className="px-6 py-5 border-b border-slate-100">
          <div className="flex items-start justify-between gap-4">
            <div>
              <h2 className="text-lg font-semibold text-slate-900">Predictive Conversion Scoring</h2>
              <p className="mt-0.5 text-sm text-slate-500">
                Real-time behavioral intent scoring for active sessions — last {pcs.windowDays} days
              </p>
            </div>
            <div className="shrink-0 text-right">
              <p className="text-2xl font-bold text-slate-900">{pcs.avgScore}<span className="text-sm font-normal text-slate-400">/100</span></p>
              <p className="text-xs text-slate-400 mt-0.5">avg score</p>
            </div>
          </div>
        </div>

        <div className="p-6 space-y-8">
          {/* Metrics strip */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {[
              { label: "Sessions Scored", value: totalSessions.toLocaleString() },
              { label: "High-Intent Sessions", value: highIntentCount.toLocaleString(), sub: totalSessions > 0 ? `${Math.round((highIntentCount / totalSessions) * 100)}% of total` : undefined },
              { label: "Active (Last 30 min)", value: pcs.liveSessionsSnapshot.activeLast30Min.toLocaleString() },
              { label: "Live High-Intent", value: pcs.liveSessionsSnapshot.highIntentCount.toLocaleString(), sub: `avg ${pcs.liveSessionsSnapshot.avgScoreActive}/100` },
            ].map(({ label, value, sub }) => (
              <div key={label} className="rounded-lg border border-slate-100 bg-slate-50 px-4 py-3 text-center">
                <p className="text-xl font-bold text-slate-900">{value}</p>
                <p className="text-xs text-slate-500 mt-0.5">{label}</p>
                {sub && <p className="text-[10px] text-slate-400 mt-0.5">{sub}</p>}
              </div>
            ))}
          </div>

          {/* Score distribution */}
          <div>
            <h3 className="text-sm font-semibold text-slate-700 mb-3">Score Distribution</h3>
            <div className="space-y-2">
              {BAND_ORDER.map((band) => {
                const cfg = BAND_CONFIG[band];
                const count = pcs.scoreDistribution[band] ?? 0;
                const pct = totalSessions > 0 ? Math.round((count / totalSessions) * 100) : 0;
                const convRate = pcs.conversionRateByBand[band];
                return (
                  <div key={band} className="flex items-center gap-3">
                    <span className={`w-20 shrink-0 text-xs font-medium ${cfg.color}`}>{cfg.label}</span>
                    <div className="flex-1 h-2 bg-slate-100 rounded-full overflow-hidden">
                      <div className={`h-full rounded-full ${cfg.bar} transition-all`} style={{ width: `${pct}%` }} />
                    </div>
                    <span className="w-16 shrink-0 text-right text-xs text-slate-600">{count.toLocaleString()} <span className="text-slate-400">({pct}%)</span></span>
                    {convRate != null && (
                      <span className="w-20 shrink-0 text-right text-xs text-slate-500">{convRate}% conv.</span>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Score by channel */}
          {pcs.scoreByChannel.length > 0 && (
            <div>
              <h3 className="text-sm font-semibold text-slate-700 mb-3">Intent Score by Channel</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-slate-100">
                      <th className="text-left text-xs font-semibold text-slate-400 pb-2">Channel</th>
                      <th className="text-right text-xs font-semibold text-slate-400 pb-2">Avg Score</th>
                      <th className="text-right text-xs font-semibold text-slate-400 pb-2">Sessions</th>
                      <th className="text-right text-xs font-semibold text-slate-400 pb-2">Top Band</th>
                    </tr>
                  </thead>
                  <tbody>
                    {pcs.scoreByChannel.map((ch) => (
                      <tr key={ch.channelName} className="border-b border-slate-50 last:border-0">
                        <td className="py-2 text-slate-700 font-medium">{ch.channelName}</td>
                        <td className="py-2 text-right"><ScorePill score={ch.avgScore} /></td>
                        <td className="py-2 text-right text-slate-500">{ch.sessionCount.toLocaleString()}</td>
                        <td className="py-2 text-right">
                          <span className={`text-xs font-medium ${BAND_CONFIG[ch.topBand].color}`}>
                            {BAND_CONFIG[ch.topBand].label}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Score by AI engine */}
          {pcs.scoreByAiEngine.length > 0 && (
            <div>
              <h3 className="text-sm font-semibold text-slate-700 mb-3">Intent Score by AI Engine</h3>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                {pcs.scoreByAiEngine.map((engine) => (
                  <div key={engine.engineName} className="rounded-lg border border-indigo-100 bg-indigo-50 px-4 py-3">
                    <p className="text-sm font-semibold text-slate-800">{engine.engineName}</p>
                    <p className="text-xl font-bold text-indigo-600 mt-1">{engine.avgScore}<span className="text-xs font-normal text-slate-400">/100</span></p>
                    <p className="text-xs text-slate-500 mt-1">{engine.sessionCount.toLocaleString()} sessions</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Top scoring pages */}
          {pcs.topScoringPages.length > 0 && (
            <div>
              <h3 className="text-sm font-semibold text-slate-700 mb-3">Top Intent-Boosting Pages</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-slate-100">
                      <th className="text-left text-xs font-semibold text-slate-400 pb-2">Page</th>
                      <th className="text-right text-xs font-semibold text-slate-400 pb-2">Avg Score Boost</th>
                      <th className="text-right text-xs font-semibold text-slate-400 pb-2">High-Intent Visits</th>
                    </tr>
                  </thead>
                  <tbody>
                    {pcs.topScoringPages.map((page) => (
                      <tr key={page.pageUrl} className="border-b border-slate-50 last:border-0">
                        <td className="py-2 font-mono text-xs text-slate-600">{urlPath(page.pageUrl)}</td>
                        <td className="py-2 text-right text-emerald-600 font-semibold text-sm">+{page.avgScoreBoost} pts</td>
                        <td className="py-2 text-right text-slate-500">{page.visitCount.toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Insights */}
          {pcs.insights.length > 0 && (
            <div>
              <h3 className="text-sm font-semibold text-slate-700 mb-3">Scoring Insights</h3>
              <div className="space-y-3">
                {pcs.insights.map((ins, i) => (
                  <div key={i} className="rounded-lg border border-slate-100 bg-slate-50 p-4">
                    <p className="text-sm text-slate-700 leading-relaxed">{ins.insight}</p>
                    <p className="text-xs text-slate-400 mt-1.5">{ins.supportingMetric}</p>
                    <p className="text-xs text-indigo-600 mt-1 font-medium">{ins.businessImplication}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Patent relevance */}
          <p className="text-xs text-slate-400 italic">{pcs.patentRelevance}</p>
        </div>
      </div>
    </section>
  );
}
