"use client";

import type { VoiceSearchEligibility } from "@/lib/voice-search-eligibility/types";

interface Props {
  voiceSearchEligibility: VoiceSearchEligibility | null | undefined;
}

const RELEVANCE_CONFIG = {
  high: { label: "High Industry Relevance", class: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30" },
  medium: { label: "Medium Industry Relevance", class: "bg-amber-500/20 text-amber-400 border border-amber-500/30" },
  low: { label: "Low Industry Relevance", class: "bg-slate-500/20 text-slate-400 border border-slate-500/30" },
} 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;

const IMPACT_CONFIG = {
  high: { label: "High impact", class: "text-emerald-400" },
  medium: { label: "Medium impact", class: "text-amber-400" },
  low: { label: "Low impact", class: "text-slate-400" },
} as const;

const EFFORT_CONFIG = {
  hour: { label: "1 hour", class: "text-slate-400" },
  day: { label: "1 day", class: "text-slate-400" },
  week: { label: "1 week", class: "text-slate-400" },
} as const;

const DIM_CONFIG = {
  "speakable-schema": { label: "Speakable Schema", icon: "📄", color: "from-violet-500/20 to-violet-500/5 border-violet-500/20" },
  "conversational-query": { label: "Conversational Query", icon: "💬", color: "from-blue-500/20 to-blue-500/5 border-blue-500/20" },
  "faq-readability": { label: "FAQ Readability", icon: "❓", color: "from-amber-500/20 to-amber-500/5 border-amber-500/20" },
  "local-pack-signals": { label: "Local Pack Signals", icon: "📍", color: "from-emerald-500/20 to-emerald-500/5 border-emerald-500/20" },
} as const;

const SUB_SCORE_KEYS = [
  { key: "speakableSchema" as const, dim: "speakable-schema" as const },
  { key: "conversationalQuery" as const, dim: "conversational-query" as const },
  { key: "faqReadability" as const, dim: "faq-readability" as const },
  { key: "localPackSignals" as const, dim: "local-pack-signals" as const },
];

function scoreColor(score: number): string {
  if (score >= 70) return "text-emerald-400";
  if (score >= 45) return "text-amber-400";
  return "text-red-400";
}

function ScoreGauge({ score }: { score: number }) {
  const pct = Math.min(100, Math.max(0, score));
  const color = score >= 70 ? "bg-emerald-500" : score >= 45 ? "bg-amber-500" : "bg-red-500";
  return (
    <div className="flex items-center gap-3">
      <div className="flex-1 h-2 bg-slate-700/60 rounded-full overflow-hidden">
        <div className={`h-full rounded-full ${color}`} style={{ width: `${pct}%` }} />
      </div>
      <span className={`text-sm font-bold w-12 text-right ${scoreColor(score)}`}>{score}/100</span>
    </div>
  );
}

function SubScoreCard({ dimKey, score }: { dimKey: keyof typeof DIM_CONFIG; score: number }) {
  const { label, icon, color } = DIM_CONFIG[dimKey];
  return (
    <div className={`rounded-xl bg-gradient-to-br ${color} border p-4 space-y-3`}>
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="text-base">{icon}</span>
          <span className="text-sm font-semibold text-slate-200">{label}</span>
        </div>
        <span className={`text-sm font-bold ${scoreColor(score)}`}>{score}/100</span>
      </div>
      <ScoreGauge score={score} />
    </div>
  );
}

export function VoiceSearchEligibilitySection({ voiceSearchEligibility }: Props) {
  if (!voiceSearchEligibility?.hasData) return null;

  const { compositeScore, industryRelevance, subScores, topGaps, recommendations, patentRelevance } = voiceSearchEligibility;
  const relevanceConfig = RELEVANCE_CONFIG[industryRelevance];

  return (
    <section id="audit-voice-search-eligibility" 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">Voice Search Eligibility</h2>
          <p className="text-sm text-slate-400 mt-1">
            Structural content signals that determine eligibility for AI voice assistant responses
          </p>
        </div>
        <span className={`shrink-0 text-xs font-semibold px-3 py-1.5 rounded-full ${relevanceConfig.class}`}>
          {relevanceConfig.label}
        </span>
      </div>

      {/* Composite score */}
      <div className="rounded-xl bg-slate-900/60 border border-white/10 p-5">
        <div className="flex items-center justify-between mb-3">
          <span className="text-sm font-semibold text-slate-200">Composite Voice Search Score</span>
          <span className={`text-2xl font-bold ${scoreColor(compositeScore)}`}>{compositeScore}/100</span>
        </div>
        <ScoreGauge score={compositeScore} />
      </div>

      {/* Sub-score grid */}
      <div className="grid gap-4 sm:grid-cols-2">
        {SUB_SCORE_KEYS.map(({ key, dim }) => (
          <SubScoreCard key={dim} dimKey={dim} score={subScores[key]} />
        ))}
      </div>

      {/* Top gaps */}
      {topGaps.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Top Gaps by Score Lift</h3>
          <div className="space-y-2">
            {topGaps.map((gap, i) => {
              const dim = DIM_CONFIG[gap.dimension];
              const diff = DIFFICULTY_CONFIG[gap.implementationDifficulty];
              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 className="flex items-center gap-2">
                      <span className="text-xs">{dim.icon}</span>
                      <span className="text-xs font-semibold text-slate-500 uppercase">{dim.label}</span>
                    </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-bold text-emerald-400">+{gap.estimatedScoreLift} pts</span>
                    </div>
                  </div>
                  <p className="text-sm font-semibold text-slate-200">{gap.gap}</p>
                  <p className="text-xs text-slate-400 leading-relaxed">{gap.impactDescription}</p>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Recommendations */}
      {recommendations.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Recommendations</h3>
          <div className="space-y-2">
            {recommendations.map((rec, i) => {
              const impact = IMPACT_CONFIG[rec.impact];
              const effort = EFFORT_CONFIG[rec.effort];
              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">
                    <p className="text-sm font-semibold text-slate-200">{rec.title}</p>
                    <div className="flex items-center gap-2 shrink-0">
                      <span className={`text-xs font-semibold ${impact.class}`}>{impact.label}</span>
                      <span className="text-xs text-slate-500">{effort.label}</span>
                    </div>
                  </div>
                  <p className="text-xs text-slate-400 leading-relaxed">{rec.rationale}</p>
                </div>
              );
            })}
          </div>
        </div>
      )}

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