"use client";

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

interface Props {
  competitorAnalysis: CompetitorAnalysis | null | undefined;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function fmt(n: number | null | undefined, fallback = "—"): string {
  if (n == null) return fallback;
  return n.toLocaleString();
}

function gapColor(mag: CompetitorAnalysis["competitiveGapMatrix"]["dimensions"][0]["gapMagnitude"]): string {
  switch (mag) {
    case "critical": return "text-red-400";
    case "high":     return "text-orange-400";
    case "moderate": return "text-amber-400";
    case "low":      return "text-emerald-400";
  }
}

function rankBadgeColor(rank: 1 | 2 | 3 | 4): string {
  return rank === 1 ? "bg-emerald-500/20 text-emerald-400 border-emerald-500/30"
       : rank === 2 ? "bg-amber-500/20 text-amber-400 border-amber-500/30"
       : "bg-red-500/20 text-red-400 border-red-500/30";
}

function cellColor(val: string | number, isBrand = false): string {
  if (!isBrand) return "text-slate-400";
  return "text-white font-semibold";
}

// ─── Competitor Card ──────────────────────────────────────────────────────────

function CompetitorCard({
  comp,
  label,
}: {
  comp: CompetitorAnalysis["detectedCompetitors"][0];
  label: string;
}) {
  const presentSchema = comp.detectedSchema.filter((s) => s.present);

  return (
    <div className="rounded-xl bg-slate-800/60 border border-white/10 p-5 flex flex-col gap-4">
      {/* Header */}
      <div className="flex items-start justify-between gap-2">
        <div>
          <span className="text-[10px] text-slate-500 uppercase tracking-widest block mb-1">{label}</span>
          <a
            href={`https://${comp.domain}`}
            target="_blank"
            rel="noopener noreferrer"
            className="text-sm font-semibold text-indigo-400 hover:text-indigo-300 transition-colors"
          >
            {comp.domain}
          </a>
        </div>
        <div className="text-right shrink-0">
          <p className="text-xs font-bold tabular-nums text-white">#{comp.avgRankPosition}</p>
          <p className="text-[10px] text-slate-500">avg rank</p>
        </div>
      </div>

      {/* Authority stats */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label: "Domain Auth", value: fmt(comp.domainAuthority) },
          { label: "Ref Domains", value: fmt(comp.referringDomains) },
          { label: "Backlinks",   value: fmt(comp.totalBacklinks) },
        ].map(({ label: l, value }) => (
          <div key={l} className="rounded-lg bg-slate-700/40 px-3 py-2 text-center">
            <p className="text-sm font-bold tabular-nums text-white">{value}</p>
            <p className="text-[10px] text-slate-400 mt-0.5">{l}</p>
          </div>
        ))}
      </div>

      {/* Schema detected */}
      {presentSchema.length > 0 && (
        <div>
          <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-1.5">Schema detected</p>
          <div className="flex flex-wrap gap-1.5">
            {presentSchema.map((s) => (
              <span
                key={s.type}
                className="text-[10px] font-medium px-2 py-0.5 rounded-full bg-indigo-500/15 text-indigo-300 border border-indigo-500/25"
              >
                {s.type}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Content topics */}
      {comp.topContentTopics.length > 0 && (
        <div>
          <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-1.5">Top content topics</p>
          <ul className="space-y-1">
            {comp.topContentTopics.map((topic, i) => (
              <li key={i} className="text-xs text-slate-300 flex items-start gap-1.5">
                <span className="text-slate-600 mt-0.5">·</span>
                {topic}
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Key differentiator */}
      {comp.keyDifferentiator && (
        <div className="rounded-lg bg-slate-700/30 border border-white/5 px-4 py-3">
          <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-1">What they do differently</p>
          <p className="text-xs text-slate-300 leading-relaxed">{comp.keyDifferentiator}</p>
        </div>
      )}

      {/* Queries */}
      {comp.appearsInQueries.length > 0 && (
        <div>
          <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-1">Appears in tracked queries</p>
          <p className="text-xs text-slate-400 leading-relaxed">
            {comp.appearsInQueries.slice(0, 3).join("; ")}
            {comp.appearsInQueries.length > 3 && ` +${comp.appearsInQueries.length - 3} more`}
          </p>
        </div>
      )}
    </div>
  );
}

// ─── Gap Matrix ───────────────────────────────────────────────────────────────

function GapMatrix({
  ca,
}: {
  ca: CompetitorAnalysis;
}) {
  const competitors = ca.detectedCompetitors;
  const dims = ca.competitiveGapMatrix.dimensions;

  return (
    <div>
      <h4 className="text-xs font-semibold text-slate-100 uppercase tracking-widest mb-4">
        Competitive Gap Matrix
      </h4>
      <div className="overflow-x-auto">
        <table className="w-full text-xs min-w-[520px]">
          <thead>
            <tr className="text-[10px] text-slate-500 uppercase tracking-wider border-b border-white/10">
              <th className="text-left pb-3 pr-4 font-medium">Dimension</th>
              <th className="text-right pb-3 px-3 font-medium">Your Site</th>
              {competitors[0] && <th className="text-right pb-3 px-3 font-medium truncate max-w-[120px]">{competitors[0].domain}</th>}
              {competitors[1] && <th className="text-right pb-3 px-3 font-medium truncate max-w-[120px]">{competitors[1].domain}</th>}
              {competitors[2] && <th className="text-right pb-3 px-3 font-medium truncate max-w-[120px]">{competitors[2].domain}</th>}
              <th className="text-center pb-3 pl-3 font-medium">Gap</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {dims.map((dim) => (
              <tr key={dim.name} className="hover:bg-white/[0.02] transition-colors">
                <td className="py-2.5 pr-4 text-slate-300">{dim.name}</td>
                <td className={`py-2.5 px-3 text-right tabular-nums ${cellColor(dim.brandValue, true)}`}>
                  {String(dim.brandValue)}
                </td>
                {competitors[0] && (
                  <td className="py-2.5 px-3 text-right tabular-nums text-slate-400">
                    {String(dim.competitorAValue)}
                  </td>
                )}
                {competitors[1] && (
                  <td className="py-2.5 px-3 text-right tabular-nums text-slate-400">
                    {String(dim.competitorBValue)}
                  </td>
                )}
                {competitors[2] && (
                  <td className="py-2.5 px-3 text-right tabular-nums text-slate-400">
                    {String(dim.competitorCValue)}
                  </td>
                )}
                <td className="py-2.5 pl-3 text-center">
                  <span className={`text-[10px] font-semibold border rounded-full px-2 py-0.5 ${rankBadgeColor(dim.brandRank)}`}>
                    #{dim.brandRank}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="text-[10px] text-slate-600 mt-3">
        Rank reflects position among your site and up to 3 detected competitors (1 = leading). Color indicates gap severity.
      </p>
    </div>
  );
}

// ─── Main export ──────────────────────────────────────────────────────────────

const COMPETITOR_LABELS = ["Competitor A", "Competitor B", "Competitor C"];

const qualityConfig = {
  high:     { label: "High confidence", class: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30" },
  moderate: { label: "Moderate confidence", class: "bg-amber-500/20 text-amber-400 border border-amber-500/30" },
  low:      { label: "Limited data", class: "bg-slate-500/20 text-slate-400 border border-slate-500/30" },
};

export function CompetitorDeepDiveSection({ competitorAnalysis }: Props) {
  if (!competitorAnalysis) return null;

  const ca = competitorAnalysis;
  const conf = qualityConfig[ca.dataQuality];

  return (
    <section id="competitor-deep-dive" className="rounded-2xl bg-slate-900/60 border border-white/10 overflow-hidden">
      {/* Section header */}
      <div className="px-6 py-5 border-b border-white/10 flex items-start justify-between gap-4">
        <div>
          <h3 className="text-sm font-semibold text-slate-100">Competitive Intelligence</h3>
          <p className="text-xs text-slate-400 mt-0.5">
            Top-ranking competitors for your industry queries ·{" "}
            {ca.detectedCompetitors.length} {ca.detectedCompetitors.length === 1 ? "competitor" : "competitors"} identified
          </p>
        </div>
        <span className={`shrink-0 text-[10px] font-semibold uppercase tracking-widest px-2.5 py-1 rounded-full ${conf.class}`}>
          {conf.label}
        </span>
      </div>

      {/* Competitor cards */}
      <div className="p-6">
        <div className="grid gap-4 md:grid-cols-3 mb-8">
          {ca.detectedCompetitors.map((comp, i) => (
            <CompetitorCard key={comp.domain} comp={comp} label={COMPETITOR_LABELS[i] ?? `Competitor ${i + 1}`} />
          ))}
        </div>

        {/* Gap matrix */}
        <div className="rounded-xl bg-slate-800/40 border border-white/10 p-5">
          <GapMatrix ca={ca} />
        </div>
      </div>
    </section>
  );
}
