"use client";

/**
 * Content Brief page — v2
 * ──────────────────────────────────────────────────────────────────────────────
 * FILE TO EDIT:  src/app/content-brief/page.tsx
 *
 * Sections (top to bottom):
 *  1. Page heading
 *  2. Local Inputs          – city, service, brand, CTA (pre-filled mock)
 *  3. Keyword Strategy      – primary, secondary, long-tail, AI phrases
 *  4. Content Output        – H1 · Intro · H2s · FAQ · CTA  (Standard / Humanized)
 *  5. Internal Linking      – anchor text, target page, short reason
 *  6. Export                – Copy to Clipboard · Export to Google Docs (placeholder)
 *
 * All data is mock only. No backend or AI calls yet.
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { useSearchParams } from "next/navigation";
import { useBrand } from "@/context/brand-context";
import SchemaCodeEditor from "@/components/schema-code-editor";
import {
  FileText,
  Copy,
  RefreshCw,
  Check,
  Sparkles,
  Info,
  MapPin,
  Search,
  Link2,
  Download,
  Save,
  Loader2,
  Plus,
} from "lucide-react";
import HumanizationPanel from "@/components/content-brief/humanization-panel";
import MarkdownRenderer, { sectionsToMarkdown } from "@/components/content-brief/markdown-renderer";
import BriefSchemaSection from "@/components/content-brief/brief-schema-section";
import FeatureGate from "@/components/plan/feature-gate";

// ─── Dev-only mock data flag ─────────────────────────────────────────────────
// Mock template data (DEFAULT_INPUTS, MOCK_BLOCKS) is only surfaced when this
// flag is explicitly set in the environment. In production this is always
// false, and no mock data will ever appear in rendered UI.
const DEV_MOCK_ENABLED =
  process.env.NEXT_PUBLIC_MESEO_ENV === "development" &&
  process.env.NEXT_PUBLIC_DEBUG_MOCK_DATA === "true";

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

interface FaqItem {
  q: string;
  a: string;
}

/** A single labeled block inside the Content Output panel. */
interface BriefBlock {
  id: string;
  type: "h1" | "h2" | "h3" | "body" | "bullets" | "faq" | "cta" | "meta" | "schema";
  /** Short label shown as a pill above the content. */
  label: string;
  content?: string;
  items?: string[];   // bullet list items
  faq?: FaqItem[];
}

/** One row in the Internal Linking table. */
interface InternalLink {
  anchor: string;
  targetPage: string;
  reason: string;
  category: "service" | "location";
}

// ─── Mock: Local Inputs (default values) ────────────────────────────────────

const DEFAULT_INPUTS = {
  city:    "Austin",
  service: "HVAC Repair & Installation",
  brand:   "ComfortPro HVAC",
  cta:     "Get a free HVAC inspection today",
};

// ─── Mock: Keyword Strategy ──────────────────────────────────────────────────

const KEYWORD_STRATEGY = {
  primary: "HVAC repair Austin TX",
  secondary: [
    "AC repair Austin",
    "heating repair Austin TX",
    "local HVAC company Austin",
    "air conditioning service Austin",
  ],
  longTail: [
    "best emergency HVAC repair Austin TX",
    "affordable AC repair near me Austin Texas",
    "licensed HVAC technician Round Rock Austin",
    "how much does HVAC repair cost in Austin TX",
  ],
  aiPhrases: [
    "what is the best HVAC company in Austin",
    "who does 24/7 AC repair near Austin TX",
    "how do I find a reliable HVAC technician in Austin",
    "which HVAC company offers free estimates in Austin Texas",
  ],
};

// ─── Mock: Content Output ────────────────────────────────────────────────────
//
// Two voices: standard (professional SEO copy) and humanized (natural / expert).
// Structural blocks (H2s, H3s, bullets, FAQ, meta, schema) are shared.
// Intro paragraph and CTA text differ between modes.
// Target word count: ~1,050–1,200 words across all blocks.

const SHARED_FAQ: FaqItem[] = [
  {
    q: "How much does HVAC repair cost in Austin TX?",
    a: "Most HVAC repairs in Austin range from $150 to $600 depending on the issue. Minor fixes like capacitor or contactor replacements are on the lower end, while refrigerant recharges or blower motor replacements sit in the mid-range. Full system replacements typically run $4,000–$10,000 installed. ComfortPro HVAC provides a free diagnostic and written estimate before any work begins, so you always know the cost upfront with no surprises.",
  },
  {
    q: "Do you offer 24/7 emergency HVAC service in Austin?",
    a: "Yes. ComfortPro HVAC provides round-the-clock emergency service throughout the Austin metro, including weekends and major holidays. When you call our emergency line, a licensed technician is dispatched within 60–90 minutes. We keep a fully stocked service fleet so most emergency repairs are resolved in a single visit — no waiting on parts orders.",
  },
  {
    q: "How long does an AC repair take?",
    a: "The majority of AC repairs are completed in one to three hours. Simple fixes like thermostat replacements or capacitor swaps take under an hour. More involved repairs — such as coil cleaning, refrigerant recharges, or blower motor replacements — typically run two to four hours. Full system replacements are usually completed within a single business day. We always give you a realistic time estimate before the technician begins.",
  },
  {
    q: "What HVAC brands does ComfortPro service?",
    a: "Our technicians are trained and certified to service all major HVAC brands including Carrier, Trane, Lennox, Rheem, Goodman, York, American Standard, and Bryant. We stock common OEM and compatible parts for these brands on our service vehicles, allowing us to complete most repairs same-day without waiting on special orders.",
  },
  {
    q: "How often should I service my HVAC system in Austin?",
    a: "In Austin's climate, HVAC systems work harder and longer than in most U.S. markets. We recommend a spring tune-up before peak cooling season (April) and a fall check-up before heating season (October). Bi-annual maintenance keeps your system efficient, extends its lifespan by 3–5 years on average, and helps catch small issues — like low refrigerant or dirty coils — before they become expensive emergency repairs.",
  },
];

const SHARED_STRUCTURAL: BriefBlock[] = [
  // ── H2 #1 ──────────────────────────────────────────────────────────────────
  {
    id: "h2-1", type: "h2", label: "H2",
    content: "Why Austin Homeowners Choose ComfortPro HVAC",
  },
  {
    id: "body-1", type: "body", label: "Body Copy",
    content:
      "Austin's climate places extreme demand on HVAC systems. Summer temperatures regularly exceed 100°F, and unexpected winter freezes can push heating equipment to its limits overnight. ComfortPro HVAC has been built around these local conditions — providing fast, reliable service that keeps Austin families comfortable year-round, no matter what the weather throws at them.",
  },
  {
    id: "h3-1", type: "h3", label: "H3",
    content: "What Sets Us Apart",
  },
  {
    id: "bullets-1", type: "bullets", label: "Bullet List",
    items: [
      "Licensed and insured technicians with a minimum of 5 years of field experience",
      "Same-day service available 7 days a week, including holidays and weekends",
      "Upfront flat-rate pricing — you approve every cost before work begins",
      "100% satisfaction guarantee on all repairs and full installations",
      "4.9-star average rating across 500+ verified Google reviews",
    ],
  },

  // ── H2 #2 ──────────────────────────────────────────────────────────────────
  {
    id: "h2-2", type: "h2", label: "H2",
    content: "Our HVAC Services in Austin, TX",
  },
  {
    id: "body-2", type: "body", label: "Body Copy",
    content:
      "Whether you need a quick repair, a complete system replacement, or a preventive maintenance plan to avoid costly breakdowns, ComfortPro HVAC has the certified team and stocked fleet to handle it. We service all major brands and offer flexible financing for larger installations.",
  },
  {
    id: "h3-2a", type: "h3", label: "H3",
    content: "Residential HVAC Services",
  },
  {
    id: "bullets-2a", type: "bullets", label: "Bullet List",
    items: [
      "AC repair and emergency diagnosis — all major brands (Carrier, Trane, Lennox, Rheem)",
      "Heating system repair and replacement — gas furnaces, heat pumps, and mini-splits",
      "Duct cleaning, sealing, and replacement to improve airflow and indoor air quality",
      "Bi-annual maintenance plans — spring tune-up and fall check-up included",
      "Air purifier, UV light, and humidity control system installation",
    ],
  },
  {
    id: "h3-2b", type: "h3", label: "H3",
    content: "Commercial HVAC Services",
  },
  {
    id: "bullets-2b", type: "bullets", label: "Bullet List",
    items: [
      "Rooftop unit (RTU) installation and ongoing service for retail and office buildings",
      "Multi-zone HVAC systems for restaurants, medical offices, and warehouses",
      "Planned maintenance contracts with priority response and defined SLAs",
      "Energy efficiency assessments and system optimisation reports",
    ],
  },

  // ── H2 #3 ──────────────────────────────────────────────────────────────────
  {
    id: "h2-3", type: "h2", label: "H2",
    content: "Signs Your HVAC System Needs Repair",
  },
  {
    id: "body-3", type: "body", label: "Body Copy",
    content:
      "Many HVAC problems start small and become expensive if ignored. Catching warning signs early can save you thousands in avoidable repair or replacement costs. If you notice any of the following, contact ComfortPro HVAC for a free same-day diagnostic.",
  },
  {
    id: "h3-3", type: "h3", label: "H3",
    content: "Common Warning Signs to Watch For",
  },
  {
    id: "bullets-3", type: "bullets", label: "Bullet List",
    items: [
      "Warm or stuffy air blowing from vents despite the thermostat being set to cool",
      "Unusual sounds from the unit — grinding, squealing, banging, or rattling",
      "Short cycling: the system turns on and off more than twice per hour",
      "Rising energy bills with no change in usage or schedule",
      "Inconsistent temperatures between rooms or floors of the home",
      "Ice forming on refrigerant lines or on the outdoor condenser unit",
    ],
  },

  // ── H2 #4 ──────────────────────────────────────────────────────────────────
  {
    id: "h2-4", type: "h2", label: "H2",
    content: "Areas We Serve in Central Texas",
  },
  {
    id: "body-4", type: "body", label: "Body Copy",
    content:
      "ComfortPro HVAC dispatches service vehicles from central Austin, allowing us to reach most of the metro area within 60–90 minutes. We serve the following cities and communities with the same same-day availability and upfront pricing.",
  },
  {
    id: "h3-4", type: "h3", label: "H3",
    content: "Our Service Area",
  },
  {
    id: "bullets-4", type: "bullets", label: "Bullet List",
    items: [
      "Austin, TX — full metro coverage including East Austin, South Congress, the Domain, and Mueller",
      "Round Rock — residential and commercial service throughout the city",
      "Cedar Park & Leander — full coverage for these fast-growing northwest suburbs",
      "Georgetown — historic district and new-build developments",
      "Pflugerville & Manor — same-day response available for all areas",
    ],
  },

  // ── FAQ ────────────────────────────────────────────────────────────────────
  { id: "faq", type: "faq", label: "FAQ", faq: SHARED_FAQ },

  // ── Meta ───────────────────────────────────────────────────────────────────
  {
    id: "meta-title", type: "meta", label: "Meta Title",
    content: "Best HVAC Repair & Installation in Austin TX | ComfortPro HVAC",
  },
  {
    id: "meta-desc", type: "meta", label: "Meta Description",
    content:
      "Need HVAC repair in Austin, TX? ComfortPro HVAC offers same-day AC repair, heating installation, and emergency service across Austin, Round Rock, Cedar Park & more. Licensed, insured, and 4.9-star rated. Call for a free estimate.",
  },

  // ── Schema ─────────────────────────────────────────────────────────────────
  {
    id: "schema", type: "schema", label: "Schema (JSON-LD)",
    content: JSON.stringify(
      {
        "@context": "https://schema.org",
        "@type": "LocalBusiness",
        "name": "ComfortPro HVAC",
        "description": "Licensed HVAC repair and installation serving Austin TX and surrounding areas.",
        "url": "https://comfortprohvac.com",
        "telephone": "+1-512-555-0192",
        "priceRange": "$$",
        "address": {
          "@type": "PostalAddress",
          "streetAddress": "1800 S Lamar Blvd",
          "addressLocality": "Austin",
          "addressRegion": "TX",
          "postalCode": "78704",
          "addressCountry": "US",
        },
        "areaServed": ["Austin TX", "Round Rock TX", "Cedar Park TX", "Georgetown TX", "Pflugerville TX"],
        "openingHours": "Mo-Su 00:00-23:59",
        "aggregateRating": {
          "@type": "AggregateRating",
          "ratingValue": "4.9",
          "reviewCount": "512",
        },
      },
      null,
      2
    ),
  },
];

const MOCK_BLOCKS: Record<"standard" | "humanized", BriefBlock[]> = {
  standard: [
    {
      id: "h1", type: "h1", label: "H1",
      content: "Best HVAC Repair & Installation in Austin, Texas",
    },
    {
      id: "intro", type: "body", label: "Intro",
      content:
        "When your air conditioning fails during an Austin summer or your heating system goes down in January, you need a team that responds the same day. ComfortPro HVAC has served homeowners and businesses across the Austin metro for over 15 years. Our licensed technicians handle everything from emergency AC breakdowns to complete system installations — with upfront pricing, no hidden fees, and a 100% satisfaction guarantee on every job.",
    },
    ...SHARED_STRUCTURAL,
    {
      id: "cta", type: "cta", label: "CTA",
      content:
        "Don't wait on a broken HVAC system — Austin summers and winters don't allow for delays. Contact ComfortPro HVAC today for a free diagnostic inspection and same-day service anywhere in the Austin metro. Call us directly, book online in under 2 minutes, or request a free estimate and we'll call you back within the hour. Our licensed technicians are standing by.",
    },
  ],

  humanized: [
    {
      id: "h1", type: "h1", label: "H1",
      content: "Best HVAC Repair & Installation in Austin, Texas",
    },
    {
      id: "intro", type: "body", label: "Intro",
      content:
        "Nobody plans for the AC to quit in the middle of July in Texas. But when it happens, the last thing you want is to be on hold with a call center three states away. ComfortPro HVAC is a local Austin team — we live here, we know how brutal the summers get, and we show up fast. We'll tell you exactly what's wrong and fix it right the first time, with a price you agree to before we touch anything.",
    },
    ...SHARED_STRUCTURAL,
    {
      id: "cta", type: "cta", label: "CTA",
      content:
        "Ready to get comfortable again? Book a free inspection with ComfortPro HVAC — we're local, we're fast, and we won't surprise you with the bill. Same-day slots are available across Austin and the surrounding area. Call us, book online, or drop your number and we'll reach out within the hour.",
    },
  ],
};

// ─── Mock: Internal Linking ──────────────────────────────────────────────────
//
// Split into two categories:
//   service  — links to specific service pages (short, direct keyword anchors)
//   location — links to city/area landing pages (geo-intent anchors)

const INTERNAL_LINKS: InternalLink[] = [
  // ── Service-based ──────────────────────────────────────────────────────────
  {
    category:   "service",
    anchor:     "AC repair",
    targetPage: "/services/ac-repair",
    reason:     "Primary service anchor. Targets users with immediate cooling repair intent.",
  },
  {
    category:   "service",
    anchor:     "heating repair",
    targetPage: "/services/heating-repair",
    reason:     "Covers heating-side searches and seasonal intent during winter months.",
  },
  {
    category:   "service",
    anchor:     "duct cleaning",
    targetPage: "/services/duct-cleaning",
    reason:     "Builds topical depth around air quality — a common upsell after AC repair.",
  },
  {
    category:   "service",
    anchor:     "HVAC maintenance plan",
    targetPage: "/services/maintenance",
    reason:     "Targets lifecycle buyers looking for ongoing service, not just emergency repair.",
  },
  {
    category:   "service",
    anchor:     "emergency HVAC",
    targetPage: "/services/emergency-hvac",
    reason:     "High-intent anchor for urgent queries — short anchor improves click relevance.",
  },
  {
    category:   "service",
    anchor:     "free estimate",
    targetPage: "/free-estimate",
    reason:     "Conversion-focused link. Short anchor performs better than long phrases in CTAs.",
  },
  {
    category:   "service",
    anchor:     "indoor air quality",
    targetPage: "/services/indoor-air-quality",
    reason:     "Expands topical authority beyond core repair into a growing search category.",
  },

  // ── Location-based ─────────────────────────────────────────────────────────
  {
    category:   "location",
    anchor:     "HVAC Austin TX",
    targetPage: "/locations/austin",
    reason:     "Primary geo anchor. Reinforces local relevance for the core market.",
  },
  {
    category:   "location",
    anchor:     "AC repair Round Rock",
    targetPage: "/locations/round-rock",
    reason:     "Suburb-specific anchor. Round Rock has high search volume for local HVAC queries.",
  },
  {
    category:   "location",
    anchor:     "HVAC Cedar Park",
    targetPage: "/locations/cedar-park",
    reason:     "Fast-growing northwest suburb with rising demand for new-build HVAC installs.",
  },
  {
    category:   "location",
    anchor:     "Georgetown HVAC",
    targetPage: "/locations/georgetown",
    reason:     "Extends footprint north of Austin. Geo pages help search engines map coverage.",
  },
  {
    category:   "location",
    anchor:     "Pflugerville AC repair",
    targetPage: "/locations/pflugerville",
    reason:     "East metro coverage. Competitive long-tail local searches with lower difficulty.",
  },
  {
    category:   "location",
    anchor:     "service areas",
    targetPage: "/service-areas",
    reason:     "Catch-all geo page. Helps crawlers map the full coverage zone in one link.",
  },
];

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

/** Pill colours keyed by BriefBlock type. */
function blockPillClass(type: BriefBlock["type"]): string {
  switch (type) {
    case "h1":      return "bg-brand-600 text-white";
    case "h2":      return "bg-slate-700 text-white";
    case "h3":      return "bg-slate-200 text-slate-600";
    case "body":    return "bg-slate-100 text-slate-500";
    case "bullets": return "bg-sky-50    text-sky-700";
    case "faq":     return "bg-amber-50  text-amber-700";
    case "cta":     return "bg-green-600 text-white";
    case "meta":    return "bg-violet-50 text-violet-700";
    case "schema":  return "bg-slate-800 text-slate-200";
  }
}

// ─── Page component ──────────────────────────────────────────────────────────

// Brand ID mapping
// SEO Content Brief is a Growth+ feature. FeatureGate wrapper catches
// direct navigations that bypass the sidebar's locked-click handler.
export default function ContentBriefPageGated() {
  return (
    <FeatureGate feature="seo_content_brief">
      <ContentBriefPage />
    </FeatureGate>
  );
}

function ContentBriefPage() {
  const { brand: selectedBrand } = useBrand();

  // ── Local input state — pre-populated from brand profile, editable ──
  const [city,    setCity]    = useState("");
  const [service, setService] = useState("");
  const [brand,   setBrand]   = useState(selectedBrand?.name ?? "");
  const [cta,     setCta]     = useState("");
  const [profileLoaded, setProfileLoaded] = useState(false);

  // ── Live keyword research data ──
  const [kwData, setKwData] = useState<{
    primary: { keyword: string; searchVolume: number | null; difficulty: number | null; cpc: number | null; intent: string | null } | null;
    secondary: Array<{ keyword: string; searchVolume: number | null; difficulty: number | null; intent: string | null }>;
    longTail: string[];
    questions: string[];
    source: string;
  } | null>(null);
  const [kwLoading, setKwLoading] = useState(false);

  // ── Live brief insights (GSC + competitor + local + internal-links) ──
  interface InsightsResponse {
    keyword: string;
    serp: {
      gscConnected: boolean;
      totals: { clicks: number; impressions: number; avgPosition: number | null; ctr: number | null; matchedQueries: number } | null;
      topPages: Array<{ pageUrl: string; clicks: number; impressions: number; position: number }>;
      matchingQueries: Array<{ query: string; clicks: number; impressions: number; position: number }>;
    };
    competitor: {
      pages: Array<{ competitorDomain: string; url: string; title: string | null; wordCount: number | null }>;
      domainsCovered: number;
      medianWordCount: number | null;
    };
  }
  const [insights, setInsights] = useState<InsightsResponse | null>(null);
  const [insightsLoading, setInsightsLoading] = useState(false);

  // Track the detected specialty label separately so we can display
  // "Cardiology" instead of the generic Brand.industry = "Healthcare"
  // on the Local Insights service field.
  const [detectedSpecialty, setDetectedSpecialty] = useState<string | null>(null);

  // Live AI-generated Content Output. When null we fall back to the
  // mock blocks (dev mode) or an empty CTA; when populated we render
  // the returned Markdown inline in the Content Output panel.
  const [generatedContent, setGeneratedContent] = useState<string | null>(null);
  const [generateError, setGenerateError] = useState<string | null>(null);

  // Pre-populate local inputs from BrandProfile on mount / brand change.
  // Also resets all input fields so switching brands doesn't carry
  // stale data from the previous brand's saved brief or profile.
  useEffect(() => {
    if (!selectedBrand?.id) return;
    // Clear stale values from previous brand FIRST
    setCity("");
    setService("");
    setBrand(selectedBrand?.name ?? "");
    setCta("");
    setProfileLoaded(false);
    setDetectedSpecialty(null);

    fetch(`/api/content-briefs/brand-profile?brandId=${selectedBrand?.id}`)
      .then((r) => r.ok ? r.json() : null)
      .then((data) => {
        if (!data) return;
        if (data.locations?.length) setCity(data.locations[0]);

        const specialty: string | null = data.specialty?.label ?? null;
        if (specialty) setDetectedSpecialty(specialty);

        if (data.services?.length) {
          setService(data.services[0]);
        } else if (specialty) {
          const primary = specialty.split("/")[0].trim();
          setService(primary.charAt(0).toUpperCase() + primary.slice(1));
        } else if (data.industry) {
          setService(data.industry);
        }

        if (data.cta) setCta(data.cta);
        else {
          const ctaLabel = specialty ? specialty.split("/")[0].trim() : data.industry;
          setCta(ctaLabel ? `Get a free ${ctaLabel.toLowerCase()} consultation` : "");
        }
      })
      .catch(() => {})
      .finally(() => setProfileLoaded(true));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedBrand?.id]);

  // ── Keyword research fetch ──
  async function fetchKeywordData() {
    if (kwLoading || !selectedBrand?.id) return;
    const seed = service && city ? `${service} ${city}` : service || city;
    if (!seed) return;
    setKwLoading(true);
    try {
      const res = await fetch("/api/keyword-research/for-brief", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId: selectedBrand?.id, keyword: seed, city, service }),
      });
      if (res.ok) {
        setKwData(await res.json());
      } else {
        console.warn("[content-brief] keyword research failed:", res.status);
      }
    } catch (err) {
      console.warn("[content-brief] keyword research error:", err);
    }
    setKwLoading(false);
  }

  // ── Live insights fetch (SERP + competitors + local + internal links) ──
  // The effective keyword is whatever the user has targeted — falls back
  // to the service input so a brand with no keyword research yet still
  // pulls relevant GSC / competitor data.
  const effectiveKeyword = (kwData?.primary?.keyword || service || "").trim();

  const loadInsights = useCallback(async () => {
    if (!selectedBrand?.id || effectiveKeyword.length < 2) return;
    setInsightsLoading(true);
    try {
      const res = await fetch(
        `/api/content-briefs/insights?brandId=${selectedBrand?.id}&keyword=${encodeURIComponent(effectiveKeyword)}`,
      );
      if (res.ok) setInsights(await res.json());
      else console.warn("[content-brief] insights failed:", res.status);
    } catch (err) { console.warn("[content-brief] insights error:", err); }
    setInsightsLoading(false);
  }, [selectedBrand?.id, effectiveKeyword]);

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

  // ── Content output mode ──
  const [mode, setMode] = useState<"standard" | "humanized">("standard");

  // ── Output controls ──
  const [outputTone,        setOutputTone]        = useState("Professional");
  const [humanizationLevel, setHumanizationLevel] = useState("Medium");

  // ── Schema editing state ──
  const originalSchemaRef = useRef<string>("");
  const [schemaOverrides, setSchemaOverrides] = useState<Record<string, string>>({});
  const updateBlock = useCallback((blockId: string, content: string) => {
    setSchemaOverrides((prev) => ({ ...prev, [blockId]: content }));
  }, []);

  // Store original schema on first render
  useEffect(() => {
    const schemaBlock = MOCK_BLOCKS.standard.find((b) => b.type === "schema");
    if (schemaBlock && !originalSchemaRef.current) originalSchemaRef.current = schemaBlock.content || "";
  }, []);

  // ── Interaction feedback ──
  const [copied,       setCopied]       = useState(false);
  const [regenerating, setRegenerating] = useState(false);
  const [exportNotice, setExportNotice] = useState<string | null>(null);

  // ── Backend state ──
  const urlParams = useSearchParams();
  const [briefId, setBriefId] = useState<string | null>(urlParams.get("briefId"));
  // Deep link support — /content-brief?keyword=X (sent by Topic Map,
  // Keyword Research "Create Brief" actions, etc.). The keyword rides
  // through the `service` input since that's what drives the
  // effectiveKeyword used by insights + keyword research.
  const deepLinkKeyword = (urlParams.get("keyword") || "").trim();
  useEffect(() => {
    if (deepLinkKeyword && !service) setService(deepLinkKeyword);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deepLinkKeyword]);
  const [saving, setSaving] = useState(false);
  const [saveNotice, setSaveNotice] = useState<string | null>(null);
  const [backendLinks, setBackendLinks] = useState<InternalLink[] | null>(null);
  const [initialLoadDone, setInitialLoadDone] = useState(false);
  const [createError, setCreateError] = useState<string | null>(null);

  // Fetch existing briefs from backend
  const loadBrief = useCallback(async () => {
    try {
      const res = await fetch(`/api/content-briefs?brandId=${selectedBrand?.id}&type=seo`);
      if (!res.ok) {
        setInitialLoadDone(true);
        return;
      }
      const briefs = await res.json();
      if (Array.isArray(briefs) && briefs.length > 0) {
        const b = briefs[0];
        setBriefId(b.id);
        if (b.city) setCity(b.city);
        // Don't overwrite a deep-linked keyword (?keyword=X) with
        // the saved brief's service field — the deep link is the
        // user's explicit intent (e.g. from Competitor Intel "Create").
        if (b.service && !deepLinkKeyword) setService(b.service);
        if (b.brandName) setBrand(b.brandName);
        if (b.ctaOffer) setCta(b.ctaOffer);
        if (b.tone) setOutputTone(b.tone === "conversational" ? "Conversational" : "Professional");
        if (b.humanizationMode) setMode("humanized");
        if (b.internalLinks && Array.isArray(b.internalLinks) && b.internalLinks.length > 0) {
          setBackendLinks(b.internalLinks.map((l: Record<string, string>) => ({
            anchor: l.anchorText || l.anchor || "",
            targetPage: l.targetUrl || l.targetPage || "",
            reason: l.context || l.reason || "Suggested link",
            category: (l.targetUrl || "").includes("location") ? "location" as const : "service" as const,
          })));
        }
      }
    } catch {
      // Network error — don't inject mock data, just show empty state
    }
    setInitialLoadDone(true);
  }, [selectedBrand?.id]);

  // Reset brief-specific state on brand change (input fields are
  // reset in the profile-fetch effect above).
  useEffect(() => {
    setBriefId(null);
    setInitialLoadDone(false);
    setBackendLinks(null);
  }, [selectedBrand?.id]);

  // Create a new empty brief — called from the empty state CTA
  async function createEmptyBrief() {
    if (!selectedBrand?.id) return;
    setSaving(true);
    setCreateError(null);
    try {
      const res = await fetch("/api/content-briefs", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "create",
          brandId: selectedBrand?.id,
          type: "seo",
          title: "New SEO Content Brief",
          status: "draft",
        }),
      });
      if (!res.ok) {
        setCreateError("Failed to create brief. Please try again.");
        setSaving(false);
        return;
      }
      const created = await res.json();
      if (created?.id) setBriefId(created.id);
    } catch {
      setCreateError("Network error. Please try again.");
    }
    setSaving(false);
  }

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

  // Save brief to backend
  async function handleSave() {
    setSaving(true);
    try {
      const payload = {
        action: briefId ? "update" : "create",
        ...(briefId ? { briefId } : { brandId: selectedBrand?.id, type: "seo" }),
        title: `${service} in ${city}`,
        primaryKeyword: KEYWORD_STRATEGY.primary,
        secondaryKeywords: KEYWORD_STRATEGY.secondary,
        city,
        service,
        brandName: brand,
        ctaOffer: cta,
        tone: outputTone.toLowerCase(),
        humanizationMode: mode === "humanized",
        status: "draft",
      };

      const res = await fetch("/api/content-briefs", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (res.ok) {
        const data = await res.json();
        if (!briefId) setBriefId(data.id);
        setSaveNotice("Brief saved!");
        setTimeout(() => setSaveNotice(null), 2500);
      }
    } catch {
      setSaveNotice("Failed to save");
      setTimeout(() => setSaveNotice(null), 2500);
    }
    setSaving(false);
  }

  // ── Handlers ──

  function handleCopy() {
    // Prefer real generated content when we have it, fall back to dev
    // mock blocks (local development only). The final "nothing yet"
    // branch is effectively unreachable once the user has generated
    // once, but stays here as a defensive copy-path.
    const text = generatedContent
      ? generatedContent
      : DEV_MOCK_ENABLED
      ? sectionsToMarkdown(MOCK_BLOCKS[mode])
      : "No content generated yet.";
    navigator.clipboard.writeText(text).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  async function handleRegenerate() {
    if (!selectedBrand?.id || !effectiveKeyword) {
      setGenerateError("Add a target service or run keyword research first.");
      setTimeout(() => setGenerateError(null), 3000);
      return;
    }
    setRegenerating(true);
    setGenerateError(null);
    try {
      const res = await fetch("/api/content-briefs/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          brandId: selectedBrand?.id,
          keyword: effectiveKeyword,
          type: "seo",
          tone: outputTone,
          humanization: mode === "humanized",
          topic: service || effectiveKeyword,
          brandName: brand,
          city,
          service,
          specialty: detectedSpecialty,
          ctaOffer: cta,
        }),
      });
      if (!res.ok) throw new Error(`Generation failed (${res.status})`);
      const data = await res.json();
      setGeneratedContent(typeof data?.content === "string" ? data.content : null);
    } catch (err) {
      setGenerateError(err instanceof Error ? err.message : "Generation failed");
      setTimeout(() => setGenerateError(null), 4000);
    }
    setRegenerating(false);
  }

  function handlePlaceholderExport(label: string) {
    setExportNotice(`${label} export coming soon.`);
    setTimeout(() => setExportNotice(null), 3000);
  }

  // ─────────────────────────────────────────────────────────────────────────

  // ── Loading state (before first API load completes) ──
  // Auto-create a brief when arriving via deep link (?keyword=X) so the
  // user sees the full form immediately instead of the empty state.
  useEffect(() => {
    if (briefId || !deepLinkKeyword || !selectedBrand?.id || saving) return;
    createEmptyBrief();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deepLinkKeyword, selectedBrand?.id]);

  if (!initialLoadDone) {
    return (
      <div className="space-y-6 max-w-3xl">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">SEO Content Brief</h1>
          <p className="text-slate-500 text-sm mt-1">
            Build SEO-optimised content briefs with long-tail keywords, localised copy, and search-engine‑friendly structure.
          </p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 px-6 py-16 text-center">
          <Loader2 className="w-6 h-6 text-brand-500 animate-spin mx-auto" />
          <p className="text-sm text-slate-500 mt-3">Loading content briefs…</p>
        </div>
      </div>
    );
  }

  // ── Empty state (no saved briefs, not in dev-mock mode) ──
  if (!briefId && !DEV_MOCK_ENABLED && !deepLinkKeyword) {
    return (
      <div className="space-y-6 max-w-3xl">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">SEO Content Brief</h1>
          <p className="text-slate-500 text-sm mt-1">
            Build SEO-optimised content briefs with long-tail keywords, localised copy, and search-engine‑friendly structure.
          </p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 px-6 py-16 text-center">
          <div className="w-14 h-14 rounded-2xl bg-brand-50 flex items-center justify-center mx-auto mb-4">
            <FileText className="w-7 h-7 text-brand-600" />
          </div>
          <h2 className="text-lg font-bold text-slate-900 mb-1">No Content Briefs Yet</h2>
          <p className="text-sm text-slate-500 max-w-md mx-auto mb-5 leading-relaxed">
            Create your first content brief to get AI-powered SEO recommendations for your content — with long-tail keywords, localised copy, and structured output.
          </p>
          <button
            onClick={createEmptyBrief}
            disabled={saving || !selectedBrand?.id}
            className="inline-flex items-center gap-1.5 px-5 py-2.5 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
            {saving ? "Creating…" : "Create Content Brief"}
          </button>
          {createError && <p className="text-xs text-red-600 mt-3">{createError}</p>}
          {!selectedBrand?.id && <p className="text-xs text-slate-400 mt-3">Select a brand first.</p>}
        </div>
      </div>
    );
  }

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

      {/* ── 1. Heading ── */}
      <div>
        <h1 className="text-2xl font-bold text-slate-900">SEO Content Brief</h1>
        <p className="text-slate-500 text-sm mt-1">
          Build SEO-optimised content briefs with long-tail keywords, localised copy, and search-engine‑friendly structure.
        </p>
      </div>

      {/* ── 1b. SEO Content Score card ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-5 flex items-center gap-5 sm:gap-8">

          {/* Circular score */}
          <div className="relative w-[60px] h-[60px] shrink-0">
            <svg viewBox="0 0 64 64" className="w-[60px] h-[60px] -rotate-90">
              <circle cx="32" cy="32" r="27" fill="none" stroke="#e2e8f0" strokeWidth="5" />
              <circle
                cx="32" cy="32" r="27"
                fill="none"
                stroke="#16a34a"
                strokeWidth="5"
                strokeLinecap="round"
                strokeDasharray="142.9 169.6"
              />
            </svg>
            <div className="absolute inset-0 flex flex-col items-center justify-center">
              <span className="text-base font-bold text-slate-400 leading-none">—</span>
              <span className="text-[9px] text-slate-400 font-medium">/100</span>
            </div>
          </div>

          {/* Title + summary note */}
          <div className="flex-1 min-w-0">
            <p className="text-sm font-bold text-slate-900 mb-1">SEO Content Score</p>
            <p className="text-xs text-slate-500 leading-relaxed">
              Complete the brief and generate content to receive a real-time SEO content score based on keyword structure, readability, and content depth.
            </p>
          </div>
        </div>
        <div className="px-6 pb-4">
          <p className="text-[11px] text-slate-400 leading-relaxed">
            SEO score focuses on content structure, keyword targeting, and direct internal linking — optimised for search engine crawlers and ranking signals.
          </p>
        </div>

      </div>

      {/* ── SERP Insights ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <div className="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center shrink-0">
            <Search className="w-4 h-4 text-blue-600" />
          </div>
          <div>
            <h2 className="font-bold text-slate-900 text-sm">SERP Insights</h2>
            <p className="text-[11px] text-slate-500">What currently ranks on Google for your target keyword.</p>
          </div>
          <span className="ml-auto text-[10px] font-semibold text-blue-600 bg-blue-50 border border-blue-200 rounded-full px-2 py-0.5">Google-focused</span>
        </div>

        <div className="px-6 py-5 space-y-4">
          {/* Live GSC data via /api/content-briefs/insights. Three
              states: not-connected → install hint; connected-but-no-
              match → "no GSC data for this keyword" note; has data →
              totals + ranking pages + query variants. */}
          {!insights && insightsLoading && (
            <div className="flex items-center justify-center py-6 text-xs text-slate-400">
              <Loader2 className="w-4 h-4 animate-spin mr-2" /> Loading SERP data for &ldquo;{effectiveKeyword}&rdquo;…
            </div>
          )}

          {insights && !insights.serp.gscConnected && (
            <div className="text-center py-6">
              <Search className="w-10 h-10 text-slate-200 mx-auto mb-3" />
              <p className="text-sm font-semibold text-slate-700 mb-1">Connect Google Search Console for SERP insights</p>
              <p className="text-xs text-slate-500 max-w-sm mx-auto mb-4">Once GSC is connected, this panel shows your current ranking position, clicks, and top pages for the target keyword.</p>
              <a href="/integrations" className="inline-flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700">Open Integrations</a>
            </div>
          )}

          {insights && insights.serp.gscConnected && !insights.serp.totals && (
            <div className="text-center py-6">
              <Search className="w-10 h-10 text-slate-200 mx-auto mb-3" />
              <p className="text-sm font-semibold text-slate-700 mb-1">No GSC matches yet for &ldquo;{effectiveKeyword}&rdquo;</p>
              <p className="text-xs text-slate-500 max-w-sm mx-auto">GSC is connected, but you don&apos;t yet have ranking data for this exact keyword family. Try a broader term or wait a few days for new impressions to accumulate.</p>
            </div>
          )}

          {insights?.serp.totals && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Avg Position</p>
                  <p className="text-lg font-bold text-slate-900">{insights.serp.totals.avgPosition ?? "—"}</p>
                  <p className="text-[10px] text-slate-400">across {insights.serp.totals.matchedQueries} {insights.serp.totals.matchedQueries === 1 ? "query" : "queries"}</p>
                </div>
                <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Clicks (90d)</p>
                  <p className="text-lg font-bold text-slate-900">{insights.serp.totals.clicks.toLocaleString()}</p>
                  <p className="text-[10px] text-slate-400">organic visits</p>
                </div>
                <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Impressions</p>
                  <p className="text-lg font-bold text-slate-900">{insights.serp.totals.impressions.toLocaleString()}</p>
                  <p className="text-[10px] text-slate-400">SERP appearances</p>
                </div>
                <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">CTR</p>
                  <p className="text-lg font-bold text-slate-900">{insights.serp.totals.ctr != null ? `${insights.serp.totals.ctr}%` : "—"}</p>
                  <p className="text-[10px] text-slate-400">click-through rate</p>
                </div>
              </div>

              {insights.serp.topPages.length > 0 && (
                <div>
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">Your Top Ranking Pages</p>
                  <div className="space-y-2">
                    {insights.serp.topPages.map((page) => (
                      <div key={page.pageUrl} className="flex items-center gap-3 py-2 px-3 bg-slate-50/50 rounded-lg">
                        <span className="w-8 h-6 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 bg-slate-100 text-slate-600">
                          #{Math.round(page.position)}
                        </span>
                        <span className="text-xs font-mono text-brand-600 truncate flex-1" title={page.pageUrl}>{page.pageUrl}</span>
                        <span className="text-[10px] text-slate-500 shrink-0">{page.clicks.toLocaleString()} clicks</span>
                        <span className="text-[10px] text-slate-400 shrink-0">{page.impressions.toLocaleString()} imp</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {insights.serp.matchingQueries.length > 0 && (
                <div>
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">Related Queries You Rank For</p>
                  <div className="flex flex-wrap gap-1.5">
                    {insights.serp.matchingQueries.slice(0, 10).map((q) => (
                      <span key={q.query} className="inline-flex items-center gap-1 px-2.5 py-1 rounded-md bg-white border border-slate-200 text-[11px] text-slate-600" title={`${q.clicks} clicks · #${q.position}`}>
                        {q.query}
                        <span className="text-[9px] font-mono text-slate-400">#{Math.round(q.position)}</span>
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {DEV_MOCK_ENABLED && !insights && (<div className="space-y-4">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Avg Word Count</p>
              <p className="text-lg font-bold text-slate-900">1,850</p>
              <p className="text-[10px] text-slate-400">Top 10 results</p>
            </div>
            <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Avg H2 Count</p>
              <p className="text-lg font-bold text-slate-900">8</p>
              <p className="text-[10px] text-slate-400">Sections per page</p>
            </div>
            <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">FAQ Schema</p>
              <p className="text-lg font-bold text-green-600">7/10</p>
              <p className="text-[10px] text-slate-400">Have FAQ markup</p>
            </div>
            <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
              <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Keyword Difficulty</p>
              <p className="text-lg font-bold text-amber-600">62</p>
              <p className="text-[10px] text-slate-400">Moderate competition</p>
            </div>
          </div>

          {/* Top ranking pages */}
          <div>
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">Top Ranking Pages</p>
            <div className="space-y-2">
              {[
                { pos: 1, url: "competitor-a.com/hvac-repair-guide",   words: 2400, da: 72, features: ["FAQ", "Schema", "Video"] },
                { pos: 2, url: "competitor-b.com/ac-repair-services",  words: 1900, da: 65, features: ["FAQ", "Schema"] },
                { pos: 3, url: "competitor-c.com/hvac-repair-cost",    words: 2100, da: 58, features: ["FAQ", "Images"] },
                { pos: 4, url: "localsite.com/emergency-hvac",         words: 1400, da: 42, features: ["Schema"] },
                { pos: 5, url: "hvac-directory.com/repair-services",   words: 1600, da: 68, features: ["FAQ", "Schema", "Reviews"] },
              ].map((page) => (
                <div key={page.pos} className="flex items-center gap-3 py-2 px-3 bg-slate-50/50 rounded-lg hover:bg-slate-50 transition-colors">
                  <span className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 ${page.pos <= 3 ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-500"}`}>
                    {page.pos}
                  </span>
                  <span className="text-xs font-mono text-brand-600 truncate flex-1">{page.url}</span>
                  <span className="text-[10px] text-slate-500 shrink-0">{page.words.toLocaleString()} words</span>
                  <span className="text-[10px] text-slate-400 shrink-0">DA {page.da}</span>
                  <div className="flex items-center gap-1 shrink-0">
                    {page.features.map((f) => (
                      <span key={f} className="text-[8px] font-bold text-slate-500 bg-slate-100 rounded px-1.5 py-0.5">{f}</span>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>)}
        </div>
      </div>

      {/* ── Win Factors — gated behind real AI analysis ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <div className="w-8 h-8 rounded-lg bg-green-50 flex items-center justify-center shrink-0">
            <svg className="w-4 h-4 text-green-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" /><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" /><path d="M4 22h16" /><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" /><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" /><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z" /></svg>
          </div>
          <div>
            <h2 className="font-bold text-slate-900 text-sm">Competitive Insights</h2>
            <p className="text-[11px] text-slate-500">AI-powered analysis of what top-ranking pages are doing right.</p>
          </div>
        </div>

        <div className="px-6 py-5">
          {/* Inline competitor data sourced from /insights. Falls back
              to a "set up Competitor Intel" nudge when the brand has
              no indexed competitor pages for this topic yet. */}
          {insightsLoading && !insights && (
            <div className="flex items-center justify-center py-6 text-xs text-slate-400">
              <Loader2 className="w-4 h-4 animate-spin mr-2" /> Loading competitor coverage…
            </div>
          )}

          {insights && insights.competitor.pages.length === 0 && (
            <div className="text-center py-4">
              <Sparkles className="w-10 h-10 text-slate-200 mx-auto mb-3" />
              <p className="text-sm font-semibold text-slate-700 mb-1">No competitor pages cover &ldquo;{effectiveKeyword}&rdquo; yet</p>
              <p className="text-xs text-slate-500 max-w-md mx-auto mb-4">Add competitors in Competitor Intel so we can index their pages and surface content gaps here.</p>
              <a href="/competitors" className="inline-flex items-center gap-1.5 px-4 py-2 bg-white text-slate-700 border border-slate-200 text-xs font-semibold rounded-lg hover:bg-slate-50">Open Competitor Intel</a>
            </div>
          )}

          {insights && insights.competitor.pages.length > 0 && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Competitors Covering</p>
                  <p className="text-lg font-bold text-slate-900">{insights.competitor.domainsCovered}</p>
                  <p className="text-[10px] text-slate-400">distinct domains</p>
                </div>
                <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Pages Found</p>
                  <p className="text-lg font-bold text-slate-900">{insights.competitor.pages.length}</p>
                  <p className="text-[10px] text-slate-400">on this topic</p>
                </div>
                <div className="bg-slate-50 rounded-lg px-3.5 py-2.5">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Median Length</p>
                  <p className="text-lg font-bold text-slate-900">{insights.competitor.medianWordCount ? `${insights.competitor.medianWordCount.toLocaleString()}w` : "—"}</p>
                  <p className="text-[10px] text-slate-400">target to match</p>
                </div>
              </div>

              <div>
                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">Competitor Pages on &ldquo;{effectiveKeyword}&rdquo;</p>
                <ul className="space-y-2">
                  {insights.competitor.pages.slice(0, 6).map((p) => (
                    <li key={`${p.competitorDomain}-${p.url}`} className="flex items-center gap-3 py-2 px-3 bg-slate-50/50 rounded-lg">
                      <span className="text-[10px] font-bold text-slate-500 bg-slate-100 rounded px-2 py-0.5 shrink-0">{p.competitorDomain}</span>
                      <a href={p.url} target="_blank" rel="noreferrer" className="text-xs font-mono text-brand-600 truncate flex-1 hover:underline" title={p.url}>
                        {new URL(p.url).pathname}
                      </a>
                      {p.title && <span className="text-[11px] text-slate-500 truncate max-w-[200px]" title={p.title}>{p.title}</span>}
                      {typeof p.wordCount === "number" && p.wordCount > 0 && (
                        <span className="text-[10px] text-slate-400 shrink-0">~{p.wordCount.toLocaleString()}w</span>
                      )}
                    </li>
                  ))}
                </ul>
                <p className="text-[11px] text-slate-500 mt-3">
                  Aim for depth matching or exceeding the median ({insights.competitor.medianWordCount ? `${insights.competitor.medianWordCount.toLocaleString()} words` : "competitor-level detail"}) and cover angles these pages miss to win the ranking battle.
                </p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* ── 2. Local Inputs ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <MapPin className="w-4 h-4 text-brand-600" />
          <h2 className="font-semibold text-slate-800 text-sm">Local Inputs</h2>
          <span className="ml-auto text-xs text-slate-400">Auto-filled from brand profile</span>
        </div>
        <div className="px-6 py-5 grid grid-cols-1 sm:grid-cols-2 gap-4">

          {/* City */}
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-medium text-slate-600">City</label>
            <input
              value={city}
              onChange={(e) => setCity(e.target.value)}
              placeholder="e.g. Austin"
              className="rounded-lg border border-slate-200 px-3 py-2.5 text-sm text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
            />
          </div>

          {/* Service */}
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-medium text-slate-600">Service</label>
            <input
              value={service}
              onChange={(e) => setService(e.target.value)}
              placeholder="e.g. HVAC Repair"
              className="rounded-lg border border-slate-200 px-3 py-2.5 text-sm text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
            />
          </div>

          {/* Brand */}
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-medium text-slate-600">Brand Name</label>
            <input
              value={brand}
              onChange={(e) => setBrand(e.target.value)}
              placeholder="e.g. ComfortPro HVAC"
              className="rounded-lg border border-slate-200 px-3 py-2.5 text-sm text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
            />
          </div>

          {/* CTA */}
          <div className="flex flex-col gap-1.5">
            <label className="text-xs font-medium text-slate-600">CTA / Offer</label>
            <input
              value={cta}
              onChange={(e) => setCta(e.target.value)}
              placeholder="e.g. Get a free inspection today"
              className="rounded-lg border border-slate-200 px-3 py-2.5 text-sm text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
            />
          </div>

        </div>
      </div>

      {/* ── 3. Keyword Strategy ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <Search className="w-4 h-4 text-brand-600" />
          <h2 className="font-semibold text-slate-800 text-sm">Keyword Strategy</h2>
        </div>
        {kwData ? (
          <div className="px-6 py-5 space-y-5">
            {kwData.primary && (
              <div>
                <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Primary Keyword</p>
                <div className="flex items-center gap-3">
                  <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand-50 border border-brand-100 text-sm font-semibold text-brand-700">{kwData.primary.keyword}</span>
                  {kwData.primary.searchVolume != null && <span className="text-xs text-slate-500">{kwData.primary.searchVolume.toLocaleString()} vol/mo</span>}
                  {kwData.primary.difficulty != null && <span className={`text-xs font-bold ${kwData.primary.difficulty > 60 ? "text-red-500" : kwData.primary.difficulty > 30 ? "text-amber-600" : "text-green-600"}`}>Diff: {kwData.primary.difficulty}</span>}
                  {kwData.source === "ai_estimated" && <span className="text-[9px] text-slate-400 italic">AI estimated</span>}
                </div>
              </div>
            )}
            {kwData.secondary.length > 0 && (
              <div>
                <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Secondary Keywords</p>
                <div className="flex flex-wrap gap-2">
                  {kwData.secondary.map((k) => (
                    <span key={k.keyword} className="px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 text-xs font-medium border border-slate-200" title={`Vol: ${k.searchVolume ?? "?"} · Diff: ${k.difficulty ?? "?"}`}>{k.keyword}</span>
                  ))}
                </div>
              </div>
            )}
            {kwData.longTail.length > 0 && (
              <div>
                <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Long-Tail Opportunities</p>
                <ul className="space-y-1.5">{kwData.longTail.map((kw) => <li key={kw} className="flex items-start gap-2 text-sm text-slate-700"><span className="mt-1 w-1.5 h-1.5 rounded-full bg-brand-400 shrink-0" />{kw}</li>)}</ul>
              </div>
            )}
            {kwData.questions.length > 0 && (
              <div>
                <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">People Also Ask</p>
                <ul className="space-y-1.5">{kwData.questions.map((q) => <li key={q} className="flex items-start gap-2 text-sm text-slate-700"><span className="mt-1 w-1.5 h-1.5 rounded-full bg-violet-400 shrink-0" />{q}</li>)}</ul>
              </div>
            )}
          </div>
        ) : !DEV_MOCK_ENABLED ? (
          <div className="px-6 py-8 text-center">
            <Search className="w-10 h-10 text-slate-200 mx-auto mb-3" />
            <p className="text-sm font-semibold text-slate-700 mb-1">Keyword Research</p>
            <p className="text-xs text-slate-500 max-w-sm mx-auto mb-4">
              Enter a service and city above, then research keywords to get volume, difficulty, related terms, and question keywords.
            </p>
            <button onClick={fetchKeywordData} disabled={kwLoading || (!service && !city)} className="inline-flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700 disabled:opacity-50">
              {kwLoading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Search className="w-3.5 h-3.5" />}
              {kwLoading ? "Researching…" : "Research Keywords"}
            </button>
          </div>
        ) : (
        <div className="px-6 py-5 space-y-5">

          {/* Primary keyword */}
          <div>
            <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">
              Primary Keyword
            </p>
            <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand-50 border border-brand-100 text-sm font-semibold text-brand-700">
              {KEYWORD_STRATEGY.primary}
            </span>
          </div>

          {/* Secondary keywords */}
          <div>
            <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">
              Secondary Keywords
            </p>
            <div className="flex flex-wrap gap-2">
              {KEYWORD_STRATEGY.secondary.map((kw) => (
                <span
                  key={kw}
                  className="px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 text-xs font-medium border border-slate-200"
                >
                  {kw}
                </span>
              ))}
            </div>
          </div>

          {/* Long-tail */}
          <div>
            <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">
              Long-Tail Keyword Opportunities
            </p>
            <ul className="space-y-1.5">
              {KEYWORD_STRATEGY.longTail.map((kw) => (
                <li key={kw} className="flex items-start gap-2 text-sm text-slate-700">
                  <span className="mt-1 w-1.5 h-1.5 rounded-full bg-brand-400 shrink-0" />
                  {kw}
                </li>
              ))}
            </ul>
          </div>

          {/* AI / conversational phrases */}
          <div>
            <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">
              AI / Conversational Search Phrases
            </p>
            <ul className="space-y-1.5">
              {KEYWORD_STRATEGY.aiPhrases.map((phrase) => (
                <li key={phrase} className="flex items-start gap-2 text-sm text-slate-700">
                  <span className="mt-1 w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0" />
                  {phrase}
                </li>
              ))}
            </ul>
            <p className="text-xs text-slate-400 mt-3 leading-relaxed">
              These phrases mirror how real users ask questions to AI tools like ChatGPT, Perplexity, and Google SGE.
              Including them in your content improves AI-search visibility.
            </p>
          </div>

        </div>
        )}
      </div>

      {/* ── 4. Content Output ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">

        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <Sparkles className="w-4 h-4 text-brand-600" />
          <h2 className="font-semibold text-slate-800 text-sm">Content Output</h2>
        </div>

        <div className="px-6 py-5 space-y-4">

          {/* Output controls */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pb-4 border-b border-slate-100">
            <div className="flex flex-col gap-1.5">
              <label className="text-xs font-medium text-slate-600">Tone</label>
              <select
                value={outputTone}
                onChange={(e) => setOutputTone(e.target.value)}
                className="rounded-lg border border-slate-200 px-3 py-2.5 text-sm text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
              >
                <option>Professional</option>
                <option>Conversational</option>
                <option>Persuasive</option>
              </select>
            </div>
            <div className="flex flex-col gap-1.5">
              <label className="text-xs font-medium text-slate-600">Humanization Level</label>
              <select
                value={humanizationLevel}
                onChange={(e) => setHumanizationLevel(e.target.value)}
                className="rounded-lg border border-slate-200 px-3 py-2.5 text-sm text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
              >
                <option>Low</option>
                <option>Medium</option>
                <option>High</option>
              </select>
              <p className="text-xs text-slate-400 leading-relaxed">
                Higher humanization makes content feel more natural and less robotic.
              </p>
            </div>
          </div>

          {/* Humanization toggle */}
          <div className="flex items-start justify-between gap-4 flex-wrap pb-4 border-b border-slate-100">
            <div>
              <div className="flex items-center gap-3">
                <div className="flex items-center bg-slate-100 rounded-lg p-1 gap-1">
                  <button
                    onClick={() => setMode("standard")}
                    className={`px-4 py-1.5 rounded-md text-xs font-semibold transition-colors ${
                      mode === "standard"
                        ? "bg-white text-slate-800 shadow-sm"
                        : "text-slate-500 hover:text-slate-700"
                    }`}
                  >
                    Standard
                  </button>
                  <button
                    onClick={() => setMode("humanized")}
                    className={`px-4 py-1.5 rounded-md text-xs font-semibold transition-colors ${
                      mode === "humanized"
                        ? "bg-white text-brand-600 shadow-sm"
                        : "text-slate-500 hover:text-slate-700"
                    }`}
                  >
                    Humanized
                  </button>
                </div>
                <select
                  value={outputTone}
                  onChange={(e) => setOutputTone(e.target.value)}
                  className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-700 bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
                >
                  <option>Professional</option>
                  <option>Conversational</option>
                  <option>Persuasive</option>
                </select>
              </div>
              <p className="text-xs text-slate-400 mt-2">
                Humanized content is written to feel more natural, conversational, and less robotic.
              </p>
              {mode === "humanized" && (
                <p className="text-xs text-brand-600 font-medium mt-1">
                  Humanized SEO content keeps structure strong while making the writing feel more natural.
                </p>
              )}
            </div>

            <div className="flex items-center gap-2">
              <button
                onClick={handleCopy}
                className={`flex items-center gap-1.5 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
                  copied
                    ? "bg-green-50 text-green-700 border-green-200"
                    : "bg-white text-slate-600 border-slate-200 hover:bg-slate-50"
                }`}
              >
                {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                {copied ? "Copied!" : "Copy"}
              </button>
              <button
                onClick={handleRegenerate}
                disabled={regenerating}
                className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-brand-600 bg-brand-600 text-white text-xs font-medium hover:bg-brand-700 disabled:opacity-60 disabled:cursor-not-allowed transition-colors"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${regenerating ? "animate-spin" : ""}`} />
                {regenerating ? "Regenerating…" : "Regenerate"}
              </button>
            </div>
          </div>

          {/* Structured content preview */}
          <div className="relative">
            {regenerating && (
              <div className="absolute inset-0 bg-white/70 rounded-lg z-10 flex items-center justify-center">
                <div className="flex items-center gap-2 text-sm text-slate-500">
                  <RefreshCw className="w-4 h-4 animate-spin text-brand-600" />
                  Generating new content…
                </div>
              </div>
            )}

            {generatedContent ? (
              // Live AI output — rendered as Markdown via <pre>. A
              // Markdown component would be nicer but the brief pages
              // intentionally keep zero new deps; the copy button and
              // downstream exports all read the raw string anyway.
              <div className="rounded-lg border border-slate-200 bg-slate-50 px-5 py-4 max-h-[640px] overflow-y-auto">
                <pre className="whitespace-pre-wrap font-sans text-sm text-slate-800 leading-relaxed">{generatedContent}</pre>
                {generateError && (
                  <p className="mt-3 text-xs text-red-600">{generateError}</p>
                )}
              </div>
            ) : !DEV_MOCK_ENABLED ? (
              <div className="rounded-lg border border-slate-200 bg-slate-50 px-6 py-10 text-center">
                <div className="w-12 h-12 rounded-2xl bg-violet-50 border border-violet-200 flex items-center justify-center mx-auto mb-3">
                  <Sparkles className="w-6 h-6 text-violet-400" />
                </div>
                <h3 className="text-sm font-bold text-slate-700 mb-1">AI Content Generation</h3>
                <p className="text-xs text-slate-500 max-w-sm mx-auto leading-relaxed mb-4">
                  Click <span className="font-semibold text-slate-700">Regenerate</span> to build a publication-ready SEO draft — H1/H2 hierarchy, meta tags, body sections, FAQ, and CTA — using your brief inputs above.
                </p>
                {generateError && (
                  <p className="text-xs text-red-600 mb-2">{generateError}</p>
                )}
                <button
                  onClick={handleRegenerate}
                  disabled={regenerating || !effectiveKeyword}
                  className="inline-flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700 disabled:opacity-50"
                >
                  {regenerating ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
                  {regenerating ? "Generating…" : "Generate Content"}
                </button>
              </div>
            ) : (
            <div className="rounded-lg border border-slate-200 bg-slate-50 divide-y divide-slate-200 max-h-[640px] overflow-y-auto">
              {MOCK_BLOCKS[mode].map((rawBlock) => {
                const block = schemaOverrides[rawBlock.id] !== undefined ? { ...rawBlock, content: schemaOverrides[rawBlock.id] } : rawBlock;
                return (
                <div key={block.id} className="px-5 py-4">

                  {/* Type label pill */}
                  <span
                    className={`inline-block text-[10px] font-bold uppercase tracking-widest px-2 py-0.5 rounded mb-2.5 ${blockPillClass(block.type)}`}
                  >
                    {block.label}
                  </span>

                  {/* H1 */}
                  {block.type === "h1" && (
                    <p className="text-lg font-bold text-slate-900 leading-snug">
                      {block.content}
                    </p>
                  )}

                  {/* H2 */}
                  {block.type === "h2" && (
                    <p className="text-base font-bold text-slate-800 leading-snug">
                      {block.content}
                    </p>
                  )}

                  {/* H3 */}
                  {block.type === "h3" && (
                    <p className="text-sm font-semibold text-slate-700 leading-snug">
                      {block.content}
                    </p>
                  )}

                  {/* Body copy */}
                  {block.type === "body" && (
                    <p className="text-sm text-slate-600 leading-relaxed">
                      {block.content}
                    </p>
                  )}

                  {/* Bullet list */}
                  {block.type === "bullets" && block.items && (
                    <ul className="space-y-1.5 mt-1">
                      {block.items.map((item, i) => (
                        <li key={i} className="flex items-start gap-2 text-sm text-slate-600">
                          <span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-brand-500 shrink-0" />
                          {item}
                        </li>
                      ))}
                    </ul>
                  )}

                  {/* CTA */}
                  {block.type === "cta" && (
                    <div className="space-y-2">
                      <p className="text-sm text-slate-700 leading-relaxed">
                        {block.content}
                      </p>
                      <div className="flex flex-wrap gap-2 pt-1">
                        <span className="inline-flex items-center px-3 py-1.5 rounded-md bg-brand-600 text-white text-xs font-semibold">
                          Book Online — Free Estimate
                        </span>
                        <span className="inline-flex items-center px-3 py-1.5 rounded-md bg-white border border-brand-200 text-brand-700 text-xs font-semibold">
                          Call (512) 555-0192
                        </span>
                      </div>
                    </div>
                  )}

                  {/* FAQ list */}
                  {block.type === "faq" && block.faq && (
                    <ul className="space-y-2.5 mt-1">
                      {block.faq.map((item, i) => (
                        <li
                          key={i}
                          className="bg-white rounded-lg border border-slate-200 px-4 py-3"
                        >
                          <p className="text-xs font-semibold text-slate-800 mb-1.5">
                            Q: {item.q}
                          </p>
                          <p className="text-xs text-slate-600 leading-relaxed">
                            A: {item.a}
                          </p>
                        </li>
                      ))}
                    </ul>
                  )}

                  {/* Meta Title / Meta Description */}
                  {block.type === "meta" && (
                    <p className="text-sm text-slate-700 leading-relaxed font-mono bg-white border border-slate-200 rounded-md px-3 py-2">
                      {block.content}
                    </p>
                  )}

                  {/* Schema JSON-LD — editable */}
                  {block.type === "schema" && (
                    <SchemaCodeEditor
                      value={block.content || ""}
                      onChange={(v) => updateBlock(block.id, v)}
                      originalValue={originalSchemaRef.current}
                      showReset
                      height="h-56"
                    />
                  )}

                </div>
                ); })}
            </div>
            )}
          </div>

          {DEV_MOCK_ENABLED && (
            <p className="text-xs text-amber-600">
              Dev mock mode: preview blocks are placeholder content. Real generation requires an AI integration.
            </p>
          )}

        </div>
      </div>

      {/* ── Humanization Score ── */}
      {DEV_MOCK_ENABLED && (
        <HumanizationPanel
          content={sectionsToMarkdown(MOCK_BLOCKS[mode])}
        />
      )}

      {/* ── 5. Internal Linking ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <Link2 className="w-4 h-4 text-brand-600" />
          <h2 className="font-semibold text-slate-800 text-sm">Internal Linking Opportunities</h2>
          <span className="ml-auto text-xs text-slate-400">
            {(backendLinks || (DEV_MOCK_ENABLED ? INTERNAL_LINKS : [])).length} suggested links
          </span>
        </div>

        {(backendLinks || (DEV_MOCK_ENABLED ? INTERNAL_LINKS : [])).length === 0 ? (
          <div className="px-6 py-8 text-center">
            <Link2 className="w-10 h-10 text-slate-200 mx-auto mb-3" />
            <p className="text-sm font-semibold text-slate-700 mb-1">No internal linking data yet</p>
            <p className="text-xs text-slate-500 max-w-sm mx-auto">Run a technical audit to discover internal linking opportunities based on your site&apos;s crawled pages.</p>
          </div>
        ) : (<>
        {/* Column headers */}
        <div className="hidden sm:grid sm:grid-cols-[1fr_160px_1fr] gap-4 px-6 py-2.5 bg-slate-50 border-b border-slate-100 text-[10px] font-bold uppercase tracking-widest text-slate-400">
          <span>Anchor Text</span>
          <span>Target Page</span>
          <span>Why This Link</span>
        </div>

        {/* Service-based group */}
        <div className="px-6 pt-4 pb-1">
          <div className="flex items-center gap-2 mb-3">
            <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-widest bg-brand-50 text-brand-700 border border-brand-100">
              Service Links
            </span>
            <span className="text-xs text-slate-400">
              {(backendLinks || (DEV_MOCK_ENABLED ? INTERNAL_LINKS : [])).filter(l => l.category === "service").length} links
            </span>
          </div>
          <div className="divide-y divide-slate-100 rounded-lg border border-slate-200 overflow-hidden">
            {(backendLinks || (DEV_MOCK_ENABLED ? INTERNAL_LINKS : [])).filter(l => l.category === "service").map((link, i) => (
              <div key={i} className="grid grid-cols-1 sm:grid-cols-[1fr_160px_1fr] gap-3 px-4 py-3 hover:bg-slate-50 transition-colors">
                <p className="text-sm font-semibold text-brand-700">
                  &ldquo;{link.anchor}&rdquo;
                </p>
                <p className="text-xs text-slate-500 font-mono self-center truncate">
                  {link.targetPage}
                </p>
                <p className="text-xs text-slate-600 leading-relaxed self-center">
                  {link.reason}
                </p>
              </div>
            ))}
          </div>
        </div>

        {/* Location-based group */}
        <div className="px-6 pt-4 pb-4">
          <div className="flex items-center gap-2 mb-3">
            <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-widest bg-sky-50 text-sky-700 border border-sky-100">
              Location Links
            </span>
            <span className="text-xs text-slate-400">
              {(backendLinks || (DEV_MOCK_ENABLED ? INTERNAL_LINKS : [])).filter(l => l.category === "location").length} links
            </span>
          </div>
          <div className="divide-y divide-slate-100 rounded-lg border border-slate-200 overflow-hidden">
            {(backendLinks || (DEV_MOCK_ENABLED ? INTERNAL_LINKS : [])).filter(l => l.category === "location").map((link, i) => (
              <div key={i} className="grid grid-cols-1 sm:grid-cols-[1fr_160px_1fr] gap-3 px-4 py-3 hover:bg-slate-50 transition-colors">
                <p className="text-sm font-semibold text-sky-700">
                  &ldquo;{link.anchor}&rdquo;
                </p>
                <p className="text-xs text-slate-500 font-mono self-center truncate">
                  {link.targetPage}
                </p>
                <p className="text-xs text-slate-600 leading-relaxed self-center">
                  {link.reason}
                </p>
              </div>
            ))}
          </div>
        </div>

        {DEV_MOCK_ENABLED && (
          <div className="px-6 py-3 bg-slate-50 border-t border-slate-100">
            <p className="text-xs text-amber-600">
              Dev mock mode: suggestions are placeholder content. Real recommendations will be generated from your site&apos;s indexed pages and keyword gaps.
            </p>
          </div>
        )}
        </>)}
      </div>

      {/* ── 6. Export ── */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <Download className="w-4 h-4 text-brand-600" />
          <h2 className="font-semibold text-slate-800 text-sm">Export</h2>
        </div>

        <div className="px-6 py-5 space-y-4">

          {/* Export notice (placeholder feedback) */}
          {exportNotice && (
            <div className="flex items-center gap-2 px-3 py-2.5 rounded-lg bg-slate-50 border border-slate-200">
              <Info className="w-3.5 h-3.5 text-slate-500 shrink-0" />
              <p className="text-xs text-slate-600">{exportNotice}</p>
            </div>
          )}

          {/* Save notice */}
          {saveNotice && (
            <div className={`flex items-center gap-2 px-3 py-2.5 rounded-lg border ${saveNotice.includes("Failed") ? "bg-red-50 border-red-200" : "bg-green-50 border-green-200"}`}>
              <Check className={`w-3.5 h-3.5 shrink-0 ${saveNotice.includes("Failed") ? "text-red-500" : "text-green-500"}`} />
              <p className={`text-xs ${saveNotice.includes("Failed") ? "text-red-600" : "text-green-600"}`}>{saveNotice}</p>
            </div>
          )}

          {/* Buttons */}
          <div className="flex flex-wrap gap-3">

            {/* Save to Database */}
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex items-center gap-2 px-4 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50 transition-colors"
            >
              <Save className="w-4 h-4" />
              {saving ? "Saving..." : briefId ? "Save Changes" : "Save Brief"}
            </button>

            {/* Copy to Clipboard — functional */}
            <button
              onClick={handleCopy}
              className={`flex items-center gap-2 px-4 py-2.5 rounded-lg border text-sm font-medium transition-colors ${
                copied
                  ? "bg-green-50 text-green-700 border-green-200"
                  : "bg-white text-slate-700 border-slate-200 hover:bg-slate-50"
              }`}
            >
              {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
              {copied ? "Copied!" : "Copy to Clipboard"}
            </button>

            {/* Export to Google Docs — coming soon */}
            <button
              disabled
              title="Google Docs export coming soon"
              className="flex items-center gap-2 px-4 py-2.5 rounded-lg border border-slate-200 bg-slate-50 text-slate-400 text-sm font-medium cursor-not-allowed"
            >
              <FileText className="w-4 h-4" />
              Export to Google Docs
              <span className="text-[10px] font-semibold bg-slate-100 text-slate-400 rounded-full px-1.5 py-0.5 uppercase tracking-wide ml-1">
                Coming Soon
              </span>
            </button>

          </div>

          {/* What this brief is formatted for */}
          <div className="rounded-lg border border-slate-200 bg-slate-50 px-4 py-4">
            <p className="text-xs font-semibold text-slate-600 mb-2">
              This brief is formatted for:
            </p>
            <ul className="space-y-1">
              {[
                "Proper H1 → H2 → Body Copy hierarchy",
                "FAQ formatting optimised for featured snippets",
                "Long-tail keyword targeting throughout",
                "AI-search friendly structure (LLMO)",
                "Writer handoff — no raw HTML tags",
              ].map((item) => (
                <li key={item} className="flex items-center gap-2 text-xs text-slate-600">
                  <Check className="w-3 h-3 text-green-500 shrink-0" />
                  {item}
                </li>
              ))}
            </ul>
          </div>

        </div>
      </div>

      {/* Inline Schema Markup — scaffolds JSON-LD from the brief's
          title / keyword / mode so the user can copy-paste it into
          their CMS <head> when they publish. Rendered only once
          there's something meaningful to scaffold off (a saved
          briefId OR an effective keyword), so the empty initial
          state doesn't show a half-baked "Generate Schema" button
          with no context to feed it. */}
      {(briefId || effectiveKeyword) && selectedBrand?.id && (
        <BriefSchemaSection
          brandId={selectedBrand?.id}
          briefType="seo"
          title={service || effectiveKeyword || undefined}
          description={kwData?.primary?.keyword ? `Content targeting "${kwData.primary.keyword}" for ${selectedBrand?.name || selectedBrand?.domain || ""}` : undefined}
          keyword={effectiveKeyword || undefined}
          secondaryKeywords={kwData?.secondary?.slice(0, 5).map((k) => k.keyword)}
          mode={mode}
          contentSignal={[service, city, effectiveKeyword].filter(Boolean).join(" ")}
        />
      )}

    </div>
  );
}
