"use client";

import type { PageStrategicPass, PageHealthCard } from "@/lib/audit/types";

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

const PAGE_TYPE_PILL: Record<string, string> = {
  homepage: "bg-indigo-500/15 text-indigo-400 border border-indigo-500/20",
  contact: "bg-emerald-500/15 text-emerald-400 border border-emerald-500/20",
  service: "bg-blue-500/15 text-blue-400 border border-blue-500/20",
  product: "bg-cyan-500/15 text-cyan-400 border border-cyan-500/20",
  about: "bg-violet-500/15 text-violet-400 border border-violet-500/20",
  blog: "bg-slate-500/15 text-slate-400 border border-slate-500/20",
  pricing: "bg-amber-500/15 text-amber-400 border border-amber-500/20",
  faq: "bg-teal-500/15 text-teal-400 border border-teal-500/20",
  other: "bg-slate-500/15 text-slate-400 border border-slate-500/20",
};

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

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

function ScoreRing({ score }: { score: number }) {
  const r = 18;
  const circumference = 2 * Math.PI * r;
  const dash = (score / 100) * circumference;
  return (
    <svg width={48} height={48} className="flex-shrink-0">
      <circle cx={24} cy={24} r={r} className="stroke-white/10" strokeWidth={4} fill="none" />
      <circle
        cx={24} cy={24} r={r}
        className={healthScoreRing(score)}
        strokeWidth={4}
        fill="none"
        strokeDasharray={`${dash} ${circumference}`}
        strokeDashoffset={circumference * 0.25}
        strokeLinecap="round"
        transform="rotate(-90 24 24)"
      />
      <text x={24} y={28} textAnchor="middle" className={`text-[10px] font-bold fill-current ${healthScoreColor(score)}`} fontSize={10} fontWeight="bold">
        {score}
      </text>
    </svg>
  );
}

function PageCard({ card }: { card: PageHealthCard }) {
  const path = card.url.replace(/^https?:\/\/[^/]+/, "") || "/";

  return (
    <div className="rounded-xl bg-slate-900/60 border border-white/8 overflow-hidden">
      {/* Card header */}
      <div className="px-5 py-4 flex items-start gap-4 border-b border-white/8">
        <ScoreRing score={card.healthScore} />
        <div className="flex-1 min-w-0">
          <div className="flex flex-wrap items-center gap-2 mb-1">
            <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wide ${PAGE_TYPE_PILL[card.pageType]}`}>
              {card.pageType}
            </span>
            <span className="text-[10px] text-slate-500">{card.selectionReason}</span>
          </div>
          <p className="text-sm font-mono text-slate-200 truncate" title={card.url}>{path}</p>
        </div>
      </div>

      {/* Structural signals */}
      <div className="px-5 py-3 border-b border-white/8 grid grid-cols-2 sm:grid-cols-4 gap-x-4 gap-y-2">
        <Signal label="H1" ok={card.structuralSignals.hasH1} value={card.structuralSignals.h1Text ?? undefined} />
        <Signal label="Schema" ok={card.structuralSignals.hasSchema}
          value={card.structuralSignals.schemaTypes.length > 0 ? card.structuralSignals.schemaTypes.slice(0, 2).join(", ") : undefined} />
        <Signal label="CTA" ok={card.structuralSignals.hasCTA ?? false}
          value={card.structuralSignals.ctaExamples[0]} />
        <Signal label="Content depth"
          ok={(card.structuralSignals.wordCount ?? 0) >= 300}
          value={card.structuralSignals.wordCount != null ? `${card.structuralSignals.wordCount} words` : undefined} />

        {card.behavioralSignals && (
          <>
            <Signal label="Bounce rate"
              ok={(card.behavioralSignals.bounceRate ?? 1) < 0.55}
              value={card.behavioralSignals.bounceRate != null ? `${Math.round(card.behavioralSignals.bounceRate * 100)}%` : undefined} />
            <Signal label="Conversions (30d)"
              ok={card.behavioralSignals.conversionCount > 0}
              value={String(card.behavioralSignals.conversionCount)} />
          </>
        )}
        {card.aiSignals && (
          <Signal label="AI visits (30d)"
            ok={card.aiSignals.aiVisits30d > 0}
            value={String(card.aiSignals.aiVisits30d)} />
        )}
      </div>

      {/* Issues */}
      {card.topIssues.length > 0 && (
        <div className="px-5 py-3 border-b border-white/8 space-y-1.5">
          {card.topIssues.map((issue, i) => (
            <div key={i} className="flex items-start gap-2">
              <span className={`mt-0.5 text-[9px] font-semibold px-1.5 py-0.5 rounded uppercase tracking-wide flex-shrink-0 ${SEVERITY_PILL[issue.severity]}`}>
                {issue.severity}
              </span>
              <span className="text-xs text-slate-400">{issue.issue}</span>
            </div>
          ))}
        </div>
      )}

      {/* Top recommendation */}
      <div className="px-5 py-3">
        <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-1">Top Recommendation</p>
        <p className="text-xs text-slate-300">{card.topRecommendation}</p>
        {card.crossReferences.length > 0 && (
          <div className="flex flex-wrap gap-2 mt-2">
            {card.crossReferences.map((ref) => (
              <a key={ref.sectionId} href={`#${ref.sectionId}`}
                className="text-[10px] text-indigo-400 hover:text-indigo-300 underline underline-offset-2">
                {ref.label}
              </a>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function Signal({ label, ok, value }: { label: string; ok: boolean; value?: string }) {
  return (
    <div>
      <p className="text-[10px] text-slate-500">{label}</p>
      <div className="flex items-center gap-1 mt-0.5">
        <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${ok ? "bg-emerald-400" : "bg-red-500"}`} />
        <span className="text-xs text-slate-300 truncate">{value ?? (ok ? "Present" : "Missing")}</span>
      </div>
    </div>
  );
}

interface Props {
  pageStrategicPass: PageStrategicPass | null | undefined;
}

export function PageStrategicPassSection({ pageStrategicPass }: Props) {
  if (!pageStrategicPass?.pages.length) return null;

  const { pages } = pageStrategicPass;
  const avgScore = Math.round(pages.reduce((s, p) => s + p.healthScore, 0) / pages.length);
  const criticalCount = pages.reduce((n, p) => n + p.topIssues.filter((i) => i.severity === "critical").length, 0);

  return (
    <section id="audit-page-review" 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">Page-by-Page Review</h3>
        <p className="text-xs text-slate-400 mt-1">
          Structural health assessment for {pages.length} high-priority page{pages.length !== 1 ? "s" : ""}
        </p>
      </div>

      {/* Summary strip */}
      <div className="px-6 py-4 border-b border-white/10 grid grid-cols-3 gap-4">
        <div>
          <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-1">Pages Reviewed</p>
          <p className="text-2xl font-bold tabular-nums text-slate-100">{pages.length}</p>
        </div>
        <div>
          <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-1">Avg Health Score</p>
          <p className={`text-2xl font-bold tabular-nums ${healthScoreColor(avgScore)}`}>{avgScore}<span className="text-sm font-normal text-slate-500">/100</span></p>
        </div>
        <div>
          <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-1">Critical Issues</p>
          <p className={`text-2xl font-bold tabular-nums ${criticalCount > 0 ? "text-red-400" : "text-emerald-400"}`}>{criticalCount}</p>
        </div>
      </div>

      {/* Page cards */}
      <div className="p-6 space-y-4">
        {pages.map((card) => (
          <PageCard key={card.url} card={card} />
        ))}
      </div>
    </section>
  );
}
