import React, { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import {
  Globe,
  Mail,
  Shield,
  Zap,
  CheckCircle2,
  AlertTriangle,
  Server,
  RefreshCw,
  Terminal,
  Lock,
  ArrowRight,
  Search,
  Key,
  Layers,
  BarChart3,
  Send,
  User,
  LogOut,
  Sliders,
  Database,
  ExternalLink,
  Copy,
  Check,
  Play,
  Clock,
  ChevronRight,
  ShieldCheck,
  Cpu,
  FileText
} from "lucide-react";

export function App() {
  // Navigation & User State
  const [activeTab, setActiveTab] = useState("store"); // 'store' | 'my-instances' | 'email-dashboard' | 'admin'
  const [user, setUser] = useState(null);
  const [authMode, setAuthMode] = useState("login");
  const [registerName, setRegisterName] = useState("");
  const [registerCompany, setRegisterCompany] = useState("");
  const [platformHealth, setPlatformHealth] = useState(null);
  const [checkoutNotice, setCheckoutNotice] = useState("");

  // Store & Search State
  const [searchQuery, setSearchQuery] = useState("acme-email");
  const [searchResults, setSearchResults] = useState([]);
  const [selectedDomain, setSelectedDomain] = useState(null);
  const [selectedPlan, setSelectedPlan] = useState({
    name: "Pro",
    price: 79.00,
    emails: "100,000 / mo",
    features: ["Dedicated Sending IP", "Auto SPF, DKIM & DMARC", "Email Campaign Builder", "Priority Delivery Worker"]
  });
  const [isSearching, setIsSearching] = useState(false);

  // Modals
  const [showCheckoutModal, setShowCheckoutModal] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [showDnsModal, setShowDnsModal] = useState(null); // domain object
  const [activeDeploymentId, setActiveDeploymentId] = useState("dep_sample_01");

  // Deployments & Customer Data
  const [deployments, setDeployments] = useState([]);
  const [selectedDeployment, setSelectedDeployment] = useState(null);
  const [dnsRecords, setDnsRecords] = useState([]);
  const [provisioningJobs, setProvisioningJobs] = useState([]);

  // Auth Form State
  const [loginEmail, setLoginEmail] = useState("demo@acme.com");
  const [loginPassword, setLoginPassword] = useState("demo123");

  // Instance OTP Login State
  const [otpEmail, setOtpEmail] = useState("demo@acme.com");
  const [otpCode, setOtpCode] = useState("RMS-8K92-X7P1");
  const [otpLoginError, setOtpLoginError] = useState("");
  const [requiresReset, setRequiresReset] = useState(false);
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [instanceData, setInstanceData] = useState(null);
  const [testEmailAddress, setTestEmailAddress] = useState("sarah@acme.com");
  const [testEmailResult, setTestEmailResult] = useState("");

  // Campaign State
  const [campaignTitle, setCampaignTitle] = useState("Summer Product Launch");
  const [campaignSubject, setCampaignSubject] = useState("Introducing our new Cloud Features!");
  const [campaignRecipients, setCampaignRecipients] = useState(1500);
  const [campaignStatus, setCampaignStatus] = useState("");

  // Admin Telemetry State
  const [adminOverview, setAdminOverview] = useState(null);

  // Copied Toast State
  const [copiedText, setCopiedText] = useState("");

  useEffect(() => {
    handleDomainSearch("acme-email");
    restoreSession();
    fetch("/api/health").then((r) => r.json()).then(setPlatformHealth).catch(() => {});
    const params = new URLSearchParams(window.location.search);
    if (params.get("checkout") === "success") {
      setCheckoutNotice("Payment received. Provisioning has started.");
      setActiveTab("my-instances");
      const dep = params.get("deploymentId");
      if (dep) setActiveDeploymentId(dep);
    }
    if (params.get("checkout") === "cancel") setCheckoutNotice("Checkout canceled. No charge was made.");
    if (params.get("oauth") === "success") setShowLoginModal(false);
    if (params.get("oauth") === "error") setCheckoutNotice("OAuth sign-in failed. Check provider credentials.");
    if (params.get("signin") === "1") setShowLoginModal(true);
  }, []);

  useEffect(() => {
    if (user) {
      fetchDeployments();
      if (user.role === "admin") fetchAdminOverview();
    }
  }, [user]);

  useEffect(() => {
    if (activeDeploymentId) {
      fetchDeploymentDetails(activeDeploymentId);
    }
  }, [activeDeploymentId]);

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

  const restoreSession = async () => {
    try {
      const res = await fetch("./api/auth/me");
      const data = await res.json();
      if (data.user) {
        setUser(data.user);
        const next = new URLSearchParams(window.location.search).get("next");
        if (next === "/studio" || next === "/studio/" || next === "/studio/index.html") {
          window.location.href = "/studio/index.html";
        }
      }
    } catch (err) {
      console.error("session restore failed", err);
    }
  };

  const handleDomainSearch = async (queryToSearch) => {
    const q = queryToSearch || searchQuery;
    if (!q) return;
    setIsSearching(true);
    try {
      const res = await fetch(`./api/domains/search?q=${encodeURIComponent(q)}`);
      const data = await res.json();
      setSearchResults(data.results || []);
      if (data.results && data.results.length > 0 && !selectedDomain) {
        setSelectedDomain(data.results[0]);
      }
    } catch (err) {
      console.error("Domain search failed", err);
    } finally {
      setIsSearching(false);
    }
  };

  const fetchDeployments = async () => {
    try {
      const res = await fetch(`./api/deployments?userId=${user ? user.id : ""}`);
      const data = await res.json();
      setDeployments(data.deployments || []);
      if (data.deployments && data.deployments.length > 0 && !activeDeploymentId) {
        setActiveDeploymentId(data.deployments[0].id);
      }
    } catch (err) {
      console.error("Failed to fetch deployments", err);
    }
  };

  const fetchDeploymentDetails = async (id) => {
    try {
      const res = await fetch(`./api/deployments/${id}`);
      const data = await res.json();
      setSelectedDeployment(data.deployment);
      setDnsRecords(data.dnsRecords || []);
      setProvisioningJobs(data.jobs || []);
    } catch (err) {
      console.error("Failed to fetch deployment details", err);
    }
  };

  const fetchAdminOverview = async () => {
    try {
      const res = await fetch("./api/admin/overview");
      const data = await res.json();
      setAdminOverview(data);
    } catch (err) {
      console.error("Failed to fetch admin overview", err);
    }
  };

  const handleCheckoutSubmit = async (e) => {
    e.preventDefault();
    if (!selectedDomain) return;
    if (!user) {
      setShowCheckoutModal(false);
      setShowLoginModal(true);
      return;
    }

    try {
      const resSession = await fetch("./api/checkout/create-session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userId: user.id,
          domainName: selectedDomain.domainName,
          tld: selectedDomain.tld,
          domainPrice: selectedDomain.priceYear,
          planName: selectedPlan.name,
          planPrice: selectedPlan.price
        })
      });
      const sessionData = await resSession.json();
      if (!resSession.ok) {
        alert(sessionData.error || "Unable to start checkout");
        return;
      }

      if (sessionData.mode === "stripe" && sessionData.checkoutUrl) {
        window.location.href = sessionData.checkoutUrl;
        return;
      }

      const resPay = await fetch("./api/checkout/pay", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          orderId: sessionData.orderId,
          deploymentId: sessionData.deploymentId
        })
      });
      if (!resPay.ok) {
        const payErr = await resPay.json();
        alert(payErr.error || "Payment failed");
        return;
      }

      setShowCheckoutModal(false);
      setActiveDeploymentId(sessionData.deploymentId);
      setActiveTab("my-instances");
      fetchDeployments();
      if (user.role === "admin") fetchAdminOverview();
    } catch (err) {
      alert("Checkout failed: " + err.message);
    }
  };

  const handleAdvancePipelineStep = async (depId) => {
    try {
      await fetch(`./api/deployments/${depId}/advance`, { method: "POST" });
      fetchDeploymentDetails(depId);
      fetchDeployments();
      fetchAdminOverview();
    } catch (err) {
      console.error("Failed to advance step", err);
    }
  };

  const handleRetryPipeline = async (depId) => {
    try {
      await fetch(`./api/deployments/${depId}/retry`, { method: "POST" });
      fetchDeploymentDetails(depId);
      fetchDeployments();
      fetchAdminOverview();
    } catch (err) {
      console.error("Failed to retry pipeline", err);
    }
  };

  const handleOtpLogin = async (e) => {
    e.preventDefault();
    setOtpLoginError("");
    try {
      const res = await fetch("./api/instance/login-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: otpEmail, otpCode })
      });
      const data = await res.json();
      if (!res.ok) {
        setOtpLoginError(data.error || "OTP Login failed");
        return;
      }

      if (data.requiresPasswordReset) {
        setRequiresReset(true);
        setActiveDeploymentId(data.deploymentId);
      } else {
        fetchInstanceOverview(data.deploymentId);
      }
    } catch (err) {
      setOtpLoginError(err.message);
    }
  };

  const handlePasswordReset = async (e) => {
    e.preventDefault();
    if (newPassword !== confirmPassword) {
      alert("Passwords do not match!");
      return;
    }
    try {
      const res = await fetch("./api/instance/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          deploymentId: activeDeploymentId,
          newPassword
        })
      });
      const data = await res.json();
      if (res.ok) {
        setRequiresReset(false);
        fetchInstanceOverview(activeDeploymentId);
        fetchDeployments();
      } else {
        alert(data.error || "Password reset failed");
      }
    } catch (err) {
      alert("Error resetting password");
    }
  };

  const fetchInstanceOverview = async (deployId) => {
    try {
      const res = await fetch(`./api/instance/overview/${deployId}`);
      const data = await res.json();
      setInstanceData(data);
      setActiveDeploymentId(deployId);
      setActiveTab("email-dashboard");
    } catch (err) {
      console.error("Failed to fetch instance data", err);
    }
  };

  const handleSendTestEmail = async (e) => {
    e.preventDefault();
    setTestEmailResult("Sending via Cloudflare Email Worker...");
    try {
      const res = await fetch("./api/instance/send-test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          deploymentId: activeDeploymentId,
          recipientEmail: testEmailAddress
        })
      });
      const data = await res.json();
      setTestEmailResult(data.message);
    } catch (err) {
      setTestEmailResult("Failed to send test email.");
    }
  };

  const handleCreateCampaign = async (e) => {
    e.preventDefault();
    setCampaignStatus("Scheduling campaign...");
    try {
      const res = await fetch("./api/instance/campaigns", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          deploymentId: activeDeploymentId,
          title: campaignTitle,
          subject: campaignSubject,
          senderName: "Marketing Team",
          senderEmail: `news@${selectedDeployment ? selectedDeployment.domain_name : "acme.com"}`,
          recipientCount: parseInt(campaignRecipients)
        })
      });
      if (res.ok) {
        setCampaignStatus("Campaign scheduled successfully!");
        fetchInstanceOverview(activeDeploymentId);
      }
    } catch (err) {
      setCampaignStatus("Error creating campaign.");
    }
  };

  const handleSimulateFailure = async (depId) => {
    try {
      await fetch("./api/admin/simulate-failure", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ deploymentId: depId })
      });
      fetchDeploymentDetails(depId);
      fetchDeployments();
      fetchAdminOverview();
    } catch (err) {
      alert("Simulation failed");
    }
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch("./api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: loginEmail, password: loginPassword })
      });
      const data = await res.json();
      if (res.ok) {
        setUser(data.user);
        setShowLoginModal(false);
        fetchDeployments();
        if (data.user.role === "admin") fetchAdminOverview();
        const next = new URLSearchParams(window.location.search).get("next");
        if (next === "/studio" || next === "/studio/" || next === "/studio/index.html") {
          window.location.href = "/studio/index.html";
        }
      } else {
        alert(data.error || "Login failed");
      }
    } catch (err) {
      alert("Login error");
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch("./api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: loginEmail,
          password: loginPassword,
          full_name: registerName,
          company: registerCompany
        })
      });
      const data = await res.json();
      if (res.ok) {
        setUser(data.user);
        setShowLoginModal(false);
        const next = new URLSearchParams(window.location.search).get("next");
        if (next === "/studio" || next === "/studio/" || next === "/studio/index.html") {
          window.location.href = "/studio/index.html";
        }
      } else {
        alert(data.error || "Registration failed");
      }
    } catch (err) {
      alert("Registration error");
    }
  };

  const handleLogout = async () => {
    await fetch("./api/auth/logout", { method: "POST" });
    setUser(null);
    setInstanceData(null);
    setActiveTab("store");
  };

  return (
    <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}>
      {/* TOP HEADER / NAVIGATION */}
      <header
        style={{
          height: "56px",
          backgroundColor: "#FFFFFF",
          borderBottom: "1px solid #E2E8F0",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "0 24px",
          position: "sticky",
          top: 0,
          zIndex: 50
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: "24px" }}>
          <div
            onClick={() => setActiveTab("store")}
            style={{
              display: "flex",
              alignItems: "center",
              gap: "8px",
              cursor: "pointer",
              fontWeight: 700,
              fontSize: "16px",
              color: "#0F172A"
            }}
          >
            <div
              style={{
                width: "28px",
                height: "28px",
                borderRadius: "6px",
                backgroundColor: "#5E6AD2",
                color: "#FFF",
                display: "flex",
                alignItems: "center",
                justifyContent: "center"
              }}
            >
              <Globe size={18} />
            </div>
            <span>registermysite<span style={{ color: "#5E6AD2" }}>.com</span></span>
          </div>

          <nav style={{ display: "flex", alignItems: "center", gap: "4px" }}>
            <button
              onClick={() => setActiveTab("store")}
              className={`btn ${activeTab === "store" ? "btn-secondary" : "btn-ghost"}`}
            >
              <Globe size={14} /> Domain & SaaS Store
            </button>
            <button
              onClick={() => {
                setActiveTab("my-instances");
                fetchDeployments();
              }}
              className={`btn ${activeTab === "my-instances" ? "btn-secondary" : "btn-ghost"}`}
            >
              <Layers size={14} /> My Instances ({deployments.length})
            </button>
            <a href={user ? "/studio/index.html" : "/?signin=1&next=/studio"} className="btn btn-ghost">
              <Mail size={14} /> Try Email Studio
            </a>
            <button
              onClick={() => setActiveTab("email-dashboard")}
              className={`btn ${activeTab === "email-dashboard" ? "btn-secondary" : "btn-ghost"}`}
            >
              <Mail size={14} /> Email Dashboard
            </button>
            {user && user.role === "admin" && (
              <button
                onClick={() => {
                  setActiveTab("admin");
                  fetchAdminOverview();
                }}
                className={`btn ${activeTab === "admin" ? "btn-secondary" : "btn-ghost"}`}
              >
                <Sliders size={14} /> Admin Operations
              </button>
            )}
          </nav>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
          {user ? (
            <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
              <span className="badge badge-info" style={{ textTransform: "none" }}>
                <User size={12} /> {user.full_name} ({user.email})
              </span>
              <button onClick={handleLogout} className="btn btn-ghost btn-sm" title="Log Out">
                <LogOut size={14} />
              </button>
            </div>
          ) : (
            <button onClick={() => setShowLoginModal(true)} className="btn btn-secondary btn-sm">
              <User size={14} /> Sign In
            </button>
          )}
        </div>
      </header>

      {/* MAIN CONTENT AREA */}
      <main style={{ flex: 1, padding: "24px", maxWidth: "1280px", margin: "0 auto", width: "100%" }}>
        {checkoutNotice && (
          <div className="card" style={{ marginBottom: "16px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>{checkoutNotice}</span>
            <button className="btn btn-ghost btn-sm" onClick={() => setCheckoutNotice("")}>Dismiss</button>
          </div>
        )}
        {platformHealth && (
          <div style={{ display: "flex", gap: "8px", marginBottom: "16px", flexWrap: "wrap" }}>
            <span className={`badge ${platformHealth.stripe ? "badge-success" : "badge-warning"}`}>
              Stripe {platformHealth.stripe ? "live keys" : "demo mode"}
            </span>
            <span className={`badge ${platformHealth.oauth.github ? "badge-success" : "badge-neutral"}`}>GitHub OAuth</span>
            <span className={`badge ${platformHealth.oauth.google ? "badge-success" : "badge-neutral"}`}>Google OAuth</span>
            <span className={`badge ${platformHealth.registrar ? "badge-success" : "badge-warning"}`}>
              Registrar {platformHealth.registrar ? "live" : "RDAP fallback"}
            </span>
            <span className="badge badge-info">Durable Object SQLite</span>
          </div>
        )}
        {/* ========================================================= */}
        {/* TAB 1: STORE & DOMAIN REGISTRAR SEARCH */}
        {/* ========================================================= */}
        {activeTab === "store" && (
          <div>
            {/* HERO SECTION */}
            <div
              style={{
                backgroundColor: "#FFFFFF",
                border: "1px solid #E2E8F0",
                borderRadius: "12px",
                padding: "40px",
                marginBottom: "32px",
                backgroundImage: "radial-gradient(circle, #EEF0FB 1px, transparent 1px)",
                backgroundSize: "24px 24px"
              }}
            >
              <div style={{ maxWidth: "780px" }}>
                <div className="badge badge-info" style={{ marginBottom: "16px" }}>
                  <ShieldCheck size={12} /> Cloudflare Registrar + LLM Email Studio demo before you buy
                </div>
                <h1 style={{ fontSize: "32px", fontWeight: 700, tracking: "-0.02em", color: "#0F172A", marginBottom: "12px" }}>
                  Register Domain & Launch Your Business Email Dashboard in Minutes
                </h1>
                <p style={{ fontSize: "15px", color: "#475569", marginBottom: "16px" }}>
                  Search for a domain, or first try the same LLM Email Studio we deploy after checkout — generate Outlook-safe HTML, export to the composer, and send a test from our onboarded zones.
                </p>
                <div style={{ marginBottom: "28px" }}>
                  <a href={user ? "/studio/index.html" : "/?signin=1&next=/studio"} className="btn btn-secondary">
                    <Mail size={14} /> Open Email Studio demo
                  </a>
                </div>

                {/* SEARCH BAR */}
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    handleDomainSearch();
                  }}
                  style={{ display: "flex", gap: "8px", maxWidth: "640px" }}
                >
                  <div style={{ position: "relative", flex: 1 }}>
                    <Search
                      size={18}
                      style={{
                        position: "absolute",
                        left: "14px",
                        top: "50%",
                        transform: "translateY(-50%)",
                        color: "#94A3B8"
                      }}
                    />
                    <input
                      type="text"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      placeholder="Search domain name (e.g. acme-email, mysite, launchpad)..."
                      className="input"
                      style={{ paddingLeft: "42px", height: "46px", fontSize: "15px" }}
                    />
                  </div>
                  <button type="submit" disabled={isSearching} className="btn btn-primary btn-lg">
                    {isSearching ? <RefreshCw size={16} className="spin" /> : <Search size={16} />} Search Domains
                  </button>
                </form>
              </div>
            </div>

            {/* DOMAIN SEARCH RESULTS */}
            {searchResults.length > 0 && (
              <div style={{ marginBottom: "40px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
                  <h2 style={{ fontSize: "18px", fontWeight: 600 }}>Live domain availability</h2>
                  <span className="mono" style={{ fontSize: "12px", color: "#64748B" }}>
                    Cloudflare Registrar domain-check (authoritative price + availability)
                  </span>
                </div>

                <div className="card" style={{ padding: 0, overflow: "hidden" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px" }}>
                    <thead>
                      <tr style={{ backgroundColor: "#F8FAFC", borderBottom: "1px solid #E2E8F0", textAlign: "left" }}>
                        <th style={{ padding: "12px 16px", color: "#475569", fontWeight: 600 }}>Domain Name</th>
                        <th style={{ padding: "12px 16px", color: "#475569", fontWeight: 600 }}>Status</th>
                        <th style={{ padding: "12px 16px", color: "#475569", fontWeight: 600 }}>Registrar Pricing</th>
                        <th style={{ padding: "12px 16px", color: "#475569", fontWeight: 600 }}>Includes</th>
                        <th style={{ padding: "12px 16px", textAlign: "right" }}>Action</th>
                      </tr>
                    </thead>
                    <tbody>
                      {searchResults.map((item, idx) => {
                        const isSelected = selectedDomain?.domainName === item.domainName;
                        return (
                          <tr
                            key={idx}
                            style={{
                              borderBottom: "1px solid #E2E8F0",
                              backgroundColor: isSelected ? "#EEF0FB" : "transparent"
                            }}
                          >
                            <td style={{ padding: "14px 16px", fontWeight: 600 }}>
                              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                                <Globe size={16} style={{ color: "#5E6AD2" }} />
                                <span style={{ fontSize: "15px" }}>{item.domainName}</span>
                                {item.popular && <span className="badge badge-info">Popular</span>}
                              </div>
                            </td>
                            <td style={{ padding: "14px 16px" }}>
                              {item.available ? (
                                <span className="badge badge-success">
                                  <CheckCircle2 size={12} /> Available
                                </span>
                              ) : (
                                <span className="badge badge-error">
                                  <AlertTriangle size={12} /> Taken
                                </span>
                              )}
                              {item.reason && (
                                <div style={{ fontSize: "11px", color: "#94A3B8", marginTop: "4px" }}>{item.reason}</div>
                              )}
                            </td>
                            <td style={{ padding: "14px 16px" }}>
                              {item.available ? (
                                <>
                                  <span className="mono" style={{ fontSize: "15px", fontWeight: 600 }}>
                                    ${Number(item.priceYear || 0).toFixed(2)}
                                  </span>{" "}
                                  <span style={{ fontSize: "12px", color: "#64748B" }}>/ first year</span>
                                  <div style={{ fontSize: "11px", color: "#94A3B8" }}>
                                    Renews ${Number(item.renewalPrice || item.priceYear || 0).toFixed(2)} / yr
                                    {item.priceSource === "cloudflare-registrar" ? " · Cloudflare Registrar" : " · estimate"}
                                  </div>
                                </>
                              ) : (
                                <span style={{ fontSize: "12px", color: "#94A3B8" }}>—</span>
                              )}
                            </td>
                            <td style={{ padding: "14px 16px" }}>
                              <div style={{ display: "flex", gap: "6px", flexWrap: "wrap" }}>
                                <span className="badge badge-neutral">WHOIS Privacy</span>
                                <span className="badge badge-neutral">DNSSEC</span>
                                <span className="badge badge-neutral">Cloudflare DNS</span>
                              </div>
                            </td>
                            <td style={{ padding: "14px 16px", textAlign: "right" }}>
                              {item.available && (
                                <button
                                  onClick={() => {
                                    setSelectedDomain(item);
                                    setShowCheckoutModal(true);
                                  }}
                                  className={`btn ${isSelected ? "btn-primary" : "btn-secondary"} btn-sm`}
                                >
                                  Select & Order <ArrowRight size={14} />
                                </button>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* SOFTWARE SUBSCRIPTION PLANS */}
            <div style={{ marginTop: "32px" }}>
              <div style={{ textAlign: "center", marginBottom: "32px" }}>
                <h2 style={{ fontSize: "24px", fontWeight: 700, color: "#0F172A", marginBottom: "8px" }}>
                  Select Business Email Dashboard Plan
                </h2>
                <p style={{ color: "#475569" }}>
                  Every plan automatically deploys a private Cloudflare Worker instance with full custom domain DNS setup.
                </p>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "24px" }}>
                {/* PLAN 1 */}
                <div
                  className="card"
                  style={{
                    border: selectedPlan.name === "Starter" ? "2px solid #5E6AD2" : "1px solid #E2E8F0",
                    display: "flex",
                    flexDirection: "column"
                  }}
                >
                  <div style={{ marginBottom: "16px" }}>
                    <h3 style={{ fontSize: "18px", fontWeight: 600 }}>Starter</h3>
                    <p style={{ fontSize: "12px", color: "#64748B" }}>Ideal for new transactional sending</p>
                  </div>
                  <div style={{ marginBottom: "20px" }}>
                    <span className="mono" style={{ fontSize: "32px", fontWeight: 700 }}>$29</span>
                    <span style={{ color: "#64748B" }}> / month</span>
                  </div>
                  <ul style={{ listStyle: "none", spaceY: "10px", flex: 1, marginBottom: "24px" }}>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> 10,000 Emails / month
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> 1 Custom Domain Auto-DNS
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> Automatic SPF/DKIM/DMARC Setup
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> One-Time Password OTP Access
                    </li>
                  </ul>
                  <button
                    onClick={() => {
                      setSelectedPlan({
                        name: "Starter",
                        price: 29.00,
                        emails: "10,000 / mo",
                        features: ["1 Custom Domain", "Auto SPF/DKIM", "Cloudflare Email Routing"]
                      });
                      if (selectedDomain) setShowCheckoutModal(true);
                    }}
                    className={`btn ${selectedPlan.name === "Starter" ? "btn-primary" : "btn-secondary"}`}
                  >
                    Select Starter Plan
                  </button>
                </div>

                {/* PLAN 2 - PRO RECOMMENDED */}
                <div
                  className="card"
                  style={{
                    border: "2px solid #5E6AD2",
                    backgroundColor: "#FFFFFF",
                    position: "relative",
                    display: "flex",
                    flexDirection: "column"
                  }}
                >
                  <div
                    style={{
                      position: "absolute",
                      top: "-12px",
                      right: "20px",
                      backgroundColor: "#5E6AD2",
                      color: "#FFF",
                      fontSize: "11px",
                      fontWeight: 600,
                      padding: "2px 10px",
                      borderRadius: "10px"
                    }}
                  >
                    MOST POPULAR
                  </div>
                  <div style={{ marginBottom: "16px" }}>
                    <h3 style={{ fontSize: "18px", fontWeight: 600 }}>Pro Sending Suite</h3>
                    <p style={{ fontSize: "12px", color: "#64748B" }}>High volume transactional + campaigns</p>
                  </div>
                  <div style={{ marginBottom: "20px" }}>
                    <span className="mono" style={{ fontSize: "32px", fontWeight: 700 }}>$79</span>
                    <span style={{ color: "#64748B" }}> / month</span>
                  </div>
                  <ul style={{ listStyle: "none", spaceY: "10px", flex: 1, marginBottom: "24px" }}>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> 100,000 Emails / month
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> Isolated Cloudflare Worker Repo
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> Full Campaign Builder & Analytics
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> Dedicated IP Warmup Routing
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> REST API Key Token Generation
                    </li>
                  </ul>
                  <button
                    onClick={() => {
                      setSelectedPlan({
                        name: "Pro",
                        price: 79.00,
                        emails: "100,000 / mo",
                        features: ["Dedicated Sending IP", "Auto SPF, DKIM & DMARC", "Email Campaign Builder", "Priority Delivery Worker"]
                      });
                      if (selectedDomain) setShowCheckoutModal(true);
                    }}
                    className="btn btn-primary"
                  >
                    Select Pro Plan
                  </button>
                </div>

                {/* PLAN 3 */}
                <div
                  className="card"
                  style={{
                    border: selectedPlan.name === "Enterprise" ? "2px solid #5E6AD2" : "1px solid #E2E8F0",
                    display: "flex",
                    flexDirection: "column"
                  }}
                >
                  <div style={{ marginBottom: "16px" }}>
                    <h3 style={{ fontSize: "18px", fontWeight: 600 }}>Enterprise Scale</h3>
                    <p style={{ fontSize: "12px", color: "#64748B" }}>Unlimited sending & high availability</p>
                  </div>
                  <div style={{ marginBottom: "20px" }}>
                    <span className="mono" style={{ fontSize: "32px", fontWeight: 700 }}>$199</span>
                    <span style={{ color: "#64748B" }}> / month</span>
                  </div>
                  <ul style={{ listStyle: "none", flex: 1, marginBottom: "24px" }}>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> Unlimited Email Dispatch
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> Multi-Region Cloudflare Workers
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px", marginBottom: "8px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> Dedicated DKIM RSA 2048 Keys
                    </li>
                    <li style={{ display: "flex", gap: "8px", fontSize: "13px" }}>
                      <CheckCircle2 size={16} style={{ color: "#16A34A" }} /> 99.99% Deliverability SLA
                    </li>
                  </ul>
                  <button
                    onClick={() => {
                      setSelectedPlan({
                        name: "Enterprise",
                        price: 199.00,
                        emails: "Unlimited",
                        features: ["Multi-Region Workers", "Custom DKIM RSA 2048", "Dedicated SLA Support"]
                      });
                      if (selectedDomain) setShowCheckoutModal(true);
                    }}
                    className={`btn ${selectedPlan.name === "Enterprise" ? "btn-primary" : "btn-secondary"}`}
                  >
                    Select Enterprise Plan
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ========================================================= */}
        {/* TAB 2: MY INSTANCES & PROVISIONING TRACKER */}
        {/* ========================================================= */}
        {activeTab === "my-instances" && (
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "24px" }}>
              <div>
                <h1 style={{ fontSize: "24px", fontWeight: 700 }}>My Domains & Provisioned Instances</h1>
                <p style={{ color: "#64748B", fontSize: "14px" }}>
                  Monitor Cloudflare Registrar status, DNS propagation, and automated Worker deployments.
                </p>
              </div>
              <button onClick={() => setActiveTab("store")} className="btn btn-primary">
                + Purchase New Domain & Dashboard
              </button>
            </div>

            {/* INSTANCES & DEPLOYMENT LIST */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: "24px" }}>
              <div>
                {deployments.length === 0 ? (
                  <div className="card" style={{ textAlign: "center", padding: "48px 24px" }}>
                    <Server size={48} style={{ color: "#CBD5E1", margin: "0 auto 16px" }} />
                    <h3 style={{ fontSize: "16px", fontWeight: 600, marginBottom: "8px" }}>No active deployments yet</h3>
                    <p style={{ color: "#64748B", marginBottom: "20px" }}>
                      Search and purchase a domain to launch your Business Email Sending Dashboard.
                    </p>
                    <button onClick={() => setActiveTab("store")} className="btn btn-primary">
                      Search Domains
                    </button>
                  </div>
                ) : (
                  deployments.map((dep) => {
                    const isSelected = dep.id === activeDeploymentId;
                    return (
                      <div
                        key={dep.id}
                        className="card"
                        style={{
                          marginBottom: "16px",
                          border: isSelected ? "2px solid #5E6AD2" : "1px solid #E2E8F0"
                        }}
                      >
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "16px" }}>
                          <div>
                            <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                              <h3 style={{ fontSize: "18px", fontWeight: 600 }}>{dep.domain_name}</h3>
                              <span
                                className={`badge ${
                                  dep.status === "ready"
                                    ? "badge-success"
                                    : dep.status === "failed"
                                    ? "badge-error"
                                    : "badge-warning"
                                }`}
                              >
                                {dep.status === "ready" ? <CheckCircle2 size={12} /> : <RefreshCw size={12} className="spin" />}
                                {dep.status.toUpperCase()}
                              </span>
                            </div>
                            <div style={{ fontSize: "12px", color: "#64748B", marginTop: "4px" }}>
                              Plan: <strong>{dep.plan_name}</strong> • Repo: <code>{dep.github_repo}</code>
                            </div>
                          </div>

                          <div style={{ display: "flex", gap: "8px" }}>
                            <button
                              onClick={() => {
                                setActiveDeploymentId(dep.id);
                                fetchDeploymentDetails(dep.id);
                              }}
                              className="btn btn-secondary btn-sm"
                            >
                              <Terminal size={14} /> Pipeline Logs
                            </button>

                            {dep.status === "ready" && (
                              <button
                                onClick={() => {
                                  fetchInstanceOverview(dep.id);
                                }}
                                className="btn btn-primary btn-sm"
                              >
                                Launch Dashboard <ExternalLink size={14} />
                              </button>
                            )}
                          </div>
                        </div>

                        {/* OTP CREDENTIALS BANNER */}
                        <div
                          style={{
                            backgroundColor: "#F8FAFC",
                            border: "1px solid #E2E8F0",
                            borderRadius: "6px",
                            padding: "12px 16px",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "space-between"
                          }}
                        >
                          <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                            <Key size={16} style={{ color: "#5E6AD2" }} />
                            <div>
                              <div style={{ fontSize: "11px", color: "#64748B", textTransform: "uppercase" }}>One-Time Password OTP</div>
                              <span className="mono" style={{ fontSize: "14px", fontWeight: 600 }}>
                                {dep.otp_code}
                              </span>
                            </div>
                          </div>

                          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                            <span className={`badge ${dep.otp_used ? "badge-success" : "badge-warning"}`}>
                              {dep.otp_used ? "Permanent Password Set" : "OTP Pending First Login"}
                            </span>
                            <button
                              onClick={() => copyToClipboard(dep.otp_code)}
                              className="btn btn-ghost btn-sm"
                              title="Copy OTP"
                            >
                              {copiedText === dep.otp_code ? <Check size={14} /> : <Copy size={14} />}
                            </button>
                          </div>
                        </div>
                      </div>
                    );
                  })
                )}
              </div>

              {/* REAL-TIME PROVISIONING PIPELINE TRACKER */}
              <div>
                <div className="card" style={{ position: "sticky", top: "80px" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
                    <h3 style={{ fontSize: "15px", fontWeight: 600 }}>Provisioning Pipeline</h3>
                    {selectedDeployment && (
                      <button
                        onClick={() => handleAdvancePipelineStep(selectedDeployment.id)}
                        className="btn btn-ghost btn-sm"
                        title="Step Advance"
                      >
                        <Play size={12} /> Advance
                      </button>
                    )}
                  </div>

                  {selectedDeployment ? (
                    <div>
                      <div style={{ fontSize: "12px", color: "#64748B", marginBottom: "16px" }}>
                        Domain: <strong>{selectedDeployment.domain_name}</strong>
                      </div>

                      {/* STEP STATE MACHINE */}
                      <div style={{ paddingLeft: "4px", marginBottom: "20px" }}>
                        {/* STEP 1 */}
                        <div
                          className={`step-node ${
                            selectedDeployment.current_step === "REGISTER_DOMAIN" && selectedDeployment.status !== "ready"
                              ? "active"
                              : selectedDeployment.status === "ready" || selectedDeployment.current_step !== "REGISTER_DOMAIN"
                              ? "completed"
                              : ""
                          }`}
                        >
                          <div className="step-icon">1</div>
                          <div>
                            <div style={{ fontWeight: 600, fontSize: "13px" }}>Register Domain</div>
                            <div style={{ fontSize: "11px", color: "#64748B" }}>Cloudflare Registrar API v4</div>
                          </div>
                        </div>

                        {/* STEP 2 */}
                        <div
                          className={`step-node ${
                            selectedDeployment.current_step === "CONFIGURE_DNS" && selectedDeployment.status !== "ready"
                              ? "active"
                              : selectedDeployment.status === "ready" || ["PROVISION_WORKER_INSTANCE", "CONFIGURE_ENV_SECRETS", "DISPATCH_OTP", "COMPLETED"].includes(selectedDeployment.current_step)
                              ? "completed"
                              : ""
                          }`}
                        >
                          <div className="step-icon">2</div>
                          <div>
                            <div style={{ fontWeight: 600, fontSize: "13px" }}>Configure DNS Records</div>
                            <div style={{ fontSize: "11px", color: "#64748B" }}>MX, SPF, DKIM & DMARC</div>
                          </div>
                        </div>

                        {/* STEP 3 */}
                        <div
                          className={`step-node ${
                            selectedDeployment.current_step === "PROVISION_WORKER_INSTANCE" && selectedDeployment.status !== "ready"
                              ? "active"
                              : selectedDeployment.status === "ready" || ["CONFIGURE_ENV_SECRETS", "DISPATCH_OTP", "COMPLETED"].includes(selectedDeployment.current_step)
                              ? "completed"
                              : ""
                          }`}
                        >
                          <div className="step-icon">3</div>
                          <div>
                            <div style={{ fontWeight: 600, fontSize: "13px" }}>Deploy Worker Instance</div>
                            <div style={{ fontSize: "11px", color: "#64748B" }}>GitHub repo build & route</div>
                          </div>
                        </div>

                        {/* STEP 4 */}
                        <div
                          className={`step-node ${
                            selectedDeployment.current_step === "CONFIGURE_ENV_SECRETS" && selectedDeployment.status !== "ready"
                              ? "active"
                              : selectedDeployment.status === "ready" || ["DISPATCH_OTP", "COMPLETED"].includes(selectedDeployment.current_step)
                              ? "completed"
                              : ""
                          }`}
                        >
                          <div className="step-icon">4</div>
                          <div>
                            <div style={{ fontWeight: 600, fontSize: "13px" }}>Set Env Secrets</div>
                            <div style={{ fontSize: "11px", color: "#64748B" }}>Tenant keys & isolation</div>
                          </div>
                        </div>

                        {/* STEP 5 */}
                        <div
                          className={`step-node ${
                            selectedDeployment.status === "ready" || selectedDeployment.current_step === "COMPLETED"
                              ? "completed"
                              : selectedDeployment.current_step === "DISPATCH_OTP"
                              ? "active"
                              : ""
                          }`}
                        >
                          <div className="step-icon">5</div>
                          <div>
                            <div style={{ fontWeight: 600, fontSize: "13px" }}>Dispatch Credentials</div>
                            <div style={{ fontSize: "11px", color: "#64748B" }}>OTP welcome email sent</div>
                          </div>
                        </div>
                      </div>

                      {/* TERMINAL LOGS OUTPUT */}
                      <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B", marginBottom: "6px" }}>
                        PIPELINE STDOUT LOGS
                      </div>
                      <div className="log-box">
                        {provisioningJobs.length > 0
                          ? provisioningJobs.map((j) => {
                              let parsed = [];
                              try {
                                parsed = JSON.parse(j.logs);
                              } catch (e) {
                                parsed = [j.logs];
                              }
                              return parsed.map((line, idx) => (
                                <div key={idx} style={{ marginBottom: "2px" }}>
                                  <span style={{ color: "#64748B" }}>[&gt;]</span> {line}
                                </div>
                              ));
                            })
                          : "> Initializing deployment environment..."}
                      </div>

                      {selectedDeployment.status === "failed" && (
                        <div style={{ marginTop: "12px" }}>
                          <div style={{ color: "#DC2626", fontSize: "12px", marginBottom: "8px" }}>
                            <strong>Error:</strong> {selectedDeployment.error_message || "Pipeline execution halted"}
                          </div>
                          <button onClick={() => handleRetryPipeline(selectedDeployment.id)} className="btn btn-danger btn-sm" style={{ width: "100%" }}>
                            <RefreshCw size={14} /> Retry Provisioning Pipeline
                          </button>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div style={{ fontSize: "12px", color: "#94A3B8" }}>Select a deployment to view step tracking</div>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ========================================================= */}
        {/* TAB 3: EMBEDDED BUSINESS EMAIL SENDING DASHBOARD */}
        {/* ========================================================= */}
        {activeTab === "email-dashboard" && (
          <div>
            {/* FORCED FIRST LOGIN PASSWORD RESET OVERLAY IF OTP PENDING */}
            {requiresReset ? (
              <div
                className="card"
                style={{
                  maxWidth: "480px",
                  margin: "40px auto",
                  padding: "32px",
                  border: "2px solid #5E6AD2",
                  boxShadow: "0 20px 25px -5px rgba(0,0,0,0.1)"
                }}
              >
                <div style={{ textAlign: "center", marginBottom: "24px" }}>
                  <div
                    style={{
                      width: "48px",
                      height: "48px",
                      borderRadius: "50%",
                      backgroundColor: "#EEF0FB",
                      color: "#5E6AD2",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      margin: "0 auto 12px"
                    }}
                  >
                    <Lock size={24} />
                  </div>
                  <h2 style={{ fontSize: "20px", fontWeight: 700 }}>Security First: Set Permanent Password</h2>
                  <p style={{ fontSize: "13px", color: "#64748B", marginTop: "4px" }}>
                    You have authenticated using a One-Time Password (OTP). As per our security policy, you must set a permanent password before accessing your Email Sending Dashboard.
                  </p>
                </div>

                <form onSubmit={handlePasswordReset}>
                  <div style={{ marginBottom: "16px" }}>
                    <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>
                      New Permanent Password
                    </label>
                    <input
                      type="password"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      required
                      minLength={8}
                      placeholder="Minimum 8 characters..."
                      className="input"
                    />
                  </div>

                  <div style={{ marginBottom: "24px" }}>
                    <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>
                      Confirm Permanent Password
                    </label>
                    <input
                      type="password"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      required
                      placeholder="Re-enter password..."
                      className="input"
                    />
                  </div>

                  <button type="submit" className="btn btn-primary" style={{ width: "100%" }}>
                    <ShieldCheck size={16} /> Set Password & Unlock Dashboard
                  </button>
                </form>
              </div>
            ) : !instanceData ? (
              /* OTP LOGIN FORM IF NOT LOGGED IN */
              <div className="card" style={{ maxWidth: "440px", margin: "40px auto", padding: "32px" }}>
                <div style={{ textAlign: "center", marginBottom: "24px" }}>
                  <div
                    style={{
                      width: "44px",
                      height: "44px",
                      borderRadius: "8px",
                      backgroundColor: "#5E6AD2",
                      color: "#FFF",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      margin: "0 auto 12px"
                    }}
                  >
                    <Mail size={22} />
                  </div>
                  <h2 style={{ fontSize: "20px", fontWeight: 700 }}>Log Into Business Email Dashboard</h2>
                  <p style={{ fontSize: "13px", color: "#64748B", marginTop: "4px" }}>
                    Enter your provisioned domain email and the One-Time Password (OTP) received upon checkout.
                  </p>
                </div>

                {otpLoginError && (
                  <div className="badge badge-error" style={{ width: "100%", padding: "8px 12px", marginBottom: "16px" }}>
                    <AlertTriangle size={14} /> {otpLoginError}
                  </div>
                )}

                <form onSubmit={handleOtpLogin}>
                  <div style={{ marginBottom: "16px" }}>
                    <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>
                      Admin Email
                    </label>
                    <input
                      type="email"
                      value={otpEmail}
                      onChange={(e) => setOtpEmail(e.target.value)}
                      required
                      className="input"
                    />
                  </div>

                  <div style={{ marginBottom: "20px" }}>
                    <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>
                      One-Time Password (OTP)
                    </label>
                    <input
                      type="text"
                      value={otpCode}
                      onChange={(e) => setOtpCode(e.target.value)}
                      required
                      placeholder="e.g. RMS-8K92-X7P1"
                      className="input mono"
                    />
                  </div>

                  <button type="submit" className="btn btn-primary" style={{ width: "100%" }}>
                    Log In with OTP <ArrowRight size={16} />
                  </button>
                </form>
              </div>
            ) : (
              /* ACTIVE INSTANCE BUSINESS EMAIL DASHBOARD */
              <div>
                {/* DASHBOARD TOP BAR */}
                <div
                  style={{
                    backgroundColor: "#FFFFFF",
                    border: "1px solid #E2E8F0",
                    borderRadius: "12px",
                    padding: "20px 24px",
                    marginBottom: "24px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between"
                  }}
                >
                  <div>
                    <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                      <h1 style={{ fontSize: "22px", fontWeight: 700 }}>{instanceData.domainName}</h1>
                      <span className="badge badge-success">
                        <CheckCircle2 size={12} /> Active Cloudflare Worker Route
                      </span>
                    </div>
                    <p style={{ color: "#64748B", fontSize: "13px", marginTop: "2px" }}>
                      Plan: <strong>{instanceData.planName}</strong> • Target: <code>{instanceData.appUrl}</code>
                    </p>
                  </div>

                  <button
                    onClick={() => {
                      setInstanceData(null);
                    }}
                    className="btn btn-secondary btn-sm"
                  >
                    Switch Instance
                  </button>
                </div>

                {/* METRICS TILES */}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "24px" }}>
                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B", textTransform: "uppercase" }}>
                      Total Emails Dispatched
                    </div>
                    <div className="mono" style={{ fontSize: "28px", fontWeight: 700, marginTop: "4px" }}>
                      14,250
                    </div>
                    <div style={{ fontSize: "12px", color: "#16A34A", marginTop: "4px" }}>↑ 18% this month</div>
                  </div>

                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B", textTransform: "uppercase" }}>
                      Delivery Rate
                    </div>
                    <div className="mono" style={{ fontSize: "28px", fontWeight: 700, marginTop: "4px" }}>
                      99.4%
                    </div>
                    <div style={{ fontSize: "12px", color: "#16A34A", marginTop: "4px" }}>High Reputation</div>
                  </div>

                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B", textTransform: "uppercase" }}>
                      Bounce Rate
                    </div>
                    <div className="mono" style={{ fontSize: "28px", fontWeight: 700, marginTop: "4px" }}>
                      0.2%
                    </div>
                    <div style={{ fontSize: "12px", color: "#16A34A", marginTop: "4px" }}>Well within limits</div>
                  </div>

                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B", textTransform: "uppercase" }}>
                      Domain Reputation Score
                    </div>
                    <div className="mono" style={{ fontSize: "28px", fontWeight: 700, marginTop: "4px" }}>
                      98 / 100
                    </div>
                    <div style={{ fontSize: "12px", color: "#5E6AD2", marginTop: "4px" }}>Optimal Inbox Placement</div>
                  </div>
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "24px" }}>
                  {/* AUTHENTICATION & DNS SECURITY STATUS */}
                  <div className="card">
                    <h3 style={{ fontSize: "16px", fontWeight: 600, marginBottom: "16px" }}>
                      Email Security & DNS Authentication
                    </h3>

                    <div style={{ spaceY: "12px" }}>
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          padding: "10px 12px",
                          backgroundColor: "#F8FAFC",
                          borderRadius: "6px",
                          marginBottom: "8px"
                        }}
                      >
                        <div>
                          <div style={{ fontWeight: 600, fontSize: "13px" }}>SPF (Sender Policy Framework)</div>
                          <div className="mono" style={{ fontSize: "11px", color: "#64748B" }}>v=spf1 include:mail.registermysite.com ~all</div>
                        </div>
                        <span className="badge badge-success"><CheckCircle2 size={12} /> Valid</span>
                      </div>

                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          padding: "10px 12px",
                          backgroundColor: "#F8FAFC",
                          borderRadius: "6px",
                          marginBottom: "8px"
                        }}
                      >
                        <div>
                          <div style={{ fontWeight: 600, fontSize: "13px" }}>DKIM Signature (RSA-2048)</div>
                          <div className="mono" style={{ fontSize: "11px", color: "#64748B" }}>rms2026._domainkey.{instanceData.domainName}</div>
                        </div>
                        <span className="badge badge-success"><CheckCircle2 size={12} /> Active</span>
                      </div>

                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          padding: "10px 12px",
                          backgroundColor: "#F8FAFC",
                          borderRadius: "6px",
                          marginBottom: "8px"
                        }}
                      >
                        <div>
                          <div style={{ fontWeight: 600, fontSize: "13px" }}>DMARC Policy Enforcement</div>
                          <div className="mono" style={{ fontSize: "11px", color: "#64748B" }}>p=quarantine; rua=mailto:dmarc@{instanceData.domainName}</div>
                        </div>
                        <span className="badge badge-success"><CheckCircle2 size={12} /> Enforced</span>
                      </div>

                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          padding: "10px 12px",
                          backgroundColor: "#F8FAFC",
                          borderRadius: "6px"
                        }}
                      >
                        <div>
                          <div style={{ fontWeight: 600, fontSize: "13px" }}>MX Mail Exchange Endpoint</div>
                          <div className="mono" style={{ fontSize: "11px", color: "#64748B" }}>10 feedback-smtp.registermysite.com</div>
                        </div>
                        <span className="badge badge-success"><CheckCircle2 size={12} /> Configured</span>
                      </div>
                    </div>
                  </div>

                  {/* TEST EMAIL DISPATCHER */}
                  <div className="card">
                    <h3 style={{ fontSize: "16px", fontWeight: 600, marginBottom: "16px" }}>
                      Send Test Transactional Email
                    </h3>

                    <form onSubmit={handleSendTestEmail}>
                      <div style={{ marginBottom: "16px" }}>
                        <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>
                          Recipient Email Address
                        </label>
                        <input
                          type="email"
                          value={testEmailAddress}
                          onChange={(e) => setTestEmailAddress(e.target.value)}
                          required
                          className="input"
                        />
                      </div>

                      <div style={{ marginBottom: "16px" }}>
                        <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>
                          Sender
                        </label>
                        <input
                          type="text"
                          value={`no-reply@${instanceData.domainName}`}
                          disabled
                          className="input"
                          style={{ backgroundColor: "#F8FAFC", color: "#64748B" }}
                        />
                      </div>

                      <button type="submit" className="btn btn-primary" style={{ width: "100%" }}>
                        <Send size={14} /> Dispatch Test Email via Cloudflare Worker
                      </button>
                    </form>

                    {testEmailResult && (
                      <div style={{ marginTop: "16px", padding: "10px", backgroundColor: "#EEF0FB", borderRadius: "6px", fontSize: "12px", color: "#5E6AD2" }}>
                        {testEmailResult}
                      </div>
                    )}
                  </div>
                </div>

                {/* CAMPAIGN BUILDER & HISTORY */}
                <div style={{ marginTop: "24px" }}>
                  <div className="card">
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
                      <h3 style={{ fontSize: "16px", fontWeight: 600 }}>Email Campaigns</h3>
                      <button
                        onClick={() => {
                          const form = document.getElementById("campaign-form");
                          if (form) form.style.display = form.style.display === "none" ? "block" : "none";
                        }}
                        className="btn btn-secondary btn-sm"
                      >
                        + Create Campaign
                      </button>
                    </div>

                    {/* NEW CAMPAIGN FORM */}
                    <div id="campaign-form" style={{ display: "none", marginBottom: "20px", padding: "16px", backgroundColor: "#F8FAFC", borderRadius: "8px" }}>
                      <h4 style={{ fontSize: "14px", fontWeight: 600, marginBottom: "12px" }}>New Broadcast Campaign</h4>
                      <form onSubmit={handleCreateCampaign} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
                        <div>
                          <label style={{ fontSize: "11px", fontWeight: 600 }}>Campaign Title</label>
                          <input
                            type="text"
                            value={campaignTitle}
                            onChange={(e) => setCampaignTitle(e.target.value)}
                            required
                            className="input"
                          />
                        </div>
                        <div>
                          <label style={{ fontSize: "11px", fontWeight: 600 }}>Subject Line</label>
                          <input
                            type="text"
                            value={campaignSubject}
                            onChange={(e) => setCampaignSubject(e.target.value)}
                            required
                            className="input"
                          />
                        </div>
                        <div>
                          <label style={{ fontSize: "11px", fontWeight: 600 }}>Target Recipients Count</label>
                          <input
                            type="number"
                            value={campaignRecipients}
                            onChange={(e) => setCampaignRecipients(e.target.value)}
                            className="input"
                          />
                        </div>
                        <div style={{ display: "flex", alignItems: "flex-end" }}>
                          <button type="submit" className="btn btn-primary" style={{ width: "100%" }}>
                            Schedule Campaign
                          </button>
                        </div>
                      </form>
                      {campaignStatus && (
                        <div style={{ marginTop: "8px", fontSize: "12px", color: "#16A34A" }}>{campaignStatus}</div>
                      )}
                    </div>

                    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px" }}>
                      <thead>
                        <tr style={{ borderBottom: "1px solid #E2E8F0", textAlign: "left", color: "#64748B" }}>
                          <th style={{ padding: "10px" }}>Title</th>
                          <th style={{ padding: "10px" }}>Subject</th>
                          <th style={{ padding: "10px" }}>Recipients</th>
                          <th style={{ padding: "10px" }}>Open Rate</th>
                          <th style={{ padding: "10px" }}>Status</th>
                        </tr>
                      </thead>
                      <tbody>
                        {instanceData.campaigns && instanceData.campaigns.length > 0 ? (
                          instanceData.campaigns.map((cmp) => (
                            <tr key={cmp.id} style={{ borderBottom: "1px solid #E2E8F0" }}>
                              <td style={{ padding: "12px 10px", fontWeight: 600 }}>{cmp.title}</td>
                              <td style={{ padding: "12px 10px", color: "#475569" }}>{cmp.subject}</td>
                              <td className="mono" style={{ padding: "12px 10px" }}>{cmp.recipient_count}</td>
                              <td className="mono" style={{ padding: "12px 10px" }}>{cmp.open_rate}%</td>
                              <td style={{ padding: "12px 10px" }}>
                                <span className={`badge ${cmp.status === "completed" ? "badge-success" : "badge-info"}`}>
                                  {cmp.status}
                                </span>
                              </td>
                            </tr>
                          ))
                        ) : (
                          <tr>
                            <td colSpan={5} style={{ padding: "20px", textAlign: "center", color: "#94A3B8" }}>
                              No campaigns sent yet.
                            </td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* ========================================================= */}
        {/* TAB 4: ADMIN OPERATIONS & AUDIT TRAIL */}
        {/* ========================================================= */}
        {activeTab === "admin" && (
          <div>
            <div style={{ marginBottom: "24px" }}>
              <h1 style={{ fontSize: "24px", fontWeight: 700 }}>Admin Platform Telemetry & Audit</h1>
              <p style={{ color: "#64748B" }}>
                Platform-wide deployment queue monitoring, failure testing, and audit trail logs.
              </p>
            </div>

            {adminOverview && (
              <div>
                {/* METRICS */}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "16px", marginBottom: "24px" }}>
                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B" }}>TOTAL REGISTERED USERS</div>
                    <div className="mono" style={{ fontSize: "26px", fontWeight: 700, marginTop: "4px" }}>
                      {adminOverview.metrics.totalUsers}
                    </div>
                  </div>

                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B" }}>DOMAINS REGISTERED</div>
                    <div className="mono" style={{ fontSize: "26px", fontWeight: 700, marginTop: "4px" }}>
                      {adminOverview.metrics.totalDomains}
                    </div>
                  </div>

                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B" }}>TOTAL SAAS REVENUE</div>
                    <div className="mono" style={{ fontSize: "26px", fontWeight: 700, color: "#16A34A", marginTop: "4px" }}>
                      ${adminOverview.metrics.totalRevenueUSD.toFixed(2)}
                    </div>
                  </div>

                  <div className="card">
                    <div style={{ fontSize: "11px", fontWeight: 600, color: "#64748B" }}>ACTIVE WORKER DEPLOYMENTS</div>
                    <div className="mono" style={{ fontSize: "26px", fontWeight: 700, color: "#5E6AD2", marginTop: "4px" }}>
                      {adminOverview.metrics.activeDeployments} / {adminOverview.metrics.totalDeployments}
                    </div>
                  </div>
                </div>

                {/* PROVISIONING QUEUE MONITOR & SIMULATE FAILURE TOOL */}
                <div className="card" style={{ marginBottom: "24px" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
                    <h3 style={{ fontSize: "16px", fontWeight: 600 }}>Provisioning Queue Monitor</h3>
                    <span className="badge badge-info">Real-time Durable Object Engine</span>
                  </div>

                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px" }}>
                    <thead>
                      <tr style={{ borderBottom: "1px solid #E2E8F0", textAlign: "left", color: "#64748B" }}>
                        <th style={{ padding: "10px" }}>Domain</th>
                        <th style={{ padding: "10px" }}>Current Step</th>
                        <th style={{ padding: "10px" }}>Status</th>
                        <th style={{ padding: "10px" }}>Admin Email</th>
                        <th style={{ padding: "10px" }}>OTP Code</th>
                        <th style={{ padding: "10px", textAlign: "right" }}>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {adminOverview.deployments.map((d) => (
                        <tr key={d.id} style={{ borderBottom: "1px solid #E2E8F0" }}>
                          <td style={{ padding: "12px 10px", fontWeight: 600 }}>{d.domain_name}</td>
                          <td className="mono" style={{ padding: "12px 10px" }}>{d.current_step}</td>
                          <td style={{ padding: "12px 10px" }}>
                            <span className={`badge ${d.status === "ready" ? "badge-success" : d.status === "failed" ? "badge-error" : "badge-warning"}`}>
                              {d.status}
                            </span>
                          </td>
                          <td style={{ padding: "12px 10px", color: "#475569" }}>{d.admin_email}</td>
                          <td className="mono" style={{ padding: "12px 10px" }}>{d.otp_code}</td>
                          <td style={{ padding: "12px 10px", textAlign: "right" }}>
                            <div style={{ display: "flex", gap: "6px", justifyContent: "flex-end" }}>
                              <button
                                onClick={() => handleAdvancePipelineStep(d.id)}
                                className="btn btn-secondary btn-sm"
                                title="Advance Step"
                              >
                                Step
                              </button>
                              <button
                                onClick={() => handleSimulateFailure(d.id)}
                                className="btn btn-ghost btn-sm"
                                style={{ color: "#DC2626" }}
                                title="Simulate Failure"
                              >
                                Test Fail
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* AUDIT LOGS TRAIL */}
                <div className="card">
                  <h3 style={{ fontSize: "16px", fontWeight: 600, marginBottom: "16px" }}>System Security & Audit Trail</h3>

                  <div style={{ maxHeight: "320px", overflowY: "auto" }}>
                    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "12px" }}>
                      <thead>
                        <tr style={{ borderBottom: "1px solid #E2E8F0", textAlign: "left", color: "#64748B" }}>
                          <th style={{ padding: "8px" }}>Timestamp</th>
                          <th style={{ padding: "8px" }}>User</th>
                          <th style={{ padding: "8px" }}>Action</th>
                          <th style={{ padding: "8px" }}>Resource</th>
                          <th style={{ padding: "8px" }}>Details</th>
                        </tr>
                      </thead>
                      <tbody>
                        {adminOverview.recentAuditLogs.map((log) => (
                          <tr key={log.id} style={{ borderBottom: "1px solid #E2E8F0" }}>
                            <td className="mono" style={{ padding: "8px", color: "#64748B" }}>
                              {new Date(log.created_at).toLocaleTimeString()}
                            </td>
                            <td style={{ padding: "8px", fontWeight: 500 }}>{log.user_id}</td>
                            <td style={{ padding: "8px" }}>
                              <span className="badge badge-neutral">{log.action}</span>
                            </td>
                            <td className="mono" style={{ padding: "8px" }}>{log.resource_type}:{log.resource_id}</td>
                            <td style={{ padding: "8px", color: "#475569", fontFamily: "monospace", fontSize: "11px" }}>
                              {log.details}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
      </main>

      {/* CHECKOUT MODAL */}
      {showCheckoutModal && selectedDomain && (
        <div className="modal-backdrop" onClick={() => setShowCheckoutModal(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <div style={{ padding: "20px 24px", borderBottom: "1px solid #E2E8F0", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 style={{ fontSize: "18px", fontWeight: 700 }}>Complete Order & Deploy</h3>
              <button onClick={() => setShowCheckoutModal(false)} className="btn btn-ghost btn-sm">✕</button>
            </div>

            <div style={{ padding: "24px" }}>
              {/* SUMMARY CARDS */}
              <div style={{ backgroundColor: "#F8FAFC", border: "1px solid #E2E8F0", borderRadius: "8px", padding: "16px", marginBottom: "20px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "8px", fontSize: "13px" }}>
                  <span>Domain Registration (1 Year)</span>
                  <span className="mono" style={{ fontWeight: 600 }}>${selectedDomain.priceYear.toFixed(2)}</span>
                </div>
                <div style={{ fontSize: "12px", color: "#64748B", marginBottom: "12px", display: "flex", alignItems: "center", gap: "6px" }}>
                  <Globe size={12} /> {selectedDomain.domainName} (Cloudflare Registrar)
                </div>

                <div style={{ borderTop: "1px solid #E2E8F0", paddingTop: "8px", display: "flex", justifyContent: "space-between", marginBottom: "8px", fontSize: "13px" }}>
                  <span>Business Email Dashboard ({selectedPlan.name} Plan)</span>
                  <span className="mono" style={{ fontWeight: 600 }}>${selectedPlan.price.toFixed(2)}</span>
                </div>

                <div style={{ borderTop: "1px solid #CBD5E1", paddingTop: "12px", marginTop: "12px", display: "flex", justifyContent: "space-between", fontSize: "16px", fontWeight: 700 }}>
                  <span>Total Due Today</span>
                  <span className="mono" style={{ color: "#5E6AD2" }}>
                    ${(selectedDomain.priceYear + selectedPlan.price).toFixed(2)} USD
                  </span>
                </div>
              </div>

              {/* PAYMENT FORM */}
              <form onSubmit={handleCheckoutSubmit}>
                <div style={{ marginBottom: "16px" }}>
                  <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>
                    Owner Email (Dashboard & OTP Credentials Recipient)
                  </label>
                  <input
                    type="email"
                    value={user ? user.email : ""}
                    disabled
                    className="input"
                    style={{ backgroundColor: "#F8FAFC" }}
                    placeholder="Sign in first"
                  />
                </div>

                <p style={{ fontSize: "12px", color: "#64748B", marginBottom: "16px" }}>
                  {platformHealth && platformHealth.stripe
                    ? "You will be redirected to Stripe Checkout (PCI-compliant card entry)."
                    : "Stripe keys are not configured. This environment will run the demo provisioning pipeline without charging a card. Use test key sk_test_... in production setup."}
                </p>

                <button type="submit" className="btn btn-primary btn-lg" style={{ width: "100%" }} disabled={!user}>
                  <ShieldCheck size={18} /> {user ? `Pay $${(selectedDomain.priceYear + selectedPlan.price).toFixed(2)} with Stripe` : "Sign in to continue"}
                </button>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* LOGIN MODAL */}
      {showLoginModal && (
        <div className="modal-backdrop" onClick={() => setShowLoginModal(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: "400px" }}>
            <div style={{ padding: "20px 24px", borderBottom: "1px solid #E2E8F0", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 style={{ fontSize: "16px", fontWeight: 700 }}>Store Account Login</h3>
              <button onClick={() => setShowLoginModal(false)} className="btn btn-ghost btn-sm">✕</button>
            </div>

            <div style={{ padding: "24px" }}>
              <div style={{ display: "flex", gap: "8px", marginBottom: "16px" }}>
                <a className="btn btn-secondary" style={{ flex: 1 }} href="/api/auth/oauth/github">Continue with GitHub</a>
                <a className="btn btn-secondary" style={{ flex: 1 }} href="/api/auth/oauth/google">Continue with Google</a>
              </div>
              <div style={{ textAlign: "center", fontSize: "12px", color: "#94A3B8", marginBottom: "16px" }}>or use email</div>
              <form onSubmit={authMode === "register" ? handleRegister : handleLogin}>
                {authMode === "register" && (
                  <>
                    <div style={{ marginBottom: "12px" }}>
                      <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>Full name</label>
                      <input className="input" value={registerName} onChange={(e) => setRegisterName(e.target.value)} required />
                    </div>
                    <div style={{ marginBottom: "12px" }}>
                      <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>Company</label>
                      <input className="input" value={registerCompany} onChange={(e) => setRegisterCompany(e.target.value)} />
                    </div>
                  </>
                )}
                <div style={{ marginBottom: "16px" }}>
                  <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>Email</label>
                  <input
                    type="email"
                    value={loginEmail}
                    onChange={(e) => setLoginEmail(e.target.value)}
                    className="input"
                    required
                  />
                </div>

                <div style={{ marginBottom: "20px" }}>
                  <label style={{ display: "block", fontSize: "12px", fontWeight: 600, marginBottom: "6px" }}>Password</label>
                  <input
                    type="password"
                    value={loginPassword}
                    onChange={(e) => setLoginPassword(e.target.value)}
                    className="input"
                    required
                  />
                </div>

                <button type="submit" className="btn btn-primary" style={{ width: "100%" }}>
                  {authMode === "register" ? "Create account" : "Sign In"}
                </button>
              </form>
              <button
                className="btn btn-ghost"
                style={{ width: "100%", marginTop: "10px" }}
                onClick={() => setAuthMode(authMode === "register" ? "login" : "register")}
              >
                {authMode === "register" ? "Have an account? Sign in" : "Need an account? Register"}
              </button>
              <p style={{ fontSize: "11px", color: "#94A3B8", marginTop: "12px" }}>
                Demo: demo@acme.com / demo123 · Admin: admin@registermysite.com / admin123
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

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