"use client";

import {
  CheckCircle2, XCircle, Circle, Globe, Bot, Smartphone,
  Link2, FileCode, AlignLeft, AlertTriangle, BarChart2,
} from "lucide-react";

interface SummaryData {
  hasSitemap?: boolean;
  hasRobotsTxt?: boolean;
  mobileFriendly?: boolean | null;
  totalPages?: number;
}

interface TechnicalMetrics {
  brokenLinksTotal?: number;
  schemaPercent?: number;
  nonIndexablePages?: number;
  redirectChainsCount?: number;
  missingTitles?: number;
  missingDescriptions?: number;
  missingH1?: number;
}

interface WebVitalRow {
  url: string;
  samples: number;
  lcp75?: number;
  cls75?: number;
  inp75?: number;
  ttfb75?: number;
}

interface RawData {
  pagesScanned?: number;
  summary?: SummaryData;
  technicalMetrics?: TechnicalMetrics;
  webVitalsSummary?: WebVitalRow[];
}

interface Props {
  rawData?: RawData | null;
  degradedMode?: boolean | null;
}

function lcpRating(ms?: number): "good" | "warn" | "bad" | "na" {
  if (ms == null) return "na";
  return ms < 2500 ? "good" : ms < 4000 ? "warn" : "bad";
}
function inpRating(ms?: number): "good" | "warn" | "bad" | "na" {
  if (ms == null) return "na";
  return ms < 200 ? "good" : ms < 500 ? "warn" : "bad";
}
function clsRating(v?: number): "good" | "warn" | "bad" | "na" {
  if (v == null) return "na";
  return v < 0.1 ? "good" : v < 0.25 ? "warn" : "bad";
}
function ttfbRating(ms?: number): "good" | "warn" | "bad" | "na" {
  if (ms == null) return "na";
  return ms < 800 ? "good" : ms < 1800 ? "warn" : "bad";
}

const RATING_CLASS = {
  good: "text-green-600 font-semibold",
  warn: "text-amber-600 font-semibold",
  bad: "text-red-600 font-semibold",
  na: "text-slate-400",
};

function fmtLcp(ms?: number) { return ms == null ? "—" : `${(ms / 1000).toFixed(2)}s`; }
function fmtMs(ms?: number) { return ms == null ? "—" : `${Math.round(ms)}ms`; }
function fmtCls(v?: number) { return v == null ? "—" : v.toFixed(3); }

function StatusIcon({ pass }: { pass: boolean | null | undefined }) {
  if (pass === true) return <CheckCircle2 className="w-4 h-4 text-green-500 shrink-0" />;
  if (pass === false) return <XCircle className="w-4 h-4 text-red-400 shrink-0" />;
  return <Circle className="w-4 h-4 text-slate-300 shrink-0" />;
}

function CountBadge({ count, warnIf }: { count?: number; warnIf?: "positive" | "nonzero" }) {
  if (count == null) return <span className="text-slate-400">—</span>;
  const bad = warnIf === "positive" ? count > 0 : count !== 0;
  return (
    <span className={`font-semibold tabular-nums ${bad ? "text-red-600" : "text-green-600"}`}>
      {count}
    </span>
  );
}

export function TechnicalHealthSection({ rawData, degradedMode }: Props) {
  const summary = rawData?.summary;
  const tm = rawData?.technicalMetrics;
  const cwv = rawData?.webVitalsSummary;

  if (!rawData && degradedMode) {
    return (
      <div id="audit-technical-health" className="bg-white rounded-2xl border border-slate-200 p-6 sm:p-8">
        <div className="flex items-center gap-2 mb-3">
          <BarChart2 className="w-4 h-4 text-slate-400" />
          <h2 className="text-[11px] font-semibold uppercase tracking-widest text-slate-400">Technical Health</h2>
        </div>
        <div className="flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-xl">
          <AlertTriangle className="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
          <p className="text-sm text-amber-800 leading-relaxed">
            Detailed crawl diagnostics are available when the site is accessible to the crawler. This audit was completed in telemetry mode.
          </p>
        </div>
      </div>
    );
  }

  if (!rawData) return null;

  const structuralItems: Array<{ icon: React.ReactNode; label: string; pass: boolean | null | undefined; detail: string }> = [];

  if (summary) {
    structuralItems.push(
      {
        icon: <Globe className="w-4 h-4 text-slate-400 shrink-0" />,
        label: "XML Sitemap",
        pass: summary.hasSitemap,
        detail: summary.hasSitemap ? "Found at /sitemap.xml" : "Not detected — add at /sitemap.xml",
      },
      {
        icon: <Bot className="w-4 h-4 text-slate-400 shrink-0" />,
        label: "Robots.txt",
        pass: summary.hasRobotsTxt,
        detail: summary.hasRobotsTxt ? "Found at /robots.txt" : "Not detected — add to guide crawlers",
      },
      {
        icon: <Smartphone className="w-4 h-4 text-slate-400 shrink-0" />,
        label: "Mobile-Friendly",
        pass: summary.mobileFriendly,
        detail:
          summary.mobileFriendly === true
            ? "Mobile usability signals detected"
            : summary.mobileFriendly === false
            ? "Mobile issues found"
            : "Not measured",
      },
    );
  }

  const hasExtended = !!(tm?.brokenLinksTotal != null || tm?.schemaPercent != null || tm?.missingTitles != null);

  return (
    <div id="audit-technical-health" className="bg-white rounded-2xl border border-slate-200 p-6 sm:p-8">
      <div className="flex items-center gap-2 mb-5">
        <BarChart2 className="w-4 h-4 text-slate-400" />
        <h2 className="text-[11px] font-semibold uppercase tracking-widest text-slate-400">Technical Health</h2>
        {rawData.pagesScanned != null && (
          <span className="text-[11px] text-slate-400 ml-auto">
            {rawData.pagesScanned} page{rawData.pagesScanned === 1 ? "" : "s"} scanned
          </span>
        )}
      </div>

      {structuralItems.length > 0 && (
        <div className="grid sm:grid-cols-3 gap-3 mb-5">
          {structuralItems.map((item) => (
            <div key={item.label} className="border border-slate-100 rounded-xl p-4 flex items-start gap-3">
              {item.icon}
              <div className="min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-sm font-medium text-slate-800">{item.label}</span>
                  <StatusIcon pass={item.pass} />
                </div>
                <p className="text-xs text-slate-500 leading-relaxed">{item.detail}</p>
              </div>
            </div>
          ))}
        </div>
      )}

      {hasExtended && tm && (
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
          {tm.missingTitles != null && (
            <div className="border border-slate-100 rounded-xl p-3.5">
              <div className="flex items-center gap-1.5 mb-1">
                <FileCode className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                <span className="text-xs text-slate-500">Missing Titles</span>
              </div>
              <CountBadge count={tm.missingTitles} warnIf="positive" />
            </div>
          )}
          {tm.missingDescriptions != null && (
            <div className="border border-slate-100 rounded-xl p-3.5">
              <div className="flex items-center gap-1.5 mb-1">
                <AlignLeft className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                <span className="text-xs text-slate-500">Missing Descriptions</span>
              </div>
              <CountBadge count={tm.missingDescriptions} warnIf="positive" />
            </div>
          )}
          {tm.brokenLinksTotal != null && (
            <div className="border border-slate-100 rounded-xl p-3.5">
              <div className="flex items-center gap-1.5 mb-1">
                <Link2 className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                <span className="text-xs text-slate-500">Broken Links</span>
              </div>
              <CountBadge count={tm.brokenLinksTotal} warnIf="positive" />
            </div>
          )}
          {tm.schemaPercent != null && (
            <div className="border border-slate-100 rounded-xl p-3.5">
              <div className="flex items-center gap-1.5 mb-1">
                <FileCode className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                <span className="text-xs text-slate-500">Schema Coverage</span>
              </div>
              <span className={`font-semibold tabular-nums ${tm.schemaPercent >= 50 ? "text-green-600" : tm.schemaPercent >= 25 ? "text-amber-600" : "text-red-600"}`}>
                {tm.schemaPercent.toFixed(0)}%
              </span>
            </div>
          )}
        </div>
      )}

      {cwv && cwv.length > 0 && (
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
            Core Web Vitals · p75 real user data
          </p>
          <div className="overflow-x-auto">
            <table className="w-full text-xs min-w-[400px]">
              <thead>
                <tr className="text-slate-400 border-b border-slate-100">
                  <th className="text-left font-medium pb-2.5 pr-4">URL</th>
                  <th className="text-right font-medium pb-2.5 px-3">LCP</th>
                  <th className="text-right font-medium pb-2.5 px-3">INP</th>
                  <th className="text-right font-medium pb-2.5 px-3">CLS</th>
                  <th className="text-right font-medium pb-2.5 pl-3">TTFB</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {cwv.slice(0, 10).map((row, i) => {
                  let path = row.url;
                  try { path = new URL(row.url).pathname || "/"; } catch {/* keep full */}
                  return (
                    <tr key={i}>
                      <td className="py-2.5 pr-4 font-mono text-indigo-600 truncate max-w-[180px]">{path}</td>
                      <td className={`py-2.5 px-3 text-right ${RATING_CLASS[lcpRating(row.lcp75)]}`}>{fmtLcp(row.lcp75)}</td>
                      <td className={`py-2.5 px-3 text-right ${RATING_CLASS[inpRating(row.inp75)]}`}>{fmtMs(row.inp75)}</td>
                      <td className={`py-2.5 px-3 text-right ${RATING_CLASS[clsRating(row.cls75)]}`}>{fmtCls(row.cls75)}</td>
                      <td className={`py-2.5 pl-3 text-right ${RATING_CLASS[ttfbRating(row.ttfb75)]}`}>{fmtMs(row.ttfb75)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
