/* ========================================================================
   screens-system.jsx — Settings, Export centre, Pricing/billing, Admin
   ====================================================================== */

const SettingsScreen = () => (
  <div style={{ height: "100%", display: "flex", background: "#1A1813" }}>
    <SidebarNav active="settings" />
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <TopBar />
      <div style={{ flex: 1, overflowY: "auto", padding: "24px 28px 40px" }}>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, letterSpacing: "0.22em", color: "#EFFF00", fontWeight: 800, textTransform: "uppercase", display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 8 }}><span style={{ width: 18, height: 1, background: "#EFFF00" }} />SETTINGS</div>
        <h1 style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 48, lineHeight: 1, textTransform: "uppercase", margin: "6px 0 24px", color: "#FFF" }}>Workspace · Joel</h1>

        <div className="bk-settings-grid" style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 20 }}>
          {/* settings nav */}
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {[
              { l: "Account",         on: true,  i: "user" },
              { l: "Workspace",       on: false, i: "briefcase" },
              { l: "Brand defaults",  on: false, i: "palette" },
              { l: "AI &amp; OpenAI",     on: false, i: "brain" },
              { l: "Supabase &amp; Storage", on: false, i: "globe" },
              { l: "Usage &amp; limits",  on: false, i: "trend" },
              { l: "Billing",         on: false, i: "receipt" },
              { l: "Team &amp; seats",    on: false, i: "users" },
              { l: "Data export",     on: false, i: "download" },
              { l: "Danger zone",     on: false, i: "alert" },
            ].map(it => (
              <button key={it.l} data-bk-bound="true" onClick={() => window.BoltKitToast?.(`${it.l.replace(/&amp;/g, "&")} settings are ${it.on ? "open" : "coming after the first beta pass"}.`)} style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 12px", background: it.on ? "#EFFF00" : "#201E18", color: it.on ? "#1A1813" : "#C8C8C5", border: it.on ? "1px solid #ADC700" : "1px solid #3A372F", fontSize: 12, fontWeight: 700, textAlign: "left", cursor: "pointer" }}>
                <Icon name={it.i} size={13} stroke={2} />
                <span dangerouslySetInnerHTML={{ __html: it.l }} />
              </button>
            ))}
          </div>

          {/* settings body */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="card has-corners" style={{ padding: 20 }}>
              <div className="card-title" style={{ marginBottom: 14 }}>Profile</div>
              <div className="bk-settings-profile-grid" style={{ display: "grid", gridTemplateColumns: "auto 1fr 1fr", gap: 14, alignItems: "center" }}>
                <div style={{ width: 64, height: 64, borderRadius: 99, background: "#EFFF00", color: "#1A1813", display: "grid", placeItems: "center", fontFamily: "'Anton', Impact, sans-serif", fontSize: 26 }}>JL</div>
                <div>
                  <label className="field-label">Display name</label>
                  <input className="input" defaultValue="Joel · BoltKit" />
                </div>
                <div>
                  <label className="field-label">Email</label>
                  <input className="input" defaultValue="joel@boltkit.co.uk" />
                </div>
              </div>
            </div>

            <div className="card" style={{ padding: 20 }}>
              <div className="card-title" style={{ marginBottom: 12 }}>Sync &amp; storage</div>
              <div className="bk-settings-sync-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
                {[
                  { l: "Supabase",         v: "Server sync when env vars are configured", st: "sync" },
                  { l: "Storage bucket",   v: "Assets and Instagram media buckets",       st: "sync" },
                  { l: "OpenAI key",       v: "Server-side only · never shown in browser", st: "sync" },
                  { l: "Sora rendering",   v: "Not enabled · add billing key",   st: "local" },
                  { l: "Anthropic key",    v: "Not connected",                   st: "local" },
                  { l: "Instagram Graph",  v: "Not connected · waiting on Meta", st: "fail" },
                ].map(t => (
                  <div key={t.l} style={{ padding: 12, background: "#201E18", border: "1px solid #3A372F" }}>
                    <div style={{ display: "flex", justifyContent: "space-between" }}>
                      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", color: "#8A8A8A", fontWeight: 800, textTransform: "uppercase" }}>{t.l}</span>
                      <SyncChip state={t.st} />
                    </div>
                    <div style={{ marginTop: 8, color: "#FFF", fontSize: 12.5 }}>{t.v}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="card" style={{ padding: 20 }}>
              <div className="card-title" style={{ marginBottom: 12 }}>AI defaults</div>
              <div className="bk-settings-form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                <div>
                  <label className="field-label">Default model</label>
                  <select className="select"><option>GPT-5 · gpt-5-2026-09 (recommended)</option></select>
                </div>
                <div>
                  <label className="field-label">Brand-lock strictness</label>
                  <select className="select"><option>High · refuse off-brand outputs</option></select>
                </div>
                <div>
                  <label className="field-label">Default tone</label>
                  <select className="select"><option>Builder · punchy · premium</option></select>
                </div>
                <div>
                  <label className="field-label">Founder voice</label>
                  <select className="select"><option>Trained · v2 · 124 posts</option></select>
                </div>
              </div>
            </div>

            {/* danger */}
            <div style={{ border: "1px solid rgba(255,77,94,0.3)", background: "rgba(255,77,94,0.04)", padding: 20 }}>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.18em", color: "#FF4D5E", fontWeight: 800, textTransform: "uppercase", marginBottom: 8 }}>DANGER ZONE</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "center", padding: "10px 0", borderBottom: "1px dashed #333" }}>
                <span style={{ fontSize: 13, color: "#FFF" }}>Export workspace data (JSON + assets)</span>
                <button data-bk-bound="true" className="btn btn-secondary btn-sm" onClick={() => window.BoltKitGo?.("exports")}>Export</button>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "center", padding: "10px 0" }}>
                <span style={{ fontSize: 13, color: "#FFF" }}>Delete workspace permanently</span>
                <button data-bk-bound="true" className="btn btn-secondary btn-sm" style={{ color: "#FF4D5E", borderColor: "rgba(255,77,94,0.4)" }} onClick={() => {
                  const ok = window.confirm?.("Delete workspace is disabled for beta safety. Open support instead?");
                  if (ok) window.BoltKitGo?.("feedback", "Tell us what you need deleted and we will handle it safely.");
                  else window.BoltKitToast?.("Delete cancelled. No data was removed.");
                }}>Delete</button>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "center", padding: "10px 0", borderTop: "1px dashed #333" }}>
                <span style={{ fontSize: 13, color: "#FFF" }}>Reset local demo workspace for a clean test run</span>
                <button data-bk-bound="true" className="btn btn-secondary btn-sm" onClick={() => {
                  const ok = window.confirm?.("Reset local demo data in this browser? This does not delete Supabase production data.");
                  if (ok) window.BoltKitResetDemo?.();
                  else window.BoltKitToast?.("Reset cancelled. No local data was changed.");
                }}>Reset demo</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

const ExportCentreScreen = () => (
  <div style={{ height: "100%", display: "flex", background: "#1A1813" }}>
    <SidebarNav active="exports" />
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <TopBar />
      <div style={{ flex: 1, overflowY: "auto", padding: "24px 28px 40px" }}>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, letterSpacing: "0.22em", color: "#EFFF00", fontWeight: 800, textTransform: "uppercase", display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 8 }}><span style={{ width: 18, height: 1, background: "#EFFF00" }} />EXPORT CENTRE</div>
        <h1 style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 48, lineHeight: 1, textTransform: "uppercase", margin: "6px 0 22px", color: "#FFF" }}>Ship the folder.</h1>

        {/* main export cards */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
          {[
            { i: "zip",  l: "Full Launch ZIP",       d: "Markdown · CSV · JSON · all assets", c: "EXPORT NOW", hl: true },
            { i: "md",   l: "Markdown bundle",       d: "All packs as .md files",             c: "EXPORT" },
            { i: "csv",  l: "Content calendar CSV",  d: "Schedule rows · platform · date",    c: "EXPORT" },
            { i: "json", l: "Project JSON",          d: "Raw project data for backup",        c: "EXPORT" },
          ].map(t => (
            <div key={t.l} style={{ padding: 20, background: t.hl ? "#EFFF00" : "#26241E", color: t.hl ? "#1A1813" : "#FFF", border: t.hl ? "1px solid #ADC700" : "1px solid #3A372F", position: "relative", overflow: "hidden" }}>
              {t.hl && <div style={{ position: "absolute", top: 10, right: 10, fontFamily: "'JetBrains Mono', monospace", fontSize: 9, padding: "2px 6px", background: "#1A1813", color: "#EFFF00", letterSpacing: "0.18em", fontWeight: 800 }}>HERO</div>}
              <div style={{ width: 38, height: 38, background: t.hl ? "#1A1813" : "#2C2A23", border: t.hl ? "1px solid #1A1813" : "1px solid #3A372F", display: "grid", placeItems: "center", color: t.hl ? "#EFFF00" : "#EFFF00" }}>
                <Icon name={t.i} size={16} stroke={2} />
              </div>
              <div style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 26, marginTop: 12, letterSpacing: "0.02em", textTransform: "uppercase" }}>{t.l}</div>
              <div style={{ fontSize: 12, marginTop: 4, opacity: t.hl ? 0.8 : 1, color: t.hl ? "#1A1813" : "#8A8A8A" }}>{t.d}</div>
              <button className={"btn " + (t.hl ? "btn-dark" : "btn-primary")} style={{ marginTop: 14, width: "100%" }}>
                <Icon name="download" size={12} stroke={2} /> {t.c}
              </button>
            </div>
          ))}
        </div>

        {/* zip preview + history */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 16 }}>
          <div className="card" style={{ padding: 18 }}>
            <div className="card-title" style={{ marginBottom: 10 }}>ZIP structure preview</div>
            <pre className="tree" style={{ margin: 0 }}>{`📁 BoltKit Export · Renoo · v3.2/
├── 📄 brand-summary.md
├── 📄 launch-pack.md
├── 📄 instagram-posts.md     · 30 captions
├── 📄 video-scripts.md       · 12 reels
├── 📄 paid-ads.md            · 28 A/B
├── 📄 app-store-copy.md
├── 📄 landing-page-copy.md
├── 📄 seo-pack.md
├── 📄 claude-prompts.md
├── 📄 codex-prompts.md
├── 📄 content-calendar.csv
├── 📄 project-data.json
└── 📁 assets/ · 64 files`}</pre>
          </div>

          <div className="card" style={{ padding: 18 }}>
            <div className="card-title" style={{ marginBottom: 10 }}>Export history</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {[
                { l: "Renoo-v3.2-export.zip",        sz: "4.2 MB · 132 files", t: "09:02 today", st: "READY" },
                { l: "Renoo-v3.1-export.zip",        sz: "4.0 MB · 124 files", t: "Thu 08:41",  st: "READY" },
                { l: "Atelier-launch-pack.zip",      sz: "2.8 MB · 96 files",  t: "Wed 17:14",  st: "READY" },
                { l: "content-calendar-NOV.csv",     sz: "12 KB",              t: "Mon 11:02",  st: "READY" },
                { l: "Lofti-export.zip",             sz: "1.8 MB · 64 files",  t: "Sun 22:11",  st: "EXPIRED" },
              ].map(h => (
                <div key={h.l} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 10, padding: "8px 10px", background: "#201E18", border: "1px solid #3A372F", alignItems: "center" }}>
                  <div style={{ width: 30, height: 30, background: "#1A1813", border: "1px solid #3A372F", display: "grid", placeItems: "center", color: h.st === "READY" ? "#EFFF00" : "#5C5C5C" }}>
                    <Icon name="zip" size={13} stroke={2} />
                  </div>
                  <div>
                    <div style={{ fontSize: 12, color: "#FFF", fontWeight: 700 }}>{h.l}</div>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, color: "#8A8A8A", letterSpacing: "0.12em", textTransform: "uppercase", marginTop: 2 }}>{h.sz} · {h.t}</div>
                  </div>
                  <span className={"pill " + (h.st === "READY" ? "pill-yellow" : "pill-dark")} style={{ fontSize: 9 }}>{h.st}</span>
                  <button data-bk-bound="true" className="icon-btn" onClick={() => window.BoltKitGo?.("exports")} aria-label={`Download ${h.l}`}><Icon name="download" size={12} stroke={2} /></button>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

const billingPlans = [
  { key: "starter", n: "Starter", m: 12, y: 120, u: ["5 projects", "Social content packs", "ZIP exports", "Content calendar"], cta: "Start Starter" },
  { key: "pro", n: "Pro", m: 29, y: 290, u: ["Unlimited projects", "Full launch packs", "AI prompts", "Advanced exports"], cta: "Start Pro", hl: true },
  { key: "business", n: "Business", m: 89, y: 890, u: ["Client workspaces", "Multi-brand operations", "Priority support", "Agency exports"], cta: "Start Business" },
];

const BillingStatusPanel = ({ status, loading, message, onPortal, onRefresh }) => {
  const sub = status || {};
  const tone = sub.is_active || sub.is_trialing ? "green" : sub.is_past_due ? "amber" : "dark";
  const renewal = sub.current_period_end ? new Date(sub.current_period_end).toLocaleDateString() : "Not active";
  return (
    <div className="ai-surface billing-status-panel">
      <div>
        <div className="ig-eyebrow"><span />BILLING STATUS</div>
        <h2>{sub.plan_key ? sub.plan_key.toUpperCase() : "FREE"} · {sub.status || "none"}</h2>
        <p>{sub.is_past_due ? "Payment needs attention. Premium access may be limited until Stripe confirms payment." : sub.is_cancelled ? "This subscription is cancelled or ending." : "Subscription state is synced from Stripe webhooks when configured."}</p>
        <div className="billing-status-grid">
          <span><b>Renewal</b>{renewal}</span>
          <span><b>Cancel at period end</b>{sub.cancel_at_period_end ? "Yes" : "No"}</span>
          <span><b>Access</b>{sub.has_premium_access ? "Premium" : sub.has_grace_access ? "Grace" : "Free / blocked"}</span>
        </div>
        {message && <div className="billing-message">{message}</div>}
      </div>
      <div className="billing-actions">
        <button data-bk-bound="true" className="btn btn-primary" disabled={loading} onClick={onPortal}>Manage billing</button>
        <button data-bk-bound="true" className="btn btn-secondary" disabled={loading} onClick={onRefresh}>Refresh</button>
      </div>
    </div>
  );
};

const PricingBillingScreen = () => {
  const [interval, setInterval] = React.useState("monthly");
  const [loading, setLoading] = React.useState("");
  const [message, setMessage] = React.useState("");
  const [status, setStatus] = React.useState(null);
  const isPricing = window.location.pathname === "/pricing" || window.location.hash === "#pricing";
  const organisationId = window.BoltKitOrganisationId?.() || "11111111-1111-4111-8111-111111111111";

  const refreshStatus = React.useCallback(async () => {
    try {
      setLoading("status");
      const data = await fetch("/api/billing/status", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ organisation_id: organisationId })
      }).then(r => r.json());
      if (data.ok) setStatus(data.subscription);
      else setMessage(data.error || "Billing status is not available yet.");
    } catch {
      setMessage("Billing status could not be loaded. You can still use the demo workspace.");
    } finally {
      setLoading("");
    }
  }, [organisationId]);

  React.useEffect(() => { refreshStatus(); }, [refreshStatus]);

  const startCheckout = async (planKey) => {
    try {
      setLoading(planKey);
      setMessage("");
      const data = await fetch("/api/billing/create-checkout-session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ organisation_id: organisationId, plan_key: planKey, billing_interval: interval })
      }).then(r => r.json());
      if (data.url) {
        window.location.href = data.url;
        return;
      }
      setMessage(data.error || "Stripe checkout is not configured yet.");
      window.BoltKitToast?.("Stripe checkout is not configured yet.");
    } catch {
      setMessage("Could not start checkout. Check Stripe server configuration.");
    } finally {
      setLoading("");
    }
  };

  const openPortal = async () => {
    try {
      setLoading("portal");
      const data = await fetch("/api/billing/create-portal-session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ organisation_id: organisationId })
      }).then(r => r.json());
      if (data.url) {
        window.location.href = data.url;
        return;
      }
      setMessage(data.error || "Billing portal is not ready yet.");
    } catch {
      setMessage("Could not open Stripe Billing Portal.");
    } finally {
      setLoading("");
    }
  };

  return (
    <div className="billing-page">
      <SidebarNav active="billing" />
      <div className="billing-main">
        <TopBar />
        <div className="billing-content">
          <div className="billing-hero">
            <div>
              <div className="ig-eyebrow"><span />STRIPE BILLING</div>
              <h1>{isPricing ? "Choose a platform plan" : "Manage your BoltKit plan"}</h1>
              <p>These subscriptions bill businesses for using BoltKit. Your own customers' payments stay separate from BoltKit platform billing.</p>
            </div>
            <div className="billing-toggle" role="group" aria-label="Billing interval">
              {["monthly", "yearly"].map(value => (
                <button key={value} data-bk-bound="true" className={interval === value ? "active" : ""} onClick={() => setInterval(value)}>{value}</button>
              ))}
            </div>
          </div>

          {!isPricing && (
            <BillingStatusPanel status={status} loading={Boolean(loading)} message={message} onPortal={openPortal} onRefresh={refreshStatus} />
          )}
          {isPricing && message && <div className="billing-message">{message}</div>}

          <div className="billing-plan-grid">
            {billingPlans.map(plan => {
              const price = interval === "yearly" ? plan.y : plan.m;
              const current = status?.plan_key === plan.key && (status?.is_active || status?.is_trialing);
              return (
                <div key={plan.key} className={"billing-plan-card" + (plan.hl ? " is-popular" : "")}>
                  {plan.hl && <span className="pill pill-yellow">POPULAR</span>}
                  {current && <span className="pill pill-green">CURRENT</span>}
                  <div className="billing-plan-name">{plan.n}</div>
                  <div className="billing-price">£{price}<span>/{interval === "yearly" ? "yr" : "mo"}</span></div>
                  <ul>
                    {plan.u.map(item => <li key={item}><Icon name="check" size={13} stroke={3} />{item}</li>)}
                  </ul>
                  <button data-bk-bound="true" className={plan.hl ? "btn btn-dark" : "btn btn-primary"} disabled={Boolean(loading) || current} onClick={() => startCheckout(plan.key)}>
                    {loading === plan.key ? "Starting..." : current ? "Current plan" : plan.cta}
                  </button>
                </div>
              );
            })}
          </div>

          <div className="billing-note">
            <b>Future-ready:</b> Stripe Connect, marketplace fees, per-seat billing and usage billing are intentionally isolated for later. This build only bills BoltKit customers for their BoltKit subscription.
          </div>
        </div>
      </div>
    </div>
  );
};

const BillingSuccessScreen = () => {
  const [message, setMessage] = React.useState("Checking your Stripe subscription...");
  React.useEffect(() => {
    let active = true;
    const organisationId = window.BoltKitOrganisationId?.() || "11111111-1111-4111-8111-111111111111";
    const timer = window.setInterval(async () => {
      try {
        const data = await fetch("/api/billing/status", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ organisation_id: organisationId })
        }).then(r => r.json());
        if (!active) return;
        if (data.subscription?.is_active || data.subscription?.is_trialing) setMessage("Your subscription is active. You can return to the dashboard.");
        else setMessage("Stripe is still activating your subscription. Webhooks can take a moment.");
      } catch {
        if (active) setMessage("Subscription refresh failed. Open Billing to check again.");
      }
    }, 3000);
    return () => { active = false; window.clearInterval(timer); };
  }, []);
  return (
    <div className="billing-page">
      <SidebarNav active="billing" />
      <div className="billing-main">
        <TopBar />
        <main className="billing-content">
          <div className="ai-surface billing-success-card">
            <div className="ig-eyebrow"><span />CHECKOUT COMPLETE</div>
            <h1>Subscription is being activated</h1>
            <p>{message}</p>
            <div className="customer-actions">
              <button data-bk-bound="true" className="btn btn-primary" onClick={() => window.BoltKitGo?.("dashboard")}>Back to dashboard</button>
              <button data-bk-bound="true" className="btn btn-secondary" onClick={() => window.BoltKitGo?.("billing")}>Open billing</button>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
};

const AdminBillingScreen = () => {
  const [rows, setRows] = React.useState([]);
  const [filter, setFilter] = React.useState("all");
  const [message, setMessage] = React.useState("Loading admin billing...");
  React.useEffect(() => {
    fetch("/api/admin/billing", { headers: { "x-boltkit-user-email": window.BoltKitSession?.user?.email || "" } })
      .then(r => r.json())
      .then(data => {
        if (data.ok) {
          setRows(data.rows || []);
          setMessage("");
        } else setMessage(data.error || "Admin billing is not available.");
      })
      .catch(() => setMessage("Admin billing could not be loaded."));
  }, []);
  const filtered = rows.filter(row => filter === "all" ? true : filter === "no_subscription" ? !row.status : row.status === filter);
  return (
    <div className="billing-page">
      <SidebarNav active="billing" />
      <div className="billing-main">
        <TopBar />
        <main className="billing-content">
          <div className="billing-hero">
            <div>
              <div className="ig-eyebrow"><span />OWNER ADMIN</div>
              <h1>Billing dashboard</h1>
              <p>Owner-only view of BoltKit platform subscriptions. Keep this hidden from normal users.</p>
            </div>
          </div>
          {message && <div className="billing-message">{message}</div>}
          <div className="billing-filter-row">
            {["all", "active", "trialing", "past_due", "unpaid", "cancelled", "no_subscription"].map(value => (
              <button key={value} data-bk-bound="true" className={filter === value ? "active" : ""} onClick={() => setFilter(value)}>{value.replace("_", " ")}</button>
            ))}
          </div>
          <div className="billing-admin-table">
            {filtered.map(row => (
              <div key={row.id || row.stripe_subscription_id} className="billing-admin-row">
                <b>{row.organisations?.name || row.organisation_id || "Organisation"}</b>
                <span>{row.plan_key || "free"} · {row.status || "none"}</span>
                <span>{row.current_period_end ? new Date(row.current_period_end).toLocaleDateString() : "No renewal"}</span>
                <code>{row.stripe_customer_id || "no_customer"}</code>
                <code>{row.stripe_subscription_id || "no_subscription"}</code>
              </div>
            ))}
          </div>
        </main>
      </div>
    </div>
  );
};

const AdminScreen = () => (
  <div style={{ height: "100%", display: "flex", background: "#1A1813" }}>
    {/* admin uses a distinct red-accented sidebar to make ownership obvious */}
    <div style={{ width: 220, background: "#080000", borderRight: "1px solid #2A0000", display: "flex", flexDirection: "column" }}>
      <div style={{ padding: "16px 14px", borderBottom: "1px solid #2A0000", display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ width: 30, height: 30, background: "#FF4D5E", color: "#FFF", display: "grid", placeItems: "center", borderRadius: 4 }}>
          <Icon name="shield" size={16} stroke={2} />
        </div>
        <div>
          <div style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 18, color: "#FFF" }}>ADMIN · CRM</div>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, color: "#FF4D5E", letterSpacing: "0.16em", fontWeight: 800 }}>OWNER-ONLY</div>
        </div>
      </div>
      <div style={{ padding: 10 }}>
        {[
          { l: "Dashboard",       i: "grid",   on: true },
          { l: "Customers",       i: "users",  n: "182" },
          { l: "Projects",        i: "folder", n: "1.2k" },
          { l: "Credits / Plans", i: "receipt" },
          { l: "AI jobs",         i: "brain",  n: "12" },
          { l: "IG scheduler",    i: "insta" },
          { l: "Exports",         i: "download" },
          { l: "Feature flags",   i: "settings" },
          { l: "System health",   i: "trend" },
          { l: "Activity log",    i: "list" },
          { l: "Support notes",   i: "doc" },
        ].map(it => (
          <div key={it.l} style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 10px", borderRadius: 4, color: it.on ? "#1A1813" : "#C8C8C5", background: it.on ? "#FF4D5E" : "transparent", fontSize: 12, fontWeight: 700, marginBottom: 2 }}>
            <Icon name={it.i} size={13} stroke={2} />
            <span>{it.l}</span>
            {it.n && <span style={{ marginLeft: "auto", fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, padding: "1px 5px", background: it.on ? "#1A1813" : "#1A1A1A", color: it.on ? "#FF4D5E" : "#8A8A8A", borderRadius: 3, fontWeight: 700 }}>{it.n}</span>}
          </div>
        ))}
      </div>
    </div>

    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ height: 52, background: "rgba(20,0,0,0.6)", borderBottom: "1px solid #2A0000", display: "flex", alignItems: "center", padding: "0 16px", gap: 10 }}>
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.22em", color: "#FF4D5E", fontWeight: 800, textTransform: "uppercase" }}>OWNER ADMIN · joel@boltkit.co.uk</span>
        <SyncChip state="sync" />
        <span style={{ marginLeft: "auto", fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: "#8A8A8A", letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 800 }}>v1.4.2 · production</span>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "24px 28px 40px" }}>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, letterSpacing: "0.22em", color: "#FF4D5E", fontWeight: 800, textTransform: "uppercase", display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 8 }}><span style={{ width: 18, height: 1, background: "#FF4D5E" }} />ADMIN · INTERNAL</div>
        <h1 style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 48, lineHeight: 1, textTransform: "uppercase", margin: "6px 0 22px", color: "#FFF" }}>System Overview</h1>

        <div className="mini-tiles">
          <div className="mini-tile" style={{ borderColor: "#2A0000" }}>
            <div className="l">CUSTOMERS</div>
            <div className="v">182</div>
            <div className="t"><span style={{ color: "#FF4D5E", fontWeight: 800 }}>+14</span> this week</div>
          </div>
          <div className="mini-tile" style={{ borderColor: "#2A0000" }}>
            <div className="l">PROJECTS</div>
            <div className="v">1,284</div>
            <div className="t">avg 7 per customer</div>
          </div>
          <div className="mini-tile" style={{ borderColor: "#2A0000" }}>
            <div className="l">AI CALLS · 24H</div>
            <div className="v">18.2<span className="u">K</span></div>
            <div className="t">12 jobs queued</div>
          </div>
          <div className="mini-tile" style={{ borderColor: "#2A0000" }}>
            <div className="l">REVENUE · MRR</div>
            <div className="v">£0</div>
            <div className="t">Payments not enabled</div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14, marginTop: 18 }}>
          <div className="card" style={{ padding: 18, borderColor: "#2A0000" }}>
            <div className="card-title" style={{ marginBottom: 12 }}>Customer activity</div>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
              <thead>
                <tr style={{ color: "#5C5C5C", fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 800 }}>
                  {["Customer","Plan","Projects","Packs","Last seen","Status"].map(h => <th key={h} style={{ textAlign: "left", padding: "8px 6px", borderBottom: "1px solid #2A0000" }}>{h}</th>)}
                </tr>
              </thead>
              <tbody>
                {[
                  { c: "joel@boltkit.co.uk",  p: "Owner",    pj: 6,  pk: 11, t: "now",       s: "ACTIVE" },
                  { c: "amy@studio42.io",     p: "Pro",      pj: 4,  pk: 8,  t: "12 m ago",  s: "ACTIVE" },
                  { c: "raj@halftone.app",    p: "Starter",  pj: 2,  pk: 3,  t: "1 h ago",   s: "ACTIVE" },
                  { c: "kai@lofti.live",      p: "Free",     pj: 1,  pk: 1,  t: "3 h ago",   s: "TRIAL" },
                  { c: "sam@atelier.design",  p: "Pro",      pj: 9,  pk: 22, t: "yesterday", s: "ACTIVE" },
                  { c: "mira@spritely.io",    p: "Free",     pj: 1,  pk: 1,  t: "4 d ago",   s: "STALE" },
                ].map(r => (
                  <tr key={r.c} style={{ borderBottom: "1px solid #1A0000" }}>
                    <td style={{ padding: "10px 6px", color: "#FFF" }}>{r.c}</td>
                    <td style={{ padding: "10px 6px", color: "#C8C8C5" }}>{r.p}</td>
                    <td style={{ padding: "10px 6px", color: "#C8C8C5" }}>{r.pj}</td>
                    <td style={{ padding: "10px 6px", color: "#C8C8C5" }}>{r.pk}</td>
                    <td style={{ padding: "10px 6px", color: "#8A8A8A", fontFamily: "'JetBrains Mono', monospace" }}>{r.t}</td>
                    <td style={{ padding: "10px 6px" }}>
                      <Pill tone={r.s === "ACTIVE" ? "green" : r.s === "TRIAL" ? "amber" : "dark"}>{r.s}</Pill>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* AI jobs */}
          <div className="card" style={{ padding: 18, borderColor: "#2A0000" }}>
            <div className="card-title" style={{ marginBottom: 10 }}>AI jobs · live</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {[
                { l: "Renoo · Full Launch Pack",   s: "RUN", p: 78 },
                { l: "Atelier · Instagram 90",     s: "RUN", p: 42 },
                { l: "Lofti · Video Scripts",      s: "QUEUE", p: 0 },
                { l: "Halftone · App Store",       s: "QUEUE", p: 0 },
                { l: "Renoo · Codex Prompts · v3", s: "DONE", p: 100 },
              ].map(j => (
                <div key={j.l} style={{ padding: "8px 10px", background: "#201E18", border: "1px solid #1A0000" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                    <span style={{ fontSize: 12, color: "#FFF" }}>{j.l}</span>
                    <span className={"pill " + (j.s === "RUN" ? "pill-yellow" : j.s === "QUEUE" ? "pill-dark" : "pill-green")} style={{ fontSize: 9 }}>{j.s}</span>
                  </div>
                  <div style={{ height: 3, background: "#1A0000" }}>
                    <div style={{ width: j.p + "%", height: "100%", background: j.s === "DONE" ? "#4ADE80" : "#EFFF00" }} />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

Object.assign(window, { SettingsScreen, ExportCentreScreen, PricingBillingScreen, BillingSuccessScreen, AdminBillingScreen, AdminScreen });
