"use client";

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

interface Props {
  aiSnippetEligibility: AiSnippetEligibility | null | undefined;
}

const STATUS_CONFIG = {
  eligible: { icon: "✓", class: "text-emerald-400 bg-emerald-500/15", label: "Eligible" },
  partial: { icon: "◑", class: "text-amber-400 bg-amber-500/15", label: "Partial" },
  not_eligible: { icon: "✗", class: "text-red-400 bg-red-500/15", label: "Not eligible" },
} as const;

const TRAFFIC_CONFIG = {
  high: { label: "High", class: "text-emerald-400" },
  moderate: { label: "Moderate", class: "text-amber-400" },
  low: { label: "Low", class: "text-slate-400" },
} as const;

const DIFFICULTY_CONFIG = {
  easy: { label: "Easy", class: "bg-emerald-500/15 text-emerald-400" },
  moderate: { label: "Moderate", class: "bg-amber-500/15 text-amber-400" },
  hard: { label: "Hard", class: "bg-red-500/15 text-red-400" },
} as const;

function urlPath(q: string): string {
  return q.length > 50 ? q.slice(0, 49) + "…" : q;
}

export function AiSnippetEligibilitySection({ aiSnippetEligibility }: Props) {
  if (!aiSnippetEligibility) return null;

  const { perQuery, topOpportunities, aggregateStats } = aiSnippetEligibility;

  return (
    <section id="audit-snippet-eligibility" className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-lg font-semibold text-slate-100">AI Snippet Eligibility Analysis</h2>
        <p className="text-sm text-slate-400 mt-1">
          SERP feature presence and capture opportunities across {aggregateStats.totalQueriesAnalyzed} tracked queries
        </p>
      </div>

      {/* Aggregate stats strip */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: "Queries Analyzed", value: aggregateStats.totalQueriesAnalyzed },
          { label: "With Eligible Features", value: aggregateStats.queriesWithEligibleFeatures },
          { label: "Features Present", value: aggregateStats.totalFeaturesPresent },
          { label: "Eligibility Rate", value: `${aggregateStats.eligibilityRatePercent}%` },
        ].map((stat, i) => (
          <div key={i} className="rounded-xl bg-slate-900/60 border border-white/10 p-4 text-center">
            <div className="text-xl font-bold text-slate-100">{stat.value}</div>
            <div className="text-xs text-slate-400 mt-1">{stat.label}</div>
          </div>
        ))}
      </div>

      {/* Per-Query Snippet Matrix */}
      {perQuery.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">
            Per-Query Snippet Matrix
          </h3>
          <div className="space-y-2">
            {perQuery.map((q, qi) => (
              <div key={qi} className="rounded-xl bg-slate-900/60 border border-white/10 overflow-hidden">
                <div className="px-4 py-3 border-b border-white/5 flex items-center justify-between gap-3">
                  <div className="flex items-center gap-2 min-w-0">
                    <span className="text-sm font-semibold text-slate-200 truncate">{urlPath(q.query)}</span>
                    {q.brandRanking != null && (
                      <span className="shrink-0 text-xs text-slate-500">rank #{q.brandRanking}</span>
                    )}
                  </div>
                  <span className="shrink-0 text-xs text-slate-500">
                    {q.serpFeaturesPresent.length} feature{q.serpFeaturesPresent.length !== 1 ? "s" : ""}
                  </span>
                </div>
                <div className="p-3 flex flex-wrap gap-2">
                  {q.perFeatureEligibility.map((f, fi) => {
                    const cfg = STATUS_CONFIG[f.eligibilityStatus];
                    return (
                      <div
                        key={fi}
                        className={`flex items-center gap-1.5 text-xs font-medium px-2.5 py-1.5 rounded-lg ${cfg.class}`}
                        title={f.missingFactors.join(" | ")}
                      >
                        <span className="text-xs">{cfg.icon}</span>
                        {f.feature}
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Top Opportunities */}
      {topOpportunities.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">
            Top Capture Opportunities
          </h3>
          <div className="space-y-3">
            {topOpportunities.map((opp, i) => {
              // Find the matching eligibility entry to get difficulty/traffic
              const matchedQuery = perQuery.find((q) => q.query === opp.query);
              const matchedFeature = matchedQuery?.perFeatureEligibility.find(
                (f) => f.feature === opp.feature
              );
              const diff = matchedFeature ? DIFFICULTY_CONFIG[matchedFeature.implementationDifficulty] : DIFFICULTY_CONFIG.moderate;
              const traffic = matchedFeature ? TRAFFIC_CONFIG[matchedFeature.estimatedTraffic] : TRAFFIC_CONFIG.moderate;
              return (
                <div key={i} className="rounded-xl bg-slate-900/60 border border-white/10 p-4 space-y-2">
                  <div className="flex items-start justify-between gap-3 flex-wrap">
                    <div>
                      <div className="text-xs text-slate-500 mb-1">"{opp.query}"</div>
                      <div className="text-sm font-semibold text-slate-200">{opp.feature}</div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={`text-xs font-semibold px-2 py-0.5 rounded ${diff.class}`}>{diff.label}</span>
                      <span className={`text-xs font-semibold ${traffic.class}`}>{traffic.label} traffic</span>
                    </div>
                  </div>
                  <p className="text-xs text-slate-400 leading-relaxed">{opp.rationale}</p>
                  <div className="rounded-lg bg-slate-800/60 px-3 py-2">
                    <span className="text-xs font-semibold text-slate-400">Quickest path: </span>
                    <span className="text-xs text-slate-300">{opp.quickestPath}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </section>
  );
}
