"use client";

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

interface Props {
  aiSourceAttributionComparison: AiSourceAttributionComparison | null | undefined;
}

const GAP_MAGNITUDE_CONFIG = {
  minimal: {
    label: "Minimal Gap",
    class: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",
  },
  moderate: {
    label: "Moderate Gap",
    class: "bg-amber-500/20 text-amber-400 border border-amber-500/30",
  },
  significant: {
    label: "Significant Gap",
    class: "bg-red-500/20 text-red-400 border border-red-500/30",
  },
} as const;

const DIRECTION_CONFIG = {
  predicted_overestimated: {
    label: "Over-predicted",
    deltaClass: "text-red-400",
    badgeClass: "bg-red-500/15 text-red-400 border border-red-500/20",
  },
  predicted_underestimated: {
    label: "Under-predicted",
    deltaClass: "text-emerald-400",
    badgeClass: "bg-emerald-500/15 text-emerald-400 border border-emerald-500/20",
  },
  aligned: {
    label: "Aligned",
    deltaClass: "text-slate-400",
    badgeClass: "bg-slate-500/15 text-slate-400 border border-slate-500/20",
  },
} as const;

const CONFIDENCE_CONFIG = {
  high: "bg-emerald-500/20 text-emerald-400",
  moderate: "bg-amber-500/20 text-amber-400",
  low: "bg-slate-500/20 text-slate-400",
} as const;

function formatValue(v: number | string): string {
  if (typeof v === "number") {
    return Number.isInteger(v) ? v.toLocaleString() : `${v.toFixed(1)}%`;
  }
  return v;
}

export function AiSourceAttributionComparisonSection({ aiSourceAttributionComparison }: Props) {
  if (!aiSourceAttributionComparison || !aiSourceAttributionComparison.hasFirstPartyData) return null;

  const { predictionVsActual, topInsights, overallGapMagnitude, overallGapNarrative, comparisonWindow } = aiSourceAttributionComparison;
  const magnitudeConfig = GAP_MAGNITUDE_CONFIG[overallGapMagnitude];

  return (
    <section id="audit-ai-attribution-comparison" className="space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-lg font-semibold text-slate-100">
            Public Signal Prediction vs First-Party Measurement
          </h2>
          <p className="text-sm text-slate-400 mt-1">
            {comparisonWindow.daysCovered}-day comparison window
          </p>
        </div>
        <span className={`text-xs font-semibold px-3 py-1.5 rounded-full ${magnitudeConfig.class}`}>
          {magnitudeConfig.label}
        </span>
      </div>

      {/* Gap narrative callout */}
      <div className="rounded-xl bg-slate-900/60 border border-white/10 p-5">
        <p className="text-sm text-slate-300 leading-relaxed">{overallGapNarrative}</p>
      </div>

      {/* Dimension grid */}
      {predictionVsActual.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">
            Dimension-by-Dimension Comparison
          </h3>
          <div className="grid gap-3 sm:grid-cols-2">
            {predictionVsActual.map((dim) => {
              const dir = DIRECTION_CONFIG[dim.deltaDirection];
              const conf = CONFIDENCE_CONFIG[dim.publicSignalPrediction.confidence];
              const deltaSign = dim.deltaPercent >= 0 ? "+" : "";
              return (
                <div
                  key={dim.dimension}
                  className="rounded-xl bg-slate-900/60 border border-white/10 p-4 space-y-3"
                >
                  <div className="flex items-start justify-between gap-2">
                    <span className="text-sm font-semibold text-slate-200">{dim.dimension}</span>
                    <span className={`shrink-0 text-xs font-medium px-2 py-0.5 rounded-full ${dir.badgeClass}`}>
                      {dir.label}
                    </span>
                  </div>

                  <div className="grid grid-cols-2 gap-2 text-xs">
                    <div className="space-y-0.5">
                      <div className="text-slate-500">Predicted</div>
                      <div className="font-semibold text-slate-300">{formatValue(dim.publicSignalPrediction.value)}</div>
                      <div className={`mt-1 px-1.5 py-0.5 rounded text-[10px] inline-block ${conf}`}>
                        {dim.publicSignalPrediction.confidence} confidence
                      </div>
                    </div>
                    <div className="space-y-0.5">
                      <div className="text-slate-500">Actual (first-party)</div>
                      <div className="font-semibold text-slate-300">{formatValue(dim.firstPartyActual.value)}</div>
                      <div className="text-slate-500 text-[10px] mt-1">
                        n={dim.firstPartyActual.sampleSize.toLocaleString()}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <span className={`text-sm font-bold ${dir.deltaClass}`}>
                      {deltaSign}{dim.deltaPercent.toFixed(1)}%
                    </span>
                    <span className="text-xs text-slate-500">delta</span>
                  </div>

                  <p className="text-xs text-slate-400 leading-relaxed">{dim.explanation}</p>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Top insights */}
      {topInsights.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">
            Key Insights
          </h3>
          <div className="rounded-xl bg-slate-900/60 border border-white/10 divide-y divide-white/5">
            {topInsights.map((insight, i) => (
              <div key={i} className="p-4 space-y-1.5">
                <p className="text-sm text-slate-200">{insight.insight}</p>
                <p className="text-xs text-slate-500">{insight.patentRelevance}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Why this matters */}
      <div className="rounded-xl bg-violet-500/10 border border-violet-500/20 p-4">
        <p className="text-xs font-semibold text-violet-400 mb-1 uppercase tracking-wider">Why this matters</p>
        <p className="text-sm text-slate-300 leading-relaxed">
          Public signal analysis can only estimate AI referral behavior from what is observable in search results. First-party Site Tag data measures what actually happens. The gap between prediction and measurement is where optimization opportunity lives.
        </p>
      </div>
    </section>
  );
}
