import React, { useState, useEffect, useRef } from "react";
import { createRoot } from "react-dom/client";
import {
  Search,
  Globe,
  MapPin,
  Phone,
  Building2,
  Sparkles,
  CheckCircle2,
  AlertTriangle,
  ShieldCheck,
  ExternalLink,
  RefreshCw,
  Plus,
  Trash2,
  Download,
  LogIn,
  LogOut,
  FileText,
  Activity,
  ChevronRight,
  BarChart3,
  Filter,
  Copy,
  Check,
  Info,
  Layers,
  Eye,
  ArrowUpRight,
  Cpu,
  User,
  ArrowLeft,
  Send,
  Moon,
  Sun,
  X,
  HelpCircle,
  Tag,
  Star,
  MessageSquare,
} from "lucide-react";

function apiPath(path) {
  const normalized = path.startsWith("/") ? path : `/${path}`;
  return normalized.startsWith("/api/") || normalized === "/api" ? normalized : `/api${normalized}`;
}

function authHeaders(token, extra = {}) {
  return {
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
    ...extra,
  };
}


// Platform Icon Badges helper
function PlatformBadge({ platformKey, name }) {
  const getColors = () => {
    switch (platformKey) {
      case "google_maps":
        return "bg-blue-500/10 text-blue-400 border-blue-500/20";
      case "apple_maps":
        return "bg-slate-500/10 text-slate-300 border-slate-500/20";
      case "yelp":
        return "bg-red-500/10 text-red-400 border-red-500/20";
      case "facebook":
      case "instagram":
        return "bg-indigo-500/10 text-indigo-400 border-indigo-500/20";
      case "bing_places":
        return "bg-teal-500/10 text-teal-400 border-teal-500/20";
      case "tripadvisor":
        return "bg-emerald-500/10 text-emerald-400 border-emerald-500/20";
      default:
        return "bg-purple-500/10 text-purple-400 border-purple-500/20";
    }
  };

  return (
    <span
      className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-xs font-medium border ${getColors()}`}
    >
      <Globe className="w-3 h-3 shrink-0" />
      {name}
    </span>
  );
}

// Status Pill helper
function StatusTag({ status }) {
  const map = {
    claimed: { label: "Claimed & Verified", bg: "bg-emerald-500/15 text-emerald-400 border-emerald-500/30" },
    unclaimed: { label: "Unclaimed", bg: "bg-amber-500/15 text-amber-400 border-amber-500/30" },
    needs_verification: { label: "Needs Verification", bg: "bg-blue-500/15 text-blue-400 border-blue-500/30" },
    inconsistent: { label: "Inconsistent NAP", bg: "bg-red-500/15 text-red-400 border-red-500/30" },
    not_found: { label: "Not Discovered", bg: "bg-neutral-500/15 text-neutral-400 border-neutral-500/30" },
    in_progress: { label: "Claim In Progress", bg: "bg-cyan-500/15 text-cyan-400 border-cyan-500/30" },
    ignored: { label: "Ignored", bg: "bg-neutral-600/20 text-neutral-400 border-neutral-600/30" },
    flagged: { label: "Flagged", bg: "bg-purple-500/15 text-purple-400 border-purple-500/30" },
  };

  const current = map[status] || { label: status, bg: "bg-neutral-500/15 text-neutral-400 border-neutral-500/30" };

  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded text-[11px] font-medium border ${current.bg}`}>
      {current.label}
    </span>
  );
}


function AuthScreen({ mode, setMode, onSuccess, oauthError }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(oauthError || "");
  const [pending, setPending] = useState(false);
  const isRegister = mode === "register";

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    setPending(true);
    try {
      const res = await fetch(apiPath(isRegister ? "/api/auth/register" : "/api/auth/login"), {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(isRegister ? { name, email, password } : { email, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error || "Authentication failed");
        return;
      }
      onSuccess(data.user, data.token);
    } catch {
      setError("Network error. Please try again.");
    } finally {
      setPending(false);
    }
  };

  return (
    <div className="min-h-screen w-screen bg-canvas flex items-center justify-center p-6">
      <div className="w-full max-w-md">
        <div className="flex items-center gap-3 mb-6">
          <div className="w-10 h-10 rounded-lg bg-brand-600 flex items-center justify-center text-white">
            <Sparkles className="w-5 h-5" />
          </div>
          <div>
            <h1 className="font-semibold text-lg text-neutral-900 dark:text-white">ListingForge</h1>
            <p className="text-xs text-neutral-500">Local SEO scanner and citation command center</p>
          </div>
        </div>

        <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 shadow-sm">
          <div className="grid grid-cols-2 gap-1 p-1 rounded-lg bg-neutral-100 dark:bg-neutral-900 mb-5">
            <button
              type="button"
              onClick={() => { setMode("login"); setError(""); }}
              className={`py-2 rounded-md text-xs font-semibold transition-colors ${
                !isRegister ? "bg-brand-600 text-white" : "text-neutral-600 dark:text-neutral-300"
              }`}
            >
              Login
            </button>
            <button
              type="button"
              onClick={() => { setMode("register"); setError(""); }}
              className={`py-2 rounded-md text-xs font-semibold transition-colors ${
                isRegister ? "bg-brand-600 text-white" : "text-neutral-600 dark:text-neutral-300"
              }`}
            >
              Register
            </button>
          </div>

          <h2 className="text-base font-bold text-neutral-900 dark:text-white mb-1">
            {isRegister ? "Create your workspace" : "Welcome back"}
          </h2>
          <p className="text-xs text-neutral-500 mb-4">
            {isRegister
              ? "Register with email to save businesses, scans, and action plans."
              : "Log in to continue scanning listings and managing citation work."}
          </p>

          <form onSubmit={submit} className="space-y-3">
            {isRegister && (
              <label className="block">
                <span className="text-[11px] font-semibold uppercase tracking-wide text-neutral-500">Full name</span>
                <input
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="mt-1 w-full rounded-md border border-neutral-300 dark:border-neutral-700 bg-canvas px-3 py-2 text-sm outline-none focus:border-brand-500"
                  placeholder="Jordan Hale"
                />
              </label>
            )}
            <label className="block">
              <span className="text-[11px] font-semibold uppercase tracking-wide text-neutral-500">Email</span>
              <input
                required
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="mt-1 w-full rounded-md border border-neutral-300 dark:border-neutral-700 bg-canvas px-3 py-2 text-sm outline-none focus:border-brand-500"
                placeholder="you@company.com"
              />
            </label>
            <label className="block">
              <span className="text-[11px] font-semibold uppercase tracking-wide text-neutral-500">Password</span>
              <input
                required
                type="password"
                minLength={isRegister ? 10 : 1}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="mt-1 w-full rounded-md border border-neutral-300 dark:border-neutral-700 bg-canvas px-3 py-2 text-sm outline-none focus:border-brand-500"
                placeholder={isRegister ? "At least 10 characters, letters + numbers" : "Your password"}
              />
            </label>

            {error ? (
              <div className="text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-md px-3 py-2">
                {error}
              </div>
            ) : null}

            <button
              type="submit"
              disabled={pending}
              className="w-full py-2.5 rounded-md bg-brand-600 hover:bg-brand-700 text-white text-sm font-semibold disabled:opacity-60"
            >
              {pending ? "Please wait..." : isRegister ? "Register" : "Login"}
            </button>
          </form>

          <div className="my-4 flex items-center gap-3 text-[11px] text-neutral-500">
            <div className="h-px flex-1 bg-neutral-200 dark:bg-neutral-800" />
            or continue with
            <div className="h-px flex-1 bg-neutral-200 dark:bg-neutral-800" />
          </div>

          <div className="grid grid-cols-2 gap-2">
            <button
              type="button"
              onClick={() => window.location.assign(apiPath("/api/auth/oauth/start?provider=google"))}
              className="py-2 rounded-md border border-neutral-300 dark:border-neutral-700 text-xs font-medium hover:bg-neutral-100 dark:hover:bg-neutral-800"
            >
              Google
            </button>
            <button
              type="button"
              onClick={() => window.location.assign(apiPath("/api/auth/oauth/start?provider=github"))}
              className="py-2 rounded-md border border-neutral-300 dark:border-neutral-700 text-xs font-medium hover:bg-neutral-100 dark:hover:bg-neutral-800"
            >
              GitHub
            </button>
          </div>

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

function App() {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(localStorage.getItem("lf_token") || "");
  const [businesses, setBusinesses] = useState([]);
  const [selectedBusiness, setSelectedBusiness] = useState(null);
  const [currentScanJob, setCurrentScanJob] = useState(null);
  const [activeTab, setActiveTab] = useState("dashboard"); // 'dashboard' | 'businesses' | 'scan_view' | 'game_plan'
  const [gamePlanTab, setGamePlanTab] = useState("overview"); // 'overview' | 'tasks' | 'listings' | 'chat' | 'export'

  const [isDarkMode, setIsDarkMode] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [isCreateBusOpen, setIsCreateBusOpen] = useState(false);
  const [selectedListingDetail, setSelectedListingDetail] = useState(null);
  const [selectedTaskDetail, setSelectedTaskDetail] = useState(null);

  // Form State
  const [newBus, setNewBus] = useState({
    name: "",
    street_address: "",
    city: "",
    state: "",
    postal_code: "",
    country: "United States",
    phone: "",
    website: "",
    category: "Dental & Healthcare",
    notes: "",
  });

  // Action Plan Data State
  const [listings, setListings] = useState([]);
  const [actionPlan, setActionPlan] = useState(null);
  const [chatMessages, setChatMessages] = useState([
    { role: "assistant", text: "Hello! I am ListingForge AI. Ask me any question about your local business citations, NAP consistency, or ranking strategies." },
  ]);
  const [chatInput, setChatInput] = useState("");
  const [isSendingChat, setIsSendingChat] = useState(false);
  const [copiedText, setCopiedText] = useState("");
  const [authChecked, setAuthChecked] = useState(false);
  const [authMode, setAuthMode] = useState("login");
  const [authError, setAuthError] = useState("");

  const logsEndRef = useRef(null);

  // Initialize
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const err = params.get("auth_error");
    if (err) {
      setAuthError(err === "invalid_state" ? "Sign-in expired. Please try again." : "OAuth sign-in failed.");
      setAuthMode("login");
      window.history.replaceState({}, "", window.location.pathname);
    }
    checkAuth();
  }, []);

  const applySession = (nextUser, nextToken) => {
    setUser(nextUser);
    setToken(nextToken || "");
    if (nextToken) localStorage.setItem("lf_token", nextToken);
    setBusinesses([]);
    setSelectedBusiness(null);
    setCurrentScanJob(null);
    setListings([]);
    setActionPlan(null);
    if (nextUser) fetchBusinesses(nextToken || token);
  };

  const checkAuth = async () => {
    try {
      const res = await fetch(apiPath("/api/auth/me"), {
        credentials: "include",
        headers: authHeaders(token),
      });
      const data = await res.json();
      if (data.user) {
        setUser(data.user);
        fetchBusinesses();
      }
    } catch (err) {
      console.error(err);
    } finally {
      setAuthChecked(true);
    }
  };

  const loginOAuth = (provider) => {
    window.location.assign(apiPath(`/api/auth/oauth/start?provider=${encodeURIComponent(provider)}`));
  };

  const logout = async () => {
    await fetch(apiPath("/api/auth/logout"), {
      method: "POST",
      credentials: "include",
      headers: authHeaders(token),
    });
    setUser(null);
    setToken("");
    localStorage.removeItem("lf_token");
    setBusinesses([]);
    setSelectedBusiness(null);
    setCurrentScanJob(null);
    setListings([]);
    setActionPlan(null);
    setAuthMode("login");
  };

  const fetchBusinesses = async (authToken = token) => {
    try {
      const res = await fetch(apiPath("/api/businesses"), {
        credentials: "include",
        headers: authHeaders(authToken),
      });
      const data = await res.json();
      if (data.businesses) {
        setBusinesses(data.businesses);
        if (data.businesses.length > 0 && !selectedBusiness) {
          selectBusiness(data.businesses[0]);
        }
      }
    } catch (err) {
      console.error(err);
    }
  };

  const selectBusiness = async (bus) => {
    setSelectedBusiness(bus);
    if (bus.latest_scan) {
      loadScanDetails(bus.latest_scan.id);
    }
  };

  const handleCreateBusiness = async (e) => {
    e.preventDefault();
    if (!newBus.name) return;
    setIsLoading(true);
    try {
      const res = await fetch(apiPath("/api/businesses"), {
        method: "POST",
        credentials: "include",
        headers: authHeaders(token, { "Content-Type": "application/json" }),
        body: JSON.stringify(newBus),
      });
      const data = await res.json();
      if (data.business) {
        setIsCreateBusOpen(false);
        setNewBus({
          name: "",
          street_address: "",
          city: "",
          state: "",
          postal_code: "",
          country: "United States",
          phone: "",
          website: "",
          category: "Dental & Healthcare",
          notes: "",
        });
        await fetchBusinesses();
        selectBusiness(data.business);
        triggerScan(data.business.id);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

  const triggerScan = async (busId) => {
    setIsLoading(true);
    try {
      const res = await fetch(apiPath(`/api/businesses/${busId}/scan`), {
        method: "POST",
        credentials: "include",
        headers: authHeaders(token),
      });
      const data = await res.json();
      if (data.scanJobId) {
        setActiveTab("scan_view");
        startScanStream(data.scanJobId);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

  const startScanStream = (scanJobId) => {
    const streamUrl = apiPath(`/api/scans/${scanJobId}/stream`) + `?token=${encodeURIComponent(token)}`;
    const eventSource = new EventSource(streamUrl);

    eventSource.addEventListener("INIT", (e) => {
      const data = JSON.parse(e.data);
      setCurrentScanJob(data.scanJob);
    });

    eventSource.addEventListener("PROGRESS", (e) => {
      const data = JSON.parse(e.data);
      setCurrentScanJob((prev) => ({
        ...prev,
        ...data,
      }));

      if (data.status === "completed") {
        eventSource.close();
        loadScanDetails(scanJobId);
      }
    });

    return () => eventSource.close();
  };

  const loadScanDetails = async (scanJobId) => {
    try {
      // 1. Fetch scan job
      const scanRes = await fetch(apiPath(`/api/scans/${scanJobId}`), {
        credentials: "include",
        headers: authHeaders(token),
      });
      const scanData = await scanRes.json();
      if (scanData.scanJob) {
        setCurrentScanJob(scanData.scanJob);
      }

      // 2. Fetch listings
      const listRes = await fetch(apiPath(`/api/scans/${scanJobId}/listings`), {
        credentials: "include",
        headers: authHeaders(token),
      });
      const listData = await listRes.json();
      if (listData.listings) {
        setListings(listData.listings);
      }

      // 3. Fetch Action Plan
      const planRes = await fetch(apiPath(`/api/scans/${scanJobId}/action-plan`), {
        credentials: "include",
        headers: authHeaders(token),
      });
      const planData = await planRes.json();
      if (planData.actionPlan) {
        setActionPlan(planData.actionPlan);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const updateListingStatus = async (listingId, newStatus) => {
    try {
      await fetch(apiPath(`/api/listings/${listingId}/status`), {
        method: "PUT",
        credentials: "include",
        headers: authHeaders(token, { "Content-Type": "application/json" }),
        body: JSON.stringify({ status: newStatus }),
      });

      setListings((prev) =>
        prev.map((l) => (l.id === listingId ? { ...l, user_status: newStatus } : l))
      );
    } catch (err) {
      console.error(err);
    }
  };

  const sendChatMessage = async (e) => {
    e.preventDefault();
    if (!chatInput.trim() || !currentScanJob) return;

    const userMsg = chatInput;
    setChatInput("");
    setChatMessages((prev) => [...prev, { role: "user", text: userMsg }]);
    setIsSendingChat(true);

    try {
      const res = await fetch(apiPath(`/api/scans/${currentScanJob.id}/chat`), {
        method: "POST",
        credentials: "include",
        headers: authHeaders(token, { "Content-Type": "application/json" }),
        body: JSON.stringify({ message: userMsg }),
      });
      const data = await res.json();
      if (data.reply) {
        setChatMessages((prev) => [...prev, { role: "assistant", text: data.reply }]);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsSendingChat(false);
    }
  };

  const copyToClipboard = (text, label) => {
    navigator.clipboard.writeText(text);
    setCopiedText(label);
    setTimeout(() => setCopiedText(""), 2000);
  };

  const toggleTheme = () => {
    const nextDark = !isDarkMode;
    setIsDarkMode(nextDark);
    if (nextDark) {
      document.documentElement.classList.add("dark");
      document.documentElement.classList.remove("light");
    } else {
      document.documentElement.classList.remove("dark");
      document.documentElement.classList.add("light");
    }
  };

  if (!authChecked) {
    return (
      <div className="h-screen w-screen bg-canvas flex items-center justify-center text-sm text-neutral-500">
        Loading ListingForge...
      </div>
    );
  }

  if (!user) {
    return (
      <AuthScreen
        mode={authMode}
        setMode={setAuthMode}
        oauthError={authError}
        onSuccess={(nextUser, nextToken) => applySession(nextUser, nextToken)}
      />
    );
  }

  return (
    <div className="flex h-screen w-screen overflow-hidden bg-canvas text-neutral-900 dark:text-neutral-100">
      {/* SIDEBAR */}
      <aside className="w-64 shrink-0 border-r border-neutral-200 dark:border-neutral-800 bg-surface flex flex-col justify-between select-none">
        <div>
          {/* LOGO */}
          <div className="p-4 border-b border-neutral-200 dark:border-neutral-800 flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div className="w-8 h-8 rounded-lg bg-brand-600 flex items-center justify-center text-white shadow-sm font-bold">
                <Sparkles className="w-5 h-5 text-white" />
              </div>
              <div>
                <h1 className="font-semibold text-base leading-tight tracking-tight text-neutral-900 dark:text-white">
                  ListingForge
                </h1>
                <p className="text-[11px] text-neutral-500 font-medium">Local SEO Crawler & LLM</p>
              </div>
            </div>
          </div>

          {/* NAV ITEMS */}
          <nav className="p-2 space-y-1">
            <button
              onClick={() => setActiveTab("dashboard")}
              className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-md text-xs font-medium transition-colors ${
                activeTab === "dashboard"
                  ? "bg-brand-500/10 text-brand-600 dark:text-brand-fg font-semibold"
                  : "text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800/50"
              }`}
            >
              <Activity className="w-4 h-4" />
              Dashboard & Overview
            </button>

            <button
              onClick={() => setActiveTab("businesses")}
              className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-md text-xs font-medium transition-colors ${
                activeTab === "businesses"
                  ? "bg-brand-500/10 text-brand-600 dark:text-brand-fg font-semibold"
                  : "text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800/50"
              }`}
            >
              <Building2 className="w-4 h-4" />
              Saved Businesses
              <span className="ml-auto bg-neutral-200 dark:bg-neutral-800 px-1.5 py-0.5 rounded text-[10px] tabular-nums font-mono">
                {businesses.length}
              </span>
            </button>

            {currentScanJob && (
              <button
                onClick={() => setActiveTab("scan_view")}
                className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-md text-xs font-medium transition-colors ${
                  activeTab === "scan_view"
                    ? "bg-brand-500/10 text-brand-600 dark:text-brand-fg font-semibold"
                    : "text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800/50"
                }`}
              >
                <Cpu className="w-4 h-4 text-brand-500" />
                Live Scanner Monitor
                {currentScanJob.status === "running" && (
                  <span className="ml-auto flex h-2 w-2 relative">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
                    <span className="relative inline-flex rounded-full h-2 w-2 bg-brand-500"></span>
                  </span>
                )}
              </button>
            )}

            {actionPlan && (
              <button
                onClick={() => setActiveTab("game_plan")}
                className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-md text-xs font-medium transition-colors ${
                  activeTab === "game_plan"
                    ? "bg-brand-500/10 text-brand-600 dark:text-brand-fg font-semibold"
                    : "text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800/50"
                }`}
              >
                <Sparkles className="w-4 h-4 text-emerald-400" />
                AI Game Plan
              </button>
            )}
          </nav>

          {/* ACTIVE BUSINESS CARD */}
          {selectedBusiness && (
            <div className="m-3 p-3 rounded-lg border border-neutral-200 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-900/40">
              <div className="flex items-center justify-between mb-1.5">
                <span className="text-[10px] uppercase tracking-wider text-neutral-500 font-semibold">Active Business</span>
                <span className="text-[10px] text-brand-500 font-mono">{selectedBusiness.category}</span>
              </div>
              <h4 className="font-semibold text-xs text-neutral-900 dark:text-white truncate">{selectedBusiness.name}</h4>
              <p className="text-[11px] text-neutral-500 truncate mt-0.5">{selectedBusiness.city}, {selectedBusiness.state}</p>
              
              <button
                onClick={() => triggerScan(selectedBusiness.id)}
                disabled={isLoading}
                className="mt-2.5 w-full inline-flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded text-xs font-medium bg-brand-600 hover:bg-brand-700 text-white transition-colors shadow-xs"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${isLoading ? "animate-spin" : ""}`} />
                Launch Scanner
              </button>
            </div>
          )}
        </div>

        {/* BOTTOM USER & THEME CONTROLS */}
        <div className="p-3 border-t border-neutral-200 dark:border-neutral-800 space-y-2">
          <div className="flex items-center justify-between pt-1">
            <div className="flex items-center gap-2 min-w-0">
              <div className="w-7 h-7 rounded-full bg-brand-600/20 text-brand-400 border border-brand-500/30 flex items-center justify-center text-xs font-bold shrink-0">
                {user?.name?.[0] || "U"}
              </div>
              <div className="min-w-0">
                <p className="text-xs font-medium text-neutral-900 dark:text-white truncate">{user?.name || "Account"}</p>
                <p className="text-[10px] text-neutral-500 truncate">{user?.email || ""}</p>
              </div>
            </div>

            <div className="flex items-center gap-1">
              <button
                onClick={toggleTheme}
                title="Toggle Light/Dark Theme"
                className="p-1.5 rounded hover:bg-neutral-100 dark:hover:bg-neutral-800 text-neutral-500"
              >
                {isDarkMode ? <Sun className="w-4 h-4 text-amber-400" /> : <Moon className="w-4 h-4" />}
              </button>
              <button
                onClick={logout}
                title="Sign out"
                className="p-1.5 rounded hover:bg-neutral-100 dark:hover:bg-neutral-800 text-neutral-500 hover:text-red-400"
              >
                <LogOut className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </aside>

      {/* MAIN CONTENT AREA */}
      <main className="flex-1 overflow-y-auto bg-canvas flex flex-col">
        {/* TOPBAR */}
        <header className="h-12 border-b border-neutral-200 dark:border-neutral-800 bg-surface px-6 flex items-center justify-between shrink-0 select-none">
          <div className="flex items-center gap-3">
            <span className="text-xs text-neutral-500">ListingForge Platform</span>
            <span className="text-neutral-400">/</span>
            <span className="text-xs font-semibold text-neutral-900 dark:text-white capitalize">
              {activeTab.replace("_", " ")}
            </span>
          </div>

          <div className="flex items-center gap-3">
            {user.provider === "demo" ? (
              <div className="flex items-center gap-2">
                <button
                  onClick={async () => {
                    await fetch(apiPath("/api/auth/logout"), {
                      method: "POST",
                      credentials: "include",
                      headers: authHeaders(token),
                    });
                    localStorage.removeItem("lf_token");
                    setToken("");
                    setUser(null);
                    setAuthMode("login");
                  }}
                  className="px-3 py-1.5 text-xs font-semibold rounded-md border border-neutral-300 dark:border-neutral-700 hover:bg-neutral-100 dark:hover:bg-neutral-800"
                >
                  Login
                </button>
                <button
                  onClick={async () => {
                    await fetch(apiPath("/api/auth/logout"), {
                      method: "POST",
                      credentials: "include",
                      headers: authHeaders(token),
                    });
                    localStorage.removeItem("lf_token");
                    setToken("");
                    setUser(null);
                    setAuthMode("register");
                  }}
                  className="px-3 py-1.5 text-xs font-semibold rounded-md bg-white text-neutral-900 border border-neutral-300 hover:bg-neutral-100"
                >
                  Register
                </button>
              </div>
            ) : null}

            <button
              onClick={() => setIsCreateBusOpen(true)}
              className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white transition-colors shadow-xs"
            >
              <Plus className="w-3.5 h-3.5" />
              New Business Scan
            </button>
          </div>
        </header>

        {/* VIEW 1: DASHBOARD */}
        {activeTab === "dashboard" && (
          <div className="p-6 max-w-7xl mx-auto w-full space-y-6">
            {/* HERO BAR */}
            <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4 p-6 rounded-xl border border-neutral-200 dark:border-neutral-800 bg-surface shadow-xs">
              <div>
                <h2 className="text-xl font-bold tracking-tight text-neutral-900 dark:text-white">
                  Distributed Local SEO & Business Listing Scanner
                </h2>
                <p className="text-xs text-neutral-500 dark:text-neutral-400 mt-1 max-w-2xl">
                  Automatically discover, crawl, and audit your business citations across Google Maps, Apple Maps, Yelp, Facebook, Instagram, Bing, YellowPages, and 10+ major directories.
                </p>
              </div>
              <button
                onClick={() => setIsCreateBusOpen(true)}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white transition-colors shadow-sm shrink-0"
              >
                <Plus className="w-4 h-4" />
                Add Business & Scan
              </button>
            </div>

            {/* KPI CARDS */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-lg p-4">
                <p className="text-[11px] font-semibold uppercase text-neutral-500 tracking-wider">Total Businesses</p>
                <div className="mt-2 flex items-baseline gap-2">
                  <span className="text-2xl font-bold font-mono text-neutral-900 dark:text-white">{businesses.length}</span>
                  <span className="text-xs text-emerald-400 font-medium">Active</span>
                </div>
              </div>

              <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-lg p-4">
                <p className="text-[11px] font-semibold uppercase text-neutral-500 tracking-wider">Total Citations Discovered</p>
                <div className="mt-2 flex items-baseline gap-2">
                  <span className="text-2xl font-bold font-mono text-neutral-900 dark:text-white">{listings.length}</span>
                  <span className="text-xs text-brand-400 font-medium">Across 13 Platforms</span>
                </div>
              </div>

              <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-lg p-4">
                <p className="text-[11px] font-semibold uppercase text-neutral-500 tracking-wider">NAP Consistency Index</p>
                <div className="mt-2 flex items-baseline gap-2">
                  <span className="text-2xl font-bold font-mono text-emerald-400">
                    {actionPlan ? `${actionPlan.nap_recommendation?.consistency_score ?? 0}%` : "—"}
                  </span>
                  <span className="text-xs text-neutral-500">Google Map Pack Score</span>
                </div>
              </div>

              <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-lg p-4">
                <p className="text-[11px] font-semibold uppercase text-neutral-500 tracking-wider">Pending Action Items</p>
                <div className="mt-2 flex items-baseline gap-2">
                  <span className="text-2xl font-bold font-mono text-amber-400">
                    {actionPlan?.prioritized_tasks?.length || 0}
                  </span>
                  <span className="text-xs text-amber-400/80 font-medium">High Impact</span>
                </div>
              </div>
            </div>

            {/* BUSINESSES TABLE OVERVIEW */}
            <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl overflow-hidden shadow-xs">
              <div className="p-4 border-b border-neutral-200 dark:border-neutral-800 flex items-center justify-between">
                <div>
                  <h3 className="font-semibold text-sm text-neutral-900 dark:text-white">Saved Business Profiles</h3>
                  <p className="text-xs text-neutral-500">Select a business to view scan results or launch a new distributed crawl.</p>
                </div>
                <button
                  onClick={() => setIsCreateBusOpen(true)}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium border border-neutral-300 dark:border-neutral-700 hover:bg-neutral-100 dark:hover:bg-neutral-800"
                >
                  <Plus className="w-3.5 h-3.5" />
                  New Business
                </button>
              </div>

              {businesses.length === 0 ? (
                <div className="p-12 text-center">
                  <Building2 className="w-10 h-10 mx-auto text-neutral-400 mb-3 stroke-1" />
                  <h4 className="font-semibold text-sm">No business profiles created yet</h4>
                  <p className="text-xs text-neutral-500 mt-1 max-w-sm mx-auto">
                    Add your business name, address, phone, and website to launch your first scan.
                  </p>
                  <div className="mt-4 flex items-center justify-center gap-3">
                    <button
                      onClick={() => setIsCreateBusOpen(true)}
                      className="px-3.5 py-2 rounded-md text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white"
                    >
                      Create Business Profile
                    </button>
                  </div>
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-neutral-50 dark:bg-neutral-900/50 text-neutral-500 uppercase tracking-wider font-semibold border-b border-neutral-200 dark:border-neutral-800">
                      <tr>
                        <th className="px-4 py-3">Business Name</th>
                        <th className="px-4 py-3">Location & Phone</th>
                        <th className="px-4 py-3">Category</th>
                        <th className="px-4 py-3">Last Scan Status</th>
                        <th className="px-4 py-3">NAP Score</th>
                        <th className="px-4 py-3 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-neutral-200 dark:divide-neutral-800">
                      {businesses.map((bus) => (
                        <tr
                          key={bus.id}
                          className={`hover:bg-neutral-50 dark:hover:bg-neutral-900/40 transition-colors cursor-pointer ${
                            selectedBusiness?.id === bus.id ? "bg-brand-500/5" : ""
                          }`}
                          onClick={() => selectBusiness(bus)}
                        >
                          <td className="px-4 py-3.5">
                            <div className="font-semibold text-neutral-900 dark:text-white">{bus.name}</div>
                            {bus.website && (
                              <a
                                href={bus.website}
                                target="_blank"
                                rel="noreferrer"
                                onClick={(e) => e.stopPropagation()}
                                className="text-[11px] text-brand-400 hover:underline inline-flex items-center gap-1 mt-0.5"
                              >
                                {bus.website} <ExternalLink className="w-2.5 h-2.5" />
                              </a>
                            )}
                          </td>
                          <td className="px-4 py-3.5 text-neutral-500">
                            <div>{bus.street_address}, {bus.city}, {bus.state}</div>
                            <div className="font-mono text-[11px] text-neutral-400 mt-0.5">{bus.phone}</div>
                          </td>
                          <td className="px-4 py-3.5">
                            <span className="inline-block px-2 py-0.5 rounded text-[11px] bg-neutral-100 dark:bg-neutral-800 font-medium">
                              {bus.category || "General"}
                            </span>
                          </td>
                          <td className="px-4 py-3.5">
                            {bus.latest_scan ? (
                              <StatusTag status={bus.latest_scan.status} />
                            ) : (
                              <span className="text-neutral-500 text-[11px]">Never scanned</span>
                            )}
                          </td>
                          <td className="px-4 py-3.5 font-mono font-bold text-emerald-400">
                            {bus.latest_scan?.nap_score ? `${bus.latest_scan.nap_score}%` : "—"}
                          </td>
                          <td className="px-4 py-3.5 text-right">
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                selectBusiness(bus);
                                triggerScan(bus.id);
                              }}
                              className="inline-flex items-center gap-1 px-2.5 py-1 rounded text-xs font-medium bg-brand-600 hover:bg-brand-700 text-white transition-colors"
                            >
                              <RefreshCw className="w-3 h-3" />
                              Scan Now
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        )}

        {/* VIEW 2: BUSINESSES LIST */}
        {activeTab === "businesses" && (
          <div className="p-6 max-w-7xl mx-auto w-full space-y-6">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-lg font-bold">Saved Business Locations</h2>
                <p className="text-xs text-neutral-500">Manage business profiles, canonical address records, and scan history.</p>
              </div>
              <button
                onClick={() => setIsCreateBusOpen(true)}
                className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white"
              >
                <Plus className="w-4 h-4" />
                Add Business
              </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {businesses.map((bus) => (
                <div
                  key={bus.id}
                  className={`bg-surface border rounded-xl p-4 flex flex-col justify-between transition-all ${
                    selectedBusiness?.id === bus.id
                      ? "border-brand-500/50 ring-1 ring-brand-500/30"
                      : "border-neutral-200 dark:border-neutral-800 hover:border-neutral-300"
                  }`}
                >
                  <div>
                    <div className="flex items-start justify-between gap-2 mb-2">
                      <span className="px-2 py-0.5 rounded text-[10px] font-medium bg-brand-500/10 text-brand-400 border border-brand-500/20">
                        {bus.category}
                      </span>
                      {bus.latest_scan && <StatusTag status={bus.latest_scan.status} />}
                    </div>

                    <h3 className="font-bold text-sm text-neutral-900 dark:text-white">{bus.name}</h3>
                    
                    <div className="mt-2 space-y-1 text-xs text-neutral-500">
                      <div className="flex items-center gap-1.5">
                        <MapPin className="w-3.5 h-3.5 shrink-0 text-neutral-400" />
                        <span className="truncate">{bus.street_address}, {bus.city}, {bus.state} {bus.postal_code}</span>
                      </div>
                      <div className="flex items-center gap-1.5 font-mono text-[11px]">
                        <Phone className="w-3.5 h-3.5 shrink-0 text-neutral-400" />
                        <span>{bus.phone}</span>
                      </div>
                      <div className="flex items-center gap-1.5 text-brand-400">
                        <Globe className="w-3.5 h-3.5 shrink-0" />
                        <a href={bus.website} target="_blank" rel="noreferrer" className="truncate hover:underline">
                          {bus.website}
                        </a>
                      </div>
                    </div>
                  </div>

                  <div className="mt-4 pt-3 border-t border-neutral-200 dark:border-neutral-800 flex items-center justify-between">
                    <button
                      onClick={() => {
                        selectBusiness(bus);
                        setActiveTab("game_plan");
                      }}
                      className="text-xs text-brand-400 font-medium hover:underline inline-flex items-center gap-1"
                    >
                      View Report <ChevronRight className="w-3 h-3" />
                    </button>

                    <button
                      onClick={() => {
                        selectBusiness(bus);
                        triggerScan(bus.id);
                      }}
                      className="inline-flex items-center gap-1 px-3 py-1.5 rounded text-xs font-semibold bg-brand-600 text-white hover:bg-brand-700"
                    >
                      <RefreshCw className="w-3 h-3" />
                      Run Scan
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* VIEW 3: REAL-TIME SCAN MONITOR */}
        {activeTab === "scan_view" && currentScanJob && (
          <div className="p-6 max-w-5xl mx-auto w-full space-y-6">
            {/* PROGRESS CARD */}
            <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl p-6 shadow-sm space-y-5">
              <div className="flex items-center justify-between">
                <div>
                  <span className="text-[10px] font-bold uppercase tracking-wider text-brand-400">Live Crawl Pipeline</span>
                  <h2 className="text-lg font-bold text-neutral-900 dark:text-white mt-0.5">
                    Scanning {selectedBusiness?.name || "Business"}
                  </h2>
                </div>
                <StatusTag status={currentScanJob.status} />
              </div>

              {/* PROGRESS RING / BAR */}
              <div className="space-y-2">
                <div className="flex items-center justify-between text-xs font-medium">
                  <span className="text-neutral-400">{currentScanJob.current_stage || "Scanning..."}</span>
                  <span className="font-mono text-brand-400 font-bold">{currentScanJob.progress}%</span>
                </div>
                <div className="h-2.5 w-full bg-neutral-200 dark:bg-neutral-800 rounded-full overflow-hidden">
                  <div
                    className="h-full bg-brand-600 transition-all duration-300"
                    style={{ width: `${currentScanJob.progress}%` }}
                  />
                </div>
              </div>

              {/* LIVE METRICS STRIP */}
              <div className="grid grid-cols-3 gap-4 pt-2">
                <div className="p-3 bg-neutral-50 dark:bg-neutral-900/50 rounded-lg border border-neutral-200 dark:border-neutral-800">
                  <div className="text-[10px] uppercase font-semibold text-neutral-500">Citations Found</div>
                  <div className="text-xl font-bold font-mono text-neutral-900 dark:text-white mt-1">
                    {currentScanJob.total_found}
                  </div>
                </div>

                <div className="p-3 bg-neutral-50 dark:bg-neutral-900/50 rounded-lg border border-neutral-200 dark:border-neutral-800">
                  <div className="text-[10px] uppercase font-semibold text-neutral-500">Claimed & Verified</div>
                  <div className="text-xl font-bold font-mono text-emerald-400 mt-1">
                    {currentScanJob.claimed_count}
                  </div>
                </div>

                <div className="p-3 bg-neutral-50 dark:bg-neutral-900/50 rounded-lg border border-neutral-200 dark:border-neutral-800">
                  <div className="text-[10px] uppercase font-semibold text-neutral-500">Action Required</div>
                  <div className="text-xl font-bold font-mono text-amber-400 mt-1">
                    {currentScanJob.unclaimed_count}
                  </div>
                </div>
              </div>
            </div>

            {/* STREAMING LOGS TERMINAL */}
            <div className="bg-neutral-950 border border-neutral-800 rounded-xl overflow-hidden font-mono text-xs">
              <div className="px-4 py-2.5 bg-neutral-900 border-b border-neutral-800 flex items-center justify-between text-neutral-400">
                <div className="flex items-center gap-2">
                  <div className="flex gap-1.5">
                    <span className="w-2.5 h-2.5 rounded-full bg-red-500/80"></span>
                    <span className="w-2.5 h-2.5 rounded-full bg-amber-500/80"></span>
                    <span className="w-2.5 h-2.5 rounded-full bg-emerald-500/80"></span>
                  </div>
                  <span className="text-[11px] font-semibold text-neutral-300 ml-2">crawler_worker_stdout.log</span>
                </div>
                {currentScanJob.status === "completed" && (
                  <button
                    onClick={() => setActiveTab("game_plan")}
                    className="inline-flex items-center gap-1 px-2.5 py-1 rounded bg-emerald-500 text-black text-[11px] font-bold hover:bg-emerald-400"
                  >
                    View AI Game Plan →
                  </button>
                )}
              </div>

              <div className="p-4 h-64 overflow-y-auto space-y-1.5 text-neutral-300">
                {(currentScanJob.logs || []).map((log, idx) => (
                  <div key={idx} className="leading-relaxed">
                    {log.includes("✓") ? (
                      <span className="text-emerald-400 font-medium">{log}</span>
                    ) : log.includes("❌") ? (
                      <span className="text-red-400 font-medium">{log}</span>
                    ) : log.includes("Crawling") ? (
                      <span className="text-brand-400">{log}</span>
                    ) : (
                      <span>{log}</span>
                    )}
                  </div>
                ))}
                <div ref={logsEndRef} />
              </div>
            </div>
          </div>
        )}

        {/* VIEW 4: LLM GAME PLAN & AUDIT REPORT */}
        {activeTab === "game_plan" && actionPlan && (
          <div className="p-6 max-w-7xl mx-auto w-full space-y-6">
            {/* SUB TAB BAR */}
            <div className="border-b border-neutral-200 dark:border-neutral-800 flex items-center justify-between select-none">
              <div className="flex gap-6">
                <button
                  onClick={() => setGamePlanTab("overview")}
                  className={`py-3 text-xs font-semibold border-b-2 transition-colors ${
                    gamePlanTab === "overview"
                      ? "border-brand-500 text-brand-400"
                      : "border-transparent text-neutral-500 hover:text-neutral-300"
                  }`}
                >
                  Game Plan Overview
                </button>
                <button
                  onClick={() => setGamePlanTab("tasks")}
                  className={`py-3 text-xs font-semibold border-b-2 transition-colors flex items-center gap-1.5 ${
                    gamePlanTab === "tasks"
                      ? "border-brand-500 text-brand-400"
                      : "border-transparent text-neutral-500 hover:text-neutral-300"
                  }`}
                >
                  Prioritized Action Tasks
                  <span className="bg-amber-500/20 text-amber-400 px-1.5 py-0.2 rounded text-[10px] font-mono">
                    {actionPlan.prioritized_tasks?.length || 0}
                  </span>
                </button>
                <button
                  onClick={() => setGamePlanTab("listings")}
                  className={`py-3 text-xs font-semibold border-b-2 transition-colors flex items-center gap-1.5 ${
                    gamePlanTab === "listings"
                      ? "border-brand-500 text-brand-400"
                      : "border-transparent text-neutral-500 hover:text-neutral-300"
                  }`}
                >
                  Discovered Listings ({listings.length})
                </button>
                <button
                  onClick={() => setGamePlanTab("chat")}
                  className={`py-3 text-xs font-semibold border-b-2 transition-colors flex items-center gap-1.5 ${
                    gamePlanTab === "chat"
                      ? "border-brand-500 text-brand-400"
                      : "border-transparent text-neutral-500 hover:text-neutral-300"
                  }`}
                >
                  <MessageSquare className="w-3.5 h-3.5" />
                  Ask AI Assistant
                </button>
              </div>

              {/* EXPORT BUTTONS */}
              <div className="flex items-center gap-2 pb-2">
                <a
                  href={apiPath(`/api/scans/${actionPlan.scan_job_id}/export?format=csv`)}
                  download
                  className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded text-xs font-medium border border-neutral-300 dark:border-neutral-700 hover:bg-neutral-800"
                >
                  <Download className="w-3 h-3" /> CSV
                </a>
                <a
                  href={apiPath(`/api/scans/${actionPlan.scan_job_id}/export?format=md`)}
                  download
                  className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded text-xs font-medium border border-neutral-300 dark:border-neutral-700 hover:bg-neutral-800"
                >
                  <Download className="w-3 h-3" /> Markdown Report
                </a>
              </div>
            </div>

            {/* TAB CONTENT 1: OVERVIEW */}
            {gamePlanTab === "overview" && (
              <div className="space-y-6">
                {/* AI EXECUTIVE SUMMARY */}
                <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl p-5 shadow-xs space-y-3">
                  <div className="flex items-center gap-2 text-brand-400 font-bold text-xs uppercase tracking-wider">
                    <Sparkles className="w-4 h-4" />
                    ListingForge AI Executive Summary
                  </div>
                  <p className="text-sm leading-relaxed text-neutral-800 dark:text-neutral-200 font-medium">
                    {actionPlan.summary}
                  </p>
                </div>

                {/* CANONICAL NAP RECOMMENDATION BOX */}
                <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl p-6 shadow-xs space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-bold text-base text-neutral-900 dark:text-white">
                        Standardized Canonical NAP Recommendation
                      </h3>
                      <p className="text-xs text-neutral-500 mt-0.5">
                        Copy and use this exact text across every business directory to eliminate citation penalties.
                      </p>
                    </div>
                    <button
                      onClick={() =>
                        copyToClipboard(
                          `${actionPlan.nap_recommendation.canonical_name}\n${actionPlan.nap_recommendation.canonical_address}\n${actionPlan.nap_recommendation.canonical_phone}\n${actionPlan.nap_recommendation.canonical_website}`,
                          "canonical_nap"
                        )
                      }
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-semibold bg-brand-600/10 text-brand-400 hover:bg-brand-600/20 border border-brand-500/20"
                    >
                      {copiedText === "canonical_nap" ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                      {copiedText === "canonical_nap" ? "Copied!" : "Copy Canonical NAP"}
                    </button>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="p-3.5 bg-neutral-50 dark:bg-neutral-900/50 rounded-lg border border-neutral-200 dark:border-neutral-800">
                      <span className="text-[10px] font-semibold text-neutral-500 uppercase">Official Business Name</span>
                      <div className="font-semibold text-sm text-neutral-900 dark:text-white mt-1">
                        {actionPlan.nap_recommendation.canonical_name}
                      </div>
                    </div>

                    <div className="p-3.5 bg-neutral-50 dark:bg-neutral-900/50 rounded-lg border border-neutral-200 dark:border-neutral-800">
                      <span className="text-[10px] font-semibold text-neutral-500 uppercase">Primary Phone</span>
                      <div className="font-mono font-semibold text-sm text-neutral-900 dark:text-white mt-1">
                        {actionPlan.nap_recommendation.canonical_phone}
                      </div>
                    </div>

                    <div className="p-3.5 bg-neutral-50 dark:bg-neutral-900/50 rounded-lg border border-neutral-200 dark:border-neutral-800">
                      <span className="text-[10px] font-semibold text-neutral-500 uppercase">Canonical Address</span>
                      <div className="font-semibold text-sm text-neutral-900 dark:text-white mt-1">
                        {actionPlan.nap_recommendation.canonical_address}
                      </div>
                    </div>

                    <div className="p-3.5 bg-neutral-50 dark:bg-neutral-900/50 rounded-lg border border-neutral-200 dark:border-neutral-800">
                      <span className="text-[10px] font-semibold text-neutral-500 uppercase">Target Website URL</span>
                      <div className="font-semibold text-sm text-brand-400 mt-1 truncate">
                        {actionPlan.nap_recommendation.canonical_website}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* TAB CONTENT 2: PRIORITIZED TASKS */}
            {gamePlanTab === "tasks" && (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-bold text-base">Prioritized Claim & Link Checklist</h3>
                  <span className="text-xs text-neutral-500">Sorted by strategic importance score</span>
                </div>

                <div className="space-y-3">
                  {(actionPlan.prioritized_tasks || []).map((task) => (
                    <div
                      key={task.id}
                      className="p-5 bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl space-y-3 hover:border-neutral-300 transition-colors"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <div className="flex items-center gap-2">
                          <span
                            className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                              task.priority === "HIGH"
                                ? "bg-red-500/15 text-red-400 border border-red-500/30"
                                : "bg-amber-500/15 text-amber-400 border border-amber-500/30"
                            }`}
                          >
                            {task.priority} PRIORITY
                          </span>
                          <PlatformBadge platformKey={task.platform_key} name={task.platform_name} />
                          <span className="text-xs font-mono text-neutral-400">Score: {task.importance_score}/100</span>
                        </div>

                        <a
                          href={task.claim_url}
                          target="_blank"
                          rel="noreferrer"
                          className="inline-flex items-center gap-1 px-3 py-1.5 rounded text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white transition-colors"
                        >
                          Execute Step <ArrowUpRight className="w-3.5 h-3.5" />
                        </a>
                      </div>

                      <h4 className="font-bold text-sm text-neutral-900 dark:text-white">{task.title}</h4>
                      <p className="text-xs text-neutral-600 dark:text-neutral-400 leading-relaxed">{task.description}</p>

                      <div className="pt-2 border-t border-neutral-200 dark:border-neutral-800/60 flex items-center justify-between text-xs">
                        <span className="text-emerald-400 font-medium">⚡ Impact: {task.estimated_impact}</span>
                        <button
                          onClick={() => setSelectedTaskDetail(task)}
                          className="text-brand-400 font-medium hover:underline inline-flex items-center gap-1"
                        >
                          View Step-by-Step Guide →
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* TAB CONTENT 3: LISTINGS TABLE */}
            {gamePlanTab === "listings" && (
              <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl overflow-hidden shadow-xs">
                <div className="p-4 border-b border-neutral-200 dark:border-neutral-800 flex items-center justify-between">
                  <h3 className="font-bold text-sm">Discovered Listings Inventory</h3>
                  <span className="text-xs text-neutral-500">Click any row to inspect raw crawl snapshot & NAP diff</span>
                </div>

                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-neutral-50 dark:bg-neutral-900/50 text-neutral-500 uppercase tracking-wider font-semibold border-b border-neutral-200 dark:border-neutral-800">
                      <tr>
                        <th className="px-4 py-3">Platform</th>
                        <th className="px-4 py-3">Listing Title & URL</th>
                        <th className="px-4 py-3">Discovered Phone</th>
                        <th className="px-4 py-3">Importance</th>
                        <th className="px-4 py-3">Claim Status</th>
                        <th className="px-4 py-3 text-right">User Tracking</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-neutral-200 dark:divide-neutral-800">
                      {listings.map((l) => (
                        <tr
                          key={l.id}
                          onClick={() => setSelectedListingDetail(l)}
                          className="hover:bg-neutral-50 dark:hover:bg-neutral-900/40 cursor-pointer transition-colors"
                        >
                          <td className="px-4 py-3.5">
                            <PlatformBadge platformKey={l.platform_key} name={l.platform_name} />
                          </td>
                          <td className="px-4 py-3.5">
                            <div className="font-semibold text-neutral-900 dark:text-white">{l.title}</div>
                            <a
                              href={l.url}
                              target="_blank"
                              rel="noreferrer"
                              onClick={(e) => e.stopPropagation()}
                              className="text-[11px] text-brand-400 hover:underline truncate max-w-xs block mt-0.5"
                            >
                              {l.url}
                            </a>
                          </td>
                          <td className="px-4 py-3.5 font-mono text-[11px]">
                            {l.phone || "—"}
                          </td>
                          <td className="px-4 py-3.5 font-mono font-bold text-neutral-300">
                            {l.importance_score}
                          </td>
                          <td className="px-4 py-3.5">
                            <StatusTag status={l.claimed_status} />
                          </td>
                          <td className="px-4 py-3.5 text-right" onClick={(e) => e.stopPropagation()}>
                            <select
                              value={l.user_status}
                              onChange={(e) => updateListingStatus(l.id, e.target.value)}
                              className="bg-neutral-100 dark:bg-neutral-800 border border-neutral-300 dark:border-neutral-700 rounded px-2 py-1 text-xs"
                            >
                              <option value="pending">Pending</option>
                              <option value="claimed">Claimed</option>
                              <option value="in_progress">In Progress</option>
                              <option value="ignored">Ignored</option>
                              <option value="flagged">Flagged</option>
                            </select>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* TAB CONTENT 4: AI CHAT ASSISTANT */}
            {gamePlanTab === "chat" && (
              <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl p-5 space-y-4 max-w-3xl mx-auto">
                <div className="flex items-center gap-2 border-b border-neutral-200 dark:border-neutral-800 pb-3">
                  <Sparkles className="w-5 h-5 text-brand-400" />
                  <div>
                    <h3 className="font-bold text-sm">ListingForge AI Strategy Assistant</h3>
                    <p className="text-xs text-neutral-500">Ask questions about your citation profile or local SEO map pack strategy.</p>
                  </div>
                </div>

                <div className="h-80 overflow-y-auto space-y-3 p-2 font-sans text-xs">
                  {chatMessages.map((msg, idx) => (
                    <div
                      key={idx}
                      className={`p-3 rounded-lg max-w-xl ${
                        msg.role === "user"
                          ? "bg-brand-600 text-white ml-auto"
                          : "bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 mr-auto"
                      }`}
                    >
                      {msg.text}
                    </div>
                  ))}
                </div>

                <form onSubmit={sendChatMessage} className="flex gap-2">
                  <input
                    type="text"
                    value={chatInput}
                    onChange={(e) => setChatInput(e.target.value)}
                    placeholder="Ask about your business listings, verification postcard rules, or local citations..."
                    className="flex-1 bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded-lg px-3 py-2 text-xs focus:outline-none focus:border-brand-500"
                  />
                  <button
                    type="submit"
                    disabled={isSendingChat}
                    className="px-4 py-2 bg-brand-600 hover:bg-brand-700 text-white rounded-lg text-xs font-semibold flex items-center gap-1.5"
                  >
                    <Send className="w-3.5 h-3.5" />
                    Ask
                  </button>
                </form>
              </div>
            )}
          </div>
        )}
      </main>

      {/* MODAL 1: CREATE BUSINESS MODAL */}
      {isCreateBusOpen && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl max-w-lg w-full p-6 space-y-4 shadow-xl">
            <div className="flex items-center justify-between border-b border-neutral-200 dark:border-neutral-800 pb-3">
              <h3 className="font-bold text-base">New Business Scan</h3>
              <button onClick={() => setIsCreateBusOpen(false)} className="text-neutral-400 hover:text-white">
                <X className="w-4 h-4" />
              </button>
            </div>

            <form onSubmit={handleCreateBusiness} className="space-y-3 text-xs">
              <div>
                <label className="block font-medium mb-1">Business Name (Required) *</label>
                <input
                  type="text"
                  required
                  value={newBus.name}
                  onChange={(e) => setNewBus({ ...newBus, name: e.target.value })}
                  placeholder="e.g. Apex Dental Care"
                  className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-medium mb-1">Street Address</label>
                  <input
                    type="text"
                    value={newBus.street_address}
                    onChange={(e) => setNewBus({ ...newBus, street_address: e.target.value })}
                    placeholder="350 Congress Ave"
                    className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="block font-medium mb-1">City</label>
                  <input
                    type="text"
                    value={newBus.city}
                    onChange={(e) => setNewBus({ ...newBus, city: e.target.value })}
                    placeholder="Austin"
                    className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                  />
                </div>
              </div>

              <div className="grid grid-cols-3 gap-3">
                <div>
                  <label className="block font-medium mb-1">State/Province</label>
                  <input
                    type="text"
                    value={newBus.state}
                    onChange={(e) => setNewBus({ ...newBus, state: e.target.value })}
                    placeholder="TX"
                    className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="block font-medium mb-1">Postal Code</label>
                  <input
                    type="text"
                    value={newBus.postal_code}
                    onChange={(e) => setNewBus({ ...newBus, postal_code: e.target.value })}
                    placeholder="78701"
                    className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="block font-medium mb-1">Category</label>
                  <select
                    value={newBus.category}
                    onChange={(e) => setNewBus({ ...newBus, category: e.target.value })}
                    className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                  >
                    <option value="Dental & Healthcare">Dental & Healthcare</option>
                    <option value="Restaurant & Food">Restaurant & Food</option>
                    <option value="Automotive & Repair">Automotive & Repair</option>
                    <option value="Legal & Financial">Legal & Financial</option>
                    <option value="Real Estate">Real Estate</option>
                    <option value="Home Services">Home Services</option>
                    <option value="General Retail">General Retail</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-medium mb-1">Phone Number</label>
                  <input
                    type="text"
                    value={newBus.phone}
                    onChange={(e) => setNewBus({ ...newBus, phone: e.target.value })}
                    placeholder="+1 (512) 555-0144"
                    className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="block font-medium mb-1">Official Website</label>
                  <input
                    type="text"
                    value={newBus.website}
                    onChange={(e) => setNewBus({ ...newBus, website: e.target.value })}
                    placeholder="https://apexdentalaustin.com"
                    className="w-full bg-neutral-50 dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded p-2 focus:border-brand-500 focus:outline-none"
                  />
                </div>
              </div>

              <div className="pt-3 border-t border-neutral-200 dark:border-neutral-800 flex justify-end gap-2">
                <button
                  type="button"
                  onClick={() => setIsCreateBusOpen(false)}
                  className="px-3 py-1.5 rounded border border-neutral-300 dark:border-neutral-700 text-xs font-medium"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isLoading}
                  className="px-4 py-1.5 rounded bg-brand-600 hover:bg-brand-700 text-white text-xs font-semibold"
                >
                  Save & Launch Scanner
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 2: TASK DETAIL MODAL */}
      {selectedTaskDetail && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-surface border border-neutral-200 dark:border-neutral-800 rounded-xl max-w-lg w-full p-6 space-y-4 shadow-xl">
            <div className="flex items-center justify-between border-b border-neutral-200 dark:border-neutral-800 pb-3">
              <h3 className="font-bold text-base">{selectedTaskDetail.title}</h3>
              <button onClick={() => setSelectedTaskDetail(null)} className="text-neutral-400 hover:text-white">
                <X className="w-4 h-4" />
              </button>
            </div>

            <p className="text-xs text-neutral-400">{selectedTaskDetail.description}</p>

            <div className="space-y-2">
              <h4 className="text-xs font-bold uppercase text-neutral-500">Step-by-Step Instructions:</h4>
              <ol className="list-decimal list-inside text-xs space-y-1.5 text-neutral-200">
                {selectedTaskDetail.step_by_step.map((step, idx) => (
                  <li key={idx} className="leading-relaxed">{step}</li>
                ))}
              </ol>
            </div>

            <div className="pt-3 border-t border-neutral-200 dark:border-neutral-800 flex justify-between items-center">
              <span className="text-xs text-emerald-400 font-medium">Estimated Impact: {selectedTaskDetail.estimated_impact}</span>
              <a
                href={selectedTaskDetail.claim_url}
                target="_blank"
                rel="noreferrer"
                className="px-4 py-1.5 rounded bg-brand-600 hover:bg-brand-700 text-white text-xs font-semibold inline-flex items-center gap-1"
              >
                Go to Portal <ArrowUpRight className="w-3.5 h-3.5" />
              </a>
            </div>
          </div>
        </div>
      )}

      {/* MODAL 3: LISTING DETAIL DRAWER */}
      {selectedListingDetail && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex justify-end">
          <div className="bg-surface border-l border-neutral-200 dark:border-neutral-800 w-full max-w-md h-full p-6 space-y-5 overflow-y-auto">
            <div className="flex items-center justify-between border-b border-neutral-200 dark:border-neutral-800 pb-3">
              <PlatformBadge platformKey={selectedListingDetail.platform_key} name={selectedListingDetail.platform_name} />
              <button onClick={() => setSelectedListingDetail(null)} className="text-neutral-400 hover:text-white">
                <X className="w-4 h-4" />
              </button>
            </div>

            <div>
              <h3 className="font-bold text-base text-neutral-900 dark:text-white">{selectedListingDetail.title}</h3>
              <a href={selectedListingDetail.url} target="_blank" rel="noreferrer" className="text-xs text-brand-400 hover:underline block mt-0.5">
                {selectedListingDetail.url}
              </a>
            </div>

            <div className="space-y-3 text-xs">
              <div className="p-3 bg-neutral-900/60 rounded-lg border border-neutral-800 space-y-2">
                <div className="font-semibold text-neutral-400 uppercase text-[10px]">Crawl Data Snapshot</div>
                <div>Address: <span className="font-mono text-neutral-200">{selectedListingDetail.address || "N/A"}</span></div>
                <div>Phone: <span className="font-mono text-neutral-200">{selectedListingDetail.phone || "N/A"}</span></div>
                <div>Website: <span className="font-mono text-neutral-200">{selectedListingDetail.website || "N/A"}</span></div>
                <div>Rating: <span className="font-mono text-amber-400">{selectedListingDetail.rating || "N/A"} ({selectedListingDetail.review_count || 0} reviews)</span></div>
              </div>

              <div className="p-3 bg-neutral-900/60 rounded-lg border border-neutral-800 space-y-2">
                <div className="font-semibold text-neutral-400 uppercase text-[10px]">NAP Accuracy Checks</div>
                <div className="flex items-center justify-between">
                  <span>Name Match:</span>
                  <span className={selectedListingDetail.nap_matches?.name ? "text-emerald-400" : "text-red-400"}>
                    {selectedListingDetail.nap_matches?.name ? "MATCH" : "MISMATCH"}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span>Phone Match:</span>
                  <span className={selectedListingDetail.nap_matches?.phone ? "text-emerald-400" : "text-red-400"}>
                    {selectedListingDetail.nap_matches?.phone ? "MATCH" : "MISMATCH"}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span>Address Match:</span>
                  <span className={selectedListingDetail.nap_matches?.address ? "text-emerald-400" : "text-red-400"}>
                    {selectedListingDetail.nap_matches?.address ? "MATCH" : "MISMATCH"}
                  </span>
                </div>
              </div>
            </div>

            <div className="pt-4 border-t border-neutral-200 dark:border-neutral-800">
              <a
                href={selectedListingDetail.url}
                target="_blank"
                rel="noreferrer"
                className="w-full py-2 bg-brand-600 hover:bg-brand-700 text-white rounded text-xs font-semibold inline-flex items-center justify-center gap-1.5"
              >
                Visit Listing Page <ExternalLink className="w-3.5 h-3.5" />
              </a>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

const root = createRoot(document.getElementById("root"));
root.render(<App />);
