"use client";

import { useState, useEffect, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { useBrand } from "@/context/brand-context";
import {
  AlertCircle,
  AlertTriangle,
  Info,
  ArrowLeft,
  ExternalLink,
  ClipboardPlus,
  CheckCircle2,
  Link2,
  Zap,
  Clock,
  Shield,
  FileText,
  TrendingUp,
  ListChecks,
} from "lucide-react";

// ─── Types ───────────────────────────────────────────────────────────────────

interface IssueData {
  source: string;
  title: string;
  category: string;
  severity: string;
  impact: string;
  effort: string;
  status: string;
  detail: string;
  suggestedFix: string;
  affectedUrl: string;
  affectedUrls: string[];
  affectedCount: number;
  sourceUrl?: string;
  anchorText?: string;
  evidence?: Array<{
    sourcePageUrl: string;
    brokenHref: string;
    anchorText: string;
    selector: string;
    snippet: string;
    statusCode: number;
  }>;
  auditCrawlHealth?: number;
  auditPagesScanned?: number;
}

interface RelatedTask {
  id: string;
  title: string;
  status: string;
  priority: string;
  createdAt: string;
}

// ─── Config ──────────────────────────────────────────────────────────────────

const SEVERITY_CFG: Record<string, { label: string; color: string; bg: string; border: string; icon: typeof AlertCircle }> = {
  critical: { label: "Critical", color: "text-red-700",    bg: "bg-red-50",    border: "border-red-200",    icon: AlertCircle },
  high:     { label: "High",     color: "text-orange-700", bg: "bg-orange-50", border: "border-orange-200", icon: AlertTriangle },
  medium:   { label: "Medium",   color: "text-amber-700",  bg: "bg-amber-50",  border: "border-amber-200",  icon: AlertTriangle },
  low:      { label: "Low",      color: "text-blue-700",   bg: "bg-blue-50",   border: "border-blue-200",   icon: Info },
};

const IMPACT_CFG: Record<string, string> = {
  high:   "text-green-700 bg-green-50 border-green-200",
  medium: "text-amber-700 bg-amber-50 border-amber-200",
  low:    "text-slate-500 bg-slate-50 border-slate-200",
};

const EFFORT_CFG: Record<string, string> = {
  low:    "text-green-600 bg-green-50 border-green-200",
  medium: "text-amber-600 bg-amber-50 border-amber-200",
  high:   "text-red-600 bg-red-50 border-red-200",
};

const SOURCE_CFG: Record<string, { label: string; icon: typeof Shield; color: string }> = {
  technical_audit:   { label: "Technical Audit",   icon: Shield,      color: "text-brand-600" },
  dead_pages:        { label: "Dead 404 Pages",    icon: AlertCircle, color: "text-red-600" },
  performance_audit: { label: "Performance Audit", icon: TrendingUp,  color: "text-blue-600" },
};

const TASK_STATUS_CFG: Record<string, { label: string; color: string; bg: string }> = {
  todo:        { label: "To Do",       color: "text-slate-600", bg: "bg-slate-50 border-slate-200" },
  in_progress: { label: "In Progress", color: "text-blue-600",  bg: "bg-blue-50 border-blue-200" },
  completed:   { label: "Completed",   color: "text-green-600", bg: "bg-green-50 border-green-200" },
};


// ─── Page ────────────────────────────────────────────────────────────────────

export default function IssueDetailPage() {
  const searchParams = useSearchParams();
  const { brand, siteId } = useBrand();

  // Toast state for the "Site Tag not installed" warning shown when the
  // user clicks Highlight/Open-with-Overlay but the brand has no site tag.
  const [toast, setToast] = useState<string | null>(null);
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 4000);
    return () => clearTimeout(t);
  }, [toast]);

  // Normalise any URL (absolute, root-relative, or bare) into an absolute
  // URL we can attach query params to. Used by both the per-evidence
  // "Highlight" button and the page-level "Open with Overlay" button.
  function absolutise(raw: string): URL | null {
    try {
      if (/^https?:\/\//i.test(raw)) return new URL(raw);
      if (brand.domain) {
        const origin = brand.domain.startsWith("http") ? brand.domain : `https://${brand.domain}`;
        const path = raw.startsWith("/") ? raw : `/${raw}`;
        return new URL(origin.replace(/\/$/, "") + path);
      }
      return new URL(`https://${raw}`);
    } catch {
      return null;
    }
  }

  // Click handler for the per-evidence "Highlight" button. Opens the
  // SOURCE page (the page containing the broken link) in a new tab with
  // ?meseo_audit=true&meseo_tag_id=<id>&highlight=<issueId>:<evidenceIdx>.
  // The overlay mapper explodes each issue into one synthetic
  // OverlayIssue per evidence item (id "<issueId>:<idx>"), so this lands
  // directly on the specific broken element with target emphasis styling.
  function handleHighlight(sourcePageUrl: string, evidenceIdx: number) {
    if (!siteId) {
      setToast("Install the meSEO Site Tag on this website to use the Live Audit Overlay.");
      return;
    }
    const base = absolutise(sourcePageUrl);
    if (!base) {
      setToast("Could not resolve the source page URL.");
      return;
    }
    base.searchParams.set("meseo_audit", "true");
    base.searchParams.set("meseo_tag_id", siteId);
    base.searchParams.set("highlight", `${issueId}:${evidenceIdx}`);
    window.open(base.toString(), "_blank", "noopener,noreferrer");
  }

  // Click handler for the page-level "Open with Overlay" button. Opens
  // the issue's primary affected URL with the overlay active and the
  // issue id as the target highlight.
  function handleOpenWithOverlay(rawUrl: string) {
    if (!siteId) {
      setToast("Install the meSEO Site Tag on this website to use the Live Audit Overlay.");
      return;
    }
    const base = absolutise(rawUrl);
    if (!base) {
      setToast("Could not resolve the page URL.");
      return;
    }
    base.searchParams.set("meseo_audit", "true");
    base.searchParams.set("meseo_tag_id", siteId);
    base.searchParams.set("highlight", issueId);
    window.open(base.toString(), "_blank", "noopener,noreferrer");
  }
  const [issue, setIssue] = useState<IssueData | null>(null);
  const [relatedTask, setRelatedTask] = useState<RelatedTask | null>(null);
  const [taskCreated, setTaskCreated] = useState(false);
  const [creating, setCreating] = useState(false);
  const [resolved, setResolved] = useState(false);

  const brandId = searchParams.get("brandId") || "";
  const issueId = searchParams.get("issueId") || "";
  const [auditDate, setAuditDate] = useState<string | null>(null);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    const domain = searchParams.get("domain") || "";

    // Build full URLs from paths — prepend https://domain if needed
    function buildFullUrl(url: string, d: string): string {
      if (!url) return "";
      if (url.startsWith("http")) return url;
      if (d) return `https://${d}${url.startsWith("/") ? "" : "/"}${url}`;
      return url;
    }

    // If we have an issueId, fetch real evidence from the API
    if (issueId) {
      fetch(`/api/technical-audit/issue?id=${issueId}`)
        .then((res) => {
          if (!res.ok) { setNotFound(true); return null; }
          return res.json();
        })
        .then((data) => {
          if (!data) return;
          const d = data.domain || domain;
          // Use real pageUrl, fall back to the audited domain homepage
          const realUrl = data.pageUrl
            ? buildFullUrl(data.pageUrl, d)
            : d ? `https://${d}` : "";
          // Build full affected URLs list
          const rawUrls = Array.isArray(data.affectedUrls) ? data.affectedUrls as string[] : [];
          const fullUrls = rawUrls.map((u: string) => buildFullUrl(u, d)).filter(Boolean);

          setIssue({
            source: "technical_audit",
            title: data.title,
            category: data.category,
            severity: data.severity,
            impact: data.severity === "critical" || data.severity === "high" ? "high" : data.severity === "medium" ? "medium" : "low",
            effort: "medium",
            status: data.status,
            detail: data.detail || "",
            suggestedFix: "",
            affectedUrl: realUrl,
            affectedUrls: fullUrls.length > 0 ? fullUrls : (realUrl ? [realUrl] : []),
            affectedCount: data.affected,
            sourceUrl: undefined,
            anchorText: undefined,
            evidence: Array.isArray(data.evidence) ? data.evidence : undefined,
            auditCrawlHealth: data.audit?.crawlHealth,
            auditPagesScanned: data.audit?.pagesScanned,
          });
          if (data.audit?.completedAt) {
            setAuditDate(new Date(data.audit.completedAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" }));
          }
        })
        .catch(() => setNotFound(true));
      return;
    }

    // Fallback: build from URL params (for non-technical-audit sources like dead_pages)
    const rawUrl = searchParams.get("url") || "";
    const rawSourceUrl = searchParams.get("sourceUrl") || "";

    if (!searchParams.get("title")) {
      setNotFound(true);
      return;
    }

    const data: IssueData = {
      source: searchParams.get("source") || "technical_audit",
      title: searchParams.get("title") || "",
      category: searchParams.get("category") || "general",
      severity: searchParams.get("severity") || "medium",
      impact: searchParams.get("impact") || "medium",
      effort: searchParams.get("effort") || "medium",
      status: searchParams.get("status") || "open",
      detail: searchParams.get("detail") || "",
      suggestedFix: searchParams.get("fix") || "",
      affectedUrl: buildFullUrl(rawUrl, domain),
      affectedUrls: rawUrl ? [buildFullUrl(rawUrl, domain)] : [],
      affectedCount: parseInt(searchParams.get("affected") || "1"),
      sourceUrl: rawSourceUrl ? buildFullUrl(rawSourceUrl, domain) : undefined,
      anchorText: searchParams.get("anchorText") || undefined,
    };
    setIssue(data);
  }, [searchParams, issueId]);

  // Check if a task already exists for this issue
  const checkRelatedTask = useCallback(async () => {
    if (!issue) return;
    try {
      const res = await fetch(`/api/tasks?brandId=${brandId}`, { cache: "no-store" });
      if (!res.ok) return;
      const tasks = await res.json();
      const match = tasks.find((t: RelatedTask) =>
        t.title.toLowerCase().includes(issue.title.toLowerCase().slice(0, 30)) ||
        t.title.toLowerCase() === `fix: ${issue.title.toLowerCase()}`
      );
      if (match) {
        setRelatedTask(match);
        setTaskCreated(true);
      }
    } catch { /* non-critical — don't break page */ }
  }, [issue, brandId]);

  useEffect(() => { checkRelatedTask(); }, [checkRelatedTask]);

  async function handleCreateTask() {
    if (!issue || taskCreated) return;
    setCreating(true);

    try {
      const res = await fetch("/api/tasks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "create",
          brandId,
          title: `Fix: ${issue.title}`,
          description: issue.detail || `${issue.affectedCount} page(s) affected. Category: ${issue.category}`,
          category: issue.source === "performance_audit" ? "technical" : issue.category === "links" ? "technical" : "seo",
          priority: issue.severity === "critical" ? "critical" : issue.severity,
          effort: issue.effort,
          pageUrl: issue.affectedUrl,
          recommendation: issue.suggestedFix,
          source: issue.source,
          sourceId: issueId || undefined,
        }),
      });

      if (res.ok) {
        const data = await res.json();
        if (data._duplicate) {
          setRelatedTask(data);
        } else {
          setRelatedTask(data);
        }
        setTaskCreated(true);
      }
    } catch { /* non-critical — don't break page */ }
    setCreating(false);
  }

  function handleMarkResolved() {
    setResolved(true);
    setIssue(prev => prev ? { ...prev, status: "resolved" } : prev);
  }

  if (notFound) {
    return (
      <div className="space-y-5 max-w-3xl">
        <Link href="/technical-audit" className="flex items-center gap-1.5 text-sm text-slate-500 hover:text-brand-600 transition-colors w-fit">
          <ArrowLeft className="w-4 h-4" /> Back to Technical Audit
        </Link>
        <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
          <AlertCircle className="w-10 h-10 text-slate-300 mx-auto mb-3" />
          <h2 className="text-lg font-bold text-slate-900 mb-1">Issue Not Found</h2>
          <p className="text-sm text-slate-500">This issue no longer exists or belongs to a different audit run.</p>
        </div>
      </div>
    );
  }

  if (!issue) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="w-8 h-8 border-4 border-brand-100 border-t-brand-600 rounded-full animate-spin" />
      </div>
    );
  }

  const sev = SEVERITY_CFG[issue.severity] ?? SEVERITY_CFG.medium;
  const SevIcon = sev.icon;
  const src = SOURCE_CFG[issue.source] ?? SOURCE_CFG.technical_audit;
  const SrcIcon = src.icon;
  const isResolved = issue.status === "resolved" || issue.status === "fixed" || resolved;

  return (
    <div className="space-y-5 max-w-3xl">

      {/* ── Back link ── */}
      <Link
        href={issue.source === "dead_pages" ? "/broken-links" : issue.source === "performance_audit" ? "/site-performance-audit" : "/technical-audit"}
        className="flex items-center gap-1.5 text-sm text-slate-500 hover:text-brand-600 transition-colors w-fit"
      >
        <ArrowLeft className="w-4 h-4" />
        Back to {src.label}
      </Link>

      {/* ── Quick Actions Bar ── */}
      <div className="bg-white rounded-xl border border-slate-200 px-5 py-3 flex items-center gap-2.5 flex-wrap">
        <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mr-1">Actions</span>

        {!taskCreated ? (
          <button
            onClick={handleCreateTask}
            disabled={creating}
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-brand-600 text-white text-xs font-semibold hover:bg-brand-700 disabled:opacity-50 transition-colors"
          >
            <ClipboardPlus className="w-3.5 h-3.5" />
            {creating ? "Creating..." : "Create Task"}
          </button>
        ) : (
          <Link
            href="/execution-hub"
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-green-50 border border-green-200 text-xs font-semibold text-green-700 hover:bg-green-100 transition-colors"
          >
            <CheckCircle2 className="w-3.5 h-3.5" />
            View in Execution Hub
          </Link>
        )}

        {!isResolved ? (
          <button
            onClick={handleMarkResolved}
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg border border-emerald-200 bg-emerald-50 text-xs font-semibold text-emerald-700 hover:bg-emerald-100 transition-colors"
          >
            <CheckCircle2 className="w-3.5 h-3.5" />
            Mark Resolved
          </button>
        ) : (
          <span className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-green-50 border border-green-200 text-xs font-semibold text-green-700">
            <CheckCircle2 className="w-3.5 h-3.5" />
            Resolved
          </span>
        )}

        {issue.affectedUrl && (
          <div className="flex items-center gap-2 ml-auto">
            <button
              onClick={() => handleOpenWithOverlay(issue.affectedUrl!)}
              className="flex items-center gap-1.5 px-4 py-2 rounded-lg border border-brand-200 bg-brand-50 text-xs font-semibold text-brand-700 hover:bg-brand-100 transition-colors"
              title={siteId ? "Open this page with the Live Audit Overlay active" : "Install the meSEO Site Tag to use the Live Audit Overlay"}
            >
              <ExternalLink className="w-3.5 h-3.5" />
              Open with Overlay
            </button>
            <a
              href={issue.affectedUrl.startsWith("http") ? issue.affectedUrl : `https://${issue.affectedUrl}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-1.5 px-4 py-2 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50 transition-colors"
            >
              <ExternalLink className="w-3.5 h-3.5" />
              Open Live URL
            </a>
          </div>
        )}
      </div>

      {/* Toast for Site Tag not installed warnings */}
      {toast && (
        <div className="fixed bottom-6 right-6 z-50 max-w-sm flex items-start gap-3 px-4 py-3 rounded-xl border border-amber-200 bg-amber-50 shadow-lg">
          <AlertTriangle className="w-4 h-4 text-amber-600 mt-0.5 shrink-0" />
          <div className="flex-1 text-xs text-amber-900 leading-relaxed">
            {toast}{" "}
            <Link href="/site-tag" className="font-semibold text-amber-700 underline hover:text-amber-800">
              Install it →
            </Link>
          </div>
          <button
            onClick={() => setToast(null)}
            className="text-amber-600 hover:text-amber-800 text-sm leading-none"
            aria-label="Dismiss"
          >
            ×
          </button>
        </div>
      )}

      {/* ── Issue Summary Card ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className={`px-6 py-5 ${sev.bg}/60 border-b border-slate-100`}>
          <div className="flex items-start gap-4">
            <div className={`w-12 h-12 rounded-xl ${sev.bg} ${sev.border} border flex items-center justify-center shrink-0`}>
              <SevIcon className={`w-6 h-6 ${sev.color}`} />
            </div>
            <div className="flex-1">
              <div className="flex items-center gap-2 flex-wrap mb-1.5">
                <span className={`text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded border ${sev.bg} ${sev.border} ${sev.color}`}>{sev.label}</span>
                <span className="flex items-center gap-1 text-[10px] font-semibold text-slate-400 uppercase tracking-wide">
                  <SrcIcon className={`w-3 h-3 ${src.color}`} />
                  {src.label}
                </span>
                {isResolved && (
                  <span className="text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded border bg-green-50 border-green-200 text-green-700">Resolved</span>
                )}
              </div>
              <h1 className="text-xl font-bold text-slate-900">{issue.title}</h1>
              {issue.detail && (
                <p className="text-sm text-slate-500 mt-1.5 leading-relaxed">{issue.detail}</p>
              )}
              {auditDate && (
                <p className="text-xs text-slate-400 mt-2 flex items-center gap-1.5">
                  <Clock className="w-3 h-3" /> Detected on {auditDate}
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Metadata grid */}
        <div className="grid grid-cols-2 sm:grid-cols-5 gap-px bg-slate-100">
          <div className="bg-white px-4 py-3.5">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Category</p>
            <p className="text-sm font-semibold text-slate-800 capitalize">{issue.category}</p>
          </div>
          <div className="bg-white px-4 py-3.5">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Severity</p>
            <span className={`text-[11px] font-semibold px-2 py-0.5 rounded border ${sev.bg} ${sev.border} ${sev.color}`}>{sev.label}</span>
          </div>
          <div className="bg-white px-4 py-3.5">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Impact</p>
            <span className={`text-[11px] font-semibold px-2 py-0.5 rounded border ${IMPACT_CFG[issue.impact] || IMPACT_CFG.medium}`}>
              {issue.impact.charAt(0).toUpperCase() + issue.impact.slice(1)}
            </span>
          </div>
          <div className="bg-white px-4 py-3.5">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Effort</p>
            <span className={`text-[11px] font-semibold px-2 py-0.5 rounded border ${EFFORT_CFG[issue.effort] || EFFORT_CFG.medium}`}>
              {issue.effort.charAt(0).toUpperCase() + issue.effort.slice(1)}
            </span>
          </div>
          <div className="bg-white px-4 py-3.5">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Pages</p>
            <p className="text-sm font-semibold text-slate-800">{issue.affectedCount}</p>
          </div>
        </div>
      </div>

      {/* ── Affected Pages ── */}
      {issue.affectedUrls.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <Link2 className="w-4 h-4 text-brand-600" />
            <h2 className="text-sm font-bold text-slate-800">
              Affected Page{issue.affectedCount !== 1 ? "s" : ""}
            </h2>
            <span className="text-xs text-slate-400 ml-auto">
              {issue.affectedUrls.length === issue.affectedCount
                ? `${issue.affectedCount} page${issue.affectedCount !== 1 ? "s" : ""}`
                : `Showing ${issue.affectedUrls.length} of ${issue.affectedCount} pages`}
            </span>
          </div>
          <div className="px-6 py-4 space-y-2">
            {issue.affectedUrls.map((url, i) => (
              <div key={i} className="flex items-center gap-3 p-3 bg-slate-50 rounded-lg border border-slate-100">
                <FileText className="w-4 h-4 text-slate-400 shrink-0" />
                <p className="text-sm font-mono text-brand-600 truncate flex-1 min-w-0">{url}</p>
                <a
                  href={url.startsWith("http") ? url : `https://${url}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-white transition-colors shrink-0"
                >
                  <ExternalLink className="w-3 h-3" />
                  Open
                </a>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Broken Link Evidence ── */}
      {issue.evidence && issue.evidence.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <Link2 className="w-4 h-4 text-red-500" />
            <h2 className="text-sm font-bold text-slate-800">Broken Link Instances</h2>
            <span className="text-xs text-slate-400 ml-auto">{issue.evidence.length} instance{issue.evidence.length !== 1 ? "s" : ""}</span>
          </div>
          <div className="divide-y divide-slate-100">
            {issue.evidence.map((ev, i) => (
              <div key={i} className="px-6 py-4 space-y-2">
                <div className="flex items-start gap-3">
                  <div className="flex-1 min-w-0 space-y-1.5">
                    {/* Source → Destination */}
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">From</span>
                      <span className="text-xs font-mono text-brand-600 truncate max-w-[40%]">{ev.sourcePageUrl}</span>
                      <ArrowLeft className="w-3 h-3 text-slate-300 rotate-180" />
                      <span className="text-[10px] font-bold uppercase tracking-widest text-red-400">To (broken)</span>
                      <span className="text-xs font-mono text-red-600 truncate max-w-[40%]">{ev.brokenHref}</span>
                    </div>
                    {/* Anchor text */}
                    {ev.anchorText && ev.anchorText !== "(unknown)" && (
                      <p className="text-xs text-slate-600">
                        <span className="font-semibold text-slate-400">Link text:</span> &ldquo;{ev.anchorText}&rdquo;
                      </p>
                    )}
                    {/* Snippet */}
                    {ev.snippet && (
                      <p className="text-[11px] text-slate-400 font-mono bg-slate-50 rounded px-2 py-1 truncate">
                        …{ev.snippet}…
                      </p>
                    )}
                    {/* Status + Selector */}
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-[10px] font-semibold text-red-700 bg-red-50 border border-red-200 px-1.5 py-0.5 rounded">
                        HTTP {ev.statusCode}
                      </span>
                      {ev.selector && (
                        <button
                          onClick={() => { navigator.clipboard.writeText(ev.selector); }}
                          className="text-[10px] font-mono text-slate-500 bg-slate-50 border border-slate-200 px-1.5 py-0.5 rounded hover:bg-slate-100 transition-colors cursor-pointer"
                          title="Copy selector"
                        >
                          {ev.selector}
                        </button>
                      )}
                    </div>
                  </div>
                  {/* Open source page + highlight */}
                  <div className="flex items-center gap-1.5 shrink-0">
                    <button
                      onClick={() => handleHighlight(ev.sourcePageUrl, i)}
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-brand-200 bg-brand-50 text-xs font-semibold text-brand-700 hover:bg-brand-100 transition-colors"
                      title={siteId ? "Open the source page and highlight this broken link with the Live Audit Overlay" : "Install the meSEO Site Tag to use the Live Audit Overlay"}
                    >
                      <ExternalLink className="w-3 h-3" />
                      Highlight
                    </button>
                    <a
                      href={ev.sourcePageUrl.startsWith("http") ? ev.sourcePageUrl : `https://${ev.sourcePageUrl}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50 transition-colors"
                    >
                      <ExternalLink className="w-3 h-3" />
                      Open
                    </a>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Source page (for dead pages / broken links) */}
      {issue.sourceUrl && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <ArrowLeft className="w-4 h-4 text-violet-500" />
            <h2 className="text-sm font-bold text-slate-800">Source Page</h2>
          </div>
          <div className="px-6 py-4">
            <div className="flex items-center gap-3 p-3 bg-violet-50/50 rounded-lg border border-violet-100">
              <FileText className="w-4 h-4 text-violet-400 shrink-0" />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-mono text-violet-600 truncate">{issue.sourceUrl}</p>
                {issue.anchorText && (
                  <p className="text-[11px] text-slate-400 mt-0.5">Anchor: &ldquo;{issue.anchorText}&rdquo;</p>
                )}
              </div>
              <a
                href={issue.sourceUrl.startsWith("http") ? issue.sourceUrl : `https://${issue.sourceUrl}`}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-violet-200 bg-violet-50 text-xs font-semibold text-violet-700 hover:bg-violet-100 transition-colors shrink-0"
              >
                <ExternalLink className="w-3 h-3" />
                Source
              </a>
            </div>
          </div>
        </div>
      )}

      {/* ── Audit Context ── */}
      {(issue.auditCrawlHealth != null || auditDate) && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <Shield className="w-4 h-4 text-brand-600" />
            <h2 className="text-sm font-bold text-slate-800">Audit Run</h2>
          </div>
          <div className="px-6 py-4">
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
              {issue.auditCrawlHealth != null && (
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Crawl Health</p>
                  <p className="text-sm font-semibold text-slate-800">{issue.auditCrawlHealth}/100</p>
                </div>
              )}
              {issue.auditPagesScanned != null && (
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Pages Scanned</p>
                  <p className="text-sm font-semibold text-slate-800">{issue.auditPagesScanned}</p>
                </div>
              )}
              {auditDate && (
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Completed</p>
                  <p className="text-sm font-semibold text-slate-800">{auditDate}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ── Recommended Fix ── */}
      {issue.suggestedFix && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-3.5 border-b border-slate-100 flex items-center gap-2 bg-emerald-50/60">
            <Zap className="w-4 h-4 text-emerald-600" />
            <h2 className="text-sm font-bold text-slate-800">Recommended Fix</h2>
          </div>
          <div className="px-6 py-4 space-y-3">
            <p className="text-sm text-slate-700 leading-relaxed">{issue.suggestedFix}</p>
            <div className="flex items-center gap-3 text-[11px]">
              <span className={`font-semibold px-2 py-0.5 rounded border ${IMPACT_CFG[issue.impact] || IMPACT_CFG.medium}`}>
                Impact: {issue.impact.charAt(0).toUpperCase() + issue.impact.slice(1)}
              </span>
              <span className={`font-semibold px-2 py-0.5 rounded border ${EFFORT_CFG[issue.effort] || EFFORT_CFG.medium}`}>
                Effort: {issue.effort.charAt(0).toUpperCase() + issue.effort.slice(1)}
              </span>
            </div>
          </div>
        </div>
      )}

      {/* ── Related Task Status ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-3.5 border-b border-slate-100 flex items-center gap-2">
          <ListChecks className="w-4 h-4 text-brand-600" />
          <h2 className="text-sm font-bold text-slate-800">Related Task</h2>
        </div>
        <div className="px-6 py-4">
          {relatedTask ? (
            <div className="flex items-center gap-4 p-3 bg-slate-50 rounded-lg border border-slate-100">
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-slate-800">{relatedTask.title}</p>
                <div className="flex items-center gap-2 mt-1.5">
                  {(() => {
                    const ts = TASK_STATUS_CFG[relatedTask.status] ?? TASK_STATUS_CFG.todo;
                    return <span className={`text-[10px] font-semibold px-2 py-0.5 rounded border ${ts.bg} ${ts.color}`}>{ts.label}</span>;
                  })()}
                  <span className="text-[10px] text-slate-400">
                    Created {new Date(relatedTask.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                  </span>
                </div>
              </div>
              <Link
                href="/execution-hub"
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-brand-200 bg-brand-50 text-xs font-semibold text-brand-700 hover:bg-brand-100 transition-colors shrink-0"
              >
                <ListChecks className="w-3 h-3" />
                View in Hub
              </Link>
            </div>
          ) : (
            <div className="flex items-center gap-3 p-3 bg-slate-50 rounded-lg border border-slate-100">
              <Clock className="w-4 h-4 text-slate-400" />
              <div className="flex-1">
                <p className="text-sm text-slate-500">No task created yet</p>
                <p className="text-[11px] text-slate-400 mt-0.5">Click &ldquo;Create Task&rdquo; above to track this in Execution Hub</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* ── Bottom navigation ── */}
      <div className="flex items-center gap-3">
        <Link
          href={issue.source === "dead_pages" ? "/broken-links" : issue.source === "performance_audit" ? "/site-performance-audit" : "/technical-audit"}
          className="flex items-center gap-1.5 px-4 py-2.5 rounded-lg border border-slate-200 text-sm font-semibold text-slate-600 hover:bg-slate-50 transition-colors"
        >
          <ArrowLeft className="w-3.5 h-3.5" />
          Back to {src.label}
        </Link>
        <Link
          href="/execution-hub"
          className="flex items-center gap-1.5 px-4 py-2.5 rounded-lg border border-slate-200 text-sm font-semibold text-slate-600 hover:bg-slate-50 transition-colors"
        >
          <ListChecks className="w-3.5 h-3.5" />
          Execution Hub
        </Link>
      </div>
    </div>
  );
}
