"use client";

import type { AiEnginePersonalityAnalysis, EnginePersonalityCard } from "@/lib/audit/types";

const ENGINE_COLORS: Record<string, { bg: string; border: string; dot: string }> = {
  chatgpt:  { bg: "bg-emerald-500/10",  border: "border-emerald-500/20",  dot: "bg-emerald-400" },
  perplexity: { bg: "bg-cyan-500/10",   border: "border-cyan-500/20",     dot: "bg-cyan-400" },
  claude:   { bg: "bg-violet-500/10",   border: "border-violet-500/20",   dot: "bg-violet-400" },
  gemini:   { bg: "bg-blue-500/10",     border: "border-blue-500/20",     dot: "bg-blue-400" },
  copilot:  { bg: "bg-sky-500/10",      border: "border-sky-500/20",      dot: "bg-sky-400" },
};

const SENSITIVITY_PILL: Record<string, string> = {
  high: "bg-red-500/15 text-red-400 border border-red-500/20",
  medium: "bg-amber-500/15 text-amber-400 border border-amber-500/20",
  low: "bg-emerald-500/15 text-emerald-400 border border-emerald-500/20",
};

function EngineCard({ card, isTop }: { card: EnginePersonalityCard; isTop: boolean }) {
  const colors = ENGINE_COLORS[card.engineId] ?? { bg: "bg-slate-500/10", border: "border-slate-500/20", dot: "bg-slate-400" };

  return (
    <div className={`rounded-xl border overflow-hidden ${colors.border} ${isTop ? "ring-1 ring-white/20" : ""}`}>
      {/* Engine header */}
      <div className={`px-5 py-4 flex items-center gap-3 border-b border-white/8 ${colors.bg}`}>
        <span className={`w-2.5 h-2.5 rounded-full flex-shrink-0 ${colors.dot}`} />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <h4 className="text-sm font-semibold text-slate-100">{card.displayName}</h4>
            <span className="text-[10px] text-slate-500">{card.parentCompany}</span>
            {isTop && (
              <span className="text-[9px] font-semibold px-1.5 py-0.5 rounded bg-white/10 text-white uppercase tracking-wide">
                Top source
              </span>
            )}
          </div>
          <p className="text-[10px] text-slate-400 mt-0.5 line-clamp-2">{card.citationStyle}</p>
        </div>
      </div>

      {/* 1st-party overlay (if present) */}
      {card.firstPartyOverlay && (
        <div className="px-5 py-3 border-b border-white/8 grid grid-cols-3 gap-3">
          <div>
            <p className="text-[10px] text-slate-500">AI Sessions (30d)</p>
            <p className="text-lg font-bold tabular-nums text-slate-100 mt-0.5">{card.firstPartyOverlay.sessions30d.toLocaleString()}</p>
          </div>
          <div>
            <p className="text-[10px] text-slate-500">Conversions</p>
            <p className="text-lg font-bold tabular-nums text-slate-100 mt-0.5">{card.firstPartyOverlay.conversions30d}</p>
          </div>
          <div>
            <p className="text-[10px] text-slate-500">Conv. Rate</p>
            <p className="text-lg font-bold tabular-nums text-slate-100 mt-0.5">
              {card.firstPartyOverlay.conversionRate != null ? `${card.firstPartyOverlay.conversionRate}%` : "—"}
            </p>
          </div>
          {card.firstPartyOverlay.topLandingPages.length > 0 && (
            <div className="col-span-3">
              <p className="text-[10px] text-slate-500 mb-1">Top landing pages</p>
              <div className="space-y-0.5">
                {card.firstPartyOverlay.topLandingPages.map((p) => (
                  <p key={p.url} className="text-[10px] font-mono text-slate-400 truncate">
                    {p.url.replace(/^https?:\/\/[^/]+/, "") || "/"} &middot; {p.aiVisits} visits{p.conversions > 0 ? ` · ${p.conversions} conv` : ""}
                  </p>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Signals row */}
      <div className="px-5 py-3 border-b border-white/8 flex flex-wrap gap-4">
        <div>
          <p className="text-[10px] text-slate-500 mb-1">E-E-A-T Sensitivity</p>
          <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wide ${SENSITIVITY_PILL[card.eAtSensitivity]}`}>
            {card.eAtSensitivity}
          </span>
        </div>
        <div>
          <p className="text-[10px] text-slate-500 mb-1">Recency Bias</p>
          <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wide ${SENSITIVITY_PILL[card.recencyBias]}`}>
            {card.recencyBias}
          </span>
        </div>
        <div>
          <p className="text-[10px] text-slate-500 mb-1">Schema Priorities</p>
          <div className="flex flex-wrap gap-1">
            {card.schemaPriorities.slice(0, 3).map((s) => (
              <span key={s} className="text-[9px] px-1.5 py-0.5 rounded bg-white/8 text-slate-300">{s}</span>
            ))}
          </div>
        </div>
        <div>
          <p className="text-[10px] text-slate-500 mb-1">Preferred Content</p>
          <p className="text-[10px] text-slate-400">{card.preferredContentTypes.slice(0, 3).join(", ")}</p>
        </div>
      </div>

      {/* Optimization approach */}
      <div className="px-5 py-4">
        <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-2">Optimization Approach</p>
        <ul className="space-y-1.5">
          {card.optimizationApproach.map((tip, i) => (
            <li key={i} className="flex items-start gap-2">
              <span className={`mt-1.5 w-1 h-1 rounded-full flex-shrink-0 ${colors.dot}`} />
              <span className="text-xs text-slate-400">{tip}</span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

interface Props {
  aiEnginePersonalityAnalysis: AiEnginePersonalityAnalysis | null | undefined;
}

export function AiEnginePersonalitySection({ aiEnginePersonalityAnalysis }: Props) {
  if (!aiEnginePersonalityAnalysis?.engines.length) return null;

  const { engines, topEngineId } = aiEnginePersonalityAnalysis;
  const hasFirstPartyData = engines.some((e) => e.firstPartyOverlay !== null);

  return (
    <section id="audit-ai-engines" className="rounded-2xl bg-slate-950/80 border border-white/10 overflow-hidden">
      <div className="px-6 py-5 border-b border-white/10">
        <h3 className="text-sm font-semibold text-slate-100">AI Engine Profiles</h3>
        <p className="text-xs text-slate-400 mt-1">
          How the 5 major AI engines discover and cite content — with engine-specific optimization guidance
          {hasFirstPartyData && " and your 30-day performance by engine"}
        </p>
      </div>

      <div className="p-6 grid gap-4 md:grid-cols-2 xl:grid-cols-1">
        {engines.map((card) => (
          <EngineCard
            key={card.engineId}
            card={card}
            isTop={card.engineId === topEngineId}
          />
        ))}
      </div>
    </section>
  );
}
