// ---- Client-side router ----
const RouterCtx = React.createContext({ currentScreen: "landing", navigate: () => {}, transitioning: false });

function useRouter() {
  const [currentScreen, setCurrentScreen] = React.useState(() => {
    const params = new URLSearchParams(window.location.search);
    const screen = params.get('screen');
    const validScreens = ["reset-password", "login", "signup", "dashboard"];
    return (screen && validScreens.includes(screen)) ? screen : "landing";
  });
  const [transitioning, setTransitioning] = React.useState(false);
  const navigate = React.useCallback((screen) => {
    setTransitioning(true);
    setTimeout(() => {
      setCurrentScreen(screen);
      setTransitioning(false);
    }, 120);
  }, []);
  return { currentScreen, navigate, transitioning };
}

// Variation B — "Cinemascope": true black + electric green, cinematic film-grid
const themeB = {
  bg: "#050505",
  bgSoft: "#0d0d0d",
  panel: "#0a0a0a",
  panelLine: "rgba(255,255,255,0.1)",
  text: "#F5F5F4",
  textDim: "#8A8A85",
  accent: "#39FF6A",
  accentText: "#050505",
  frame: "#000",
  tabsBg: "#000",
  shadow: "0 30px 80px rgba(0,0,0,0.7)",
};

const DISPLAY_B = "'IBM Plex Mono', ui-monospace, Menlo, monospace";

const SCREEN_LABELS = {
  dashboard:        "// DASHBOARD",
  editor:           "// EDITOR",
  marketplace:      "// MARKETPLACE",
  jobs:             "// JOBS",
  community:        "// COMMUNITY",
  tokens:           "// TOKENS",
  settings:         "// SETTINGS",
  admin:            "// ADMIN",
  support:          "// SUPPORT",
  "error-404":      "// NOT FOUND",
  "error-403":      "// FORBIDDEN",
  "error-408":      "// TIMEOUT",
  "error-429":      "// RATE LIMITED",
  "error-500":      "// SERVER ERROR",
  "error-503":      "// UNAVAILABLE",
  offline:          "// OFFLINE",
  "session-expired":"// SESSION EXPIRED",
  "payment-success":"// PAYMENT SUCCESSFUL",
  "reset-password":  "// RESET PASSWORD",
};

function VariationB({ accent, density = "comfortable" } = {}) {
  const t = accent ? { ...themeB, accent, accentText: themeB.accentText } : themeB;
  const PAD = density === "compact" ? "0 48px" : "0 64px";
  const [modal, setModal] = React.useState(null); // null | "signin" | "download"
  const openDownload = () => setModal("download");
  const [newsletterEmail, setNewsletterEmail] = React.useState("");
  const [newsletterState, setNewsletterState] = React.useState("idle"); // "idle"|"loading"|"success"|"error"
  const handleNewsletterSubmit = async (e) => {
    e.preventDefault();
    if (!newsletterEmail.trim() || newsletterState !== "idle") return;
    setNewsletterState("loading");
    try {
      const { error } = await db.from('newsletter_subscriber').insert({ email: newsletterEmail.trim(), created_at: new Date().toISOString() });
      setNewsletterState(error ? "error" : "success");
      if (!error) setNewsletterEmail("");
    } catch (err) {
      setNewsletterState("error");
    }
  };
  const routerState = useRouter();
  const { currentScreen, navigate, transitioning } = routerState;
  const { user } = useAuth();

  // After Google OAuth redirect or any sign-in, land on dashboard instead of the homepage
  React.useEffect(() => {
    if (user && currentScreen === "landing") {
      navigate("dashboard");
    }
  }, [user, currentScreen, navigate]);

  // Global Escape → dashboard (unless a modal is open)
  React.useEffect(() => {
    if (currentScreen === "landing") return;
    const onKey = (e) => {
      if (e.key === "Escape") {
        if (window.__vlModalDepth > 0) return;
        navigate("dashboard");
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [currentScreen, navigate]);

  // Global offline event → navigate to offline screen
  React.useEffect(() => {
    const handleOffline = () => navigate('offline');
    window.addEventListener('vlstudio:offline', handleOffline);
    return () => window.removeEventListener('vlstudio:offline', handleOffline);
  }, [navigate]);

  return (
    <RouterCtx.Provider value={routerState}>
    <div style={{
      width: "100%", background: t.bg, color: t.text, minHeight: currentScreen === "landing" ? 3400 : "100vh",
      fontFamily: "'Inter', -apple-system, system-ui, sans-serif",
      opacity: transitioning ? 0 : 1,
      transition: "opacity 120ms ease",
    }}>
      {currentScreen !== "landing" && (
        <AppNav t={t} currentScreen={currentScreen} navigate={navigate} />
      )}
      {currentScreen === "signup" && <SignupScreen t={t} navigate={navigate} />}
      {currentScreen === "login" && <LoginScreen t={t} navigate={navigate} />}
      {currentScreen === "dashboard" && <DashboardScreen t={t} navigate={navigate} />}
      {currentScreen === "editor" && <EditorScreen t={t} navigate={navigate} />}
      {currentScreen === "marketplace" && <MarketplaceScreen t={t} navigate={navigate} />}
      {currentScreen === "jobs" && <JobsScreen t={t} navigate={navigate} />}
      {currentScreen === "community" && <CommunityScreen t={t} navigate={navigate} />}
      {currentScreen === "tokens" && <TokensScreen t={t} navigate={navigate} />}
      {currentScreen === "settings" && <SettingsScreen t={t} navigate={navigate} />}
      {currentScreen === "admin" && <AdminScreen t={t} navigate={navigate} />}
      {currentScreen === "support" && <SupportScreen t={t} navigate={navigate} />}
      {currentScreen === "error-404" && <ErrorScreen code={404} title="PAGE NOT FOUND" message="The page you're looking for doesn't exist or has been moved." t={t} navigate={navigate} />}
      {currentScreen === "error-403" && <ErrorScreen code={403} title="FORBIDDEN" message="You don't have permission to access this resource." t={t} navigate={navigate} />}
      {currentScreen === "error-408" && <ErrorScreen code={408} title="REQUEST TIMEOUT" message="The server timed out waiting for your request. Please try again." t={t} navigate={navigate} />}
      {currentScreen === "error-429" && <ErrorScreen code={429} title="TOO MANY REQUESTS" message="You've sent too many requests. Take a short break and try again." t={t} navigate={navigate} />}
      {currentScreen === "error-500" && <ErrorScreen code={500} title="INTERNAL SERVER ERROR" message="Something went wrong on our end. We've been notified and are looking into it." t={t} navigate={navigate} />}
      {currentScreen === "error-503" && <ErrorScreen code={503} title="SERVICE UNAVAILABLE" message="VLStudio is temporarily down for maintenance. We'll be back shortly." t={t} navigate={navigate} />}
      {currentScreen === "offline" && <OfflineScreen t={t} navigate={navigate} />}
      {currentScreen === "session-expired" && <SessionExpiredScreen t={t} navigate={navigate} />}
      {currentScreen === "payment-success" && <PaymentSuccessScreen t={t} navigate={navigate} />}
      {currentScreen === "reset-password" && <ResetPasswordScreen t={t} navigate={navigate} />}
      {currentScreen === "landing" && (<>
      {/* NAV */}
      <header style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "20px 32px", borderBottom: `1px solid ${t.panelLine}`,
        position: "sticky", top: 0, background: t.bg + "ee", backdropFilter: "blur(10px)", zIndex: 10,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <VLMark color={t.accent}/>
          <span style={{ fontWeight: 700, fontSize: 16, letterSpacing: 2, fontFamily: DISPLAY_B }}>VLSTUDIO</span>
        </div>
        <nav style={{ display: "flex", gap: 28, fontSize: 13, fontWeight: 500, fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase" }}>
          {["Product", "Features", "Use cases", "About", "Contact"].map(l => (
            <a key={l} style={{ color: t.text, textDecoration: "none", cursor: "pointer" }}>{l}</a>
          ))}
        </nav>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <button onClick={() => navigate("login")} style={{
            background: "transparent", color: t.text, border: `1px solid ${t.panelLine}`, borderRadius: 4,
            padding: "10px 16px", fontSize: 12, fontWeight: 700, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}>
            Sign in
          </button>
          <button onClick={() => navigate("signup")} style={{
            background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "10px 18px", fontSize: 12, fontWeight: 800, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}>
            ▶ Get the beta
          </button>
        </div>
      </header>

      {/* HERO — film slate aesthetic */}
      <section style={{ padding: "60px 64px 80px", position: "relative" }}>
        {/* Slate strip */}
        <div style={{
          display: "flex", alignItems: "center", gap: 16, marginBottom: 40,
          fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 2, textTransform: "uppercase",
        }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: t.accent }}>
            <span style={{ width: 8, height: 8, background: t.accent, borderRadius: 99, boxShadow: `0 0 12px ${t.accent}` }}/>
            REC · BETA · v0.9.2
          </span>
          <span>SCENE 01 / TAKE 12</span>
          <span style={{ flex: 1, height: 1, background: t.panelLine }}/>
          <span>OPEN BETA · FREE TO USE</span>
        </div>

        <h1 style={{
          fontSize: 132, lineHeight: 0.88, fontWeight: 900, letterSpacing: -4,
          margin: "0 0 28px", fontFamily: DISPLAY_B,
        }}>
          POST-<wbr/>PRODUCTION,<br/>
          <span style={{ color: t.accent }}>POST-</span><span style={{
            display: "inline-block", textDecoration: "line-through", textDecorationColor: t.accent,
            textDecorationThickness: 6,
          }}>PROBLEM.</span>
        </h1>
        <p style={{ fontSize: 18, color: t.textDim, lineHeight: 1.55, maxWidth: 620, margin: "0 0 32px" }}>
          VLStudio cuts the grunt work out of editing. Auto-trim, caption, translate, and reframe in one window. Designed for the creators and small studios who post weekly — not for Hollywood.
        </p>

        {/* Two-column: editor + side rail */}
        <div style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr", gap: 24, marginTop: 48 }}>
          <MockEditor theme={t} label="ep_042_pod-cut.mov" showHint={true}/>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <StatCardB t={t} big="4 in 1" label="cut, caption, translate, reframe" sub="one window. zero plugins."/>
            <StatCardB t={t} big="$0" label="while we're in beta" sub="report bugs, keep using it"/>
            <button onClick={openDownload} style={{
              background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
              padding: "22px 24px", fontSize: 18, fontWeight: 800, cursor: "pointer",
              fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase",
              boxShadow: `0 0 0 1px ${t.accent}, 0 0 40px ${t.accent}55`,
            }}>
              ↓ DOWNLOAD FREE
            </button>
            <div style={{ fontSize: 11, color: t.textDim, fontFamily: DISPLAY_B, letterSpacing: 1, textAlign: "center", textTransform: "uppercase" }}>
              macOS · Windows · 240MB · No card
            </div>
          </div>
        </div>
      </section>

      {/* LOGO STRIP */}
      <section style={{ padding: "40px 64px", borderTop: `1px solid ${t.panelLine}`, borderBottom: `1px solid ${t.panelLine}` }}>
        <div style={{ fontSize: 11, color: t.textDim, textAlign: "center", marginBottom: 20, letterSpacing: 3, textTransform: "uppercase", fontFamily: DISPLAY_B, fontWeight: 600 }}>
          ━━ Built by creators who post weekly ━━
        </div>
        <LogoStrip items={["YOUTUBE", "TIKTOK", "INSTAGRAM", "PODCAST", "LINKEDIN", "X"]} color={t.text}/>
      </section>

      {/* FEATURE GRID — film strip layout */}
      <section style={{ padding: "100px 64px" }}>
        <div style={{ marginBottom: 56, fontFamily: DISPLAY_B }}>
          <div style={{ fontSize: 12, color: t.accent, letterSpacing: 3, marginBottom: 12, textTransform: "uppercase" }}>
            // Feature reel
          </div>
          <h2 style={{ fontSize: 88, fontWeight: 900, letterSpacing: -3, margin: 0, lineHeight: 0.9 }}>
            SIX TOOLS.<br/>NO TABS.
          </h2>
        </div>
        <FeatureRollB t={t}/>
      </section>

      {/* WALKTHROUGH — co-edit */}
      <section style={{ padding: "0 64px 100px" }}>
        <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, overflow: "hidden" }}>
          <div style={{ borderBottom: `1px solid ${t.panelLine}`, padding: "14px 24px", display: "flex", justifyContent: "space-between", fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 2, textTransform: "uppercase" }}>
            <span style={{ color: t.accent }}>● TIMELINE / CO-EDIT</span>
            <span>04 collaborators</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1.1fr", gap: 0 }}>
            <div style={{ padding: "56px", borderRight: `1px solid ${t.panelLine}` }}>
              <h2 style={{ fontSize: 56, fontWeight: 900, letterSpacing: -1.6, margin: "0 0 20px", lineHeight: 0.95, fontFamily: DISPLAY_B }}>
                YOUR EDITOR<br/>WITH PR REVIEWS.
              </h2>
              <p style={{ color: t.textDim, fontSize: 16, lineHeight: 1.6, margin: "0 0 28px" }}>
                Drop a project link in your team chat. Reviewers leave timestamped notes — or push edits straight into your timeline. Approve, skip, or counter. Like git for video.
              </p>
              <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
                {[
                  ["maya",  "00:14", "trim the 'umm' here", "merged"],
                  ["joel",  "00:38", "swap to wide cut",   "open"],
                  ["ana",   "01:02", "missing 's' in caption", "merged"],
                  ["theo",  "01:48", "drop bg music here",  "open"],
                ].map(([u, ts, msg, st], i) => (
                  <div key={i} style={{
                    display: "grid", gridTemplateColumns: "70px 60px 1fr 80px",
                    alignItems: "center", gap: 10, padding: "12px 0",
                    borderBottom: `1px dashed ${t.panelLine}`, fontSize: 13, fontFamily: DISPLAY_B,
                  }}>
                    <span style={{ color: t.accent }}>@{u}</span>
                    <span style={{ color: t.textDim }}>{ts}</span>
                    <span>{msg}</span>
                    <span style={{
                      fontSize: 10, fontWeight: 800, padding: "3px 8px", borderRadius: 2, letterSpacing: 1, textTransform: "uppercase",
                      background: st === "merged" ? t.accent : "transparent",
                      color: st === "merged" ? t.accentText : t.textDim,
                      border: st === "merged" ? "none" : `1px solid ${t.panelLine}`, textAlign: "center",
                    }}>{st}</span>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ padding: 32 }}>
              <MockEditor theme={t} label="collab-review.mov"/>
            </div>
          </div>
        </div>
      </section>

      {/* USE CASES */}
      <section style={{ padding: "0 64px 120px" }}>
        <h2 style={{ fontSize: 80, fontWeight: 900, letterSpacing: -2.5, margin: "0 0 48px", lineHeight: 0.9, fontFamily: DISPLAY_B }}>
          ONE EDIT.<br/>EVERY <span style={{ color: t.accent }}>FORMAT.</span>
        </h2>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 4 }}>
          <UseCaseFrame ratio="9/16" ratioLabel="9:16" label="SHORTS"  t={t}/>
          <UseCaseFrame ratio="9/16" ratioLabel="9:16" label="TIKTOK"  t={t} accent="#FF4FA8"/>
          <UseCaseFrame ratio="9/16" ratioLabel="9:16" label="REELS"   t={t} accent="#FFB347"/>
          <UseCaseFrame ratio="9/16" ratioLabel="1:1"  label="PODCAST" t={t} accent="#7CD3FF"/>
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: "0 64px 80px" }}>
        <div style={{
          border: `1px solid ${t.accent}`, padding: "72px 56px", borderRadius: 4,
          position: "relative", overflow: "hidden",
          background: `radial-gradient(60% 80% at 50% 0%, ${t.accent}18, transparent 70%)`,
          textAlign: "center",
        }}>
          <div style={{ fontFamily: DISPLAY_B, color: t.accent, fontSize: 12, letterSpacing: 3, marginBottom: 16, textTransform: "uppercase" }}>
            // open beta
          </div>
          <h2 style={{ fontSize: 88, fontWeight: 900, letterSpacing: -2.8, margin: "0 0 16px", lineHeight: 0.9, fontFamily: DISPLAY_B }}>
            BREAK IT.<br/>TELL US HOW.
          </h2>
          <p style={{ color: t.textDim, fontSize: 17, maxWidth: 560, margin: "0 auto 32px" }}>
            Download the beta, edit a video, file the bug. We'll read every word — and you'll get a free year of Pro when we go GA.
          </p>
          <button onClick={openDownload} style={{
            background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "22px 36px", fontSize: 18, fontWeight: 900, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase",
            boxShadow: `0 0 60px ${t.accent}55`,
          }}>
            ↓ DOWNLOAD VLSTUDIO FREE
          </button>
        </div>
      </section>

      {/* NEWSLETTER */}
      <section style={{ padding: "56px 64px", borderTop: `1px solid ${t.panelLine}`, display: "flex", flexDirection: "column", alignItems: "center", gap: 20 }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 3, textTransform: "uppercase" }}>// STAY IN THE LOOP</div>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 28, fontWeight: 900, color: t.text, letterSpacing: -0.5, textAlign: "center", textTransform: "uppercase" }}>
          Get early access updates
        </div>
        {newsletterState === "success" ? (
          <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 2, textTransform: "uppercase", border: `1px solid ${t.accent}44`, borderRadius: 4, padding: "12px 24px" }}>
            // YOU'RE ON THE LIST
          </div>
        ) : (
          <form onSubmit={handleNewsletterSubmit} style={{ display: "flex", gap: 10, width: "100%", maxWidth: 440 }}>
            <input
              type="email" required
              placeholder="your@email.com"
              value={newsletterEmail}
              onChange={e => { setNewsletterEmail(e.target.value); if (newsletterState !== "idle") setNewsletterState("idle"); }}
              style={{ flex: 1, background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, color: t.text, fontFamily: DISPLAY_B, fontSize: 12, padding: "12px 14px", outline: "none" }}
            />
            <button type="submit" disabled={newsletterState === "loading"} style={{ background: t.accent, color: t.accentText, border: "none", borderRadius: 4, padding: "12px 22px", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 800, letterSpacing: 2, textTransform: "uppercase", cursor: "pointer" }}>
              {newsletterState === "loading" ? "…" : "SUBSCRIBE →"}
            </button>
          </form>
        )}
        {newsletterState === "error" && (
          <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: "#FF4040", letterSpacing: 1.5, textTransform: "uppercase" }}>
            Something went wrong. Please try again.
          </div>
        )}
      </section>

      {/* FOOTER */}
      <footer style={{ padding: "32px 64px 48px", borderTop: `1px solid ${t.panelLine}`, display: "flex", justifyContent: "space-between", alignItems: "center", color: t.textDim, fontSize: 12, fontFamily: DISPLAY_B, letterSpacing: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <VLMark color={t.accent}/>
          <span style={{ fontWeight: 700, color: t.text, letterSpacing: 2 }}>VLSTUDIO</span>
          <span style={{ marginLeft: 12, textTransform: "uppercase" }}>© 2026 / made for creators</span>
        </div>
        <div style={{ display: "flex", gap: 24, textTransform: "uppercase" }}>
          <span>Privacy</span><span>Terms</span><span>Status</span><span>Changelog</span>
        </div>
      </footer>

      {/* Modals */}
      <SigninModal open={modal === "signin"} onClose={() => setModal(null)} t={t}/>
      <DownloadModal open={modal === "download"} onClose={() => setModal(null)} t={t}/>
      </>)}
    </div>
    </RouterCtx.Provider>
  );
}

function StatCardB({ t, big, label, sub }) {
  return (
    <div style={{
      background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: 22,
    }}>
      <div style={{ fontSize: 56, fontWeight: 900, letterSpacing: -2, color: t.accent, fontFamily: DISPLAY_B, lineHeight: 1 }}>
        {big}
      </div>
      <div style={{ fontSize: 14, fontWeight: 700, marginTop: 8 }}>{label}</div>
      <div style={{ fontSize: 12, color: t.textDim, marginTop: 4, fontFamily: DISPLAY_B }}>{sub}</div>
    </div>
  );
}

function FeatureRollB({ t }) {
  const feats = [
    { tag: "FT-01", title: "Auto-cut",         body: "Detect silences, ums, and dead air. Trim a 30-min raw take in 10 seconds." },
    { tag: "FT-02", title: "Auto-captions",    body: "98% accurate · 30+ languages. Style to your brand." },
    { tag: "FT-03", title: "BG remover",       body: "One-click greenscreen — without the greenscreen." },
    { tag: "FT-04", title: "Smart resize",     body: "16:9 → 9:16 → 1:1 with subject-aware reframing." },
    { tag: "FT-05", title: "Co-edit",          body: "Reviewers push edits straight into your timeline." },
    { tag: "FT-06", title: "Local-first",      body: "Renders on your machine. Footage stays yours." },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0, border: `1px solid ${t.panelLine}` }}>
      {feats.map((f, i) => (
        <div key={i} style={{
          padding: 32, borderRight: (i % 3 !== 2) ? `1px solid ${t.panelLine}` : "none",
          borderBottom: (i < 3) ? `1px solid ${t.panelLine}` : "none", minHeight: 220,
          position: "relative", background: t.panel,
        }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 2, marginBottom: 16 }}>
            {f.tag}
          </div>
          <div style={{ fontSize: 28, fontWeight: 900, marginBottom: 12, letterSpacing: -0.6, fontFamily: DISPLAY_B, textTransform: "uppercase" }}>
            {f.title}
          </div>
          <div style={{ fontSize: 14, color: t.textDim, lineHeight: 1.55 }}>{f.body}</div>
          <div style={{
            position: "absolute", bottom: 16, right: 16, fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim,
          }}>→</div>
        </div>
      ))}
    </div>
  );
}

window.VariationB = VariationB;

// ---- AppNav (persistent top bar for non-landing screens) ----
function AppNav({ t, currentScreen, navigate }) {
  const [dropdownOpen, setDropdownOpen] = React.useState(false);
  const { user, profile, signOut, notifications, unreadCount, setUnreadCount } = useAuth();
  const navLinks = [
    { key: "dashboard",   label: "Dashboard" },
    { key: "editor",      label: "Editor" },
    { key: "marketplace", label: "Marketplace" },
    { key: "jobs",        label: "Jobs" },
    { key: "community",   label: "Community" },
  ];
  const dropdownItems = [
    { key: "settings", label: "Settings" },
    { key: "tokens",   label: "Tokens" },
    { key: "admin",    label: "Admin" },
    { key: "support",  label: "Support" },
    { key: null,       label: "Sign out" },
  ];
  React.useEffect(() => {
    if (!dropdownOpen) return;
    const close = () => setDropdownOpen(false);
    window.addEventListener("click", close);
    return () => window.removeEventListener("click", close);
  }, [dropdownOpen]);
  return (
    <header style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "16px 32px", borderBottom: `1px solid ${t.panelLine}`,
      position: "sticky", top: 0, background: t.bg + "ee", backdropFilter: "blur(10px)", zIndex: 10,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        <button
          onClick={() => navigate("landing")}
          aria-label="Home"
          style={{ background: "none", border: "none", cursor: "pointer", padding: 0, display: "flex", alignItems: "center" }}
        >
          <VLMark color={t.accent}/>
        </button>
        <span style={{ fontFamily: DISPLAY_B, fontSize: 12, color: t.textDim, letterSpacing: 2, textTransform: "uppercase" }}>
          {SCREEN_LABELS[currentScreen] || `// ${currentScreen.toUpperCase()}`}
        </span>
        {currentScreen === "admin" && (
          <span style={{
            fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 900, letterSpacing: 2,
            textTransform: "uppercase", color: "#FF4444",
            border: "1px solid rgba(255,68,68,0.5)", borderRadius: 3,
            padding: "3px 7px", marginLeft: 4,
          }}>ADMIN</span>
        )}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
        {navLinks.map(nl => (
          <button key={nl.key} onClick={() => navigate(nl.key)} style={{
            background: "transparent", border: "none", cursor: "pointer",
            fontFamily: DISPLAY_B, fontSize: 11, letterSpacing: 1.5, textTransform: "uppercase",
            color: currentScreen === nl.key ? t.accent : t.textDim,
            padding: "6px 10px", borderRadius: 4,
          }}>
            {nl.label}
          </button>
        ))}
        {/* Bell icon with unread count */}
        <button
          onClick={() => { navigate('dashboard'); }}
          style={{ position: 'relative', background: 'transparent', border: 'none', cursor: 'pointer', color: t.textDim, padding: '4px 6px', display: 'flex', alignItems: 'center' }}
          title="Notifications"
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>
            <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
          </svg>
          {unreadCount > 0 && (
            <span style={{
              position: 'absolute', top: -2, right: -2,
              background: t.accent, color: t.accentText, borderRadius: 99,
              minWidth: 14, height: 14, fontSize: 8, fontWeight: 900,
              fontFamily: DISPLAY_B, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 3px',
            }}>{unreadCount}</span>
          )}
        </button>

        <div style={{ position: "relative", marginLeft: 6 }}>
          <button
            onClick={(e) => { e.stopPropagation(); setDropdownOpen(o => !o); }}
            style={{
              width: 34, height: 34, borderRadius: 99, border: `2px solid ${t.accent}`,
              background: t.panel, color: t.accent, cursor: "pointer",
              fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700, letterSpacing: 0.5,
              display: "flex", alignItems: "center", justifyContent: "center",
            }}
          >{profile ? (profile.username || user?.email || 'JD').slice(0,2).toUpperCase() : (user?.email || 'JD').slice(0,2).toUpperCase()}</button>
          {dropdownOpen && (
            <div
              onClick={(e) => e.stopPropagation()}
              style={{
                position: "absolute", top: 42, right: 0, background: t.panel,
                border: `1px solid ${t.panelLine}`, borderRadius: 4, minWidth: 160, zIndex: 100,
                boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
              }}
            >
              {dropdownItems.map((item, i) => (
                <button
                  key={i}
                  onClick={async () => {
                    if (item.key === null) {
                      // Sign out
                      await db.auth.signOut();
                      navigate('landing');
                    } else {
                      navigate(item.key);
                    }
                    setDropdownOpen(false);
                  }}
                  style={{
                    display: "block", width: "100%", padding: "10px 16px", textAlign: "left",
                    background: "transparent", border: "none",
                    borderBottom: i < dropdownItems.length - 1 ? `1px solid ${t.panelLine}` : "none",
                    color: item.key === null ? t.textDim : t.text, cursor: "pointer",
                    fontFamily: DISPLAY_B, fontSize: 11, letterSpacing: 1.5, textTransform: "uppercase",
                  }}
                >
                  {item.label}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </header>
  );
}

// ---- Placeholder screen (used until later prompts fill each screen in) ----
function PlaceholderScreen({ screenName, t, navigate }) {
  return (
    <div style={{
      minHeight: "calc(100vh - 65px)", background: t.bg, display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center", gap: 12,
    }}>
      <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: t.accent, letterSpacing: 3, textTransform: "uppercase" }}>
        // coming soon
      </div>
      <div style={{ fontFamily: DISPLAY_B, fontSize: 56, fontWeight: 900, color: t.accent, letterSpacing: -1, textTransform: "uppercase" }}>
        {screenName}
      </div>
      <button
        onClick={() => navigate("landing")}
        style={{
          marginTop: 20, background: "transparent", color: t.textDim,
          border: `1px solid ${t.panelLine}`, borderRadius: 4,
          padding: "10px 18px", fontFamily: DISPLAY_B, fontSize: 11,
          letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
        }}
      >
        ← Back to landing
      </button>
    </div>
  );
}

// ---- Google OAuth Button Component ----
function GoogleOAuthButton({ t }) {
  return (
    <button type="button" style={{
      width: "100%", background: "transparent", color: t.text,
      border: `1px solid ${t.panelLine}`, borderRadius: 4,
      padding: "14px 20px", fontSize: 13, fontWeight: 700, cursor: "pointer",
      fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
      display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
    }}>
      <svg width="18" height="18" viewBox="0 0 18 18">
        <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z"/>
        <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z"/>
        <path fill="#FBBC05" d="M3.964 10.707c-.18-.54-.282-1.117-.282-1.707s.102-1.167.282-1.707V4.961H.957C.347 6.175 0 7.55 0 9s.348 2.825.957 4.039l3.007-2.332z"/>
        <path fill="#EA4335" d="M9 3.582c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.961L3.964 7.293C4.672 5.163 6.656 3.582 9 3.582z"/>
      </svg>
      Continue with Google
    </button>
  );
}

function LoginScreen({ t, navigate }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [keepSignedIn, setKeepSignedIn] = React.useState(true);
  const [showResetFlow, setShowResetFlow] = React.useState(false);
  const [resetEmail, setResetEmail] = React.useState("");
  const [resetSent, setResetSent] = React.useState(false);
  const [signingIn, setSigningIn] = React.useState(false);
  const [authError, setAuthError] = React.useState("");
  const [resetLoading, setResetLoading] = React.useState(false);

  const { signIn, signInWithGoogle, user } = useAuth();
  const { navigate: routerNavigate, currentScreen } = React.useContext(RouterCtx);

  // Navigate to dashboard when user signs in
  React.useEffect(() => {
    if (user && currentScreen === 'login') {
      navigate('dashboard');
    }
  }, [user, currentScreen, navigate]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password) return;
    setSigningIn(true);
    setAuthError("");
    const { error } = await signIn(email, password);
    if (error) {
      setSigningIn(false);
      let msg = error.message || '';
      if (msg.includes('Invalid login credentials')) msg = '// INVALID EMAIL OR PASSWORD';
      else if (msg.includes('Email not confirmed')) msg = '// PLEASE CONFIRM YOUR EMAIL FIRST';
      else msg = '// ERROR: ' + msg;
      setAuthError(msg);
    }
    // On success, onAuthStateChange fires → user becomes non-null → useEffect navigates
  };

  const handleResetSubmit = async (e) => {
    e.preventDefault();
    if (!resetEmail) return;
    setResetLoading(true);
    await db.auth.resetPasswordForEmail(resetEmail, {
      redirectTo: window.location.origin + '?screen=reset-password',
    });
    setResetLoading(false);
    setResetSent(true);
  };

  return (
    <div style={{ minHeight: "100vh", background: t.bg, display: "flex", flexDirection: "column" }}>
      {/* Sticky top nav - logo only */}
      <header style={{
        display: "flex", alignItems: "center", padding: "20px 32px",
        borderBottom: `1px solid ${t.panelLine}`, position: "sticky", top: 0,
        background: t.bg + "ee", backdropFilter: "blur(10px)", zIndex: 10,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }} onClick={() => navigate("landing")}>
          <VLMark color={t.accent}/>
          <span style={{ fontWeight: 700, fontSize: 16, letterSpacing: 2, fontFamily: DISPLAY_B }}>VLSTUDIO</span>
        </div>
      </header>

      {/* Two-column layout */}
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1fr 1fr", minHeight: 0 }}>
        {/* Left side - display text */}
        <div style={{
          padding: "80px 64px", display: "flex", flexDirection: "column", justifyContent: "center",
          position: "relative",
        }}>
          <h1 style={{
            fontFamily: DISPLAY_B, fontSize: 80, fontWeight: 900, lineHeight: 0.9,
            letterSpacing: -2, margin: "0 0 20px", textTransform: "uppercase",
          }}>
            WELCOME<br/>BACK.
          </h1>
          <p style={{
            fontFamily: DISPLAY_B, fontSize: 14, color: t.textDim,
            letterSpacing: 1.5, margin: "0 0 60px", textTransform: "uppercase",
          }}>
            // sign in to your studio
          </p>
          <div style={{ position: "absolute", bottom: 80, left: 64, opacity: 0.15 }}>
            <VLMark color={t.accent} size={240}/>
          </div>
        </div>

        {/* Right side - form */}
        <div style={{
          padding: "80px 64px", display: "flex", flexDirection: "column", justifyContent: "center",
          borderLeft: `1px solid ${t.panelLine}`,
        }}>
          <div style={{ maxWidth: 440 }}>
            {!showResetFlow ? (
              <>
                <form onSubmit={handleSubmit}>
                  <FieldB t={t} label="Email" type="email" value={email} onChange={setEmail} placeholder="you@studio.com"/>
                  <FieldB t={t} label="Password" type="password" value={password} onChange={setPassword} placeholder="••••••••"/>

                  {authError && (
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: '#FF4444', letterSpacing: 1, marginBottom: 14 }}>
                      {authError}
                    </div>
                  )}

                  <div style={{
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                    marginBottom: 18, fontSize: 12, fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                  }}>
                    <label style={{
                      display: "inline-flex", alignItems: "center", gap: 6, color: t.textDim, cursor: "pointer",
                    }}>
                      <input type="checkbox" checked={keepSignedIn} onChange={(e) => setKeepSignedIn(e.target.checked)} style={{ accentColor: t.accent }}/>
                      Keep me signed in
                    </label>
                    <a onClick={() => setShowResetFlow(true)} style={{ color: t.textDim, cursor: "pointer", textDecoration: "none" }}>
                      Forgot password?
                    </a>
                  </div>

                  <button type="submit" disabled={signingIn} style={{
                    width: "100%", background: signingIn ? t.panelLine : t.accent,
                    color: signingIn ? t.textDim : t.accentText,
                    border: "none", borderRadius: 4,
                    padding: "14px 20px", fontSize: 14, fontWeight: 900,
                    cursor: signingIn ? "default" : "pointer",
                    fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase", marginBottom: 16,
                  }}>
                    {signingIn ? "// SIGNING IN…" : "SIGN IN →"}
                  </button>
                </form>

                <button type="button" onClick={() => signInWithGoogle()} style={{
                  width: "100%", background: "transparent", color: t.text,
                  border: `1px solid ${t.panelLine}`, borderRadius: 4,
                  padding: "14px 20px", fontSize: 13, fontWeight: 700, cursor: "pointer",
                  fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
                }}>
                  <svg width="18" height="18" viewBox="0 0 18 18">
                    <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z"/>
                    <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z"/>
                    <path fill="#FBBC05" d="M3.964 10.707c-.18-.54-.282-1.117-.282-1.707s.102-1.167.282-1.707V4.961H.957C.347 6.175 0 7.55 0 9s.348 2.825.957 4.039l3.007-2.332z"/>
                    <path fill="#EA4335" d="M9 3.582c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.961L3.964 7.293C4.672 5.163 6.656 3.582 9 3.582z"/>
                  </svg>
                  Continue with Google
                </button>

                <div style={{
                  textAlign: "center", color: t.textDim, fontSize: 11, fontFamily: DISPLAY_B,
                  letterSpacing: 1.5, textTransform: "uppercase", marginTop: 24,
                }}>
                  No account?{" "}
                  <span onClick={() => navigate("signup")} style={{ color: t.accent, cursor: "pointer" }}>
                    Get the beta →
                  </span>
                </div>
              </>
            ) : (
              <>
                {!resetSent ? (
                  <form onSubmit={handleResetSubmit}>
                    <div style={{
                      fontFamily: DISPLAY_B, fontSize: 24, fontWeight: 900, letterSpacing: -0.5,
                      margin: "0 0 8px", textTransform: "uppercase",
                    }}>
                      RESET PASSWORD
                    </div>
                    <p style={{
                      fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim,
                      letterSpacing: 1.5, margin: "0 0 24px", textTransform: "uppercase",
                    }}>
                      // enter your email
                    </p>
                    <FieldB t={t} label="Email" type="email" value={resetEmail} onChange={setResetEmail} placeholder="you@studio.com"/>
                    <button type="submit" disabled={resetLoading || !resetEmail} style={{
                      width: "100%", background: (resetLoading || !resetEmail) ? t.panelLine : t.accent,
                      color: (resetLoading || !resetEmail) ? t.textDim : t.accentText,
                      border: "none", borderRadius: 4,
                      padding: "14px 20px", fontSize: 14, fontWeight: 900,
                      cursor: (resetLoading || !resetEmail) ? "default" : "pointer",
                      fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase", marginBottom: 16,
                    }}>
                      {resetLoading ? "// SENDING…" : "SEND RESET LINK →"}
                    </button>
                    <button type="button" onClick={() => setShowResetFlow(false)} style={{
                      width: "100%", background: "transparent", color: t.textDim,
                      border: `1px solid ${t.panelLine}`, borderRadius: 4,
                      padding: "14px 20px", fontSize: 12, fontWeight: 700, cursor: "pointer",
                      fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                    }}>
                      ← BACK TO LOGIN
                    </button>
                  </form>
                ) : (
                  <div>
                    <div style={{
                      fontFamily: DISPLAY_B, fontSize: 32, fontWeight: 900, color: t.accent,
                      letterSpacing: -1, margin: "0 0 16px", textTransform: "uppercase",
                    }}>
                      // CHECK YOUR INBOX
                    </div>
                    <p style={{
                      color: t.textDim, fontSize: 14, lineHeight: 1.6, margin: "0 0 24px",
                    }}>
                      We sent a reset link to <span style={{ color: t.accent, fontFamily: DISPLAY_B }}>{resetEmail}</span>.
                      Click it to set a new password.
                    </p>
                    <button type="button" onClick={() => { setShowResetFlow(false); setResetSent(false); }} style={{
                      width: "100%", background: "transparent", color: t.textDim,
                      border: `1px solid ${t.panelLine}`, borderRadius: 4,
                      padding: "14px 20px", fontSize: 12, fontWeight: 700, cursor: "pointer",
                      fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                    }}>
                      ← BACK TO LOGIN
                    </button>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function SignupScreen({ t, navigate }) {
  const [role, setRole] = React.useState("CREATOR");
  const [username, setUsername] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [agreedToTerms, setAgreedToTerms] = React.useState(false);
  const [usernameStatus, setUsernameStatus] = React.useState(null); // null | "checking" | "available" | "taken"
  const [showEmailConfirm, setShowEmailConfirm] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [signupError, setSignupError] = React.useState("");
  const [validationErrors, setValidationErrors] = React.useState({});
  const usernameTimerRef = React.useRef(null);

  const { signUp, signInWithGoogle } = useAuth();

  // Real DB username availability check with debounce
  React.useEffect(() => {
    if (username.length < 3) { setUsernameStatus(null); return; }
    if (!/^[a-z0-9_]{3,}$/i.test(username)) { setUsernameStatus(null); return; }
    setUsernameStatus("checking");
    if (usernameTimerRef.current) clearTimeout(usernameTimerRef.current);
    usernameTimerRef.current = setTimeout(async () => {
      const { data, error } = await db.from('profiles').select('id').eq('username', username).single();
      if (data) {
        setUsernameStatus("taken");
      } else if (error && error.code === 'PGRST116') {
        setUsernameStatus("available");
      } else {
        setUsernameStatus(null);
      }
    }, 500);
    return () => { if (usernameTimerRef.current) clearTimeout(usernameTimerRef.current); };
  }, [username]);

  const validate = () => {
    const errs = {};
    if (!username || username.length < 3 || !/^[a-z0-9_]{3,}$/i.test(username)) errs.username = '// MIN 3 CHARS, LETTERS/NUMBERS/UNDERSCORE ONLY';
    if (!email || !email.includes('@')) errs.email = '// INVALID EMAIL ADDRESS';
    if (!password || password.length < 8) errs.password = '// MIN 8 CHARACTERS';
    if (confirmPassword !== password) errs.confirmPassword = '// PASSWORDS DO NOT MATCH';
    if (!agreedToTerms) errs.terms = '// MUST AGREE TO TERMS';
    return errs;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = validate();
    setValidationErrors(errs);
    if (Object.keys(errs).length > 0) return;
    setSubmitting(true);
    setSignupError("");
    const { error } = await signUp(email, password, { username, role: role.toLowerCase() });
    setSubmitting(false);
    if (error) {
      setSignupError('// ERROR: ' + error.message);
    } else {
      setShowEmailConfirm(true);
    }
  };

  if (showEmailConfirm) {
    return (
      <div style={{
        position: "fixed", inset: 0, background: t.bg, display: "flex",
        alignItems: "center", justifyContent: "center", padding: 24, zIndex: 1000,
      }}>
        <div style={{ maxWidth: 560, textAlign: "center" }}>
          <div style={{
            fontFamily: DISPLAY_B, fontSize: 48, fontWeight: 900, color: t.accent,
            letterSpacing: -1.5, margin: "0 0 24px", textTransform: "uppercase",
          }}>
            // CHECK YOUR EMAIL
          </div>
          <div style={{
            fontFamily: DISPLAY_B, fontSize: 28, fontWeight: 700, color: t.text,
            letterSpacing: -0.5, margin: "0 0 20px",
          }}>
            {email}
          </div>
          <p style={{
            color: t.textDim, fontSize: 16, lineHeight: 1.6, margin: "0 0 32px",
          }}>
            We sent a confirmation link to your email. Click it to activate your account and start editing.
          </p>
          <button type="button" onClick={() => setShowEmailConfirm(false)} style={{
            background: "transparent", color: t.textDim,
            border: `1px solid ${t.panelLine}`, borderRadius: 4,
            padding: "14px 28px", fontSize: 13, fontWeight: 700, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}>
            RESEND EMAIL
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: "100vh", background: t.bg, display: "flex", flexDirection: "column" }}>
      {/* Sticky top nav - logo only */}
      <header style={{
        display: "flex", alignItems: "center", padding: "20px 32px",
        borderBottom: `1px solid ${t.panelLine}`, position: "sticky", top: 0,
        background: t.bg + "ee", backdropFilter: "blur(10px)", zIndex: 10,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }} onClick={() => navigate("landing")}>
          <VLMark color={t.accent}/>
          <span style={{ fontWeight: 700, fontSize: 16, letterSpacing: 2, fontFamily: DISPLAY_B }}>VLSTUDIO</span>
        </div>
      </header>

      {/* Two-column layout */}
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1fr 1fr", minHeight: 0 }}>
        {/* Left side - display text */}
        <div style={{
          padding: "80px 64px", display: "flex", flexDirection: "column", justifyContent: "center",
          position: "relative",
        }}>
          <h1 style={{
            fontFamily: DISPLAY_B, fontSize: 80, fontWeight: 900, lineHeight: 0.9,
            letterSpacing: -2, margin: "0 0 20px", textTransform: "uppercase",
          }}>
            JOIN THE<br/>BETA.
          </h1>
          <p style={{
            fontFamily: DISPLAY_B, fontSize: 14, color: t.textDim,
            letterSpacing: 1.5, margin: "0 0 60px", textTransform: "uppercase",
          }}>
            // free while we build
          </p>
          <div style={{ position: "absolute", bottom: 80, left: 64, opacity: 0.15 }}>
            <VLMark color={t.accent} size={240}/>
          </div>
        </div>

        {/* Right side - form */}
        <div style={{
          padding: "80px 64px", display: "flex", flexDirection: "column", justifyContent: "center",
          borderLeft: `1px solid ${t.panelLine}`,
        }}>
          <div style={{ maxWidth: 440 }}>
            <form onSubmit={handleSubmit}>
              {/* Role selector */}
              <div style={{ marginBottom: 20 }}>
                <div style={{
                  fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim,
                  letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 10,
                }}>
                  I am a
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  {["CREATOR", "CLIENT"].map(r => {
                    const selected = r === role;
                    return (
                      <button
                        key={r}
                        type="button"
                        onClick={() => setRole(r)}
                        style={{
                          padding: "20px 16px", background: selected ? `${t.accent}14` : "transparent",
                          border: `1px solid ${selected ? t.accent : t.panelLine}`,
                          borderRadius: 4, cursor: "pointer", textAlign: "center",
                          fontFamily: DISPLAY_B, fontSize: 14, fontWeight: 800,
                          letterSpacing: 1.5, textTransform: "uppercase",
                          color: selected ? t.accent : t.text, transition: "all 0.2s ease",
                        }}
                      >
                        {r}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Username with availability check */}
              <label style={{ display: "block", marginBottom: validationErrors.username ? 4 : 14 }}>
                <div style={{
                  fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim,
                  letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6,
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                }}>
                  <span>Username</span>
                  {usernameStatus === "checking" && (
                    <span style={{ fontSize: 10, color: t.textDim, fontStyle: "italic" }}>
                      checking…
                    </span>
                  )}
                  {usernameStatus === "available" && (
                    <span style={{ fontSize: 10, color: t.accent, fontWeight: 700 }}>
                      // AVAILABLE ✓
                    </span>
                  )}
                  {usernameStatus === "taken" && (
                    <span style={{ fontSize: 10, color: '#FF4444', fontWeight: 700 }}>
                      // USERNAME TAKEN
                    </span>
                  )}
                </div>
                <input
                  type="text"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  placeholder="@yourname"
                  style={{
                    width: "100%", background: "#000", color: t.text,
                    border: `1px solid ${t.panelLine}`, borderRadius: 4,
                    padding: "12px 14px", fontSize: 14, fontFamily: "inherit",
                    outline: "none", boxSizing: "border-box",
                  }}
                  onFocus={(e) => e.target.style.borderColor = t.accent}
                  onBlur={(e) => e.target.style.borderColor = t.panelLine}
                />
              </label>
              {validationErrors.username && <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: '#FF4444', marginBottom: 10 }}>{validationErrors.username}</div>}

              <div style={{ marginBottom: 14 }}>
                <FieldB t={t} label="Email" type="email" value={email} onChange={setEmail} placeholder="you@studio.com"/>
                {validationErrors.email && <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: '#FF4444', marginTop: -10, marginBottom: 8 }}>{validationErrors.email}</div>}
              </div>
              <div style={{ marginBottom: 14 }}>
                <FieldB t={t} label="Password" type="password" value={password} onChange={setPassword} placeholder="••••••••"/>
                {validationErrors.password && <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: '#FF4444', marginTop: -10, marginBottom: 8 }}>{validationErrors.password}</div>}
              </div>
              <div style={{ marginBottom: 14 }}>
                <FieldB t={t} label="Confirm Password" type="password" value={confirmPassword} onChange={setConfirmPassword} placeholder="••••••••"/>
                {validationErrors.confirmPassword && <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: '#FF4444', marginTop: -10, marginBottom: 8 }}>{validationErrors.confirmPassword}</div>}
              </div>

              {/* Terms checkbox */}
              <label style={{
                display: "flex", alignItems: "flex-start", gap: 8, marginBottom: 8,
                fontSize: 12, fontFamily: DISPLAY_B, letterSpacing: 1, color: t.textDim, cursor: "pointer",
              }}>
                <input
                  type="checkbox"
                  checked={agreedToTerms}
                  onChange={(e) => setAgreedToTerms(e.target.checked)}
                  style={{ accentColor: t.accent, marginTop: 2 }}
                />
                <span>
                  I agree to the{" "}
                  <span style={{ color: t.accent, textDecoration: "underline" }}>Terms</span>
                  {" "}and{" "}
                  <span style={{ color: t.accent, textDecoration: "underline" }}>Privacy Policy</span>
                </span>
              </label>
              {validationErrors.terms && <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: '#FF4444', marginBottom: 10 }}>{validationErrors.terms}</div>}

              {signupError && <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: '#FF4444', marginBottom: 10 }}>{signupError}</div>}

              <button type="submit" disabled={submitting} style={{
                width: "100%", background: submitting ? t.panelLine : t.accent,
                color: submitting ? t.textDim : t.accentText,
                border: "none", borderRadius: 4,
                padding: "14px 20px", fontSize: 14, fontWeight: 900,
                cursor: submitting ? "default" : "pointer",
                fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase", marginBottom: 16,
              }}>
                {submitting ? "// CREATING ACCOUNT…" : "CREATE ACCOUNT →"}
              </button>
            </form>

            <button type="button" onClick={() => signInWithGoogle()} style={{
              width: "100%", background: "transparent", color: t.text,
              border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "14px 20px", fontSize: 13, fontWeight: 700, cursor: "pointer",
              fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
            }}>
              <svg width="18" height="18" viewBox="0 0 18 18">
                <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z"/>
                <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z"/>
                <path fill="#FBBC05" d="M3.964 10.707c-.18-.54-.282-1.117-.282-1.707s.102-1.167.282-1.707V4.961H.957C.347 6.175 0 7.55 0 9s.348 2.825.957 4.039l3.007-2.332z"/>
                <path fill="#EA4335" d="M9 3.582c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.961L3.964 7.293C4.672 5.163 6.656 3.582 9 3.582z"/>
              </svg>
              Continue with Google
            </button>

            <div style={{
              textAlign: "center", color: t.textDim, fontSize: 11, fontFamily: DISPLAY_B,
              letterSpacing: 1.5, textTransform: "uppercase", marginTop: 24,
            }}>
              Already have an account?{" "}
              <span onClick={() => navigate("login")} style={{ color: t.accent, cursor: "pointer" }}>
                Sign in →
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
function DashboardScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile, notifications: authNotifications, unreadCount, setUnreadCount } = useAuth();
  const [ytConnected, setYtConnected] = React.useState(false);
  const [notifications, setNotifications] = React.useState([
    { id: 1, icon: "💬", msg: "Sarah left a comment on \"Vlog #12\"", time: "2 min ago" },
    { id: 2, icon: "👥", msg: "Alex joined as collaborator on \"Brand Spot\"", time: "18 min ago" },
    { id: 3, icon: "✅", msg: "Render complete: \"Product Demo v3.mp4\"", time: "1 hr ago" },
    { id: 4, icon: "📦", msg: "Export ready: \"Summer Reel 4K.zip\"", time: "3 hr ago" },
  ]);

  const navItems = [
    { key: "dashboard",   label: "Dashboard",   icon: (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
        <rect x="1" y="1" width="6" height="6" rx="1"/><rect x="9" y="1" width="6" height="6" rx="1"/>
        <rect x="1" y="9" width="6" height="6" rx="1"/><rect x="9" y="9" width="6" height="6" rx="1"/>
      </svg>
    )},
    { key: "editor",      label: "Editor",      icon: (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
        <path d="M11 2l3 3-8 8H3v-3L11 2z"/>
      </svg>
    )},
    { key: "marketplace", label: "Marketplace", icon: (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
        <path d="M2 3h12l-1.5 6H3.5L2 3z"/><circle cx="5.5" cy="13" r="1"/><circle cx="11.5" cy="13" r="1"/>
        <path d="M1 1h1.5"/>
      </svg>
    )},
    { key: "jobs",        label: "Jobs",        icon: (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="5" width="12" height="9" rx="1"/><path d="M5 5V4a3 3 0 016 0v1"/>
      </svg>
    )},
    { key: "community",   label: "Community",   icon: (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="6" cy="6" r="2.5"/><circle cx="11" cy="5" r="2"/><path d="M1 14c0-2.2 2.2-4 5-4s5 1.8 5 4"/><path d="M11 9c1.7 0 3 1.2 3 3"/>
      </svg>
    )},
  ];

  // Real projects from DB
  const { data: dbProjects, loading: projectsLoading, error: projectsError, refetch: refetchProjects } = useQuery(
    () => user ? db.from('projects').select('*').eq('user_id', user.id).order('updated_at', { ascending: false }).limit(5) : Promise.resolve({ data: [], error: null }),
    [user?.id]
  );

  const projectStatusMap = { draft: 'DRAFT', active: 'LIVE', review: 'REVIEW', live: 'LIVE' };
  const statusColor = { LIVE: t.accent, REVIEW: "#5BE3FF", DRAFT: t.textDim };

  // SVG traffic chart data — 30 days upward-trending polyline
  const chartW = 540, chartH = 180;
  const rawVals = [28,32,29,35,31,38,42,39,44,48,45,52,50,57,55,60,58,64,62,68,70,66,74,72,78,80,76,84,88,92];
  const minV = 20, maxV = 100;
  const pts = rawVals.map((v, i) => {
    const x = 40 + (i / (rawVals.length - 1)) * (chartW - 56);
    const y = (chartH - 30) - ((v - minV) / (maxV - minV)) * (chartH - 50);
    return `${x},${y}`;
  }).join(" ");
  const xLabels = ["MAY 06","MAY 11","MAY 16","MAY 21","MAY 26","JUN 01"];
  const gridLines = [0.25, 0.5, 0.75, 1.0].map(r => (chartH - 30) - r * (chartH - 50));

  return (
    <div style={{ display: "flex", minHeight: "calc(100vh - 65px)", background: t.bg }}>
      {/* ── LEFT SIDEBAR ── */}
      <aside style={{
        width: 220, flexShrink: 0, borderRight: `1px solid ${t.panelLine}`,
        background: t.panel, display: "flex", flexDirection: "column",
        position: "sticky", top: 65, height: "calc(100vh - 65px)", overflowY: "auto",
      }}>
        {/* Wordmark */}
        <div style={{ padding: "24px 20px 20px", borderBottom: `1px solid ${t.panelLine}`, display: "flex", alignItems: "center", gap: 8 }}>
          <VLMark color={t.accent} size={24}/>
          <span style={{ fontFamily: DISPLAY_B, fontWeight: 700, fontSize: 13, letterSpacing: 2, textTransform: "uppercase" }}>VLSTUDIO</span>
        </div>

        {/* Nav */}
        <nav style={{ flex: 1, padding: "12px 0" }}>
          {navItems.map(item => {
            const active = item.key === "dashboard";
            return (
              <button
                key={item.key}
                onClick={() => navigate(item.key)}
                style={{
                  display: "flex", alignItems: "center", gap: 10,
                  width: "100%", padding: "11px 20px",
                  background: active ? `${t.accent}12` : "transparent",
                  border: "none",
                  borderLeft: active ? `3px solid ${t.accent}` : "3px solid transparent",
                  color: active ? t.accent : t.textDim,
                  fontFamily: DISPLAY_B, fontSize: 12, letterSpacing: 1.5, textTransform: "uppercase",
                  cursor: "pointer", textAlign: "left",
                }}
              >
                {item.icon}
                {item.label}
              </button>
            );
          })}
        </nav>

        {/* User card */}
        <div style={{ padding: "16px 20px", borderTop: `1px solid ${t.panelLine}` }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{
              width: 36, height: 36, borderRadius: 99, border: `2px solid ${t.accent}`,
              background: t.bg, display: "flex", alignItems: "center", justifyContent: "center",
              fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, color: t.accent, flexShrink: 0,
            }}>{profile ? (profile.username || user?.email || 'JD').slice(0,2).toUpperCase() : (user?.email || 'JD').slice(0,2).toUpperCase()}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, letterSpacing: 1, color: t.text, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{profile?.username || user?.email || 'loading…'}</div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 2, textTransform: "uppercase", marginTop: 2 }}>{profile?.role?.toUpperCase() || 'CREATOR'}</div>
            </div>
            <button
              onClick={() => navigate("settings")}
              title="Settings"
              style={{ background: "transparent", border: "none", cursor: "pointer", color: t.textDim, padding: 4, display: "flex", alignItems: "center" }}
            >
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="8" cy="8" r="2.5"/>
                <path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41"/>
              </svg>
            </button>
          </div>
        </div>
      </aside>

      {/* ── MAIN CONTENT ── */}
      <main style={{ flex: 1, padding: "28px 32px", overflowY: "auto" }}>

        {/* Page header */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 3, textTransform: "uppercase", marginBottom: 4 }}>// DASHBOARD</div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 22, fontWeight: 900, letterSpacing: -0.5, textTransform: "uppercase" }}>Creator Overview</div>
        </div>

        {/* ── STAT CARDS ── */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16 }}>
          {[
            { label: "TOTAL VIEWS",       value: "128.4K", delta: "+12% this week" },
            { label: "UNIQUE VISITORS",   value: "34.2K",  delta: null },
            { label: "ENGAGEMENT RATE",   value: "6.8%",   delta: null },
            { label: "CONVERSION RATE",   value: "3.2%",   delta: null },
          ].map(card => (
            <div key={card.label} style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "18px 20px" }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 10 }}>{card.label}</div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 32, fontWeight: 900, color: t.accent, letterSpacing: -1, lineHeight: 1 }}>{card.value}</div>
              {card.delta && (
                <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 1, marginTop: 8 }}>{card.delta}</div>
              )}
              <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 1.5, textTransform: 'uppercase', marginTop: 6, opacity: 0.6 }}>// DEMO DATA</div>
            </div>
          ))}
        </div>

        {/* ── YOUTUBE BANNER ── */}
        <div style={{
          background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4,
          padding: "14px 20px", marginBottom: 16,
          display: "flex", alignItems: "center", gap: 16,
        }}>
          {/* YouTube icon */}
          <svg width="32" height="22" viewBox="0 0 32 22" fill="none">
            <rect width="32" height="22" rx="4" fill="#FF0000"/>
            <polygon points="13,6 13,16 22,11" fill="white"/>
          </svg>
          {ytConnected ? (
            <>
              <div style={{ flex: 1 }}>
                <span style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, color: t.text, letterSpacing: 1 }}>John Doe Studio</span>
                <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, marginLeft: 16 }}>4,821 subscribers</span>
                <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, marginLeft: 16 }}>312K total views</span>
              </div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 1.5, textTransform: "uppercase" }}>✓ CONNECTED</div>
            </>
          ) : (
            <>
              <div style={{ flex: 1, fontFamily: DISPLAY_B, fontSize: 12, color: t.textDim, letterSpacing: 0.5 }}>
                Connect your YouTube channel for analytics
              </div>
              <button
                onClick={() => setYtConnected(true)}
                style={{
                  background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
                  padding: "8px 16px", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700,
                  letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
                }}
              >CONNECT →</button>
            </>
          )}
        </div>

        {/* ── MIDDLE ROW: Traffic chart + Audience ── */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 12, marginBottom: 12 }}>

          {/* Traffic SVG chart */}
          <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px 24px" }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 16 }}>// TRAFFIC · 30 DAYS</div>
            <svg viewBox={`0 0 ${chartW} ${chartH}`} width="100%" height="180" style={{ display: "block" }}>
              {/* Grid lines */}
              {gridLines.map((y, i) => (
                <line key={i} x1="40" y1={y} x2={chartW - 16} y2={y} stroke="rgba(255,255,255,0.06)" strokeWidth="1"/>
              ))}
              {/* Y-axis ticks */}
              {gridLines.map((y, i) => (
                <text key={i} x="32" y={y + 4} textAnchor="end" fill="rgba(255,255,255,0.3)" fontSize="9" fontFamily="'IBM Plex Mono', monospace">
                  {Math.round(minV + (i + 1) * (maxV - minV) / 4)}
                </text>
              ))}
              {/* Polyline fill */}
              <defs>
                <linearGradient id="chartFill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#39FF6A" stopOpacity="0.18"/>
                  <stop offset="100%" stopColor="#39FF6A" stopOpacity="0"/>
                </linearGradient>
              </defs>
              <polygon
                points={`40,${chartH - 30} ${pts} ${40 + (rawVals.length - 1) / (rawVals.length - 1) * (chartW - 56)},${chartH - 30}`}
                fill="url(#chartFill)"
              />
              {/* Polyline */}
              <polyline points={pts} fill="none" stroke="#39FF6A" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round"/>
              {/* X-axis labels */}
              {xLabels.map((lbl, i) => {
                const x = 40 + (i / (xLabels.length - 1)) * (chartW - 56);
                return (
                  <text key={i} x={x} y={chartH - 6} textAnchor="middle" fill="rgba(255,255,255,0.3)" fontSize="9" fontFamily="'IBM Plex Mono', monospace">
                    {lbl}
                  </text>
                );
              })}
            </svg>
          </div>

          {/* Audience breakdown */}
          <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px 24px" }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 20 }}>// AUDIENCE</div>

            {/* Device bars */}
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 10 }}>DEVICE SPLIT</div>
              {[
                { label: "Mobile",  pct: 58 },
                { label: "Desktop", pct: 31 },
                { label: "Tablet",  pct: 11 },
              ].map(row => (
                <div key={row.label} style={{ marginBottom: 10 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
                    <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1 }}>{row.label}</span>
                    <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.text }}>{row.pct}%</span>
                  </div>
                  <div style={{ height: 6, borderRadius: 3, background: "rgba(255,255,255,0.06)" }}>
                    <div style={{ width: `${row.pct}%`, height: "100%", borderRadius: 3, background: t.accent }}/>
                  </div>
                </div>
              ))}
            </div>

            {/* Top countries */}
            <div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 10 }}>TOP COUNTRIES</div>
              {[
                { flag: "🇺🇸", name: "United States", pct: "42%" },
                { flag: "🇬🇧", name: "United Kingdom", pct: "18%" },
                { flag: "🇨🇦", name: "Canada",         pct: "11%" },
              ].map(c => (
                <div key={c.name} style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 0", borderBottom: `1px solid ${t.panelLine}` }}>
                  <span style={{ fontSize: 16 }}>{c.flag}</span>
                  <span style={{ flex: 1, fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 0.5 }}>{c.name}</span>
                  <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.text }}>{c.pct}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* ── BOTTOM ROW: Projects + Notifications ── */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 12 }}>

          {/* Recent projects */}
          <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px 24px" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 2.5, textTransform: "uppercase" }}>// RECENT PROJECTS</div>
              <button
                onClick={() => navigate("editor")}
                style={{
                  background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
                  padding: "7px 14px", fontFamily: DISPLAY_B, fontSize: 10, fontWeight: 700,
                  letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
                }}
              >＋ NEW PROJECT</button>
            </div>
            <style>{`@keyframes vlskel{0%,100%{opacity:.4}50%{opacity:.8}}`}</style>
            {projectsLoading ? (
              <div>
                {[0,1,2,3,4].map(i => (
                  <div key={i} style={{ height: 14, background: '#1a1a1a', borderRadius: 3, marginBottom: 12, animation: 'vlskel 1.5s infinite' }}/>
                ))}
              </div>
            ) : projectsError ? (
              <div>
                <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: '#FF4444', marginBottom: 10 }}>// FAILED TO LOAD PROJECTS</div>
                <button onClick={refetchProjects} style={{ background: 'transparent', color: t.accent, border: `1px solid ${t.accent}44`, borderRadius: 3, padding: '5px 12px', fontFamily: DISPLAY_B, fontSize: 10, cursor: 'pointer', letterSpacing: 1.5, textTransform: 'uppercase' }}>RETRY →</button>
              </div>
            ) : (
              <table style={{ width: "100%", borderCollapse: "collapse" }}>
                <thead>
                  <tr>
                    {["TITLE", "STATUS", "DURATION", "LAST SAVED"].map(h => (
                      <th key={h} style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", textAlign: "left", paddingBottom: 10, borderBottom: `1px solid ${t.panelLine}` }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {(dbProjects || []).map((p, i) => {
                    const statusKey = projectStatusMap[p.status] || p.status?.toUpperCase() || 'DRAFT';
                    const sc = statusColor[statusKey] || t.textDim;
                    const dur = typeof p.duration === 'number'
                      ? `${Math.floor(p.duration/60)}:${String(p.duration%60).padStart(2,'0')}`
                      : (p.duration || '—');
                    return (
                      <tr key={p.id}>
                        <td style={{ padding: "12px 0", fontFamily: DISPLAY_B, fontSize: 12, color: t.text, letterSpacing: 0.5, borderBottom: `1px solid ${t.panelLine}` }}>{p.title}</td>
                        <td style={{ padding: "12px 8px", borderBottom: `1px solid ${t.panelLine}` }}>
                          <span style={{ fontFamily: DISPLAY_B, fontSize: 10, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", color: sc, border: `1px solid ${sc}44`, borderRadius: 3, padding: "3px 7px" }}>{statusKey}</span>
                        </td>
                        <td style={{ padding: "12px 8px", fontFamily: DISPLAY_B, fontSize: 12, color: t.textDim, borderBottom: `1px solid ${t.panelLine}` }}>{dur}</td>
                        <td style={{ padding: "12px 0", fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 0.5, borderBottom: `1px solid ${t.panelLine}` }}>{formatRelativeTime(p.updated_at)}</td>
                      </tr>
                    );
                  })}
                  {(dbProjects || []).length === 0 && (
                    <tr><td colSpan={4} style={{ padding: '20px 0', fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, textAlign: 'center' }}>No projects yet.</td></tr>
                  )}
                </tbody>
              </table>
            )}
          </div>

          {/* Notifications */}
          <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px 24px" }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 16 }}>// NOTIFICATIONS</div>
            {notifications.length === 0 ? (
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1 }}>No notifications.</div>
            ) : (
              notifications.map(n => (
                <div key={n.id} style={{
                  display: "flex", alignItems: "flex-start", gap: 10, padding: "10px 0",
                  borderBottom: `1px solid ${t.panelLine}`,
                }}>
                  <span style={{ fontSize: 16, flexShrink: 0, marginTop: 1 }}>{n.icon}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, color: t.text, lineHeight: 1.4, marginBottom: 3 }}>{n.msg}</div>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1 }}>{n.time}</div>
                  </div>
                  <button
                    onClick={() => setNotifications(prev => prev.filter(x => x.id !== n.id))}
                    style={{ background: "transparent", border: "none", cursor: "pointer", color: t.textDim, fontSize: 12, padding: "0 2px", flexShrink: 0 }}
                  >×</button>
                </div>
              ))
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
function EditorScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile } = useAuth();
  // ── LEFT PANEL STATE ──
  const [activeProjectId, setActiveProjectId] = React.useState(null);
  const [showNewProjectForm, setShowNewProjectForm] = React.useState(false);
  const [newProjectTitle, setNewProjectTitle] = React.useState("");
  const [newProjectDesc, setNewProjectDesc] = React.useState("");
  const [newProjectStatus, setNewProjectStatus] = React.useState("DRAFT");
  const [projects, setProjects] = React.useState([]);
  const [projectsLoading, setProjectsLoading] = React.useState(true);
  const [projectsError, setProjectsError] = React.useState(null);
  const [createError, setCreateError] = React.useState("");
  const [deleteConfirm, setDeleteConfirm] = React.useState(null); // project id pending delete

  // Load projects from DB
  const loadProjects = React.useCallback(async () => {
    if (!user) return;
    setProjectsLoading(true);
    setProjectsError(null);
    const { data, error } = await db.from('projects').select('*').eq('user_id', user.id).order('updated_at', { ascending: false });
    setProjectsLoading(false);
    if (error) { setProjectsError(error.message); }
    else {
      setProjects(data || []);
      if ((data || []).length > 0 && activeProjectId === null) {
        setActiveProjectId(data[0].id);
      }
    }
  }, [user, activeProjectId]);

  React.useEffect(() => { loadProjects(); }, [user?.id]);
  const [kebabOpen, setKebabOpen] = React.useState(null);

  // ── CENTER PANEL STATE ──
  const [showVersions, setShowVersions] = React.useState(false);

  // ── RIGHT PANEL STATE ──
  const [rightTab, setRightTab] = React.useState("TASKS");
  const [showAddTask, setShowAddTask] = React.useState(false);
  const [newTaskTitle, setNewTaskTitle] = React.useState("");
  const [newTaskAssignee, setNewTaskAssignee] = React.useState("");
  const [newTaskDeadline, setNewTaskDeadline] = React.useState("");
  const [tasks, setTasks] = React.useState([]);
  const [tasksLoading, setTasksLoading] = React.useState(false);
  const [tasksError, setTasksError] = React.useState(null);
  const [copied, setCopied] = React.useState(false);
  const [inviteEmail, setInviteEmail] = React.useState("");
  const [presentUsers, setPresentUsers] = React.useState([]); // realtime presence

  // Presence channel for editor
  React.useEffect(() => {
    if (!user || !activeProjectId) return;
    const channelName = 'editor-presence:' + activeProjectId;
    const channel = db.channel(channelName, { config: { presence: { key: user.id } } })
      .on('presence', { event: 'sync' }, () => {
        const state = channel.presenceState();
        const others = Object.values(state).flat().filter(p => p.user_id !== user.id);
        setPresentUsers(others);
      })
      .subscribe(async (status) => {
        if (status === 'SUBSCRIBED') {
          await channel.track({ user_id: user.id, username: profile?.username || user.email?.split('@')[0] || 'user', online_at: new Date().toISOString() });
        }
      });
    return () => { db.removeChannel(channel); setPresentUsers([]); };
  }, [user?.id, activeProjectId, profile?.username]);

  const activeProject = projects.find(p => p.id === activeProjectId) || projects[0];
  const statusColor = { ACTIVE: t.accent, REVIEW: "#FFD166", DRAFT: t.textDim };

  const handleCreateProject = async () => {
    if (!newProjectTitle.trim() || !user) return;
    setCreateError("");
    const { data, error } = await db.from('projects').insert({
      user_id: user.id,
      title: newProjectTitle,
      description: newProjectDesc,
      status: newProjectStatus.toLowerCase(),
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    }).select().single();
    if (error) { setCreateError(error.message); return; }
    setProjects(prev => [data, ...prev]);
    setNewProjectTitle(""); setNewProjectDesc(""); setNewProjectStatus("DRAFT");
    setShowNewProjectForm(false);
    setActiveProjectId(data.id);
  };

  const handleDeleteProject = async (projId) => {
    if (deleteConfirm !== projId) { setDeleteConfirm(projId); return; }
    setDeleteConfirm(null);
    const { error } = await db.from('projects').delete().eq('id', projId).eq('user_id', user.id);
    if (!error) {
      setProjects(prev => {
        const next = prev.filter(p => p.id !== projId);
        if (activeProjectId === projId) {
          setActiveProjectId(next.length > 0 ? next[0].id : null);
        }
        return next;
      });
    }
  };

  const handleCopy = () => {
    navigator.clipboard.writeText("https://vlstudio.app/share/summer-reel-2026");
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  // Load tasks when active project changes
  React.useEffect(() => {
    if (!activeProjectId) { setTasks([]); return; }
    setTasksLoading(true);
    db.from('tasks').select('*').eq('project_id', activeProjectId).order('created_at')
      .then(({ data, error }) => {
        setTasksLoading(false);
        if (error) { setTasksError(error.message); }
        else { setTasks(data || []); setTasksError(null); }
      });
  }, [activeProjectId]);

  const handleAddTask = async () => {
    if (!newTaskTitle.trim() || !activeProjectId) return;
    const optimistic = { id: Date.now(), title: newTaskTitle, assignee: newTaskAssignee || "@me", deadline: newTaskDeadline, completed: false, created_at: new Date().toISOString() };
    setTasks(prev => [optimistic, ...prev]);
    setNewTaskTitle(""); setNewTaskAssignee(""); setNewTaskDeadline("");
    setShowAddTask(false);
    const { data, error } = await db.from('tasks').insert({
      project_id: activeProjectId, title: optimistic.title,
      assignee: optimistic.assignee, deadline: optimistic.deadline,
      completed: false, created_at: optimistic.created_at,
    }).select().single();
    if (!error && data) {
      setTasks(prev => prev.map(tk => tk.id === optimistic.id ? data : tk));
    }
  };

  const toggleTask = async (id) => {
    const task = tasks.find(tk => tk.id === id);
    if (!task) return;
    const newCompleted = !task.completed;
    setTasks(prev => prev.map(tk => tk.id === id ? { ...tk, completed: newCompleted } : tk));
    const { error } = await db.from('tasks').update({ completed: newCompleted }).eq('id', id);
    if (error) {
      // Roll back on error
      setTasks(prev => prev.map(tk => tk.id === id ? { ...tk, completed: task.completed } : tk));
    }
  };

  React.useEffect(() => {
    if (kebabOpen === null) return;
    const close = () => setKebabOpen(null);
    window.addEventListener("click", close);
    return () => window.removeEventListener("click", close);
  }, [kebabOpen]);

  const inputStyle = {
    width: "100%", background: "#000", color: t.text,
    border: `1px solid ${t.panelLine}`, borderRadius: 4,
    padding: "8px 10px", fontSize: 11, fontFamily: DISPLAY_B,
    outline: "none", boxSizing: "border-box", letterSpacing: 0.5,
  };
  const outlineBtn = {
    background: "transparent", color: t.textDim, border: `1px solid ${t.panelLine}`,
    borderRadius: 3, padding: "5px 10px", fontSize: 11, fontWeight: 700,
    cursor: "pointer", fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
  };

  const editorFilename = activeProject
    ? activeProject.title.toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,"") + ".mov"
    : "untitled.mov";

  return (
    <div style={{ display: "flex", height: "calc(100vh - 65px)", background: t.bg, overflow: "hidden" }}>

      {/* ══════════════ LEFT PANEL ══════════════ */}
      <div style={{
        width: 260, flexShrink: 0,
        background: t.panel, borderRight: `1px solid ${t.panelLine}`,
        display: "flex", flexDirection: "column", overflow: "hidden",
      }}>
        {/* Header */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "10px 14px", borderBottom: `1px solid ${t.panelLine}`, flexShrink: 0,
        }}>
          <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2.5, textTransform: "uppercase" }}>
            // PROJECTS
          </span>
          <button
            onClick={() => setShowNewProjectForm(o => !o)}
            style={{ background: "transparent", border: "none", cursor: "pointer", color: t.accent, fontSize: 18, lineHeight: 1, padding: "0 2px" }}
          >＋</button>
        </div>

        {/* New project form */}
        {showNewProjectForm && (
          <div style={{
            padding: "12px 14px", borderBottom: `1px solid ${t.panelLine}`, flexShrink: 0,
            background: "#000",
          }}>
            <div style={{ marginBottom: 8 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 4 }}>Title</div>
              <input
                value={newProjectTitle} onChange={e => setNewProjectTitle(e.target.value)}
                placeholder="My new project" style={inputStyle}
                onFocus={e => e.target.style.borderColor = t.accent}
                onBlur={e => e.target.style.borderColor = t.panelLine}
              />
            </div>
            <div style={{ marginBottom: 8 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 4 }}>Description</div>
              <textarea
                value={newProjectDesc} onChange={e => setNewProjectDesc(e.target.value)}
                placeholder="Short description…" rows={2}
                style={{ ...inputStyle, resize: "none" }}
                onFocus={e => e.target.style.borderColor = t.accent}
                onBlur={e => e.target.style.borderColor = t.panelLine}
              />
            </div>
            <div style={{ marginBottom: 10 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 4 }}>Status</div>
              <div style={{ display: "flex", gap: 4 }}>
                {["DRAFT","ACTIVE","REVIEW"].map(s => (
                  <button key={s} onClick={() => setNewProjectStatus(s)} style={{
                    flex: 1, padding: "5px 4px", fontSize: 10, fontWeight: 700,
                    fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                    cursor: "pointer", borderRadius: 3,
                    background: newProjectStatus === s ? (statusColor[s] + "22") : "transparent",
                    border: `1px solid ${newProjectStatus === s ? statusColor[s] : t.panelLine}`,
                    color: newProjectStatus === s ? statusColor[s] : t.textDim,
                  }}>{s}</button>
                ))}
              </div>
            </div>
            {createError && <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: '#FF4444', marginBottom: 6 }}>{createError}</div>}
            <button onClick={handleCreateProject} style={{
              width: "100%", background: t.accent, color: t.accentText, border: "none",
              borderRadius: 3, padding: "8px 12px", fontSize: 11, fontWeight: 900,
              cursor: "pointer", fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
            }}>CREATE →</button>
          </div>
        )}

        {/* Project list */}
        <div style={{ flex: 1, overflowY: "auto" }}>
          {projectsLoading && [0,1,2,3,4].map(i => (
            <div key={i} style={{ padding: '12px 14px', borderBottom: `1px solid ${t.panelLine}` }}>
              <div style={{ height: 12, background: '#1a1a1a', borderRadius: 3, marginBottom: 6, animation: 'vlskel 1.5s infinite' }}/>
              <div style={{ height: 10, background: '#1a1a1a', borderRadius: 3, width: '60%', animation: 'vlskel 1.5s infinite' }}/>
            </div>
          ))}
          {projectsError && (
            <div style={{ padding: '12px 14px' }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: '#FF4444', marginBottom: 6 }}>// FAILED TO LOAD</div>
              <button onClick={loadProjects} style={{ background: 'transparent', color: t.accent, border: `1px solid ${t.accent}44`, borderRadius: 3, padding: '4px 8px', fontFamily: DISPLAY_B, fontSize: 10, cursor: 'pointer' }}>RETRY →</button>
            </div>
          )}
          {!projectsLoading && projects.map(proj => {
            const active = proj.id === activeProjectId;
            const projStatusKey = { draft: 'DRAFT', active: 'ACTIVE', review: 'REVIEW', live: 'ACTIVE' }[proj.status] || (proj.status || 'DRAFT').toUpperCase();
            return (
              <div
                key={proj.id}
                onClick={() => { setActiveProjectId(proj.id); setKebabOpen(null); }}
                style={{
                  position: "relative", padding: "10px 14px",
                  borderBottom: `1px solid ${t.panelLine}`,
                  borderLeft: active ? `3px solid ${t.accent}` : "3px solid transparent",
                  background: active ? (t.accent + "0a") : "transparent",
                  cursor: "pointer",
                }}
              >
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
                  <span style={{ fontSize: 12, fontWeight: 700, color: t.text, flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                    {proj.title}
                  </span>
                  <button
                    onClick={e => { e.stopPropagation(); setKebabOpen(kebabOpen === proj.id ? null : proj.id); }}
                    style={{ background: "transparent", border: "none", cursor: "pointer", color: t.textDim, fontSize: 14, padding: "0 2px", flexShrink: 0, lineHeight: 1 }}
                  >⋯</button>
                </div>
                {kebabOpen === proj.id && (
                  <div
                    onClick={e => e.stopPropagation()}
                    style={{
                      position: "absolute", top: 28, right: 10,
                      background: t.panel, border: `1px solid ${t.panelLine}`,
                      borderRadius: 4, zIndex: 50, boxShadow: "0 8px 24px rgba(0,0,0,0.5)", minWidth: 110,
                    }}
                  >
                    {["Rename", deleteConfirm === proj.id ? "Click again to delete" : "Delete"].map((action, i) => (
                      <button key={i} onClick={() => {
                        if (action === "Rename") { setKebabOpen(null); return; }
                        handleDeleteProject(proj.id);
                        if (deleteConfirm === proj.id) setKebabOpen(null);
                      }} style={{
                        display: "block", width: "100%", padding: "8px 14px", textAlign: "left",
                        background: "transparent", border: "none",
                        borderBottom: i === 0 ? `1px solid ${t.panelLine}` : "none",
                        color: action === "Rename" ? t.text : "#FF5F5F", cursor: "pointer",
                        fontFamily: DISPLAY_B, fontSize: 11, letterSpacing: 1,
                      }}>{action}</button>
                    ))}
                  </div>
                )}
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{
                    fontSize: 9, fontWeight: 800, fontFamily: DISPLAY_B, letterSpacing: 1.5,
                    textTransform: "uppercase", padding: "2px 5px", borderRadius: 2,
                    color: statusColor[projStatusKey] || t.textDim,
                    border: `1px solid ${(statusColor[projStatusKey] || t.textDim) + "55"}`,
                  }}>{projStatusKey}</span>
                  <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim }}>{
                    typeof proj.duration === 'number'
                      ? `${Math.floor(proj.duration/60)}:${String(proj.duration%60).padStart(2,'0')}`
                      : (proj.duration || '')
                  }</span>
                  <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, marginLeft: "auto" }}>{formatRelativeTime(proj.updated_at)}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* ══════════════ CENTER PANEL ══════════════ */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", minWidth: 0 }}>
        {/* Slim toolbar */}
        <div style={{
          height: 40, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "0 14px", borderBottom: `1px solid ${t.panelLine}`, background: t.panel,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 0.5 }}>
              {editorFilename}
            </span>
            {presentUsers.length > 0 && (
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 6, height: 6, borderRadius: 99, background: t.accent, display: "inline-block" }}/>
                {presentUsers.slice(0, 3).map((p, i) => (
                  <div key={p.user_id || i} title={p.username || 'collaborator'} style={{ width: 22, height: 22, borderRadius: 11, background: t.accent + '33', border: `1.5px solid ${t.accent}`, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: DISPLAY_B, fontSize: 8, fontWeight: 700, color: t.accent }}>
                    {(p.username || '?')[0].toUpperCase()}
                  </div>
                ))}
                <span style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.accent, letterSpacing: 1 }}>
                  {presentUsers.length} online
                </span>
              </div>
            )}
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            <button style={outlineBtn}>SHARE ⟳</button>
            <button style={outlineBtn}>EXPORT ↓</button>
            <button
              onClick={() => setShowVersions(o => !o)}
              style={{ ...outlineBtn, color: showVersions ? t.accent : t.textDim, borderColor: showVersions ? t.accent : t.panelLine }}
            >VERSIONS</button>
          </div>
        </div>

        {/* Version history panel */}
        {showVersions && (
          <div style={{
            flexShrink: 0, background: t.panel, borderBottom: `1px solid ${t.panelLine}`,
            padding: "8px 14px",
          }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 2, textTransform: "uppercase", marginBottom: 8 }}>// VERSION HISTORY</div>
            {[
              { label: "v4 · current", dim: null },
              { label: "v3",           dim: "2h ago" },
              { label: "v2",           dim: "yesterday" },
              { label: "v1",           dim: "3 days ago" },
            ].map((v, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 10, padding: "6px 0",
                borderBottom: i < 3 ? `1px solid ${t.panelLine}` : "none",
              }}>
                <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: i === 0 ? t.accent : t.text, flex: 1, letterSpacing: 0.5 }}>
                  {v.label}{v.dim && <span style={{ color: t.textDim, marginLeft: 8, fontSize: 10 }}>{v.dim}</span>}
                </span>
                <button style={{ ...outlineBtn, fontSize: 10, padding: "3px 8px" }}>COMPARE</button>
                <button style={{ ...outlineBtn, fontSize: 10, padding: "3px 8px" }}>RESTORE</button>
              </div>
            ))}
          </div>
        )}

        {/* Editor canvas */}
        <div style={{ flex: 1, overflow: "auto", padding: 16 }}>
          <MockEditor
            theme={t}
            showHint={true}
            autoCycle={false}
            label={activeProject ? activeProject.title + ".mov" : "untitled.mov"}
          />
        </div>
      </div>

      {/* ══════════════ RIGHT PANEL ══════════════ */}
      <div style={{
        width: 280, flexShrink: 0,
        borderLeft: `1px solid ${t.panelLine}`, background: t.panel,
        display: "flex", flexDirection: "column", overflow: "hidden",
      }}>
        {/* Tab buttons */}
        <div style={{ display: "flex", borderBottom: `1px solid ${t.panelLine}`, flexShrink: 0 }}>
          {["TASKS","COMMENTS","SHARE"].map(tab => (
            <button key={tab} onClick={() => setRightTab(tab)} style={{
              flex: 1, padding: "10px 4px", background: "transparent", border: "none",
              borderBottom: rightTab === tab ? `2px solid ${t.accent}` : "2px solid transparent",
              color: rightTab === tab ? t.accent : t.textDim,
              fontFamily: DISPLAY_B, fontSize: 10, fontWeight: 700, letterSpacing: 1.5,
              textTransform: "uppercase", cursor: "pointer",
            }}>{tab}</button>
          ))}
        </div>

        {/* Tab content */}
        <div style={{ flex: 1, overflowY: "auto", padding: "12px 14px" }}>

          {/* ── TASKS ── */}
          {rightTab === "TASKS" && (
            <div>
              <button onClick={() => setShowAddTask(o => !o)} style={{
                width: "100%", background: "transparent", color: t.accent,
                border: `1px solid ${t.accent}55`, borderRadius: 3, padding: "7px 12px",
                fontSize: 11, fontWeight: 700, cursor: "pointer",
                fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 10,
              }}>＋ ADD TASK</button>

              {showAddTask && (
                <div style={{ background: "#000", border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "10px 12px", marginBottom: 10 }}>
                  <div style={{ marginBottom: 6 }}>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 3 }}>Title</div>
                    <input value={newTaskTitle} onChange={e => setNewTaskTitle(e.target.value)} placeholder="Task title"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = t.accent}
                      onBlur={e => e.target.style.borderColor = t.panelLine}
                    />
                  </div>
                  <div style={{ marginBottom: 6 }}>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 3 }}>Assignee</div>
                    <input value={newTaskAssignee} onChange={e => setNewTaskAssignee(e.target.value)} placeholder="@username"
                      style={inputStyle}
                      onFocus={e => e.target.style.borderColor = t.accent}
                      onBlur={e => e.target.style.borderColor = t.panelLine}
                    />
                  </div>
                  <div style={{ marginBottom: 8 }}>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 3 }}>Deadline</div>
                    <input type="date" value={newTaskDeadline} onChange={e => setNewTaskDeadline(e.target.value)}
                      style={{ ...inputStyle, colorScheme: "dark" }}
                      onFocus={e => e.target.style.borderColor = t.accent}
                      onBlur={e => e.target.style.borderColor = t.panelLine}
                    />
                  </div>
                  <button onClick={handleAddTask} style={{
                    width: "100%", background: t.accent, color: t.accentText, border: "none",
                    borderRadius: 3, padding: "7px 12px", fontSize: 11, fontWeight: 900,
                    cursor: "pointer", fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                  }}>ADD →</button>
                </div>
              )}

              {tasksLoading && [0,1,2].map(i => (
                <div key={i} style={{ padding: '8px 0', borderBottom: `1px solid ${t.panelLine}` }}>
                  <div style={{ height: 10, background: '#1a1a1a', borderRadius: 3, marginBottom: 4, animation: 'vlskel 1.5s infinite' }}/>
                  <div style={{ height: 8, background: '#1a1a1a', borderRadius: 3, width: '70%', animation: 'vlskel 1.5s infinite' }}/>
                </div>
              ))}
              {tasksError && <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: '#FF4444', marginBottom: 8 }}>// {tasksError}</div>}
              {!tasksLoading && tasks.map(task => (
                <div key={task.id} style={{
                  display: "flex", alignItems: "flex-start", gap: 8, padding: "8px 0",
                  borderBottom: `1px solid ${t.panelLine}`,
                  opacity: task.completed ? 0.45 : 1, transition: "opacity 0.2s",
                }}>
                  <input
                    type="checkbox" checked={!!task.completed} onChange={() => toggleTask(task.id)}
                    style={{ accentColor: t.accent, marginTop: 3, flexShrink: 0, cursor: "pointer" }}
                  />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 12, color: t.text, marginBottom: 2,
                      textDecoration: task.completed ? "line-through" : "none",
                    }}>{task.title}</div>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 0.5 }}>
                      {task.assignee} · {task.deadline}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* ── COMMENTS ── */}
          {rightTab === "COMMENTS" && (
            <div>
              {[
                { initials: "MA", name: "maya",  time: "2 min ago",  text: "The transition at 00:14 is a bit jarring — maybe smooth it out?", tint: t.accent   },
                { initials: "JO", name: "joel",  time: "1 hr ago",   text: "Wide cut at 00:38 looks great, approved this section.",          tint: "#FFD166"  },
                { initials: "AN", name: "ana",   time: "yesterday",  text: "Missing an 's' in the caption at 01:02.",                        tint: "#7CD3FF"  },
              ].map((c, i) => (
                <div key={i} style={{ display: "flex", gap: 10, padding: "10px 0", borderBottom: `1px solid ${t.panelLine}` }}>
                  <div style={{
                    width: 30, height: 30, borderRadius: 99, flexShrink: 0,
                    background: c.tint + "22", border: `1px solid ${c.tint}55`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontFamily: DISPLAY_B, fontSize: 10, fontWeight: 700, color: c.tint,
                  }}>{c.initials}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 3 }}>
                      <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: c.tint, fontWeight: 700 }}>@{c.name}</span>
                      <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim }}>{c.time}</span>
                    </div>
                    <div style={{ fontSize: 12, color: t.text, lineHeight: 1.45 }}>{c.text}</div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* ── SHARE ── */}
          {rightTab === "SHARE" && (
            <div>
              {/* Shareable link */}
              <div style={{ marginBottom: 16 }}>
                <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 6 }}>SHAREABLE LINK</div>
                <div style={{ display: "flex", alignItems: "center", gap: 6, background: "#000", border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "8px 10px" }}>
                  <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    vlstudio.app/share/summer-reel-2026
                  </span>
                  <button onClick={handleCopy} style={{
                    background: copied ? t.accent : "transparent",
                    color: copied ? t.accentText : t.accent,
                    border: `1px solid ${t.accent}`, borderRadius: 3,
                    padding: "4px 8px", fontSize: 10, fontWeight: 700,
                    cursor: "pointer", fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                    flexShrink: 0, whiteSpace: "nowrap", transition: "background 0.15s, color 0.15s",
                  }}>{copied ? "COPIED ✓" : "COPY"}</button>
                </div>
              </div>

              {/* Add collaborator */}
              <div style={{ marginBottom: 16 }}>
                <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 6 }}>ADD COLLABORATOR</div>
                <div style={{ display: "flex", gap: 6 }}>
                  <input value={inviteEmail} onChange={e => setInviteEmail(e.target.value)}
                    placeholder="email@studio.com"
                    style={{ ...inputStyle, flex: 1 }}
                    onFocus={e => e.target.style.borderColor = t.accent}
                    onBlur={e => e.target.style.borderColor = t.panelLine}
                  />
                  <button style={{
                    background: "transparent", color: t.accent, border: `1px solid ${t.accent}55`,
                    borderRadius: 3, padding: "0 10px", fontSize: 10, fontWeight: 700,
                    cursor: "pointer", fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                    whiteSpace: "nowrap", flexShrink: 0,
                  }}>INVITE →</button>
                </div>
              </div>

              {/* Current collaborators */}
              <div>
                <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 8 }}>COLLABORATORS</div>
                {[
                  { initials: "MA", name: "maya_edits",   role: "EDITOR", tint: t.accent  },
                  { initials: "JO", name: "joel_reviews", role: "VIEWER", tint: "#7CD3FF" },
                ].map((c, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: `1px solid ${t.panelLine}` }}>
                    <div style={{
                      width: 28, height: 28, borderRadius: 99, flexShrink: 0,
                      background: c.tint + "22", border: `1px solid ${c.tint}55`,
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontFamily: DISPLAY_B, fontSize: 10, fontWeight: 700, color: c.tint,
                    }}>{c.initials}</div>
                    <span style={{ flex: 1, fontFamily: DISPLAY_B, fontSize: 11, color: t.text }}>{c.name}</span>
                    <span style={{
                      fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1.5,
                      textTransform: "uppercase", padding: "3px 6px", borderRadius: 2,
                      color: c.role === "EDITOR" ? t.accent : t.textDim,
                      border: `1px solid ${c.role === "EDITOR" ? t.accent + "55" : t.panelLine}`,
                    }}>{c.role}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}
function MarketplaceScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile } = useAuth();
  const [cart, setCart] = React.useState([]);
  const [wishlistIds, setWishlistIds] = React.useState(new Set());
  const [cartOpen, setCartOpen] = React.useState(false);
  const [subState, setSubState] = React.useState("grid"); // "grid"|"checkout"|"processing"|"success"
  const [savedProducts, setSavedProducts] = React.useState({});
  const [drawerProduct, setDrawerProduct] = React.useState(null);
  const [drawerComments, setDrawerComments] = React.useState([]);
  const [drawerCommentsLoading, setDrawerCommentsLoading] = React.useState(false);
  const [drawerCommentText, setDrawerCommentText] = React.useState("");
  const [drawerCommentPosting, setDrawerCommentPosting] = React.useState(false);
  const priceFilterTimer = React.useRef(null);

  // Load cart from DB
  React.useEffect(() => {
    if (!user) return;
    db.from('marketplace_cart_item').select('*, marketplace_product(title, price, marketplace_vendor(store_name))').eq('user_id', user.id)
      .then(({ data }) => {
        if (data) {
          setCart(data.map(item => ({
            id: item.product_id,
            title: item.marketplace_product?.title || '',
            vendor: item.marketplace_product?.marketplace_vendor?.store_name || '',
            price: item.marketplace_product?.price || 0,
            qty: item.quantity || 1,
          })));
        }
      });
    db.from('marketplace_wish_list').select('product_id').eq('user_id', user.id)
      .then(({ data }) => {
        if (data) {
          const ids = new Set(data.map(w => w.product_id));
          setWishlistIds(ids);
          const savedMap = {};
          ids.forEach(id => { savedMap[id] = true; });
          setSavedProducts(savedMap);
        }
      });
  }, [user?.id]);
  const [searchQuery, setSearchQuery] = React.useState("");

  // Filter inputs (pre-apply)
  const [fCat,    setFCat]    = React.useState("All");
  const [fMin,    setFMin]    = React.useState("");
  const [fMax,    setFMax]    = React.useState("");
  const [fRating, setFRating] = React.useState(0);
  const [fDate,   setFDate]   = React.useState("Any time");

  // Applied filters
  const [aCat,    setACat]    = React.useState("All");
  const [aMin,    setAMin]    = React.useState("");
  const [aMax,    setAMax]    = React.useState("");
  const [aRating, setARating] = React.useState(0);
  const [aDate,   setADate]   = React.useState("Any time");

  const products = [
    { id:1, title:"Cinematic LUT Pack Vol.1",  vendor:"color_lab",     price:24, rating:5, reviews:128, sold:1204, category:"LUTs",      daysAgo:5,  popular:true  },
    { id:2, title:"Lo-Fi Beats Collection",    vendor:"beatz_studio",  price:18, rating:4, reviews:87,  sold:843,  category:"Music",     daysAgo:12, popular:false },
    { id:3, title:"Podcast Intro SFX Pack",    vendor:"audio_forge",   price:15, rating:4, reviews:64,  sold:512,  category:"SFX",       daysAgo:3,  popular:true  },
    { id:4, title:"Social Media Templates",    vendor:"vl_designs",    price:29, rating:5, reviews:210, sold:2100, category:"Templates", daysAgo:20, popular:false },
    { id:5, title:"Color Presets Bundle",      vendor:"pro_grade",     price:22, rating:3, reviews:45,  sold:390,  category:"Presets",   daysAgo:8,  popular:false },
    { id:6, title:"Dialogue Enhancer Plugin",  vendor:"audiomix_pro",  price:49, rating:5, reviews:176, sold:890,  category:"Plugins",   daysAgo:2,  popular:true  },
    { id:7, title:"Vintage Film Grain LUTs",   vendor:"nostalgic_fx",  price:19, rating:4, reviews:93,  sold:720,  category:"LUTs",      daysAgo:15, popular:false },
    { id:8, title:"Ambient Sound Library",     vendor:"soundscape_co", price:35, rating:5, reviews:142, sold:1080, category:"Music",     daysAgo:7,  popular:false },
    { id:9, title:"YouTube Shorts Templates",  vendor:"social_kit",    price:14, rating:4, reviews:55,  sold:430,  category:"Templates", daysAgo:4,  popular:false },
  ];

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const subtotal  = cart.reduce((s, i) => s + i.price * i.qty, 0);

  const addToCart = async (p) => {
    setCart(prev => {
      const ex = prev.find(i => i.id === p.id);
      return ex ? prev.map(i => i.id === p.id ? { ...i, qty: i.qty + 1 } : i) : [...prev, { ...p, qty: 1 }];
    });
    if (user) {
      const ex = cart.find(i => i.id === p.id);
      if (ex) {
        db.from('marketplace_cart_item').update({ quantity: ex.qty + 1 }).eq('user_id', user.id).eq('product_id', p.id);
      } else {
        db.from('marketplace_cart_item').insert({ user_id: user.id, product_id: p.id, quantity: 1 });
      }
    }
  };
  const removeFromCart = (id) => {
    setCart(prev => prev.filter(i => i.id !== id));
    if (user) db.from('marketplace_cart_item').delete().eq('user_id', user.id).eq('product_id', id);
  };
  const changeQty = (id, d) => {
    setCart(prev => prev.map(i => i.id === id ? { ...i, qty: Math.max(1, i.qty + d) } : i));
    const item = cart.find(i => i.id === id);
    if (user && item) db.from('marketplace_cart_item').update({ quantity: Math.max(1, item.qty + d) }).eq('user_id', user.id).eq('product_id', id);
  };
  const toggleSave = async (id) => {
    const isSaved = !!savedProducts[id];
    setSavedProducts(prev => ({ ...prev, [id]: !isSaved }));
    if (!user) return;
    if (isSaved) {
      db.from('marketplace_wish_list').delete().eq('user_id', user.id).eq('product_id', id);
    } else {
      db.from('marketplace_wish_list').insert({ user_id: user.id, product_id: id, created_at: new Date().toISOString() });
    }
  };

  const applyFilters = () => { setACat(fCat); setAMin(fMin); setAMax(fMax); setARating(fRating); setADate(fDate); };
  const resetFilters = () => {
    setFCat("All"); setFMin(""); setFMax(""); setFRating(0); setFDate("Any time");
    setACat("All"); setAMin(""); setAMax(""); setARating(0); setADate("Any time");
  };

  const filtered = products.filter(p => {
    if (aCat !== "All" && p.category !== aCat) return false;
    if (aMin !== "" && p.price < +aMin) return false;
    if (aMax !== "" && p.price > +aMax) return false;
    if (aRating > 0 && p.rating < aRating) return false;
    if (aDate === "This week"  && p.daysAgo > 7)  return false;
    if (aDate === "This month" && p.daysAgo > 30) return false;
    if (searchQuery && !p.title.toLowerCase().includes(searchQuery.toLowerCase()) && !p.vendor.toLowerCase().includes(searchQuery.toLowerCase())) return false;
    return true;
  });

  const inFlow = subState !== "grid";

  return (
    <div style={{ display:"flex", minHeight:"calc(100vh - 65px)", background:t.bg, position:"relative" }}>
      <style>{`
        @keyframes vlspin  { from{transform:rotate(0deg)}   to{transform:rotate(360deg)} }
        @keyframes vldrawer{ from{transform:translateX(100%)} to{transform:translateX(0)} }
        @keyframes vlcheck { from{opacity:0;transform:scale(.85)} to{opacity:1;transform:scale(1)} }
        .mkt-input::placeholder { color:rgba(138,138,133,.55); }
        input[type=number]::-webkit-outer-spin-button,input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}
        input[type=number]{-moz-appearance:textfield}
      `}</style>

      {/* ── PRODUCT DETAIL DRAWER ── */}
      {drawerProduct && (
        <div style={{ position:"fixed", inset:0, zIndex:800, display:"flex" }}>
          {/* Backdrop */}
          <div onClick={()=>setDrawerProduct(null)} style={{ flex:1, background:"rgba(0,0,0,.55)" }}/>
          {/* Drawer panel */}
          <div style={{ width:480, background:t.panel, borderLeft:`1px solid ${t.panelLine}`, overflowY:"auto", animation:"vldrawer .25s ease", display:"flex", flexDirection:"column" }}>
            {/* Header */}
            <div style={{ padding:"20px 24px 16px", borderBottom:`1px solid ${t.panelLine}`, display:"flex", alignItems:"flex-start", gap:12 }}>
              <div style={{ flex:1 }}>
                <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.accent, letterSpacing:2.5, textTransform:"uppercase", marginBottom:6 }}>PRODUCT DETAIL</div>
                <div style={{ fontFamily:DISPLAY_B, fontSize:16, fontWeight:700, color:t.text, lineHeight:1.3, marginBottom:4 }}>{drawerProduct.title}</div>
                <div style={{ fontFamily:DISPLAY_B, fontSize:11, color:t.textDim, letterSpacing:1 }}>by {drawerProduct.vendor}</div>
              </div>
              <button onClick={()=>setDrawerProduct(null)} style={{ background:"none", border:"none", color:t.textDim, cursor:"pointer", fontSize:20, lineHeight:1, padding:4 }}>✕</button>
            </div>
            {/* Stats row */}
            <div style={{ display:"flex", gap:0, borderBottom:`1px solid ${t.panelLine}` }}>
              {[["PRICE", "$" + drawerProduct.price], ["RATING", "★".repeat(drawerProduct.rating) + "☆".repeat(5-drawerProduct.rating)], ["SOLD", drawerProduct.sold?.toLocaleString() || "—"], ["REVIEWS", drawerProduct.reviews || "—"]].map(([k,v])=>(
                <div key={k} style={{ flex:1, padding:"12px 16px", borderRight:`1px solid ${t.panelLine}`, textAlign:"center" }}>
                  <div style={{ fontFamily:DISPLAY_B, fontSize:8, color:t.textDim, letterSpacing:2, textTransform:"uppercase", marginBottom:4 }}>{k}</div>
                  <div style={{ fontFamily:DISPLAY_B, fontSize:13, fontWeight:700, color:t.text }}>{v}</div>
                </div>
              ))}
            </div>
            {/* Action buttons */}
            <div style={{ display:"flex", gap:10, padding:"16px 24px", borderBottom:`1px solid ${t.panelLine}` }}>
              <button onClick={(e)=>{ e.stopPropagation(); addToCart(drawerProduct); }} style={{ flex:1, background:t.accent, color:t.accentText, border:"none", borderRadius:4, padding:"12px 0", fontFamily:DISPLAY_B, fontSize:11, fontWeight:700, letterSpacing:2, textTransform:"uppercase", cursor:"pointer" }}>ADD TO CART</button>
              <button onClick={(e)=>{ e.stopPropagation(); toggleSave(drawerProduct.id); }} style={{ background:"transparent", border:`1px solid ${t.panelLine}`, color: savedProducts[drawerProduct.id] ? t.accent : t.textDim, borderRadius:4, padding:"12px 16px", fontFamily:DISPLAY_B, fontSize:16, cursor:"pointer" }}>{savedProducts[drawerProduct.id] ? "♥" : "♡"}</button>
            </div>
            {/* Reviews/Comments */}
            <div style={{ padding:"16px 24px 0", fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:2.5, textTransform:"uppercase", marginBottom:12 }}>REVIEWS & COMMENTS</div>
            {drawerCommentsLoading ? (
              <div style={{ padding:"0 24px" }}>
                {[1,2,3].map(i=>(
                  <div key={i} style={{ marginBottom:14 }}>
                    <div style={{ height:11, width:"40%", background:t.panelLine, borderRadius:2, marginBottom:6, animation:"vlskel 1.4s ease infinite" }}/>
                    <div style={{ height:10, width:"80%", background:t.panelLine, borderRadius:2, animation:"vlskel 1.4s ease infinite" }}/>
                  </div>
                ))}
              </div>
            ) : drawerComments.length === 0 ? (
              <div style={{ padding:"0 24px 16px", fontFamily:DISPLAY_B, fontSize:11, color:t.textDim, letterSpacing:1 }}>No reviews yet. Be the first!</div>
            ) : (
              <div style={{ padding:"0 24px" }}>
                {drawerComments.map((c,i)=>(
                  <div key={c.id||i} style={{ marginBottom:14, paddingBottom:14, borderBottom:`1px solid ${t.panelLine}` }}>
                    <div style={{ display:"flex", gap:8, alignItems:"center", marginBottom:4 }}>
                      <div style={{ width:24, height:24, borderRadius:12, background:t.accent, display:"flex", alignItems:"center", justifyContent:"center", fontFamily:DISPLAY_B, fontSize:9, fontWeight:700, color:t.accentText }}>{(c.profiles?.username||c.reviewer_name||'?')[0].toUpperCase()}</div>
                      <span style={{ fontFamily:DISPLAY_B, fontSize:11, fontWeight:600, color:t.text }}>{c.profiles?.username||c.reviewer_name||'Anonymous'}</span>
                      <span style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:1, marginLeft:"auto" }}>{formatRelativeTime(c.created_at)}</span>
                    </div>
                    {c.rating > 0 && <div style={{ fontFamily:DISPLAY_B, fontSize:11, color:t.accent, marginBottom:3 }}>{"★".repeat(c.rating)}{"☆".repeat(5-c.rating)}</div>}
                    <div style={{ fontFamily:DISPLAY_B, fontSize:12, color:t.text, lineHeight:1.55 }}>{c.body||c.comment||c.content}</div>
                  </div>
                ))}
              </div>
            )}
            {/* Comment input */}
            {user && (
              <div style={{ padding:"16px 24px 24px", borderTop:`1px solid ${t.panelLine}`, marginTop:"auto" }}>
                <textarea
                  placeholder="Write a review..."
                  value={drawerCommentText}
                  onChange={e=>setDrawerCommentText(e.target.value)}
                  rows={3}
                  style={{ width:"100%", background:t.bg, border:`1px solid ${t.panelLine}`, borderRadius:4, color:t.text, fontFamily:DISPLAY_B, fontSize:12, padding:"10px 12px", outline:"none", resize:"vertical", boxSizing:"border-box" }}
                />
                <button
                  disabled={!drawerCommentText.trim() || drawerCommentPosting}
                  onClick={async ()=>{
                    if (!drawerCommentText.trim()) return;
                    setDrawerCommentPosting(true);
                    const { data: newComment } = await db.from('marketplace_product_review').insert({
                      product_id: drawerProduct.id,
                      user_id: user.id,
                      body: drawerCommentText.trim(),
                      rating: 0,
                      created_at: new Date().toISOString(),
                    }).select('*, profiles(username)').single();
                    if (newComment) setDrawerComments(prev => [newComment, ...prev]);
                    setDrawerCommentText("");
                    setDrawerCommentPosting(false);
                  }}
                  style={{ marginTop:8, background: drawerCommentText.trim() ? t.accent : t.panelLine, color: drawerCommentText.trim() ? t.accentText : t.textDim, border:"none", borderRadius:4, padding:"10px 20px", fontFamily:DISPLAY_B, fontSize:10, fontWeight:700, letterSpacing:2, textTransform:"uppercase", cursor: drawerCommentText.trim() ? "pointer" : "default" }}
                >{drawerCommentPosting ? "POSTING…" : "POST REVIEW"}</button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* LEFT SIDEBAR — hidden during checkout flow */}
      {!inFlow && (
        <aside style={{
          width:240, flexShrink:0, borderRight:`1px solid ${t.panelLine}`,
          background:t.panel, overflowY:"auto",
          position:"sticky", top:65, height:"calc(100vh - 65px)",
        }}>
          <div style={{ padding:"20px 18px" }}>
            <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.accent, letterSpacing:3, textTransform:"uppercase", marginBottom:22 }}>
              // FILTERS
            </div>

            {/* CATEGORY */}
            <MktFilterSection t={t} title="CATEGORY">
              {["All","Templates","Presets","LUTs","Music","SFX","Plugins"].map(c => (
                <MktRadioRow key={c} label={c} checked={fCat===c} onChange={()=>setFCat(c)} t={t}/>
              ))}
            </MktFilterSection>

            {/* PRICE RANGE */}
            <MktFilterSection t={t} title="PRICE RANGE">
              <div style={{ display:"flex", gap:8, marginBottom:12 }}>
                <input className="mkt-input" type="number" placeholder="Min" value={fMin} onChange={e=>{ const v=e.target.value; setFMin(v); clearTimeout(priceFilterTimer.current); priceFilterTimer.current=setTimeout(()=>{ setAMin(v); },300); }}
                  style={{ flex:1, width:0, background:t.bg, border:`1px solid ${t.panelLine}`, borderRadius:4, color:t.text, fontFamily:DISPLAY_B, fontSize:11, padding:"6px 8px", outline:"none" }}/>
                <input className="mkt-input" type="number" placeholder="Max" value={fMax} onChange={e=>{ const v=e.target.value; setFMax(v); clearTimeout(priceFilterTimer.current); priceFilterTimer.current=setTimeout(()=>{ setAMax(v); },300); }}
                  style={{ flex:1, width:0, background:t.bg, border:`1px solid ${t.panelLine}`, borderRadius:4, color:t.text, fontFamily:DISPLAY_B, fontSize:11, padding:"6px 8px", outline:"none" }}/>
              </div>
              {/* Static range track */}
              <div style={{ height:4, background:t.panelLine, borderRadius:2, position:"relative" }}>
                <div style={{ position:"absolute", left:"15%", right:"25%", height:"100%", background:t.accent, borderRadius:2 }}/>
                <div style={{ position:"absolute", left:"calc(15% - 5px)", top:-3, width:10, height:10, background:t.accent, borderRadius:99, border:`2px solid ${t.bg}` }}/>
                <div style={{ position:"absolute", right:"calc(25% - 5px)", top:-3, width:10, height:10, background:t.accent, borderRadius:99, border:`2px solid ${t.bg}` }}/>
              </div>
            </MktFilterSection>

            {/* RATING */}
            <MktFilterSection t={t} title="RATING">
              {[5,4,3,2,1].map(s => (
                <div key={s} onClick={()=>setFRating(fRating===s?0:s)}
                  style={{ display:"flex", alignItems:"center", gap:6, padding:"5px 0", cursor:"pointer" }}>
                  <span>
                    {"★★★★★".split("").map((_, i) => (
                      <span key={i} style={{ color: i<s ? t.accent : t.panelLine, fontSize:14 }}>★</span>
                    ))}
                  </span>
                  <span style={{ fontFamily:DISPLAY_B, fontSize:10, color: fRating===s ? t.accent : t.textDim, letterSpacing:.5 }}>& up</span>
                </div>
              ))}
            </MktFilterSection>

            {/* DATE POSTED */}
            <MktFilterSection t={t} title="DATE POSTED">
              {["Any time","This week","This month"].map(d => (
                <MktRadioRow key={d} label={d} checked={fDate===d} onChange={()=>setFDate(d)} t={t}/>
              ))}
            </MktFilterSection>

            <button onClick={applyFilters} style={{
              width:"100%", background:t.accent, color:t.accentText, border:"none", borderRadius:4,
              padding:"10px 0", fontFamily:DISPLAY_B, fontSize:10, fontWeight:800, letterSpacing:2,
              textTransform:"uppercase", cursor:"pointer", marginBottom:10,
            }}>APPLY FILTERS</button>
            <div style={{ textAlign:"center" }}>
              <span onClick={resetFilters} style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, cursor:"pointer", letterSpacing:1.5, textTransform:"uppercase", textDecoration:"underline" }}>
                RESET
              </span>
            </div>
          </div>
        </aside>
      )}

      {/* MAIN */}
      <div style={{ flex:1, overflowY:"auto" }}>

        {/* ── GRID VIEW ── */}
        {subState === "grid" && (<>
          {/* Top bar */}
          <div style={{
            display:"flex", alignItems:"center", justifyContent:"space-between",
            padding:"16px 24px", borderBottom:`1px solid ${t.panelLine}`,
            position:"sticky", top:0, background:t.bg+"ee", backdropFilter:"blur(10px)", zIndex:5,
          }}>
            <span style={{ fontFamily:DISPLAY_B, fontSize:12, color:t.accent, letterSpacing:3, textTransform:"uppercase" }}>
              // MARKETPLACE
            </span>
            <div style={{ display:"flex", alignItems:"center", gap:10 }}>
              <input className="mkt-input" type="text" placeholder="Search products…"
                value={searchQuery} onChange={e=>setSearchQuery(e.target.value)}
                style={{ width:280, background:t.panel, border:`1px solid ${t.panelLine}`, borderRadius:4, color:t.text, fontFamily:DISPLAY_B, fontSize:11, padding:"8px 12px", outline:"none" }}
              />
              <button onClick={()=>setCartOpen(true)} style={{
                position:"relative", background:t.panel, border:`1px solid ${t.panelLine}`,
                borderRadius:4, padding:"7px 10px", cursor:"pointer", color:t.text,
                display:"flex", alignItems:"center",
              }}>
                <svg width="17" height="17" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M1 1.5h2l2.4 9h8l2-7H5.5"/><circle cx="7" cy="15.5" r="1.3"/><circle cx="13" cy="15.5" r="1.3"/>
                </svg>
                {cartCount > 0 && (
                  <span style={{
                    position:"absolute", top:-6, right:-6, background:t.accent, color:t.accentText,
                    borderRadius:99, minWidth:16, height:16, fontSize:9, fontWeight:900,
                    fontFamily:DISPLAY_B, display:"flex", alignItems:"center", justifyContent:"center", padding:"0 3px",
                  }}>{cartCount}</span>
                )}
              </button>
            </div>
          </div>

          {/* Product grid */}
          <div style={{ padding:"24px" }}>
            {filtered.length === 0 ? (
              <div style={{ textAlign:"center", padding:"80px 0", fontFamily:DISPLAY_B, color:t.textDim, fontSize:12, letterSpacing:3, textTransform:"uppercase" }}>
                No products match your filters.
              </div>
            ) : (
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:16 }}>
                {filtered.map(p => (
                  <MktProductCard key={p.id} product={p} t={t}
                    onAdd={()=>addToCart(p)}
                    saved={!!savedProducts[p.id]}
                    onSave={()=>toggleSave(p.id)}
                    onClick={()=>{ setDrawerProduct(p); setDrawerComments([]); setDrawerCommentText(""); setDrawerCommentsLoading(true); db.from('marketplace_product_review').select('*, profiles(username)').eq('product_id', p.id).order('created_at', { ascending: false }).limit(20).then(({data})=>{ setDrawerComments(data||[]); setDrawerCommentsLoading(false); }); }}
                  />
                ))}
              </div>
            )}
          </div>
        </>)}

        {/* ── CHECKOUT / PROCESSING / SUCCESS ── */}
        {(subState==="checkout"||subState==="processing"||subState==="success") && (
          <MktCheckoutState
            t={t} cart={cart} subtotal={subtotal}
            subState={subState} setSubState={setSubState} setCart={setCart}
          />
        )}
      </div>

      {/* CART DRAWER */}
      {cartOpen && (
        <MktCartDrawer
          t={t} cart={cart} cartCount={cartCount} subtotal={subtotal}
          onClose={()=>setCartOpen(false)}
          onRemove={removeFromCart}
          onChangeQty={changeQty}
          onCheckout={()=>{ setCartOpen(false); setSubState("checkout"); }}
        />
      )}
    </div>
  );
}

/* ── Marketplace helpers ── */

function MktFilterSection({ t, title, children }) {
  return (
    <div style={{ marginBottom:22 }}>
      <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:2.5, textTransform:"uppercase", marginBottom:10 }}>{title}</div>
      {children}
    </div>
  );
}

function MktRadioRow({ t, label, checked, onChange }) {
  return (
    <div onClick={onChange} style={{ display:"flex", alignItems:"center", gap:8, padding:"5px 0", cursor:"pointer" }}>
      <div style={{
        width:13, height:13, borderRadius:99,
        border:`1.5px solid ${checked ? t.accent : t.panelLine}`,
        background: checked ? t.accent : "transparent",
        display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0,
      }}>
        {checked && <div style={{ width:5, height:5, borderRadius:99, background:t.accentText }}/>}
      </div>
      <span style={{ fontFamily:DISPLAY_B, fontSize:11, color: checked ? t.text : t.textDim }}>{label}</span>
    </div>
  );
}

function MktProductCard({ t, product, onAdd, saved, onSave, onClick }) {
  const patterns = [
    `repeating-linear-gradient(45deg,rgba(57,255,106,.07) 0px,rgba(57,255,106,.07) 1px,transparent 1px,transparent 12px)`,
    `repeating-linear-gradient(-45deg,rgba(57,255,106,.07) 0px,rgba(57,255,106,.07) 1px,transparent 1px,transparent 10px)`,
    `radial-gradient(circle,rgba(57,255,106,.13) 1px,transparent 1px) 0 0/14px 14px`,
    `repeating-linear-gradient(0deg,rgba(57,255,106,.06) 0px,rgba(57,255,106,.06) 1px,transparent 1px,transparent 16px)`,
    `repeating-linear-gradient(90deg,rgba(57,255,106,.06) 0px,rgba(57,255,106,.06) 1px,transparent 1px,transparent 16px)`,
    `repeating-linear-gradient(30deg,rgba(57,255,106,.07) 0px,rgba(57,255,106,.07) 1px,transparent 1px,transparent 12px)`,
    `repeating-linear-gradient(135deg,rgba(57,255,106,.07) 0px,rgba(57,255,106,.07) 1px,transparent 1px,transparent 10px)`,
    `radial-gradient(circle,rgba(57,255,106,.16) 1px,transparent 1px) 0 0/10px 10px`,
    `repeating-linear-gradient(-30deg,rgba(57,255,106,.07) 0px,rgba(57,255,106,.07) 1px,transparent 1px,transparent 14px)`,
  ];
  const pat = patterns[(product.id - 1) % patterns.length];
  return (
    <div onClick={onClick} style={{ background:t.panel, border:`1px solid ${t.panelLine}`, borderRadius:4, overflow:"hidden", display:"flex", flexDirection:"column", cursor: onClick ? "pointer" : "default" }}>
      {/* Thumbnail 16:9 */}
      <div style={{
        position:"relative", paddingTop:"56.25%",
        backgroundImage:`${pat},linear-gradient(135deg,#151515 0%,#0a0a0a 100%)`,
      }}>
        {product.popular && (
          <span style={{
            position:"absolute", top:10, left:10,
            background:t.accent, color:t.accentText,
            fontFamily:DISPLAY_B, fontSize:9, fontWeight:800, letterSpacing:2, textTransform:"uppercase",
            padding:"3px 8px", borderRadius:2,
          }}>POPULAR</span>
        )}
      </div>

      {/* Info */}
      <div style={{ padding:"14px 14px 10px", flex:1, display:"flex", flexDirection:"column", gap:6 }}>
        <div style={{ fontWeight:700, fontSize:13, color:t.text, lineHeight:1.3 }}>{product.title}</div>
        <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim }}>{product.vendor}</div>
        <div style={{ display:"flex", alignItems:"center", gap:5 }}>
          {"★★★★★".split("").map((_, i) => (
            <span key={i} style={{ color: i < product.rating ? t.accent : t.panelLine, fontSize:13 }}>★</span>
          ))}
          <span style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, marginLeft:2 }}>({product.reviews})</span>
        </div>
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
          <span style={{ fontFamily:DISPLAY_B, fontSize:15, fontWeight:800, color:t.accent }}>${product.price}</span>
          <span style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim }}>{product.sold.toLocaleString()} sold</span>
        </div>
      </div>

      {/* Buttons */}
      <div style={{ display:"flex", gap:8, padding:"0 14px 14px" }}>
        <button onClick={onAdd} style={{
          flex:1, background:t.accent, color:t.accentText, border:"none", borderRadius:4,
          padding:"9px 0", fontFamily:DISPLAY_B, fontSize:9, fontWeight:800, letterSpacing:1.5,
          textTransform:"uppercase", cursor:"pointer",
        }}>ADD TO CART</button>
        <button onClick={onSave} style={{
          background:"transparent", color: saved ? t.accent : t.textDim,
          border:`1px solid ${saved ? t.accent : t.panelLine}`, borderRadius:4,
          padding:"9px 12px", fontFamily:DISPLAY_B, fontSize:11, cursor:"pointer",
        }}>{saved ? "♥ SAVED" : "♡ SAVE"}</button>
      </div>
    </div>
  );
}

function MktCartDrawer({ t, cart, cartCount, subtotal, onClose, onRemove, onChangeQty, onCheckout }) {
  return (<>
    <div onClick={onClose} style={{ position:"fixed", inset:0, background:"rgba(0,0,0,.45)", zIndex:40 }}/>
    <div style={{
      position:"fixed", top:0, right:0, bottom:0, width:280,
      background:t.panel, borderLeft:`1px solid ${t.panelLine}`,
      zIndex:50, display:"flex", flexDirection:"column",
      animation:"vldrawer .2s ease",
    }}>
      {/* Header */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"18px 20px", borderBottom:`1px solid ${t.panelLine}` }}>
        <div style={{ display:"flex", alignItems:"center", gap:8 }}>
          <span style={{ fontFamily:DISPLAY_B, fontSize:11, color:t.accent, letterSpacing:2.5, textTransform:"uppercase" }}>// CART</span>
          {cartCount > 0 && (
            <span style={{ background:t.accent, color:t.accentText, borderRadius:99, fontSize:9, fontWeight:900, fontFamily:DISPLAY_B, minWidth:16, height:16, display:"flex", alignItems:"center", justifyContent:"center", padding:"0 4px" }}>{cartCount}</span>
          )}
        </div>
        <button onClick={onClose} style={{ background:"transparent", border:`1px solid ${t.panelLine}`, borderRadius:4, color:t.textDim, cursor:"pointer", width:26, height:26, fontFamily:DISPLAY_B, fontSize:14 }}>×</button>
      </div>

      {/* Items */}
      <div style={{ flex:1, overflowY:"auto", padding:"8px 0" }}>
        {cart.length === 0 ? (
          <div style={{ padding:"40px 20px", textAlign:"center", fontFamily:DISPLAY_B, fontSize:11, color:t.textDim, letterSpacing:1.5, textTransform:"uppercase" }}>
            Your cart is empty
          </div>
        ) : cart.map(item => (
          <div key={item.id} style={{ padding:"12px 20px", borderBottom:`1px solid ${t.panelLine}` }}>
            <div style={{ display:"flex", justifyContent:"space-between", gap:8, marginBottom:8 }}>
              <div>
                <div style={{ fontSize:12, fontWeight:600, color:t.text, lineHeight:1.3 }}>{item.title}</div>
                <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, marginTop:2 }}>{item.vendor}</div>
              </div>
              <button onClick={()=>onRemove(item.id)} style={{ background:"transparent", border:"none", color:t.textDim, cursor:"pointer", fontFamily:DISPLAY_B, fontSize:16, flexShrink:0, padding:"0 2px", lineHeight:1 }}>×</button>
            </div>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
              <div style={{ display:"flex", alignItems:"center", border:`1px solid ${t.panelLine}`, borderRadius:4, overflow:"hidden" }}>
                <button onClick={()=>onChangeQty(item.id,-1)} style={{ background:"transparent", border:"none", color:t.text, cursor:"pointer", width:26, height:26, fontFamily:DISPLAY_B, fontSize:15, display:"flex", alignItems:"center", justifyContent:"center" }}>−</button>
                <span style={{ fontFamily:DISPLAY_B, fontSize:11, color:t.text, padding:"0 8px", minWidth:20, textAlign:"center" }}>{item.qty}</span>
                <button onClick={()=>onChangeQty(item.id,1)} style={{ background:"transparent", border:"none", color:t.text, cursor:"pointer", width:26, height:26, fontFamily:DISPLAY_B, fontSize:15, display:"flex", alignItems:"center", justifyContent:"center" }}>+</button>
              </div>
              <span style={{ fontFamily:DISPLAY_B, fontSize:12, fontWeight:700, color:t.accent }}>${(item.price*item.qty).toFixed(2)}</span>
            </div>
          </div>
        ))}
      </div>

      {/* Footer */}
      <div style={{ padding:"16px 20px", borderTop:`1px solid ${t.panelLine}` }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:14, fontFamily:DISPLAY_B, fontSize:12 }}>
          <span style={{ color:t.textDim, letterSpacing:1, textTransform:"uppercase" }}>Subtotal</span>
          <span style={{ color:t.text, fontWeight:700 }}>${subtotal.toFixed(2)}</span>
        </div>
        <button onClick={onCheckout} disabled={cart.length===0} style={{
          width:"100%", background: cart.length>0 ? t.accent : t.panelLine,
          color: cart.length>0 ? t.accentText : t.textDim,
          border:"none", borderRadius:4, padding:"12px 0",
          fontFamily:DISPLAY_B, fontSize:11, fontWeight:800, letterSpacing:2, textTransform:"uppercase",
          cursor: cart.length>0 ? "pointer" : "default",
        }}>CHECKOUT →</button>
      </div>
    </div>
  </>);
}

function MktCheckoutState({ t, cart, subtotal, subState, setSubState, setCart }) {
  const [coupon, setCoupon]           = React.useState("");
  const [couponApplied, setCouponApplied] = React.useState(false);
  const [couponError, setCouponError]     = React.useState("");
  const [orderNum, setOrderNum]       = React.useState("");
  const [cardName, setCardName] = React.useState("");
  const [cardNum,  setCardNum]  = React.useState("");
  const [expiry,   setExpiry]   = React.useState("");
  const [cvv,      setCvv]      = React.useState("");
  const [street,   setStreet]   = React.useState("");
  const [city,     setCity]     = React.useState("");
  const [zip,      setZip]      = React.useState("");
  const [country,  setCountry]  = React.useState("");

  const discount = couponApplied ? subtotal * 0.2 : 0;
  const total    = subtotal - discount;

  const applyCoupon = () => {
    if (coupon.trim().toUpperCase() === "BETA2026") { setCouponApplied(true); setCouponError(""); }
    else { setCouponApplied(false); setCouponError("Invalid coupon code."); }
  };

  const handlePay = async () => {
    setSubState("processing");
    const total = cart.reduce((s, i) => s + i.price * i.qty, 0);
    const discount = couponApplied ? total * 0.1 : 0;
    const finalTotal = total - discount;
    try {
      if (user) {
        // 1. Insert order
        const { data: orderData, error: orderErr } = await db.from('marketplace_orders').insert({
          user_id: user.id,
          total: finalTotal,
          status: 'pending',
          created_at: new Date().toISOString(),
        }).select().single();
        if (orderErr) throw orderErr;
        // 2. Insert payment record
        await db.from('marketplace_orders_payments').insert({
          order_id: orderData.id,
          amount: finalTotal,
          method: 'card',
          status: 'paid',
          created_at: new Date().toISOString(),
        });
        // 3. Delete cart items from DB
        await db.from('marketplace_cart_item').delete().eq('user_id', user.id);
        setOrderNum('VLS-' + orderData.id.toString().slice(-6).toUpperCase());
      } else {
        await new Promise(r => setTimeout(r, 2200));
        setOrderNum('VLS-' + Date.now().toString(36).toUpperCase());
      }
      setCart([]);
      setSubState("success");
    } catch (err) {
      console.error('Checkout error:', err);
      // Fallback: still show success with generated order number
      setOrderNum('VLS-' + Date.now().toString(36).toUpperCase());
      setCart([]);
      setSubState("success");
    }
  };

  const fmtCard = v => v.replace(/\D/g,"").slice(0,16).replace(/(.{4})/g,"$1 ").trim();
  const fmtExp  = v => { const d=v.replace(/\D/g,"").slice(0,4); return d.length>2?d.slice(0,2)+"/"+d.slice(2):d; };

  const inp = { background:t.bg, border:`1px solid ${t.panelLine}`, borderRadius:4, color:t.text, fontFamily:DISPLAY_B, fontSize:11, padding:"9px 12px", outline:"none", width:"100%", boxSizing:"border-box" };
  const lbl = { fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, letterSpacing:1.5, textTransform:"uppercase", marginBottom:5, display:"block" };

  /* PROCESSING */
  if (subState === "processing") return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", minHeight:"calc(100vh - 113px)", gap:24 }}>
      <svg width="56" height="56" viewBox="0 0 56 56" style={{ animation:"vlspin 1s linear infinite" }}>
        <circle cx="28" cy="28" r="24" fill="none" stroke={t.panelLine} strokeWidth="3"/>
        <path d="M28 4 A24 24 0 0 1 52 28" fill="none" stroke={t.accent} strokeWidth="3" strokeLinecap="round"/>
      </svg>
      <div style={{ fontFamily:DISPLAY_B, fontSize:12, color:t.textDim, letterSpacing:3, textTransform:"uppercase" }}>Processing payment…</div>
    </div>
  );

  /* SUCCESS */
  if (subState === "success") return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", minHeight:"calc(100vh - 113px)", gap:16, animation:"vlcheck .4s ease" }}>
      <svg width="64" height="64" viewBox="0 0 64 64">
        <circle cx="32" cy="32" r="30" fill="none" stroke={t.accent} strokeWidth="2"/>
        <path d="M18 32l10 10 18-20" fill="none" stroke={t.accent} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      <div style={{ fontFamily:DISPLAY_B, fontSize:22, fontWeight:900, color:t.accent, letterSpacing:3, textTransform:"uppercase", textAlign:"center" }}>
        // PAYMENT SUCCESSFUL
      </div>
      <div style={{ fontFamily:DISPLAY_B, fontSize:11, color:t.textDim, letterSpacing:2, textTransform:"uppercase" }}>Order {orderNum}</div>
      <button onClick={()=>setSubState("grid")} style={{
        marginTop:16, background:"transparent", color:t.accent, border:`1px solid ${t.accent}`,
        borderRadius:4, padding:"12px 28px", fontFamily:DISPLAY_B, fontSize:11, fontWeight:700,
        letterSpacing:2, textTransform:"uppercase", cursor:"pointer",
      }}>CONTINUE SHOPPING</button>
    </div>
  );

  /* CHECKOUT FORM */
  return (
    <div style={{ padding:"28px 32px" }}>
      {/* Header */}
      <div style={{ display:"flex", alignItems:"center", gap:16, marginBottom:28 }}>
        <button onClick={()=>setSubState("grid")} style={{
          background:"transparent", border:`1px solid ${t.panelLine}`, borderRadius:4,
          color:t.textDim, cursor:"pointer", fontFamily:DISPLAY_B, fontSize:10,
          letterSpacing:1.5, textTransform:"uppercase", padding:"6px 12px",
        }}>← Back</button>
        <span style={{ fontFamily:DISPLAY_B, fontSize:12, color:t.accent, letterSpacing:3, textTransform:"uppercase" }}>// CHECKOUT</span>
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"1fr 1.1fr", gap:40 }}>
        {/* LEFT: Order summary */}
        <div>
          <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, letterSpacing:2.5, textTransform:"uppercase", marginBottom:16 }}>ORDER SUMMARY</div>
          <div style={{ border:`1px solid ${t.panelLine}`, borderRadius:4, overflow:"hidden", marginBottom:16 }}>
            {cart.map((item,i) => (
              <div key={item.id} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"12px 16px", borderBottom: i<cart.length-1?`1px solid ${t.panelLine}`:"none" }}>
                <div>
                  <div style={{ fontSize:12, fontWeight:600, color:t.text }}>{item.title}</div>
                  <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, marginTop:2 }}>qty {item.qty}</div>
                </div>
                <span style={{ fontFamily:DISPLAY_B, fontSize:12, fontWeight:700, color:t.text }}>${(item.price*item.qty).toFixed(2)}</span>
              </div>
            ))}
          </div>

          <div style={{ display:"flex", justifyContent:"space-between", fontFamily:DISPLAY_B, fontSize:11, color:t.textDim, marginBottom:10 }}>
            <span style={{ textTransform:"uppercase", letterSpacing:1 }}>SUBTOTAL</span>
            <span style={{ color:t.text }}>${subtotal.toFixed(2)}</span>
          </div>

          {/* Coupon */}
          <div style={{ display:"flex", gap:8, marginBottom:8 }}>
            <input className="mkt-input" type="text" placeholder="Coupon code" value={coupon} onChange={e=>setCoupon(e.target.value)}
              style={{ ...inp, flex:1 }}/>
            <button onClick={applyCoupon} style={{
              background:"transparent", border:`1px solid ${t.panelLine}`, borderRadius:4,
              color:t.text, cursor:"pointer", fontFamily:DISPLAY_B, fontSize:10, fontWeight:700,
              letterSpacing:1.5, textTransform:"uppercase", padding:"0 14px", flexShrink:0,
            }}>APPLY</button>
          </div>
          {couponApplied && <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.accent, letterSpacing:1, marginBottom:6 }}>✓ 20% discount applied (BETA2026)</div>}
          {couponError  && <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:"#FF4F4F",  letterSpacing:1, marginBottom:6 }}>{couponError}</div>}
          {couponApplied && (
            <div style={{ display:"flex", justifyContent:"space-between", fontFamily:DISPLAY_B, fontSize:11, color:t.textDim, marginBottom:8 }}>
              <span style={{ textTransform:"uppercase", letterSpacing:1 }}>DISCOUNT (20%)</span>
              <span style={{ color:t.accent }}>−${discount.toFixed(2)}</span>
            </div>
          )}

          <div style={{ display:"flex", justifyContent:"space-between", fontFamily:DISPLAY_B, fontSize:14, fontWeight:800, padding:"14px 0", borderTop:`1px solid ${t.panelLine}`, marginTop:6 }}>
            <span style={{ color:t.textDim, textTransform:"uppercase", letterSpacing:2 }}>TOTAL</span>
            <span style={{ color:t.accent }}>${total.toFixed(2)}</span>
          </div>
        </div>

        {/* RIGHT: Payment form */}
        <div>
          <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, letterSpacing:2.5, textTransform:"uppercase", marginBottom:16 }}>PAYMENT</div>
          <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
            <div>
              <label style={lbl}>Cardholder Name</label>
              <input className="mkt-input" type="text" placeholder="Jane Doe" value={cardName} onChange={e=>setCardName(e.target.value)} style={inp}/>
            </div>
            <div>
              <label style={lbl}>Card Number</label>
              <input className="mkt-input" type="text" placeholder="•••• •••• •••• ••••" value={cardNum} onChange={e=>setCardNum(fmtCard(e.target.value))} maxLength={19} style={inp}/>
            </div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
              <div>
                <label style={lbl}>Expiry</label>
                <input className="mkt-input" type="text" placeholder="MM/YY" value={expiry} onChange={e=>setExpiry(fmtExp(e.target.value))} maxLength={5} style={inp}/>
              </div>
              <div>
                <label style={lbl}>CVV</label>
                <input className="mkt-input" type="password" placeholder="•••" value={cvv} onChange={e=>setCvv(e.target.value.replace(/\D/g,"").slice(0,4))} style={inp}/>
              </div>
            </div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.textDim, letterSpacing:2.5, textTransform:"uppercase", marginTop:4, borderTop:`1px solid ${t.panelLine}`, paddingTop:14 }}>
              BILLING ADDRESS
            </div>
            <div>
              <label style={lbl}>Street</label>
              <input className="mkt-input" type="text" placeholder="123 Main St" value={street} onChange={e=>setStreet(e.target.value)} style={inp}/>
            </div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
              <div>
                <label style={lbl}>City</label>
                <input className="mkt-input" type="text" placeholder="New York" value={city} onChange={e=>setCity(e.target.value)} style={inp}/>
              </div>
              <div>
                <label style={lbl}>Zip</label>
                <input className="mkt-input" type="text" placeholder="10001" value={zip} onChange={e=>setZip(e.target.value)} style={inp}/>
              </div>
            </div>
            <div>
              <label style={lbl}>Country</label>
              <input className="mkt-input" type="text" placeholder="United States" value={country} onChange={e=>setCountry(e.target.value)} style={inp}/>
            </div>
            <button onClick={handlePay} style={{
              width:"100%", background:t.accent, color:t.accentText, border:"none", borderRadius:4,
              padding:"14px 0", fontFamily:DISPLAY_B, fontSize:12, fontWeight:900,
              letterSpacing:2, textTransform:"uppercase", cursor:"pointer", marginTop:4,
            }}>PAY NOW →</button>
          </div>
        </div>
      </div>
    </div>
  );
}
// ---- Jobs Screen ----
const JOBS_INITIAL = [
  {
    id: 1, title: "Senior Video Editor", employer: "NovaCraft Studios",
    budget: 3500, status: "OPEN",
    skills: ["Premiere Pro", "After Effects", "Color Grading"],
    posted: "2026-05-28", deadline: "2026-06-20",
    description: "We need an experienced video editor to cut a 30-minute documentary series. You will work closely with our director, manage multi-cam timelines, and deliver broadcast-ready exports. Strong storytelling instincts required.",
  },
  {
    id: 2, title: "Motion Graphics Designer", employer: "Pixel Pulse Co.",
    budget: 2200, status: "OPEN",
    skills: ["After Effects", "Cinema 4D", "Illustrator"],
    posted: "2026-05-30", deadline: "2026-06-25",
    description: "Create dynamic motion graphics packages for our YouTube channel — lower thirds, intros, animated infographics. Deliverables include source files and rendered exports at 4K.",
  },
  {
    id: 3, title: "Podcast Audio Engineer", employer: "Resonance Media",
    budget: 800, status: "IN PROGRESS",
    skills: ["Audition", "Pro Tools", "Noise Reduction"],
    posted: "2026-05-20", deadline: "2026-06-10",
    description: "Mix and master 12 podcast episodes (45 min each). Noise removal, EQ, compression, loudness normalisation to -16 LUFS. Turnaround of 2 episodes per day expected.",
  },
  {
    id: 4, title: "Social Media Video Pack", employer: "BrandForge Agency",
    budget: 1400, status: "OPEN",
    skills: ["Premiere Pro", "Photoshop", "Reels"],
    posted: "2026-06-01", deadline: "2026-06-30",
    description: "Produce 20 short-form videos (15–60s) optimised for Instagram Reels and TikTok. Provided footage plus branded assets; you handle cuts, captions, and music sync.",
  },
  {
    id: 5, title: "Color Grading — Feature Film", employer: "Sundance Post",
    budget: 7500, status: "OPEN",
    skills: ["DaVinci Resolve", "LUT Design", "HDR"],
    posted: "2026-05-25", deadline: "2026-07-15",
    description: "Grade a 90-minute independent feature film in DaVinci Resolve. Deliverables: theatrical DCP, streaming SDR, and HDR10 masters. Node-based workflow with shared project file handoff.",
  },
  {
    id: 6, title: "Corporate Training Videos", employer: "GlobalEdge HR",
    budget: 2800, status: "COMPLETED",
    skills: ["Camtasia", "Premiere Pro", "Scripting"],
    posted: "2026-04-10", deadline: "2026-05-10",
    description: "Edited and delivered 8 corporate e-learning modules. Screen recordings, talking-head interviews, and animated slides combined into polished 10-minute episodes.",
  },
  {
    id: 7, title: "Event Highlight Reel", employer: "Eventide Productions",
    budget: 950, status: "IN PROGRESS",
    skills: ["Final Cut Pro", "Music Sync", "Colour"],
    posted: "2026-05-31", deadline: "2026-06-08",
    description: "Condense 6 hours of conference footage into a 3-minute sizzle reel. Fast-paced, music-driven edit. Deliver in 1080p H.264 and a 9:16 version for social.",
  },
  {
    id: 8, title: "YouTube Series — Tech Reviews", employer: "Gadget Lab",
    budget: 1200, status: "OPEN",
    skills: ["Premiere Pro", "Thumbnail Design", "B-Roll"],
    posted: "2026-06-02", deadline: "2026-07-01",
    description: "Weekly tech review editor needed for ongoing contract. Each video is 8–12 minutes, reviewer footage provided. Must turn around within 48 hrs of receiving raw files.",
  },
];

const MOCK_APPLICATIONS = [
  { id: 1, jobTitle: "Senior Video Editor",        employer: "NovaCraft Studios",  appliedDate: "2026-05-29", step: 2 },
  { id: 2, jobTitle: "Motion Graphics Designer",   employer: "Pixel Pulse Co.",    appliedDate: "2026-06-01", step: 1 },
  { id: 3, jobTitle: "Color Grading — Feature Film", employer: "Sundance Post",    appliedDate: "2026-05-26", step: 3 },
  { id: 4, jobTitle: "YouTube Series — Tech Reviews", employer: "Gadget Lab",     appliedDate: "2026-06-03", step: 0 },
];

const SAVED_SEARCHES = [
  { id: 1, name: "Video Editor > $1k", freq: "DAILY" },
  { id: 2, name: "Motion Graphics Remote", freq: "WEEKLY" },
  { id: 3, name: "Color Grading Projects", freq: "DAILY" },
];

function JobsScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile } = useAuth();
  const [searchQ, setSearchQ] = React.useState("");
  const [minBudget, setMinBudget] = React.useState("");
  const [statusFilter, setStatusFilter] = React.useState("All");
  const [savedSearches, setSavedSearches] = React.useState(SAVED_SEARCHES);
  const [jobs, setJobs] = React.useState(JOBS_INITIAL);
  const [jobsLoading, setJobsLoading] = React.useState(false);
  const [jobsError, setJobsError] = React.useState(null);
  const [appliedJobs, setAppliedJobs] = React.useState({}); // id -> true
  const [myApplications, setMyApplications] = React.useState(MOCK_APPLICATIONS);
  const [appsLoading, setAppsLoading] = React.useState(false);
  const [mainTab, setMainTab] = React.useState("board"); // "board" | "applications"
  const [detailJob, setDetailJob] = React.useState(null); // job object or null
  const [postModalOpen, setPostModalOpen] = React.useState(false);
  const [applyModalJob, setApplyModalJob] = React.useState(null); // job to apply to
  const [jobToast, setJobToast] = React.useState(null); // "Job posted!" toast
  const searchTimer = React.useRef(null);

  // Load jobs from DB on mount and when filters change
  const loadJobs = React.useCallback(async () => {
    setJobsLoading(true);
    setJobsError(null);
    try {
      let q = db.from('job').select('*').order('created_at', { ascending: false });
      if (statusFilter !== "All") q = q.eq('status', statusFilter);
      if (minBudget !== "") q = q.gte('budget', +minBudget);
      if (searchQ.trim()) q = q.or(`title.ilike.%${searchQ.trim()}%,employer.ilike.%${searchQ.trim()}%`);
      const { data, error } = await q.limit(50);
      if (error) throw error;
      if (data && data.length > 0) setJobs(data);
    } catch (err) {
      setJobsError(err.message);
      // Keep JOBS_INITIAL as fallback
    } finally {
      setJobsLoading(false);
    }
  }, [statusFilter, minBudget, searchQ]);

  React.useEffect(() => {
    loadJobs();
  }, [statusFilter, minBudget]);

  React.useEffect(() => {
    clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(() => { loadJobs(); }, 400);
    return () => clearTimeout(searchTimer.current);
  }, [searchQ]);

  // Load applications and saved searches on mount
  React.useEffect(() => {
    if (!user) return;
    setAppsLoading(true);
    db.from('jobapplication').select('*, job(title, employer)').eq('applicant_id', user.id).order('created_at', { ascending: false })
      .then(({ data }) => {
        if (data && data.length > 0) {
          const map = {};
          setMyApplications(data.map((a, i) => {
            map[a.job_id] = true;
            return { id: a.id, jobTitle: a.job?.title || '', employer: a.job?.employer || '', appliedDate: a.created_at?.slice(0,10) || '', step: a.stage || 0 };
          }));
          setAppliedJobs(map);
        }
        setAppsLoading(false);
      });
    db.from('savedjobsearch').select('*').eq('user_id', user.id).order('created_at', { ascending: false })
      .then(({ data }) => { if (data && data.length > 0) setSavedSearches(data); });
  }, [user?.id]);

  const filtered = jobs.filter(j => {
    if (statusFilter !== "All" && j.status !== statusFilter) return false;
    if (minBudget !== "" && j.budget < +minBudget) return false;
    if (searchQ && !j.title?.toLowerCase().includes(searchQ.toLowerCase()) && !j.employer?.toLowerCase().includes(searchQ.toLowerCase())) return false;
    return true;
  });

  const addJob = (job) => setJobs(prev => [job, ...prev]);
  const markApplied = (id) => setAppliedJobs(prev => ({ ...prev, [id]: true }));
  const removeSaved = async (id) => {
    setSavedSearches(prev => prev.filter(s => s.id !== id));
    if (user) await db.from('savedjobsearch').delete().eq('id', id).eq('user_id', user.id);
  };
  const saveCurrentSearch = async () => {
    if (!user || !searchQ.trim()) return;
    const name = searchQ.trim();
    const { data } = await db.from('savedjobsearch').insert({ user_id: user.id, name, freq: 'DAILY', created_at: new Date().toISOString() }).select().single();
    if (data) setSavedSearches(prev => [data, ...prev]);
  };
  const withdrawApplication = async (appId) => {
    const { error } = await db.from('jobapplication').delete().eq('id', appId).eq('applicant_id', user.id);
    if (!error) setMyApplications(prev => prev.filter(a => a.id !== appId));
  };

  const inputStyle = {
    width: "100%", background: t.bg, border: `1px solid ${t.panelLine}`, borderRadius: 4,
    color: t.text, fontFamily: DISPLAY_B, fontSize: 11, padding: "8px 10px", outline: "none",
    boxSizing: "border-box",
  };

  return (
    <div style={{ display: "flex", minHeight: "calc(100vh - 65px)", background: t.bg }}>
      <style>{`
        .jobs-input::placeholder { color: rgba(138,138,133,.55); }
        input[type=number]::-webkit-outer-spin-button,input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}
        input[type=number]{-moz-appearance:textfield}
      `}</style>

      {/* LEFT SIDEBAR */}
      <aside style={{
        width: 280, flexShrink: 0, borderRight: `1px solid ${t.panelLine}`,
        background: t.panel, overflowY: "auto",
        position: "sticky", top: 65, height: "calc(100vh - 65px)",
      }}>
        <div style={{ padding: "20px 18px", display: "flex", flexDirection: "column", gap: 20 }}>

          {/* Post a job button */}
          <button onClick={() => setPostModalOpen(true)} style={{
            width: "100%", background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "11px 0", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 800,
            letterSpacing: 2, textTransform: "uppercase", cursor: "pointer",
          }}>＋ POST A JOB</button>

          {/* Search */}
          <div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 8 }}>SEARCH</div>
            <input
              className="jobs-input" type="text" placeholder="SEARCH JOBS…"
              value={searchQ} onChange={e => setSearchQ(e.target.value)}
              style={inputStyle}
            />
            {searchQ.trim() && (
              <button onClick={saveCurrentSearch} style={{ marginTop: 6, width: "100%", background: "transparent", border: `1px solid ${t.accent}`, color: t.accent, borderRadius: 4, padding: "7px 0", fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 700, letterSpacing: 2, textTransform: "uppercase", cursor: "pointer" }}>SAVE SEARCH</button>
            )}
          </div>

          {/* Min budget */}
          <div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 8 }}>MIN. BUDGET ($)</div>
            <input
              className="jobs-input" type="number" placeholder="0"
              value={minBudget} onChange={e => setMinBudget(e.target.value)}
              style={inputStyle}
            />
          </div>

          {/* Status filter */}
          <div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 10 }}>STATUS</div>
            {["All", "OPEN", "IN PROGRESS", "COMPLETED"].map(s => (
              <JobsRadioRow key={s} t={t} label={s} checked={statusFilter === s} onChange={() => setStatusFilter(s)} />
            ))}
          </div>

          {/* Saved searches */}
          <div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.accent, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 12 }}>// SAVED SEARCHES</div>
            {savedSearches.length === 0 && (
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1 }}>No saved searches.</div>
            )}
            {savedSearches.map(s => (
              <div key={s.id} style={{
                display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "8px 0", borderBottom: `1px solid ${t.panelLine}`,
              }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.text, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name}</div>
                  <span style={{
                    fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase",
                    color: s.freq === "DAILY" ? t.accent : "#5BE3FF", marginTop: 2, display: "block",
                  }}>{s.freq}</span>
                </div>
                <button onClick={() => removeSaved(s.id)} style={{
                  background: "transparent", border: "none", color: t.textDim, cursor: "pointer",
                  fontFamily: DISPLAY_B, fontSize: 14, padding: "0 4px", lineHeight: 1,
                }}>×</button>
              </div>
            ))}
          </div>
        </div>
      </aside>

      {/* MAIN */}
      <div style={{ flex: 1, overflowY: "auto" }}>
        {/* Top bar with tabs */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "16px 24px", borderBottom: `1px solid ${t.panelLine}`,
          position: "sticky", top: 0, background: t.bg + "ee", backdropFilter: "blur(10px)", zIndex: 5,
        }}>
          <span style={{ fontFamily: DISPLAY_B, fontSize: 12, color: t.accent, letterSpacing: 3, textTransform: "uppercase" }}>
            {detailJob ? `// ${detailJob.title.toUpperCase()}` : mainTab === "board" ? "// JOB BOARD" : "// MY APPLICATIONS"}
          </span>
          {!detailJob && (
            <div style={{ display: "flex", gap: 6 }}>
              {["board", "applications"].map(tab => (
                <button key={tab} onClick={() => setMainTab(tab)} style={{
                  background: mainTab === tab ? t.accent : "transparent",
                  color: mainTab === tab ? t.accentText : t.textDim,
                  border: `1px solid ${mainTab === tab ? t.accent : t.panelLine}`,
                  borderRadius: 4, padding: "6px 14px", fontFamily: DISPLAY_B, fontSize: 10,
                  fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
                }}>
                  {tab === "board" ? "JOB BOARD" : "MY APPLICATIONS"}
                </button>
              ))}
            </div>
          )}
          {detailJob && (
            <button onClick={() => setDetailJob(null)} style={{
              background: "transparent", border: `1px solid ${t.panelLine}`, borderRadius: 4,
              color: t.textDim, fontFamily: DISPLAY_B, fontSize: 10, letterSpacing: 1.5,
              textTransform: "uppercase", cursor: "pointer", padding: "6px 14px",
            }}>← BACK TO BOARD</button>
          )}
        </div>

        {/* DETAIL VIEW */}
        {detailJob && (
          <JobDetailView
            t={t} job={detailJob}
            applied={!!appliedJobs[detailJob.id]}
            onApply={() => setApplyModalJob(detailJob)}
          />
        )}

        {/* JOB BOARD GRID */}
        {!detailJob && mainTab === "board" && (
          <div style={{ padding: 24 }}>
            <style>{`@keyframes vlskel{0%,100%{opacity:.4}50%{opacity:.8}}`}</style>
            {jobsError && (
              <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", background: "rgba(255,60,60,.06)", border: "1px solid rgba(255,60,60,.18)", borderRadius: 4, marginBottom: 20 }}>
                <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: "#FF4040", flex: 1 }}>{jobsError}</span>
                <button onClick={loadJobs} style={{ background: "transparent", border: "1px solid rgba(255,60,60,.3)", borderRadius: 4, color: "#FF6060", padding: "6px 14px", fontFamily: DISPLAY_B, fontSize: 10, cursor: "pointer", letterSpacing: 1.5, textTransform: "uppercase" }}>RETRY</button>
              </div>
            )}
            {jobsLoading ? (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                {[1,2,3,4].map(i => (
                  <div key={i} style={{ background: "rgba(255,255,255,.04)", border: "1px solid rgba(255,255,255,.06)", borderRadius: 4, padding: 20 }}>
                    <div style={{ height: 14, width: "60%", background: "rgba(255,255,255,.08)", borderRadius: 2, marginBottom: 10, animation: "vlskel 1.4s ease infinite" }}/>
                    <div style={{ height: 10, width: "40%", background: "rgba(255,255,255,.06)", borderRadius: 2, marginBottom: 16, animation: "vlskel 1.4s ease infinite" }}/>
                    <div style={{ display: "flex", gap: 6 }}>
                      {[1,2,3].map(j => <div key={j} style={{ height: 22, width: 60, background: "rgba(255,255,255,.05)", borderRadius: 2, animation: "vlskel 1.4s ease infinite" }}/>)}
                    </div>
                  </div>
                ))}
              </div>
            ) : filtered.length === 0 ? (
              <div style={{ textAlign: "center", padding: "80px 0", fontFamily: DISPLAY_B, color: t.textDim, fontSize: 12, letterSpacing: 3, textTransform: "uppercase" }}>
                No jobs match your filters.
              </div>
            ) : (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                {filtered.map(j => (
                  <JobCard
                    key={j.id} t={t} job={j}
                    applied={!!appliedJobs[j.id]}
                    onViewDetails={() => setDetailJob(j)}
                    onApply={() => setApplyModalJob(j)}
                  />
                ))}
              </div>
            )}
          </div>
        )}

        {/* MY APPLICATIONS */}
        {!detailJob && mainTab === "applications" && (
          <MyApplicationsPanel t={t} applications={myApplications} loading={appsLoading} onWithdraw={withdrawApplication} />
        )}
      </div>

      {/* JOB POSTED TOAST */}
      {jobToast && (
        <div style={{ position: "fixed", bottom: 32, left: "50%", transform: "translateX(-50%)", background: t.accent, color: t.accentText, padding: "12px 28px", borderRadius: 4, fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700, letterSpacing: 2, textTransform: "uppercase", zIndex: 900, boxShadow: "0 4px 20px rgba(0,0,0,.4)" }}>
          {jobToast}
        </div>
      )}

      {/* POST A JOB MODAL */}
      <PostJobModal
        open={postModalOpen}
        onClose={() => setPostModalOpen(false)}
        t={t}
        onPost={async (job) => {
          let savedJob = job;
          if (user) {
            const { data, error } = await db.from('job').insert({
              title: job.title, employer: job.employer || profile?.username || '', budget: job.budget,
              status: 'OPEN', description: job.description || '', skills: job.skills || [],
              deadline: job.deadline || null, user_id: user.id,
              created_at: new Date().toISOString(),
            }).select().single();
            if (!error && data) savedJob = data;
          }
          addJob(savedJob);
          setPostModalOpen(false);
          setJobToast('Job posted!');
          setTimeout(() => setJobToast(null), 3000);
        }}
      />

      {/* APPLY MODAL */}
      <ApplyModal
        open={!!applyModalJob}
        onClose={() => setApplyModalJob(null)}
        t={t}
        job={applyModalJob}
        onSubmit={async ({ coverLetter, rate } = {}) => {
          if (!applyModalJob) return;
          if (user) {
            await db.from('jobapplication').insert({
              job_id: applyModalJob.id,
              applicant_id: user.id,
              cover_letter: coverLetter || '',
              proposed_rate: rate || null,
              stage: 0,
              created_at: new Date().toISOString(),
            });
          }
          markApplied(applyModalJob.id);
          const newApp = { id: Date.now(), jobTitle: applyModalJob.title, employer: applyModalJob.employer, appliedDate: new Date().toISOString().slice(0,10), step: 0 };
          setMyApplications(prev => [newApp, ...prev]);
          setApplyModalJob(null);
        }}
      />
    </div>
  );
}

function JobsRadioRow({ t, label, checked, onChange }) {
  return (
    <div onClick={onChange} style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 0", cursor: "pointer" }}>
      <div style={{
        width: 13, height: 13, borderRadius: 99,
        border: `1.5px solid ${checked ? t.accent : t.panelLine}`,
        background: checked ? t.accent : "transparent",
        display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
      }}>
        {checked && <div style={{ width: 5, height: 5, borderRadius: 99, background: t.accentText }} />}
      </div>
      <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: checked ? t.text : t.textDim }}>{label}</span>
    </div>
  );
}

function JobStatusBadge({ t, status }) {
  const cfg = {
    "OPEN":        { bg: t.accent + "22", color: t.accent,   label: "OPEN" },
    "IN PROGRESS": { bg: "#5BE3FF22",     color: "#5BE3FF",  label: "IN PROGRESS" },
    "COMPLETED":   { bg: t.panelLine,     color: t.textDim,  label: "COMPLETED" },
  };
  const c = cfg[status] || cfg["OPEN"];
  return (
    <span style={{
      fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase",
      background: c.bg, color: c.color, border: `1px solid ${c.color}44`,
      borderRadius: 3, padding: "2px 7px",
    }}>{c.label}</span>
  );
}

function SkillChip({ t, label, onRemove }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim,
      border: `1px solid ${t.panelLine}`, borderRadius: 3,
      padding: "2px 7px", whiteSpace: "nowrap",
    }}>
      {label}
      {onRemove && (
        <span onClick={onRemove} style={{ cursor: "pointer", color: t.textDim, fontSize: 11, lineHeight: 1 }}>×</span>
      )}
    </span>
  );
}

function JobCard({ t, job, applied, onViewDetails, onApply }) {
  const descExcerpt = job.description.length > 120 ? job.description.slice(0, 120) + "…" : job.description;
  return (
    <div style={{
      background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4,
      padding: 20, display: "flex", flexDirection: "column", gap: 12,
    }}>
      {/* Title + status */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 10 }}>
        <div style={{ fontWeight: 700, fontSize: 18, color: t.text, lineHeight: 1.2 }}>{job.title}</div>
        <JobStatusBadge t={t} status={job.status} />
      </div>

      {/* Budget */}
      <div style={{ fontFamily: DISPLAY_B, fontSize: 15, fontWeight: 800, color: t.accent }}>
        ${job.budget.toLocaleString()} <span style={{ color: t.textDim, fontWeight: 400, fontSize: 11 }}>/ project</span>
      </div>

      {/* Description excerpt */}
      <div style={{ fontSize: 13, color: t.textDim, lineHeight: 1.6, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>
        {descExcerpt}
      </div>

      {/* Skills */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {job.skills.map(s => <SkillChip key={s} t={t} label={s} />)}
      </div>

      {/* Dates */}
      <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 0.5 }}>
        POSTED {job.posted} · DEADLINE {job.deadline}
      </div>

      {/* Actions */}
      <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
        <button onClick={onViewDetails} style={{
          flex: 1, background: "transparent", color: t.text,
          border: `1px solid ${t.panelLine}`, borderRadius: 4,
          padding: "9px 0", fontFamily: DISPLAY_B, fontSize: 10,
          fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
        }}>VIEW DETAILS →</button>
        {applied ? (
          <button disabled style={{
            flex: 1, background: "transparent", color: t.textDim,
            border: `1px solid ${t.panelLine}`, borderRadius: 4,
            padding: "9px 0", fontFamily: DISPLAY_B, fontSize: 10,
            fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", cursor: "default",
          }}>APPLIED ✓</button>
        ) : (
          <button onClick={onApply} style={{
            flex: 1, background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "9px 0", fontFamily: DISPLAY_B, fontSize: 10,
            fontWeight: 800, letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
          }}>APPLY →</button>
        )}
      </div>
    </div>
  );
}

function JobDetailView({ t, job, applied, onApply }) {
  return (
    <div style={{ padding: "40px 48px", maxWidth: 860 }}>
      {/* Large title */}
      <h1 style={{
        fontFamily: DISPLAY_B, fontSize: 48, fontWeight: 900, textTransform: "uppercase",
        letterSpacing: -1, color: t.text, margin: "0 0 10px", lineHeight: 1,
      }}>{job.title}</h1>
      <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 2, marginBottom: 32 }}>
        {job.employer}
      </div>

      {/* Metadata row */}
      <div style={{
        display: "flex", flexWrap: "wrap", gap: 24, padding: "18px 0",
        borderTop: `1px solid ${t.panelLine}`, borderBottom: `1px solid ${t.panelLine}`, marginBottom: 32,
      }}>
        <div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 4 }}>BUDGET</div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 20, fontWeight: 800, color: t.accent }}>${job.budget.toLocaleString()}</div>
        </div>
        <div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 4 }}>DEADLINE</div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 14, color: t.text }}>{job.deadline}</div>
        </div>
        <div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 8 }}>STATUS</div>
          <JobStatusBadge t={t} status={job.status} />
        </div>
        <div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 8 }}>REQUIRED SKILLS</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {job.skills.map(s => <SkillChip key={s} t={t} label={s} />)}
          </div>
        </div>
      </div>

      {/* Full description */}
      <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 14 }}>DESCRIPTION</div>
      <p style={{ fontSize: 15, color: t.text, lineHeight: 1.8, margin: "0 0 40px" }}>{job.description}</p>

      {/* Actions */}
      <div style={{ display: "flex", gap: 12 }}>
        <button style={{
          background: "transparent", color: t.text, border: `1px solid ${t.panelLine}`,
          borderRadius: 4, padding: "12px 24px", fontFamily: DISPLAY_B, fontSize: 11,
          fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
        }}>MESSAGE EMPLOYER</button>
        {applied ? (
          <button disabled style={{
            background: "transparent", color: t.textDim, border: `1px solid ${t.panelLine}`,
            borderRadius: 4, padding: "12px 24px", fontFamily: DISPLAY_B, fontSize: 11,
            fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", cursor: "default",
          }}>APPLIED ✓</button>
        ) : (
          <button onClick={onApply} style={{
            background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "12px 28px", fontFamily: DISPLAY_B, fontSize: 11,
            fontWeight: 800, letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
          }}>APPLY NOW →</button>
        )}
      </div>
    </div>
  );
}

function SkillTagInput({ t, skills, setSkills }) {
  const [inputVal, setInputVal] = React.useState("");
  const addSkill = (val) => {
    const trimmed = val.trim().replace(/,$/, "").trim();
    if (trimmed && !skills.includes(trimmed)) setSkills(prev => [...prev, trimmed]);
    setInputVal("");
  };
  const handleKey = (e) => {
    if (e.key === "Enter") { e.preventDefault(); addSkill(inputVal); }
    if (e.key === ",") { e.preventDefault(); addSkill(inputVal); }
  };
  const handleChange = (e) => {
    const v = e.target.value;
    if (v.endsWith(",")) { addSkill(v); } else { setInputVal(v); }
  };
  return (
    <div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 8 }}>
        {skills.map(s => (
          <SkillChip key={s} t={t} label={s} onRemove={() => setSkills(prev => prev.filter(x => x !== s))} />
        ))}
      </div>
      <input
        className="jobs-input" type="text" placeholder="Type skill + Enter or comma…"
        value={inputVal} onChange={handleChange} onKeyDown={handleKey}
        style={{
          width: "100%", background: "#000", border: `1px solid ${t.panelLine}`, borderRadius: 4,
          color: t.text, fontFamily: DISPLAY_B, fontSize: 11, padding: "8px 10px", outline: "none",
          boxSizing: "border-box",
        }}
        onFocus={e => e.target.style.borderColor = t.accent}
        onBlur={e => e.target.style.borderColor = t.panelLine}
      />
    </div>
  );
}

function PostJobModal({ open, onClose, t, onPost }) {
  const [title, setTitle] = React.useState("");
  const [desc, setDesc] = React.useState("");
  const [budget, setBudget] = React.useState("");
  const [skills, setSkills] = React.useState([]);
  const [deadline, setDeadline] = React.useState("");

  React.useEffect(() => {
    if (!open) { setTitle(""); setDesc(""); setBudget(""); setSkills([]); setDeadline(""); }
  }, [open]);

  const handlePost = () => {
    if (!title.trim()) return;
    onPost({
      id: Date.now(), title: title.trim(), employer: "You",
      budget: +budget || 0, status: "OPEN",
      skills, posted: new Date().toISOString().slice(0, 10),
      deadline: deadline || "TBD",
      description: desc.trim() || "No description provided.",
    });
  };

  const inp = {
    width: "100%", background: "#000", color: t.text, border: `1px solid ${t.panelLine}`, borderRadius: 4,
    padding: "10px 12px", fontSize: 13, fontFamily: "inherit", outline: "none", boxSizing: "border-box",
  };
  const lbl = { fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 5, display: "block" };

  return (
    <Modal open={open} onClose={onClose} t={t} title="Post a Job" subtitle="// NEW LISTING">
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div>
          <label style={lbl}>Job Title</label>
          <input className="jobs-input" type="text" placeholder="e.g. Senior Video Editor" value={title} onChange={e => setTitle(e.target.value)}
            style={inp} onFocus={e => e.target.style.borderColor = t.accent} onBlur={e => e.target.style.borderColor = t.panelLine} />
        </div>
        <div>
          <label style={lbl}>Description</label>
          <textarea className="jobs-input" rows={4} placeholder="Describe the job…" value={desc} onChange={e => setDesc(e.target.value)}
            style={{ ...inp, resize: "vertical", fontFamily: "inherit", fontSize: 13 }}
            onFocus={e => e.target.style.borderColor = t.accent} onBlur={e => e.target.style.borderColor = t.panelLine} />
        </div>
        <div>
          <label style={lbl}>Budget ($)</label>
          <input className="jobs-input" type="number" placeholder="0" value={budget} onChange={e => setBudget(e.target.value)}
            style={inp} onFocus={e => e.target.style.borderColor = t.accent} onBlur={e => e.target.style.borderColor = t.panelLine} />
        </div>
        <div>
          <label style={lbl}>Required Skills</label>
          <SkillTagInput t={t} skills={skills} setSkills={setSkills} />
        </div>
        <div>
          <label style={lbl}>Deadline</label>
          <input className="jobs-input" type="date" value={deadline} onChange={e => setDeadline(e.target.value)}
            style={{ ...inp, colorScheme: "dark" }}
            onFocus={e => e.target.style.borderColor = t.accent} onBlur={e => e.target.style.borderColor = t.panelLine} />
        </div>
        <button onClick={handlePost} style={{
          width: "100%", background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
          padding: "13px 0", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 900,
          letterSpacing: 2, textTransform: "uppercase", cursor: "pointer", marginTop: 4,
        }}>POST JOB →</button>
      </div>
    </Modal>
  );
}

function ApplyModal({ open, onClose, t, job, onSubmit }) {
  const [coverLetter, setCoverLetter] = React.useState("");
  React.useEffect(() => { if (!open) setCoverLetter(""); }, [open]);
  return (
    <Modal open={open} onClose={onClose} t={t}
      title={job ? `Apply: ${job.title}` : "Apply"}
      subtitle="// SUBMIT APPLICATION"
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6 }}>COVER LETTER</div>
          <textarea
            className="jobs-input" rows={6}
            placeholder="Tell the employer why you're the right fit…"
            value={coverLetter} onChange={e => setCoverLetter(e.target.value)}
            style={{
              width: "100%", background: "#000", color: t.text, border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "10px 12px", fontSize: 13, fontFamily: "inherit", outline: "none",
              boxSizing: "border-box", resize: "vertical",
            }}
            onFocus={e => e.target.style.borderColor = t.accent}
            onBlur={e => e.target.style.borderColor = t.panelLine}
          />
        </div>
        <button onClick={onSubmit} style={{
          width: "100%", background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
          padding: "13px 0", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 900,
          letterSpacing: 2, textTransform: "uppercase", cursor: "pointer",
        }}>SUBMIT APPLICATION →</button>
      </div>
    </Modal>
  );
}

function MyApplicationsPanel({ t, applications, loading, onWithdraw }) {
  const steps = ["Applied", "Reviewed", "Interview", "Decision"];
  const apps = applications || MOCK_APPLICATIONS;
  if (loading) {
    return (
      <div style={{ padding: "32px" }}>
        <style>{`@keyframes vlskel{0%,100%{opacity:.4}50%{opacity:.8}}`}</style>
        {[1,2,3].map(i => (
          <div key={i} style={{ padding: "22px 0", borderBottom: `1px solid rgba(255,255,255,.06)` }}>
            <div style={{ height: 16, width: "40%", background: "rgba(255,255,255,.08)", borderRadius: 2, marginBottom: 12, animation: "vlskel 1.4s ease infinite" }}/>
            <div style={{ height: 10, width: "60%", background: "rgba(255,255,255,.06)", borderRadius: 2, animation: "vlskel 1.4s ease infinite" }}/>
          </div>
        ))}
      </div>
    );
  }
  if (apps.length === 0) {
    return <div style={{ padding: "80px 32px", textAlign: "center", fontFamily: DISPLAY_B, fontSize: 12, color: "rgba(138,138,133,.6)", letterSpacing: 3, textTransform: "uppercase" }}>No applications yet.</div>;
  }
  return (
    <div style={{ padding: "32px 32px" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {apps.map((app, idx) => (
          <div key={app.id} style={{
            padding: "22px 0",
            borderBottom: idx < apps.length - 1 ? `1px solid ${t.panelLine}` : "none",
          }}>
            {/* Title + employer */}
            <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 12 }}>
              <div style={{ fontWeight: 700, fontSize: 16, color: t.text }}>{app.jobTitle}</div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim }}>— {app.employer}</div>
            </div>

            {/* Step bar */}
            <div style={{ display: "flex", alignItems: "center", gap: 0, marginBottom: 14 }}>
              {steps.map((step, i) => {
                const active = i <= app.step;
                const isLast = i === steps.length - 1;
                return (
                  <React.Fragment key={step}>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 5 }}>
                      <div style={{
                        width: 24, height: 24, borderRadius: 99,
                        background: active ? t.accent : t.panelLine,
                        border: `2px solid ${active ? t.accent : t.panelLine}`,
                        display: "flex", alignItems: "center", justifyContent: "center",
                      }}>
                        {active && <div style={{ width: 8, height: 8, borderRadius: 99, background: t.accentText }} />}
                      </div>
                      <span style={{ fontFamily: DISPLAY_B, fontSize: 9, color: active ? t.accent : t.textDim, letterSpacing: 1, textTransform: "uppercase", whiteSpace: "nowrap" }}>{step}</span>
                    </div>
                    {!isLast && (
                      <div style={{
                        flex: 1, height: 2, marginBottom: 14,
                        background: i < app.step ? t.accent : t.panelLine,
                        minWidth: 32,
                      }} />
                    )}
                  </React.Fragment>
                );
              })}
            </div>

            {/* Applied date + actions */}
            <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
              <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim }}>APPLIED {app.appliedDate}</span>
              <button style={{
                background: "transparent", border: "none", color: t.textDim, cursor: "pointer",
                fontFamily: DISPLAY_B, fontSize: 10, letterSpacing: 1.5, textTransform: "uppercase", textDecoration: "underline",
              }}>MESSAGE EMPLOYER</button>
              {onWithdraw && (
                <button onClick={() => onWithdraw(app.id)} style={{
                  background: "transparent", border: `1px solid ${t.panelLine}`, borderRadius: 4,
                  color: t.textDim, cursor: "pointer", fontFamily: DISPLAY_B, fontSize: 10,
                  letterSpacing: 1.5, textTransform: "uppercase", padding: "5px 12px",
                }}>WITHDRAW</button>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
// ---- Community screen data & helpers ----
const COMM_POSTS_INIT = [
  { id:1, user:"pixel_craft",   role:"CREATOR",       ts:"2h ago",  upvotes:24, replies:8,
    text:"Just finished my new cinematic color grading tutorial. Four hours of raw footage condensed into a tight 12-minute walkthrough. Drop a comment if you want me to cover a specific look next. The response on the last one was incredible.", media:false },
  { id:2, user:"sound_witch",   role:"PRODUCER",      ts:"4h ago",  upvotes:41, replies:12,
    text:"Hot take: spatial audio is the most underrated tool in post-production right now. Been experimenting with binaural renders for YouTube and the retention numbers are genuinely surprising. Anyone else testing this pipeline?", media:false },
  { id:3, user:"lens_lord",     role:"FILMMAKER",     ts:"6h ago",  upvotes:76, replies:22,
    text:"Behind the scenes from yesterday's exterior shoot. Captured on the A7IV with a vintage Minolta 58mm at f/1.4. The field separation and bokeh character are something else entirely. All in-camera, zero digital blur added in post.", media:true  },
  { id:4, user:"motionblur_mk", role:"EDITOR",        ts:"9h ago",  upvotes:19, replies:6,
    text:"Released a new free LUT pack — 10 looks inspired by classic Kodak film stocks. The grain structure took me two weeks to dial in, so feedback is very welcome. Download link is in my profile.", media:false },
  { id:5, user:"vox_machine",   role:"SOUND DESIGNER",ts:"1d ago",  upvotes:55, replies:17,
    text:"When clients say 'just make it sound bigger' — what does that even mean? Spent six hours on a trailer mix today. On a more serious note, here's my approach to low-end extension without introducing mud into the mix.", media:false },
  { id:6, user:"chromafield",   role:"COLORIST",      ts:"2d ago",  upvotes:38, replies:9,
    text:"Finished episode one of my new series: deconstructing the grade on iconic films. Starting with Heat — breaking down every primary and secondary adjustment used to achieve that cold urban night aesthetic.", media:true  },
];
const COMM_TRENDING = [
  { tag:"#CinematicColor", count:"1.2k posts" },
  { tag:"#SoundDesign",    count:"876 posts"  },
  { tag:"#LUTPack",        count:"743 posts"  },
  { tag:"#FilmGrain",      count:"521 posts"  },
  { tag:"#PostProduction", count:"489 posts"  },
];
const COMM_CREATORS = [
  { user:"maya_cuts",     role:"EDITOR"    },
  { user:"raw_cinematic", role:"FILMMAKER" },
  { user:"freq_lab",      role:"PRODUCER"  },
  { user:"grade_god",     role:"COLORIST"  },
];
const COMM_AVATAR_COLORS = ["#2B4EFF","#FF2B6E","#FF8C2B","#2BFFA0","#C82BFF","#2BC4FF","#FFD72B","#FF5F2B"];
function commAvatarColor(name) {
  let h = 0;
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) & 0xFFFF;
  return COMM_AVATAR_COLORS[h % COMM_AVATAR_COLORS.length];
}
function commInitials(name) {
  const parts = name.replace(/_/g," ").split(" ");
  return ((parts[0]||"?")[0] + ((parts[1]||"?")[0]||"")).toUpperCase();
}
function commMakeComments() {
  return [
    { id:1, user:"zara_v",      text:"This is exactly what I needed this week — thanks so much for sharing!",    likes:7, liked:false },
    { id:2, user:"edit_theory", text:"Really solid breakdown. The part about secondary corrections is gold.",     likes:4, liked:false },
    { id:3, user:"neon_post",   text:"Would love a follow-up covering HDR deliverables and display mapping.",     likes:2, liked:false },
  ];
}

function CommunityScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile } = useAuth();
  const [sort,          setSort]          = React.useState("Recent");
  const [searchQ,       setSearchQ]       = React.useState("");
  const [composeText,   setComposeText]   = React.useState("");
  const [postsLoading,  setPostsLoading]  = React.useState(true);
  const [postsError,    setPostsError]    = React.useState(null);
  const [posts,         setPosts]         = React.useState(() =>
    COMM_POSTS_INIT.map(p => ({ ...p, upvoted:false, expanded:false, comments:commMakeComments() }))
  );
  const [follows,       setFollows]       = React.useState({});
  const [reportPost,    setReportPost]    = React.useState(null);
  const [reportReason,  setReportReason]  = React.useState("Spam");
  const [reportDetails, setReportDetails] = React.useState("");
  const [reportedIds,   setReportedIds]   = React.useState({});
  const [upvotedIds,    setUpvotedIds]    = React.useState(new Set());
  const [commentCache,  setCommentCache]  = React.useState({}); // postId -> comments[]
  const [postSubmitting, setPostSubmitting] = React.useState(false);
  const [creators,      setCreators]      = React.useState(COMM_CREATORS);
  const commSearchTimer = React.useRef(null);
  const [commLive, setCommLive] = React.useState(false);

  // Realtime channel for community feed
  React.useEffect(() => {
    const channel = db.channel('public:communitypost')
      .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'communitypost' }, (payload) => {
        const p = payload.new;
        if (p) {
          setCommLive(true);
          setPosts(prev => {
            const newPost = {
              id: p.id, user: p.user_name || 'creator', role: 'CREATOR',
              ts: 'Just now', text: p.body || '', upvotes: 0, upvoted: false,
              replies: 0, expanded: false, comments: [],
            };
            // Don't add duplicates (own posts already added optimistically)
            if (prev.find(x => x.id === p.id)) return prev;
            return [newPost, ...prev];
          });
        }
      })
      .subscribe((status) => { if (status === 'SUBSCRIBED') setCommLive(true); });
    return () => { db.removeChannel(channel); setCommLive(false); };
  }, []);

  // Load posts from DB
  const loadPosts = React.useCallback(async () => {
    setPostsLoading(true);
    setPostsError(null);
    try {
      let q = db.from('communitypost').select('*, profiles(username, role)').order(sort === "Popular" ? "upvote_count" : "created_at", { ascending: false }).limit(30);
      if (searchQ.trim()) q = q.or(`body.ilike.%${searchQ.trim()}%`);
      const { data, error } = await q;
      if (error) throw error;
      if (data && data.length > 0) {
        setPosts(data.map(p => ({
          id: p.id, user: p.profiles?.username || p.user_name || 'creator',
          role: p.profiles?.role?.toUpperCase() || 'CREATOR',
          ts: formatRelativeTime(p.created_at), text: p.body || p.text || '',
          upvotes: p.upvote_count || 0, upvoted: upvotedIds.has(p.id),
          replies: p.reply_count || 0, expanded: false, comments: [],
        })));
      }
    } catch (err) {
      setPostsError(err.message);
    } finally {
      setPostsLoading(false);
    }
  }, [sort, searchQ]);

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

  React.useEffect(() => {
    clearTimeout(commSearchTimer.current);
    commSearchTimer.current = setTimeout(() => loadPosts(), 400);
    return () => clearTimeout(commSearchTimer.current);
  }, [searchQ]);

  // Load creators from DB (top profiles by post count)
  React.useEffect(() => {
    db.from('profiles').select('username, role').neq('username', '').limit(6).then(({ data }) => {
      if (data && data.length > 0) setCreators(data.map(p => ({ user: p.username, role: p.role?.toUpperCase() || 'CREATOR' })));
    });
  }, []);

  const shownPosts = React.useMemo(() => {
    let list = [...posts];
    if (sort === "Popular") list.sort((a, b) => b.upvotes - a.upvotes);
    return list;
  }, [posts, sort]);

  const submitPost = async () => {
    const txt = composeText.trim();
    if (!txt || postSubmitting) return;
    setPostSubmitting(true);
    const username = profile?.username || user?.email?.split('@')[0] || 'creator';
    const optimistic = {
      id: 'temp-' + Date.now(), user: username,
      role: (profile?.role || 'creator').toUpperCase(), ts: 'Just now',
      text: txt, media: false, upvotes: 0, upvoted: false, replies: 0, expanded: false, comments: [],
    };
    setPosts(prev => [optimistic, ...prev]);
    setComposeText("");
    try {
      const { data, error } = await db.from('communitypost').insert({
        user_id: user.id, body: txt, upvote_count: 0, reply_count: 0,
        created_at: new Date().toISOString(),
      }).select('*, profiles(username, role)').single();
      if (!error && data) {
        setPosts(prev => prev.map(p => p.id === optimistic.id ? {
          ...p, id: data.id, ts: formatRelativeTime(data.created_at),
        } : p));
      }
    } catch (err) { console.error('Post error:', err); }
    setPostSubmitting(false);
  };

  const toggleUpvote = async (id) => {
    const isUpvoted = upvotedIds.has(id);
    setPosts(prev => prev.map(p =>
      p.id === id ? { ...p, upvoted: !isUpvoted, upvotes: p.upvotes + (isUpvoted ? -1 : 1) } : p
    ));
    setUpvotedIds(prev => { const s = new Set(prev); isUpvoted ? s.delete(id) : s.add(id); return s; });
    if (user && typeof id === 'number') {
      if (isUpvoted) {
        await db.from('post_upvote').delete().eq('post_id', id).eq('user_id', user.id);
        await db.from('communitypost').update({ upvote_count: db.raw('upvote_count - 1') }).eq('id', id);
      } else {
        await db.from('post_upvote').insert({ post_id: id, user_id: user.id, created_at: new Date().toISOString() });
        await db.from('communitypost').update({ upvote_count: db.raw('upvote_count + 1') }).eq('id', id);
      }
    }
  };

  const toggleExpand = async (id) => {
    setPosts(prev => prev.map(p => p.id === id ? { ...p, expanded: !p.expanded } : p));
    // Lazy load comments if not cached
    if (!commentCache[id] && typeof id === 'number') {
      const { data } = await db.from('postcomment').select('*, profiles(username)').eq('post_id', id).order('created_at', { ascending: false }).limit(20);
      if (data) {
        const mapped = data.map(c => ({ id: c.id, user: c.profiles?.username || 'user', text: c.body || '', likes: c.like_count || 0, liked: false }));
        setCommentCache(prev => ({ ...prev, [id]: mapped }));
        setPosts(prev => prev.map(p => p.id === id ? { ...p, comments: mapped } : p));
      }
    }
  };

  const addComment = async (postId, text) => {
    if (!text.trim()) return;
    const username = profile?.username || user?.email?.split('@')[0] || 'creator';
    const optimistic = { id: 'c-' + Date.now(), user: username, text: text.trim(), likes: 0, liked: false };
    setPosts(prev => prev.map(p => p.id !== postId ? p : {
      ...p, replies: p.replies + 1, comments: [optimistic, ...(p.comments || [])],
    }));
    if (user && typeof postId === 'number') {
      const { data } = await db.from('postcomment').insert({
        post_id: postId, user_id: user.id, body: text.trim(),
        like_count: 0, created_at: new Date().toISOString(),
      }).select('*, profiles(username)').single();
      if (data) {
        const realComment = { id: data.id, user: data.profiles?.username || username, text: data.body, likes: 0, liked: false };
        setPosts(prev => prev.map(p => p.id !== postId ? p : {
          ...p, comments: p.comments.map(c => c.id === optimistic.id ? realComment : c),
        }));
      }
    }
  };

  const toggleCommentLike = (postId, commentId) => setPosts(prev => prev.map(p => p.id !== postId ? p : {
    ...p, comments: p.comments.map(c => c.id !== commentId ? c : { ...c, liked: !c.liked, likes: c.likes + (c.liked ? -1 : 1) }),
  }));

  const openReport = (id) => { setReportPost(id); setReportReason("Spam"); setReportDetails(""); };
  const submitReport = async () => {
    setReportedIds(prev => ({ ...prev, [reportPost]: true }));
    if (user && typeof reportPost === 'number') {
      await db.from('contentreport').insert({
        reporter_id: user.id, content_type: 'post', content_id: reportPost,
        reason: reportReason, details: reportDetails, status: 'pending',
        created_at: new Date().toISOString(),
      });
    }
    setReportPost(null);
  };

  const sideInputStyle = {
    width:"100%", background:"transparent", border:`1px solid ${t.panelLine}`, borderRadius:4,
    color:t.text, fontFamily:DISPLAY_B, fontSize:11, padding:"8px 10px", outline:"none", boxSizing:"border-box",
  };

  return (
    <div style={{ display:"flex", minHeight:"calc(100vh - 65px)", background:t.bg }}>
      <style>{`
        .comm-input::placeholder { color:rgba(138,138,133,.5); }
        .comm-ta::placeholder    { color:rgba(138,138,133,.5); }
        .comm-ta { resize:none; }
      `}</style>

      {/* ── LEFT SIDEBAR ── */}
      <aside style={{
        width:240, flexShrink:0, borderRight:`1px solid ${t.panelLine}`,
        background:t.panel, overflowY:"auto",
        position:"sticky", top:65, height:"calc(100vh - 65px)",
      }}>
        <div style={{ padding:"20px 16px", display:"flex", flexDirection:"column", gap:20 }}>

          {/* User card */}
          <div style={{ display:"flex", flexDirection:"column", alignItems:"center", gap:10, paddingBottom:16, borderBottom:`1px solid ${t.panelLine}` }}>
            <div style={{
              width:64, height:64, borderRadius:99, border:`2px solid ${t.accent}`,
              background:commAvatarColor(profile?.username||'user'), display:"flex", alignItems:"center", justifyContent:"center",
              fontFamily:DISPLAY_B, fontSize:18, fontWeight:900, color:"#fff",
            }}>{commInitials(profile?.username||user?.email||'?')}</div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:13, fontWeight:700, color:t.text }}>{profile?.username||user?.email?.split('@')[0]||'creator'}</div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.accentText, background:t.accent, padding:"2px 8px", borderRadius:2, letterSpacing:2, textTransform:"uppercase" }}>{profile?.role||'CREATOR'}</div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:4, width:"100%", marginTop:4 }}>
              {[["1.2k","Followers"],["340","Following"],["48","Posts"]].map(([v,l]) => (
                <div key={l} style={{ textAlign:"center" }}>
                  <div style={{ fontFamily:DISPLAY_B, fontSize:13, fontWeight:700, color:t.text }}>{v}</div>
                  <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:1, textTransform:"uppercase" }}>{l}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Create post button */}
          <button style={{
            width:"100%", background:t.accent, color:t.accentText, border:"none", borderRadius:4,
            padding:"11px 0", fontFamily:DISPLAY_B, fontSize:11, fontWeight:800,
            letterSpacing:2, textTransform:"uppercase", cursor:"pointer",
          }}>＋ CREATE POST</button>

          {/* // SORT */}
          <div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.accent, letterSpacing:2.5, textTransform:"uppercase", marginBottom:8 }}>// SORT</div>
            <div style={{ display:"flex", flexDirection:"column", gap:4 }}>
              {["Recent","Popular","Following"].map(s => (
                <button key={s} onClick={() => setSort(s)} style={{
                  width:"100%", textAlign:"left", padding:"8px 10px", borderRadius:4,
                  background:sort===s ? t.accent : "transparent",
                  color:sort===s ? t.accentText : t.textDim,
                  border:`1px solid ${sort===s ? t.accent : t.panelLine}`,
                  fontFamily:DISPLAY_B, fontSize:11, fontWeight:700, letterSpacing:1.5,
                  textTransform:"uppercase", cursor:"pointer",
                }}>{s}</button>
              ))}
            </div>
          </div>

          {/* // SEARCH */}
          <div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.accent, letterSpacing:2.5, textTransform:"uppercase", marginBottom:8 }}>// SEARCH</div>
            <input className="comm-input" placeholder="SEARCH POSTS…"
              value={searchQ} onChange={e => setSearchQ(e.target.value)}
              style={sideInputStyle}
            />
          </div>
        </div>
      </aside>

      {/* ── CENTER FEED ── */}
      <main style={{ flex:1, overflowY:"auto", display:"flex", justifyContent:"center", padding:"24px 16px" }}>
        <div style={{ width:"100%", maxWidth:680, display:"flex", flexDirection:"column", gap:16 }}>

          {/* LIVE indicator */}
          {commLive && (
            <div style={{ display:"flex", alignItems:"center", gap:8, padding:"8px 14px", background:"rgba(57,255,106,.06)", border:`1px solid rgba(57,255,106,.2)`, borderRadius:4 }}>
              <span style={{ width:8, height:8, borderRadius:99, background:t.accent, display:"inline-block", animation:"vlspin 2s linear infinite" }}/>
              <span style={{ fontFamily:DISPLAY_B, fontSize:10, color:t.accent, letterSpacing:2, textTransform:"uppercase" }}>● LIVE — Realtime updates active</span>
            </div>
          )}

          {/* Composer */}
          <div style={{ background:t.panel, border:`1px solid ${t.panelLine}`, borderRadius:8, padding:16 }}>
            <div style={{ display:"flex", gap:12, marginBottom:10 }}>
              <div style={{
                width:36, height:36, flexShrink:0, borderRadius:99, border:`2px solid ${t.accent}`,
                background:commAvatarColor(profile?.username||'user'), display:"flex", alignItems:"center", justifyContent:"center",
                fontFamily:DISPLAY_B, fontSize:11, fontWeight:900, color:"#fff",
              }}>{commInitials(profile?.username||user?.email||'?')}</div>
              <textarea className="comm-ta comm-input" rows={3}
                placeholder="Share something with the community…"
                value={composeText} onChange={e => setComposeText(e.target.value)}
                style={{
                  flex:1, background:"transparent", border:`1px solid ${t.panelLine}`, borderRadius:4,
                  color:t.text, fontFamily:DISPLAY_B, fontSize:12, padding:"8px 10px",
                  outline:"none", lineHeight:1.5, boxSizing:"border-box",
                }}
              />
            </div>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
              <button style={{
                background:"transparent", border:`1px solid ${t.panelLine}`, borderRadius:4,
                color:t.textDim, cursor:"pointer", padding:"6px 10px", fontSize:16, lineHeight:1,
              }}>📎</button>
              <button onClick={submitPost} disabled={postSubmitting} style={{
                background:composeText.trim() ? t.accent : t.panelLine,
                color:composeText.trim() ? t.accentText : t.textDim,
                border:"none", borderRadius:4, padding:"8px 20px",
                fontFamily:DISPLAY_B, fontSize:11, fontWeight:800,
                letterSpacing:2, textTransform:"uppercase", cursor:"pointer",
              }}>{postSubmitting ? "POSTING…" : "POST →"}</button>
            </div>
          </div>

          {/* Feed */}
          <style>{`@keyframes vlskel{0%,100%{opacity:.4}50%{opacity:.8}}`}</style>
          {postsError && (
            <div style={{ display:"flex", alignItems:"center", gap:12, padding:"12px 16px", background:"rgba(255,60,60,.06)", border:"1px solid rgba(255,60,60,.18)", borderRadius:4 }}>
              <span style={{ fontFamily:DISPLAY_B, fontSize:11, color:"#FF4040", flex:1 }}>{postsError}</span>
              <button onClick={loadPosts} style={{ background:"transparent", border:"1px solid rgba(255,60,60,.3)", borderRadius:4, color:"#FF6060", padding:"6px 14px", fontFamily:DISPLAY_B, fontSize:10, cursor:"pointer", letterSpacing:1.5, textTransform:"uppercase" }}>RETRY</button>
            </div>
          )}
          {postsLoading ? (
            [1,2,3].map(i => (
              <div key={i} style={{ background:t.panel, border:`1px solid ${t.panelLine}`, borderRadius:8, padding:16 }}>
                <div style={{ display:"flex", gap:10, marginBottom:12 }}>
                  <div style={{ width:38, height:38, borderRadius:99, background:"rgba(255,255,255,.08)", animation:"vlskel 1.4s ease infinite", flexShrink:0 }}/>
                  <div style={{ flex:1 }}>
                    <div style={{ height:12, width:"40%", background:"rgba(255,255,255,.08)", borderRadius:2, marginBottom:6, animation:"vlskel 1.4s ease infinite" }}/>
                    <div style={{ height:10, width:"25%", background:"rgba(255,255,255,.06)", borderRadius:2, animation:"vlskel 1.4s ease infinite" }}/>
                  </div>
                </div>
                <div style={{ height:10, background:"rgba(255,255,255,.06)", borderRadius:2, marginBottom:6, animation:"vlskel 1.4s ease infinite" }}/>
                <div style={{ height:10, width:"70%", background:"rgba(255,255,255,.05)", borderRadius:2, animation:"vlskel 1.4s ease infinite" }}/>
              </div>
            ))
          ) : (
            shownPosts.map(post => (
              <CommunityPostCard key={post.id} t={t} post={post}
                onUpvote={() => toggleUpvote(post.id)}
                onExpand={() => toggleExpand(post.id)}
                onReport={() => openReport(post.id)}
                onAddComment={(text) => addComment(post.id, text)}
                onCommentLike={(cid) => toggleCommentLike(post.id, cid)}
              />
            ))
          )}
          {!postsLoading && shownPosts.length === 0 && (
            <div style={{ textAlign:"center", padding:"80px 0", fontFamily:DISPLAY_B, color:t.textDim, fontSize:12, letterSpacing:3, textTransform:"uppercase" }}>
              No posts match your search.
            </div>
          )}
        </div>
      </main>

      {/* ── RIGHT SIDEBAR ── */}
      <aside style={{
        width:260, flexShrink:0, borderLeft:`1px solid ${t.panelLine}`,
        background:t.panel, overflowY:"auto",
        position:"sticky", top:65, height:"calc(100vh - 65px)",
      }}>
        <div style={{ padding:"20px 16px", display:"flex", flexDirection:"column", gap:24 }}>

          {/* // TRENDING */}
          <div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.accent, letterSpacing:2.5, textTransform:"uppercase", marginBottom:12 }}>// TRENDING</div>
            {COMM_TRENDING.map(tr => (
              <div key={tr.tag} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"9px 0", borderBottom:`1px solid ${t.panelLine}` }}>
                <div style={{ fontFamily:DISPLAY_B, fontSize:11, color:t.accent, fontWeight:700 }}>{tr.tag}</div>
                <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:1 }}>{tr.count}</div>
              </div>
            ))}
          </div>

          {/* // DISCOVER CREATORS */}
          <div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.accent, letterSpacing:2.5, textTransform:"uppercase", marginBottom:12 }}>// DISCOVER CREATORS</div>
            {creators.map(cr => {
              const isFollowing = !!follows[cr.user];
              return (
                <div key={cr.user} style={{ display:"flex", alignItems:"center", gap:10, padding:"10px 0", borderBottom:`1px solid ${t.panelLine}` }}>
                  <div style={{
                    width:34, height:34, flexShrink:0, borderRadius:99,
                    background:commAvatarColor(cr.user), display:"flex", alignItems:"center", justifyContent:"center",
                    fontFamily:DISPLAY_B, fontSize:10, fontWeight:900, color:"#fff",
                  }}>{commInitials(cr.user)}</div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontFamily:DISPLAY_B, fontSize:11, color:t.text, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{cr.user}</div>
                    <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:1, textTransform:"uppercase" }}>{cr.role}</div>
                  </div>
                  <button onClick={() => setFollows(prev => ({ ...prev, [cr.user]:!isFollowing }))} style={{
                    background:isFollowing ? "transparent" : t.accent,
                    color:isFollowing ? t.accent : t.accentText,
                    border:`1px solid ${isFollowing ? t.accent : "transparent"}`,
                    borderRadius:4, padding:"5px 10px",
                    fontFamily:DISPLAY_B, fontSize:9, fontWeight:700, letterSpacing:1.5,
                    textTransform:"uppercase", cursor:"pointer", whiteSpace:"nowrap", flexShrink:0,
                  }}>{isFollowing ? "FOLLOWING ✓" : "FOLLOW"}</button>
                </div>
              );
            })}
          </div>
        </div>
      </aside>

      {/* ── REPORT MODAL ── */}
      {reportPost !== null && (
        <CommunityReportModal t={t}
          reported={!!reportedIds[reportPost]}
          reason={reportReason} onReason={setReportReason}
          details={reportDetails} onDetails={setReportDetails}
          onSubmit={submitReport} onClose={() => setReportPost(null)}
        />
      )}
    </div>
  );
}

function CommunityPostCard({ t, post, onUpvote, onExpand, onReport, onAddComment, onCommentLike }) {
  const [newComment, setNewComment] = React.useState("");
  const [kebabOpen,  setKebabOpen]  = React.useState(false);

  React.useEffect(() => {
    if (!kebabOpen) return;
    const close = () => setKebabOpen(false);
    window.addEventListener("click", close);
    return () => window.removeEventListener("click", close);
  }, [kebabOpen]);

  const avatarBg = commAvatarColor(post.user);
  const initials = commInitials(post.user);

  return (
    <div style={{ background:t.panel, border:`1px solid ${t.panelLine}`, borderRadius:8, overflow:"hidden" }}>
      {/* Header */}
      <div style={{ padding:"14px 16px", display:"flex", alignItems:"center", gap:10 }}>
        <div style={{
          width:38, height:38, flexShrink:0, borderRadius:99,
          background:avatarBg, display:"flex", alignItems:"center", justifyContent:"center",
          fontFamily:DISPLAY_B, fontSize:11, fontWeight:900, color:"#fff",
        }}>{initials}</div>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:"flex", alignItems:"center", gap:8 }}>
            <span style={{ fontFamily:DISPLAY_B, fontSize:12, fontWeight:700, color:t.text }}>{post.user}</span>
            <span style={{ fontFamily:DISPLAY_B, fontSize:8, color:t.accentText, background:t.accent, padding:"1px 6px", borderRadius:2, letterSpacing:1.5, textTransform:"uppercase" }}>{post.role}</span>
          </div>
          <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:1, marginTop:2 }}>{post.ts}</div>
        </div>
        <div style={{ position:"relative" }}>
          <button onClick={(e) => { e.stopPropagation(); setKebabOpen(o => !o); }} style={{
            background:"transparent", border:"none", cursor:"pointer",
            color:t.textDim, fontSize:18, padding:"4px 6px", lineHeight:1,
          }}>⋯</button>
          {kebabOpen && (
            <div onClick={e => e.stopPropagation()} style={{
              position:"absolute", top:30, right:0, background:t.panel,
              border:`1px solid ${t.panelLine}`, borderRadius:4, zIndex:20, minWidth:130,
              boxShadow:"0 8px 24px rgba(0,0,0,0.5)",
            }}>
              <button onClick={() => { setKebabOpen(false); onReport(); }} style={{
                display:"block", width:"100%", padding:"10px 14px", textAlign:"left",
                background:"transparent", border:"none", color:"#FF4545", cursor:"pointer",
                fontFamily:DISPLAY_B, fontSize:11, letterSpacing:1.5, textTransform:"uppercase",
              }}>⚑ Report</button>
            </div>
          )}
        </div>
      </div>

      {/* Post text */}
      <div style={{ padding:"0 16px 12px", fontFamily:"'Inter',-apple-system,system-ui,sans-serif", fontSize:14, lineHeight:1.65, color:t.text }}>
        {post.text}
      </div>

      {/* Media placeholder */}
      {post.media && (
        <div style={{ margin:"0 16px 12px", position:"relative", borderRadius:6, overflow:"hidden", border:`1px solid ${t.panelLine}` }}>
          <div style={{ paddingTop:"56.25%", background:"#080808" }}/>
          <div style={{
            position:"absolute", inset:0,
            backgroundImage:"repeating-linear-gradient(-45deg,transparent 0px,transparent 10px,rgba(255,255,255,0.04) 10px,rgba(255,255,255,0.04) 11px)",
            display:"flex", alignItems:"center", justifyContent:"center",
          }}>
            <span style={{ fontFamily:DISPLAY_B, fontSize:12, color:t.textDim, letterSpacing:3, textTransform:"uppercase" }}>📹 VIDEO</span>
          </div>
        </div>
      )}

      {/* Action bar */}
      <div style={{ padding:"8px 16px 12px", display:"flex", gap:8, borderTop:`1px solid ${t.panelLine}` }}>
        <button onClick={onUpvote} style={{
          display:"flex", alignItems:"center", gap:5, padding:"6px 12px", borderRadius:4,
          background:post.upvoted ? t.accent : "transparent",
          color:post.upvoted ? t.accentText : t.textDim,
          border:`1px solid ${post.upvoted ? t.accent : t.panelLine}`,
          fontFamily:DISPLAY_B, fontSize:10, fontWeight:700, letterSpacing:1, cursor:"pointer",
        }}>▲ Upvote ({post.upvotes})</button>
        <button onClick={onExpand} style={{
          display:"flex", alignItems:"center", gap:5, padding:"6px 12px", borderRadius:4,
          background:"transparent",
          color:post.expanded ? t.accent : t.textDim,
          border:`1px solid ${post.expanded ? t.accent : t.panelLine}`,
          fontFamily:DISPLAY_B, fontSize:10, fontWeight:700, letterSpacing:1, cursor:"pointer",
        }}>💬 Reply ({post.replies})</button>
        <button style={{
          display:"flex", alignItems:"center", gap:5, padding:"6px 12px", borderRadius:4,
          background:"transparent", color:t.textDim, border:`1px solid ${t.panelLine}`,
          fontFamily:DISPLAY_B, fontSize:10, fontWeight:700, letterSpacing:1, cursor:"pointer",
        }}>↗ Share</button>
      </div>

      {/* Accordion: comment thread */}
      {post.expanded && (
        <div style={{ borderTop:`1px solid ${t.panelLine}`, padding:"14px 16px", background:t.bg, display:"flex", flexDirection:"column", gap:12 }}>
          {post.comments.map(c => (
            <div key={c.id} style={{ display:"flex", gap:10 }}>
              <div style={{
                width:28, height:28, flexShrink:0, borderRadius:99,
                background:commAvatarColor(c.user), display:"flex", alignItems:"center", justifyContent:"center",
                fontFamily:DISPLAY_B, fontSize:9, fontWeight:900, color:"#fff",
              }}>{commInitials(c.user)}</div>
              <div style={{ flex:1 }}>
                <div style={{ fontFamily:DISPLAY_B, fontSize:10, fontWeight:700, color:t.text, marginBottom:4 }}>{c.user}</div>
                <div style={{ fontFamily:"'Inter',-apple-system,system-ui,sans-serif", fontSize:13, color:t.text, lineHeight:1.55, marginBottom:6 }}>{c.text}</div>
                <div style={{ display:"flex", gap:12, alignItems:"center" }}>
                  <button onClick={() => onCommentLike(c.id)} style={{
                    background:"transparent", border:"none", cursor:"pointer",
                    fontFamily:DISPLAY_B, fontSize:9, letterSpacing:1,
                    color:c.liked ? t.accent : t.textDim,
                  }}>♥ {c.likes}</button>
                  <button style={{
                    background:"transparent", border:"none", cursor:"pointer",
                    fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:1, textTransform:"uppercase",
                  }}>Reply</button>
                </div>
              </div>
            </div>
          ))}
          {/* New comment input */}
          <div style={{ display:"flex", gap:8, marginTop:4 }}>
            <input className="comm-input" placeholder="ADD A COMMENT…"
              value={newComment} onChange={e => setNewComment(e.target.value)}
              onKeyDown={e => { if (e.key==="Enter") { onAddComment(newComment); setNewComment(""); } }}
              style={{
                flex:1, background:t.panel, border:`1px solid ${t.panelLine}`, borderRadius:4,
                color:t.text, fontFamily:DISPLAY_B, fontSize:11, padding:"8px 10px", outline:"none",
              }}
            />
            <button onClick={() => { onAddComment(newComment); setNewComment(""); }} style={{
              background:t.accent, color:t.accentText, border:"none", borderRadius:4,
              padding:"8px 14px", fontFamily:DISPLAY_B, fontSize:10, fontWeight:800,
              letterSpacing:2, textTransform:"uppercase", cursor:"pointer", whiteSpace:"nowrap",
            }}>COMMENT →</button>
          </div>
        </div>
      )}
    </div>
  );
}

function CommunityReportModal({ t, reported, reason, onReason, details, onDetails, onSubmit, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key==="Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);

  return (
    <div onClick={onClose} style={{
      position:"fixed", inset:0, background:"rgba(0,0,0,0.75)", backdropFilter:"blur(8px)",
      display:"flex", alignItems:"center", justifyContent:"center", zIndex:1000, padding:24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background:t.panel, border:`1px solid ${t.accent}55`, borderRadius:8, padding:32,
        width:"100%", maxWidth:440, color:t.text, position:"relative",
        boxShadow:`0 30px 80px rgba(0,0,0,0.7), 0 0 80px ${t.accent}22`,
      }}>
        <button onClick={onClose} style={{
          position:"absolute", top:12, right:12, width:28, height:28, borderRadius:4,
          background:"transparent", color:t.textDim, border:`1px solid ${t.panelLine}`,
          cursor:"pointer", fontFamily:DISPLAY_B, fontSize:12,
        }}>✕</button>
        <div style={{ fontFamily:DISPLAY_B, color:t.accent, fontSize:11, letterSpacing:2.5, textTransform:"uppercase", marginBottom:10 }}>// REPORT POST</div>
        <h3 style={{ fontFamily:DISPLAY_B, fontSize:28, fontWeight:900, letterSpacing:-0.8, margin:"0 0 20px", textTransform:"uppercase" }}>REPORT</h3>
        {reported ? (
          <div style={{ textAlign:"center", padding:"20px 0" }}>
            <div style={{ fontFamily:DISPLAY_B, fontSize:32, fontWeight:900, color:t.accent, letterSpacing:-0.5, marginBottom:8 }}>REPORTED ✓</div>
            <div style={{ fontFamily:DISPLAY_B, fontSize:12, color:t.textDim, letterSpacing:1 }}>Thank you. Our team will review this post.</div>
          </div>
        ) : (
          <>
            <div style={{ marginBottom:16 }}>
              <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:2.5, textTransform:"uppercase", marginBottom:10 }}>REASON</div>
              {["Spam","Harassment","Misinformation","Inappropriate content"].map(r => (
                <label key={r} onClick={() => onReason(r)} style={{ display:"flex", alignItems:"center", gap:10, padding:"7px 0", cursor:"pointer" }}>
                  <div style={{
                    width:16, height:16, borderRadius:99, flexShrink:0,
                    border:`2px solid ${reason===r ? t.accent : t.panelLine}`,
                    background:reason===r ? t.accent : "transparent",
                  }}/>
                  <span style={{ fontFamily:DISPLAY_B, fontSize:11, color:reason===r ? t.text : t.textDim, letterSpacing:1 }}>{r}</span>
                </label>
              ))}
            </div>
            <div style={{ marginBottom:18 }}>
              <div style={{ fontFamily:DISPLAY_B, fontSize:9, color:t.textDim, letterSpacing:2.5, textTransform:"uppercase", marginBottom:8 }}>DETAILS (OPTIONAL)</div>
              <textarea className="comm-ta" rows={3} placeholder="Add more context…"
                value={details} onChange={e => onDetails(e.target.value)}
                style={{
                  width:"100%", background:t.bg, border:`1px solid ${t.panelLine}`, borderRadius:4,
                  color:t.text, fontFamily:DISPLAY_B, fontSize:11, padding:"8px 10px",
                  outline:"none", boxSizing:"border-box", lineHeight:1.5,
                }}
              />
            </div>
            <button onClick={onSubmit} style={{
              width:"100%", background:t.accent, color:t.accentText, border:"none", borderRadius:4,
              padding:"12px 0", fontFamily:DISPLAY_B, fontSize:11, fontWeight:800,
              letterSpacing:2, textTransform:"uppercase", cursor:"pointer",
            }}>SUBMIT REPORT →</button>
          </>
        )}
      </div>
    </div>
  );
}
function TokensScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile, refreshProfile } = useAuth();
  const [modal, setModal] = React.useState(null); // null | "topup" | "transfer"

  // ── TOP UP MODAL STATE ──
  const [selectedPkg, setSelectedPkg]       = React.useState(1);
  const [topupStage, setTopupStage]         = React.useState("pick"); // "pick" | "processing" | "success"
  const [premiumTokens, setPremiumTokens]   = React.useState(profile?.premium_tokens ?? 2840);

  // ── TRANSFER MODAL STATE ──
  const [xferUsername, setXferUsername]     = React.useState("");
  const [xferAmount, setXferAmount]         = React.useState("");
  const [xferNote, setXferNote]             = React.useState("");
  const [xferStage, setXferStage]           = React.useState("form"); // "form" | "confirm"

  // ── REAL DATA STATE ──
  const [achievements, setAchievements] = React.useState([
    { name: "FIRST POST",       desc: "Published your first video project",        reward: "＋500 XP",  tier: "BRONZE", earned: true  },
    { name: "COLLAB KING",      desc: "Invited 5 collaborators to a project",      reward: "＋300 XP",  tier: "SILVER", earned: true  },
    { name: "SPEED EDITOR",     desc: "Exported a project under 10 minutes",       reward: "＋200 XP",  tier: "BRONZE", earned: true  },
    { name: "TOKEN HOARDER",    desc: "Accumulated 1,000 Premium Tokens",          reward: "＋100 PT",  tier: "SILVER", earned: true  },
    { name: "COMMUNITY MVP",    desc: "Received 50 likes on a community post",     reward: "＋750 XP",  tier: "GOLD",   earned: false },
    { name: "MARKETPLACE SELLER", desc: "Listed your first product on marketplace", reward: "＋400 XP", tier: "SILVER", earned: false },
    { name: "DAILY STREAK",     desc: "Logged in 30 days in a row",                reward: "＋1000 XP", tier: "GOLD",   earned: false },
    { name: "BUG HUNTER",       desc: "Submitted 3 verified bug reports",          reward: "＋250 XP",  tier: "BRONZE", earned: false },
    { name: "TUTORIAL MASTER",  desc: "Completed all onboarding tutorials",        reward: "＋500 XP",  tier: "SILVER", earned: false },
  ]);
  const [activity, setActivity] = React.useState([
    { icon: "📝", event: "Post published — \"Summer Reel 2026\"",    reward: "＋50 XP",  time: "2 min ago"   },
    { icon: "❤️", event: "Comment liked by @maya_edits",               reward: "＋10 XP",  time: "18 min ago"  },
    { icon: "👥", event: "Collaborator joined project",                 reward: "＋100 XP", time: "1 hr ago"    },
    { icon: "🔑", event: "Daily login bonus",                           reward: "＋25 XP",  time: "3 hr ago"    },
    { icon: "🎬", event: "Video exported — \"Brand Spot v3.mp4\"",    reward: "＋75 XP",  time: "Yesterday"   },
    { icon: "🎓", event: "Tutorial completed — Auto-captions 101",     reward: "＋200 XP", time: "2 days ago"  },
  ]);
  const [activityLoading, setActivityLoading] = React.useState(false);

  // Sync premium tokens from profile
  React.useEffect(() => {
    if (profile?.premium_tokens != null) setPremiumTokens(profile.premium_tokens);
  }, [profile?.premium_tokens]);

  // Load achievements from DB
  React.useEffect(() => {
    if (!user) return;
    db.from('user_achievements').select('*, achievement(name, description, xp_reward, tier)').eq('user_id', user.id)
      .then(({ data }) => {
        if (data && data.length > 0) {
          setAchievements(prev => prev.map(a => {
            const found = data.find(d => d.achievement?.name?.toUpperCase() === a.name);
            return found ? { ...a, earned: true } : a;
          }));
        }
      });
  }, [user?.id]);

  // Load activity log from DB
  React.useEffect(() => {
    if (!user) return;
    setActivityLoading(true);
    db.from('token_events').select('*').eq('user_id', user.id).order('created_at', { ascending: false }).limit(20)
      .then(({ data }) => {
        if (data && data.length > 0) {
          setActivity(data.map(e => ({
            icon: e.event_type === 'xp' ? '⚡' : e.event_type === 'token' ? '🪙' : '📝',
            event: e.description || e.event_type || 'Event',
            reward: (e.amount > 0 ? '＋' : '') + e.amount + ' ' + (e.unit || 'XP'),
            time: formatRelativeTime(e.created_at),
          })));
        }
        setActivityLoading(false);
      });
  }, [user?.id]);

  const closeModal = () => {
    setModal(null);
    setTopupStage("pick");
    setXferStage("form");
    setXferUsername(""); setXferAmount(""); setXferNote("");
  };

  const packages = [
    { id: 0, pt: 500,  price: "$4.99",  badge: null },
    { id: 1, pt: 1500, price: "$12.99", badge: "BEST VALUE" },
    { id: 2, pt: 5000, price: "$39.99", badge: null },
  ];

  const handlePurchase = async () => {
    setTopupStage("processing");
    const pkg = packages[selectedPkg];
    try {
      if (user) {
        await db.from('token_events').insert({
          user_id: user.id, event_type: 'token', description: `Top up — ${pkg.pt} Premium Tokens`,
          amount: pkg.pt, unit: 'PT', created_at: new Date().toISOString(),
        });
        await db.from('profiles').update({ premium_tokens: (profile?.premium_tokens || 0) + pkg.pt }).eq('id', user.id);
        await refreshProfile();
      }
      setPremiumTokens(prev => prev + pkg.pt);
      setTopupStage("success");
    } catch (err) {
      console.error('Top-up error:', err);
      setPremiumTokens(prev => prev + pkg.pt);
      setTopupStage("success");
    }
  };

  const handleTransferConfirm = () => {
    setXferStage("confirm");
  };

  const tierColor = { BRONZE: "#CD7F32", SILVER: "#C0C0C0", GOLD: "#FFD700" };
  const tierBg    = { BRONZE: "#CD7F3218", SILVER: "#C0C0C018", GOLD: "#FFD70018" };

  const inp = {
    width: "100%", background: "#000", color: t.text,
    border: `1px solid ${t.panelLine}`, borderRadius: 4,
    padding: "11px 14px", fontSize: 13, fontFamily: "inherit",
    outline: "none", boxSizing: "border-box",
  };
  const dimLabel = {
    fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim,
    letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6, display: "block",
  };

  return (
    <div style={{ background: t.bg, minHeight: "calc(100vh - 65px)", padding: "36px 0" }}>
      <style>{`
        @keyframes vlspin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }
        @keyframes vlcheck { from{opacity:0;transform:scale(.85)} to{opacity:1;transform:scale(1)} }
      `}</style>

      <div style={{ maxWidth: 900, margin: "0 auto", padding: "0 32px" }}>

        {/* ── PAGE HEADER ── */}
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 3, textTransform: "uppercase", marginBottom: 4 }}>
            // TOKENS &amp; REWARDS
          </div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 22, fontWeight: 900, letterSpacing: -0.5, textTransform: "uppercase" }}>
            Wallet Overview
          </div>
        </div>

        {/* ── STAT CARDS ROW ── */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginBottom: 24 }}>
          {[
            { label: "PREMIUM TOKENS",   value: premiumTokens.toLocaleString() + " PT", trend: "+120 PT today" },
            { label: "CREATOR POINTS",   value: ((profile?.xp || 14220)).toLocaleString() + " XP", trend: "+460 XP today" },
            { label: "GIVEAWAY TICKETS", value: (profile?.giveaway_tickets || 7) + " 🎟",  trend: "2 expiring soon" },
          ].map(card => (
            <div key={card.label} style={{
              background: t.panel, border: `1px solid ${t.panelLine}`,
              borderRadius: 4, padding: "22px 24px",
            }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 10 }}>
                {card.label}
              </div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 34, fontWeight: 900, color: t.accent, letterSpacing: -1, lineHeight: 1, marginBottom: 10 }}>
                {card.value}
              </div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 1, opacity: 0.7 }}>
                ↑ {card.trend}
              </div>
            </div>
          ))}
        </div>

        {/* ── LEVEL PROGRESS ── */}
        <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "22px 24px", marginBottom: 16 }}>
          {/* Header row */}
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 2, textTransform: "uppercase" }}>
              CREATOR LEVEL
            </div>
            <div style={{
              background: t.accent, color: t.accentText,
              fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 900, letterSpacing: 1.5,
              padding: "4px 10px", borderRadius: 4,
            }}>LV. 12</div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: t.textDim, letterSpacing: 1 }}>→ LV. 13</div>
          </div>

          {/* Main XP bar */}
          <div style={{ height: 12, background: "rgba(255,255,255,0.06)", borderRadius: 999, overflow: "hidden", marginBottom: 6 }}>
            <div style={{ width: "68%", height: "100%", background: t.accent, borderRadius: 999, boxShadow: `0 0 10px ${t.accent}66` }}/>
          </div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1, marginBottom: 18 }}>
            3,280 XP to next level
          </div>

          {/* Daily XP bar */}
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", flexShrink: 0 }}>
              DAILY XP · 420 / 1,000
            </div>
            <div style={{ flex: 1, height: 6, background: "rgba(255,255,255,0.06)", borderRadius: 999, overflow: "hidden" }}>
              <div style={{ width: "42%", height: "100%", background: t.accent, borderRadius: 999 }}/>
            </div>
          </div>
        </div>

        {/* ── QUICK ACTIONS ── */}
        <div style={{ display: "flex", gap: 10, marginBottom: 32 }}>
          <button style={{
            flex: 1, background: "transparent", color: t.text,
            border: `1px solid ${t.panelLine}`, borderRadius: 4,
            padding: "12px 0", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700,
            letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
          }}>ADJUST LIMITS</button>
          <button
            onClick={() => { setTopupStage("pick"); setModal("topup"); }}
            style={{
              flex: 1, background: t.accent, color: t.accentText,
              border: "none", borderRadius: 4,
              padding: "12px 0", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 900,
              letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
              boxShadow: `0 0 24px ${t.accent}44`,
            }}>TOP UP TOKENS ＋</button>
          <button
            onClick={() => { setXferStage("form"); setModal("transfer"); }}
            style={{
              flex: 1, background: "transparent", color: t.text,
              border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "12px 0", fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700,
              letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
            }}>TRANSFER TOKENS →</button>
        </div>

        {/* ── ACHIEVEMENTS ── */}
        <div style={{ marginBottom: 32 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 3, textTransform: "uppercase" }}>
              // ACHIEVEMENTS
            </div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 13, fontWeight: 800, color: t.accent, letterSpacing: 1 }}>
              14,220 XP EARNED
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
            {achievements.map((a, i) => (
              <div key={i} style={{
                background: a.earned ? `${t.accent}16` : t.panel,
                border: `1px solid ${a.earned ? t.accent : t.panelLine}`,
                borderRadius: 4, padding: "18px 20px",
                position: "relative",
              }}>
                {/* Tier badge */}
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                  <div style={{
                    fontFamily: DISPLAY_B, fontSize: 14, fontWeight: 900,
                    color: a.earned ? t.accent : t.text,
                    letterSpacing: 0.5, textTransform: "uppercase", lineHeight: 1.2,
                  }}>{a.name}</div>
                  <span style={{
                    fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1.5,
                    textTransform: "uppercase", padding: "3px 7px", borderRadius: 3,
                    color: tierColor[a.tier], background: tierBg[a.tier],
                    border: `1px solid ${tierColor[a.tier]}44`, flexShrink: 0,
                  }}>{a.tier}</span>
                </div>
                <div style={{ fontSize: 12, color: t.textDim, lineHeight: 1.5, marginBottom: 10 }}>
                  {a.desc}
                </div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, color: t.accent }}>
                    {a.reward}
                  </span>
                  {a.earned && (
                    <span style={{
                      fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1.5,
                      textTransform: "uppercase", color: t.accentText,
                      background: t.accent, padding: "3px 8px", borderRadius: 3,
                    }}>EARNED ✓</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* ── ACTIVITY LOG ── */}
        <div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, letterSpacing: 3, textTransform: "uppercase", marginBottom: 16 }}>
            // ACTIVITY LOG
          </div>
          <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, overflow: "hidden" }}>
            {activity.map((row, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 14,
                padding: "14px 20px",
                borderBottom: i < activity.length - 1 ? `1px solid ${t.panelLine}` : "none",
              }}>
                {/* Icon */}
                <div style={{
                  width: 32, height: 32, borderRadius: 99, flexShrink: 0,
                  background: `${t.accent}14`, border: `1px solid ${t.accent}33`,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 14,
                }}>{row.icon}</div>

                {/* Event */}
                <div style={{ flex: 1, fontSize: 13, color: t.text, lineHeight: 1.3 }}>
                  {row.event}
                </div>

                {/* Reward */}
                <div style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, color: t.accent, flexShrink: 0 }}>
                  {row.reward}
                </div>

                {/* Timestamp */}
                <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1, flexShrink: 0, minWidth: 90, textAlign: "right" }}>
                  {row.time}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ══════════════ TOP UP MODAL ══════════════ */}
      <Modal
        open={modal === "topup"}
        onClose={closeModal}
        t={t}
        title={topupStage === "success" ? "Tokens added!" : "Top up tokens"}
        subtitle="// premium tokens"
      >
        {topupStage === "pick" && (<>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 20 }}>
            {packages.map(pkg => {
              const on = selectedPkg === pkg.id;
              return (
                <button key={pkg.id} onClick={() => setSelectedPkg(pkg.id)} style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  padding: "16px 18px",
                  background: on ? `${t.accent}14` : "transparent",
                  border: `1px solid ${on ? t.accent : t.panelLine}`,
                  borderRadius: 4, cursor: "pointer", color: t.text, textAlign: "left",
                }}>
                  <div>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 16, fontWeight: 900, color: on ? t.accent : t.text, letterSpacing: 0.5 }}>
                      {pkg.pt.toLocaleString()} PT
                    </div>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, marginTop: 2 }}>
                      {pkg.price}
                    </div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    {pkg.badge && (
                      <span style={{
                        background: t.accent, color: t.accentText,
                        fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1.5,
                        textTransform: "uppercase", padding: "3px 8px", borderRadius: 3,
                      }}>{pkg.badge}</span>
                    )}
                    <div style={{
                      width: 16, height: 16, borderRadius: 99,
                      border: `1.5px solid ${on ? t.accent : t.panelLine}`,
                      background: on ? t.accent : "transparent",
                    }}/>
                  </div>
                </button>
              );
            })}
          </div>
          <button onClick={handlePurchase} style={{
            width: "100%", background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "14px 20px", fontSize: 14, fontWeight: 900, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase",
          }}>PURCHASE →</button>
        </>)}

        {topupStage === "processing" && (
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: "24px 0", gap: 20 }}>
            <svg width="48" height="48" viewBox="0 0 48 48" style={{ animation: "vlspin 1s linear infinite" }}>
              <circle cx="24" cy="24" r="20" fill="none" stroke={t.panelLine} strokeWidth="3"/>
              <path d="M24 4 A20 20 0 0 1 44 24" fill="none" stroke={t.accent} strokeWidth="3" strokeLinecap="round"/>
            </svg>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: t.textDim, letterSpacing: 2, textTransform: "uppercase" }}>Processing…</div>
          </div>
        )}

        {topupStage === "success" && (
          <div style={{ textAlign: "center", animation: "vlcheck .3s ease" }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 28, fontWeight: 900, color: t.accent, letterSpacing: 1, marginBottom: 10 }}>
              // TOKENS ADDED
            </div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 38, fontWeight: 900, color: t.accent, letterSpacing: -1, marginBottom: 6 }}>
              {premiumTokens.toLocaleString()} PT
            </div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1, marginBottom: 24 }}>
              New balance
            </div>
            <button onClick={closeModal} style={{
              background: "transparent", color: t.accent, border: `1px solid ${t.accent}`,
              borderRadius: 4, padding: "12px 28px", fontFamily: DISPLAY_B, fontSize: 11,
              fontWeight: 700, letterSpacing: 2, textTransform: "uppercase", cursor: "pointer",
            }}>DONE</button>
          </div>
        )}
      </Modal>

      {/* ══════════════ TRANSFER MODAL ══════════════ */}
      <Modal
        open={modal === "transfer"}
        onClose={closeModal}
        t={t}
        title={xferStage === "confirm" ? "Confirm transfer" : "Transfer tokens"}
        subtitle="// send premium tokens"
      >
        {xferStage === "form" && (<>
          <div style={{ marginBottom: 14 }}>
            <label style={dimLabel}>Recipient username</label>
            <input
              type="text" value={xferUsername}
              onChange={e => setXferUsername(e.target.value)}
              placeholder="@username"
              style={inp}
              onFocus={e => e.target.style.borderColor = t.accent}
              onBlur={e => e.target.style.borderColor = t.panelLine}
            />
          </div>
          <div style={{ marginBottom: 14 }}>
            <label style={dimLabel}>Amount (PT)</label>
            <input
              type="number" value={xferAmount}
              onChange={e => setXferAmount(e.target.value)}
              placeholder="100"
              style={inp}
              onFocus={e => e.target.style.borderColor = t.accent}
              onBlur={e => e.target.style.borderColor = t.panelLine}
            />
          </div>
          <div style={{ marginBottom: 20 }}>
            <label style={dimLabel}>Note (optional)</label>
            <textarea
              value={xferNote}
              onChange={e => setXferNote(e.target.value)}
              placeholder="What's this for?"
              rows={3}
              style={{ ...inp, resize: "none" }}
              onFocus={e => e.target.style.borderColor = t.accent}
              onBlur={e => e.target.style.borderColor = t.panelLine}
            />
          </div>
          <button
            onClick={handleTransferConfirm}
            disabled={!xferUsername || !xferAmount}
            style={{
              width: "100%", background: xferUsername && xferAmount ? t.accent : t.panelLine,
              color: xferUsername && xferAmount ? t.accentText : t.textDim,
              border: "none", borderRadius: 4, padding: "14px 20px",
              fontSize: 14, fontWeight: 900, cursor: xferUsername && xferAmount ? "pointer" : "default",
              fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase",
            }}>SEND TOKENS →</button>
        </>)}

        {xferStage === "confirm" && (<>
          <div style={{ background: "#000", border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "16px 18px", marginBottom: 20 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 10, fontFamily: DISPLAY_B, fontSize: 11 }}>
              <span style={{ color: t.textDim, letterSpacing: 1, textTransform: "uppercase" }}>Recipient</span>
              <span style={{ color: t.accent }}>{xferUsername}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: DISPLAY_B, fontSize: 11 }}>
              <span style={{ color: t.textDim, letterSpacing: 1, textTransform: "uppercase" }}>Amount</span>
              <span style={{ color: t.accent, fontWeight: 800, fontSize: 14 }}>{xferAmount} PT</span>
            </div>
            {xferNote && (
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: `1px solid ${t.panelLine}`, fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim }}>
                "{xferNote}"
              </div>
            )}
          </div>
          <button onClick={closeModal} style={{
            width: "100%", background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "14px 20px", fontSize: 14, fontWeight: 900, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase", marginBottom: 10,
          }}>CONFIRM TRANSFER →</button>
          <button onClick={() => setXferStage("form")} style={{
            width: "100%", background: "transparent", color: t.textDim,
            border: `1px solid ${t.panelLine}`, borderRadius: 4,
            padding: "12px 20px", fontSize: 12, fontWeight: 700, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}>← BACK</button>
        </>)}
      </Modal>
    </div>
  );
}
function SettingsToggle({ on, onToggle, accent }) {
  return (
    <div
      onClick={onToggle}
      style={{
        width: 44, height: 24, borderRadius: 12, cursor: "pointer", flexShrink: 0,
        background: on ? accent : "rgba(255,255,255,0.12)",
        position: "relative", transition: "background 0.2s ease",
      }}
    >
      <div style={{
        position: "absolute", top: 3, left: on ? 23 : 3,
        width: 18, height: 18, borderRadius: 9,
        background: "#fff", transition: "left 0.2s ease",
        boxShadow: "0 1px 4px rgba(0,0,0,0.4)",
      }}/>
    </div>
  );
}

function SettingsScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile, signOut, signInWithGoogle, refreshProfile } = useAuth();
  const TABS = ["PROFILE", "SECURITY", "NOTIFICATIONS", "SESSIONS", "DATA & PRIVACY", "CONNECTED ACCOUNTS"];
  const [activeTab, setActiveTab] = React.useState("PROFILE");

  // ── PROFILE state ──
  const [profileUsername, setProfileUsername]   = React.useState(profile?.username || "");
  const [profileEmail, setProfileEmail]         = React.useState(user?.email || "");
  const [profileDisplayName, setProfileDisplayName] = React.useState(profile?.username || "");
  const [profileSaved, setProfileSaved]         = React.useState(false);
  const [profileSaving, setProfileSaving]       = React.useState(false);
  const [profileSaveError, setProfileSaveError] = React.useState("");
  const [usernameStatus, setUsernameStatus]     = React.useState(null);
  const [deleteModalOpen, setDeleteModalOpen]   = React.useState(false);
  const [deleteInput, setDeleteInput]           = React.useState("");
  const settingsUsernameTimerRef                = React.useRef(null);

  // Sync profile state when profile loads
  React.useEffect(() => {
    if (profile) {
      setProfileUsername(profile.username || "");
      setProfileDisplayName(profile.username || "");
    }
    if (user?.email) setProfileEmail(user.email);
  }, [profile, user]);

  // Real DB username availability check with debounce
  React.useEffect(() => {
    if (profileUsername.length < 3) { setUsernameStatus(null); return; }
    if (profileUsername === profile?.username) { setUsernameStatus(null); return; }
    setUsernameStatus("checking");
    if (settingsUsernameTimerRef.current) clearTimeout(settingsUsernameTimerRef.current);
    settingsUsernameTimerRef.current = setTimeout(async () => {
      const { data, error } = await db.from('profiles').select('id').eq('username', profileUsername).single();
      if (data) { setUsernameStatus("taken"); }
      else if (error && error.code === 'PGRST116') { setUsernameStatus("available"); }
      else { setUsernameStatus(null); }
    }, 500);
    return () => { if (settingsUsernameTimerRef.current) clearTimeout(settingsUsernameTimerRef.current); };
  }, [profileUsername, profile]);

  // ── SECURITY state ──
  const [currentPw, setCurrentPw]     = React.useState("");
  const [newPw, setNewPw]             = React.useState("");
  const [confirmPw, setConfirmPw]     = React.useState("");
  const [twoFAOn, setTwoFAOn]         = React.useState(false);
  const [tfaCode, setTfaCode]         = React.useState("");
  const [recoveryEmail, setRecoveryEmail] = React.useState("");

  // ── NOTIFICATIONS state ──
  const [notifToggles, setNotifToggles] = React.useState({
    emailNotifications: true,
    pushNotifications: false,
    newCommentAlerts: true,
    collaboratorActivity: true,
    marketplaceUpdates: false,
    weeklyDigest: true,
  });
  const [notifSaved, setNotifSaved] = React.useState(false);

  // ── DATA & PRIVACY state ──
  const [exportQueued, setExportQueued] = React.useState(false);
  const [privacyToggles, setPrivacyToggles] = React.useState({
    profileVisibility: true,
    showInDiscover: true,
    analyticsSharing: false,
  });

  // ── CONNECTED ACCOUNTS state ──
  const [googleConnected, setGoogleConnected] = React.useState(true);
  const [youtubeConnected, setYoutubeConnected] = React.useState(false);

  const TAB_LABELS = {
    "PROFILE": "Profile",
    "SECURITY": "Security",
    "NOTIFICATIONS": "Notifications",
    "SESSIONS": "Sessions",
    "DATA & PRIVACY": "Data & Privacy",
    "CONNECTED ACCOUNTS": "Connected Accounts",
  };

  const sectionHeader = (text) => (
    <div style={{
      fontFamily: DISPLAY_B, fontSize: 10, color: t.accent,
      letterSpacing: 3, textTransform: "uppercase", marginBottom: 20,
    }}>{text}</div>
  );

  const subHeader = (text) => (
    <div style={{
      fontFamily: DISPLAY_B, fontSize: 13, fontWeight: 800,
      color: t.text, letterSpacing: 0.5, textTransform: "uppercase",
      marginBottom: 16, marginTop: 28, paddingBottom: 10,
      borderBottom: `1px solid ${t.panelLine}`,
    }}>{text}</div>
  );

  const accentBtn = (label, onClick, full) => (
    <button onClick={onClick} style={{
      width: full ? "100%" : "auto",
      background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
      padding: "12px 22px", fontSize: 12, fontWeight: 900, cursor: "pointer",
      fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
    }}>{label}</button>
  );

  const outlineBtn = (label, onClick, color, full) => (
    <button onClick={onClick} style={{
      width: full ? "100%" : "auto",
      background: "transparent", color: color || t.text,
      border: `1px solid ${color || t.panelLine}`, borderRadius: 4,
      padding: "12px 22px", fontSize: 12, fontWeight: 700, cursor: "pointer",
      fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
    }}>{label}</button>
  );

  const settingsInput = (value, onChange, type = "text", placeholder = "") => (
    <input
      type={type} value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        width: "100%", background: "#000", color: t.text,
        border: `1px solid ${t.panelLine}`, borderRadius: 4,
        padding: "11px 14px", fontSize: 13, fontFamily: "inherit",
        outline: "none", boxSizing: "border-box",
      }}
      onFocus={(e) => e.target.style.borderColor = t.accent}
      onBlur={(e) => e.target.style.borderColor = t.panelLine}
    />
  );

  const fieldLabel = (label) => (
    <div style={{
      fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim,
      letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6,
    }}>{label}</div>
  );

  const fieldBlock = (label, value, onChange, type, placeholder, extra) => (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim,
        letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6,
      }}>
        <span>{label}</span>
        {extra}
      </div>
      {settingsInput(value, onChange, type, placeholder)}
    </div>
  );

  // ── TAB CONTENT ──

  const renderProfile = () => (
    <div>
      {sectionHeader("// PROFILE SETTINGS")}

      {/* Avatar */}
      <div style={{ marginBottom: 28, display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 10 }}>
        <div style={{
          width: 80, height: 80, borderRadius: 99,
          border: `2px solid ${t.accent}`,
          background: `${t.accent}18`,
          display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: DISPLAY_B, fontSize: 22, fontWeight: 900, color: t.accent,
          letterSpacing: 1,
        }}>{profile ? (profile.username || user?.email || 'JD').slice(0,2).toUpperCase() : (user?.email || 'JD').slice(0,2).toUpperCase()}</div>
        <span style={{
          fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim,
          letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
        }}>CHANGE PHOTO</span>
      </div>

      {/* Username with availability check */}
      <div style={{ marginBottom: 16 }}>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim,
          letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6,
        }}>
          <span>USERNAME</span>
          {usernameStatus === "checking" && (
            <span style={{ fontSize: 10, color: t.textDim, fontStyle: "italic" }}>checking…</span>
          )}
          {usernameStatus === "available" && (
            <span style={{ fontSize: 10, color: t.accent, fontWeight: 700 }}>// AVAILABLE ✓</span>
          )}
          {usernameStatus === "taken" && (
            <span style={{ fontSize: 10, color: '#FF4444', fontWeight: 700 }}>// USERNAME TAKEN</span>
          )}
        </div>
        {settingsInput(profileUsername, setProfileUsername, "text", "@yourname")}
      </div>

      {fieldBlock("EMAIL", profileEmail, setProfileEmail, "email", "you@studio.com")}
      {fieldBlock("DISPLAY NAME", profileDisplayName, setProfileDisplayName, "text", "Your Name")}

      {/* Role badge */}
      <div style={{ marginBottom: 24 }}>
        {fieldLabel("ROLE")}
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          <span style={{
            background: `${t.accent}18`, color: t.accent, border: `1px solid ${t.accent}44`,
            fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 800, letterSpacing: 2,
            textTransform: "uppercase", padding: "6px 14px", borderRadius: 4,
          }}>{profile?.role?.toUpperCase() || 'CREATOR'}</span>
          <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1 }}>
            read-only
          </span>
        </div>
      </div>

      {/* Save */}
      <div style={{ marginBottom: 40 }}>
        {profileSaveError && <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: '#FF4444', marginBottom: 10 }}>{profileSaveError}</div>}
        <button
          disabled={profileSaving}
          onClick={async () => {
            if (!user) return;
            setProfileSaving(true);
            setProfileSaveError("");
            const { error } = await db.from('profiles').update({ username: profileUsername }).eq('id', user.id);
            setProfileSaving(false);
            if (error) { setProfileSaveError('// ERROR: ' + error.message); }
            else {
              setProfileSaved(true);
              setTimeout(() => setProfileSaved(false), 2000);
              if (refreshProfile) refreshProfile();
            }
          }}
          style={{
            background: profileSaved ? t.accent : profileSaving ? t.panelLine : t.accent,
            color: profileSaving ? t.textDim : t.accentText,
            border: "none", borderRadius: 4,
            padding: "12px 22px", fontSize: 12, fontWeight: 900,
            cursor: profileSaving ? "default" : "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}
        >
          {profileSaved ? "// SAVED ✓" : profileSaving ? "// SAVING…" : "SAVE CHANGES →"}
        </button>
      </div>

      {/* Danger Zone */}
      <div style={{
        border: `1px solid rgba(255,68,68,0.3)`, borderRadius: 4, padding: "22px 24px",
      }}>
        <div style={{
          fontFamily: DISPLAY_B, fontSize: 10, color: "#FF4444",
          letterSpacing: 3, textTransform: "uppercase", marginBottom: 10,
        }}>// DANGER ZONE</div>
        <p style={{ color: t.textDim, fontSize: 13, lineHeight: 1.6, margin: "0 0 16px" }}>
          Permanently delete your account and all associated data. This action cannot be undone.
        </p>
        <button
          onClick={() => { setDeleteInput(""); setDeleteModalOpen(true); }}
          style={{
            background: "transparent", color: "#FF4444",
            border: "1px solid rgba(255,68,68,0.5)", borderRadius: 4,
            padding: "10px 20px", fontSize: 12, fontWeight: 700, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}
        >DELETE ACCOUNT</button>
      </div>

      {/* Delete confirmation modal */}
      {deleteModalOpen && (
        <div
          onClick={() => setDeleteModalOpen(false)}
          style={{
            position: "fixed", inset: 0, background: "rgba(0,0,0,0.75)",
            backdropFilter: "blur(8px)", display: "flex", alignItems: "center",
            justifyContent: "center", zIndex: 1000, padding: 24,
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              background: t.panel, border: "1px solid rgba(255,68,68,0.4)", borderRadius: 8,
              padding: 36, width: "100%", maxWidth: 440,
              boxShadow: "0 30px 80px rgba(0,0,0,0.7)",
            }}
          >
            <div style={{
              fontFamily: DISPLAY_B, fontSize: 10, color: "#FF4444",
              letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 10,
            }}>// DANGER ZONE</div>
            <h3 style={{
              fontFamily: DISPLAY_B, fontSize: 26, fontWeight: 900,
              letterSpacing: -0.5, margin: "0 0 16px", textTransform: "uppercase", color: t.text,
            }}>DELETE ACCOUNT?</h3>
            <p style={{ color: t.textDim, fontSize: 13, lineHeight: 1.6, margin: "0 0 20px" }}>
              This will permanently delete your account. Type <span style={{ color: "#FF4444", fontFamily: DISPLAY_B }}>DELETE</span> to confirm.
            </p>
            <div style={{ marginBottom: 20 }}>
              <input
                type="text" value={deleteInput}
                onChange={(e) => setDeleteInput(e.target.value)}
                placeholder="Type DELETE to confirm"
                style={{
                  width: "100%", background: "#000", color: t.text,
                  border: `1px solid rgba(255,68,68,0.4)`, borderRadius: 4,
                  padding: "11px 14px", fontSize: 13, fontFamily: "inherit",
                  outline: "none", boxSizing: "border-box",
                }}
                onFocus={(e) => e.target.style.borderColor = "#FF4444"}
                onBlur={(e) => e.target.style.borderColor = "rgba(255,68,68,0.4)"}
              />
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <button
                disabled={deleteInput !== "DELETE"}
                onClick={async () => {
                  // Mark profile for deletion + create a support ticket, then sign out
                  // Full deletion requires a Supabase Edge Function (service role key)
                  if (user) {
                    await db.from('supportrequest').insert({
                      user_id: user.id, name: profile?.username || '', email: user.email,
                      subject: 'Account Deletion Request', message: 'User confirmed account deletion.',
                      created_at: new Date().toISOString(),
                    });
                    await db.from('profiles').update({ deletion_requested: true, deletion_requested_at: new Date().toISOString() }).eq('id', user.id);
                  }
                  await db.auth.signOut();
                  setDeleteModalOpen(false);
                  navigate('login');
                }}
                style={{
                  flex: 1, background: deleteInput === "DELETE" ? "#FF4444" : "rgba(255,68,68,0.15)",
                  color: deleteInput === "DELETE" ? "#fff" : "rgba(255,68,68,0.4)",
                  border: "none", borderRadius: 4, padding: "12px", fontSize: 12, fontWeight: 900,
                  cursor: deleteInput === "DELETE" ? "pointer" : "not-allowed",
                  fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                  transition: "all 0.2s ease",
                }}
              >CONFIRM DELETE</button>
              <button
                onClick={() => setDeleteModalOpen(false)}
                style={{
                  flex: 1, background: "transparent", color: t.textDim,
                  border: `1px solid ${t.panelLine}`, borderRadius: 4,
                  padding: "12px", fontSize: 12, fontWeight: 700, cursor: "pointer",
                  fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                }}
              >CANCEL</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );

  const [pwUpdating, setPwUpdating] = React.useState(false);
  const [pwUpdated, setPwUpdated] = React.useState(false);
  const [pwError, setPwError] = React.useState("");

  const handleUpdatePassword = async () => {
    if (newPw.length < 8) { setPwError('// MIN 8 CHARACTERS'); return; }
    if (newPw !== confirmPw) { setPwError('// PASSWORDS DO NOT MATCH'); return; }
    setPwUpdating(true);
    setPwError("");
    const { error } = await db.auth.updateUser({ password: newPw });
    setPwUpdating(false);
    if (error) { setPwError('// ERROR: ' + error.message); }
    else {
      setPwUpdated(true);
      setCurrentPw(""); setNewPw(""); setConfirmPw("");
      setTimeout(() => setPwUpdated(false), 2000);
    }
  };

  const renderSecurity = () => (
    <div>
      {sectionHeader("// SECURITY SETTINGS")}

      {subHeader("Change Password")}
      <div style={{ maxWidth: 440 }}>
        {fieldBlock("CURRENT PASSWORD", currentPw, setCurrentPw, "password", "••••••••")}
        {fieldBlock("NEW PASSWORD", newPw, setNewPw, "password", "••••••••")}
        {fieldBlock("CONFIRM NEW PASSWORD", confirmPw, setConfirmPw, "password", "••••••••")}
        {pwError && <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: '#FF4444', marginBottom: 10 }}>{pwError}</div>}
        <div style={{ marginBottom: 32 }}>
          <button disabled={pwUpdating} onClick={handleUpdatePassword} style={{
            background: pwUpdated ? t.accent : pwUpdating ? t.panelLine : t.accent,
            color: pwUpdating ? t.textDim : t.accentText,
            border: "none", borderRadius: 4, padding: "12px 22px", fontSize: 12, fontWeight: 900,
            cursor: pwUpdating ? "default" : "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}>
            {pwUpdated ? "// UPDATED ✓" : pwUpdating ? "// UPDATING…" : "UPDATE PASSWORD →"}
          </button>
        </div>
      </div>

      {subHeader("Two-Factor Authentication")}
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 20 }}>
        <SettingsToggle on={twoFAOn} onToggle={() => setTwoFAOn(v => !v)} accent={t.accent} />
        <div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase" }}>
            TWO-FACTOR AUTHENTICATION
          </div>
          <div style={{ fontSize: 12, color: t.textDim, marginTop: 3 }}>
            {twoFAOn ? "Enabled — scan QR code with your authenticator app" : "Add an extra layer of security to your account"}
          </div>
        </div>
      </div>
      {twoFAOn && (
        <div style={{ marginBottom: 28, maxWidth: 440 }}>
          {/* QR code placeholder — CSS grid pattern */}
          <div style={{
            width: 80, height: 80, background: "#111", marginBottom: 14,
            backgroundImage: `
              repeating-linear-gradient(0deg, rgba(57,255,106,0.15) 0px, rgba(57,255,106,0.15) 4px, transparent 4px, transparent 8px),
              repeating-linear-gradient(90deg, rgba(57,255,106,0.15) 0px, rgba(57,255,106,0.15) 4px, transparent 4px, transparent 8px)
            `,
            border: `2px solid ${t.accent}44`, borderRadius: 4, position: "relative",
          }}>
            <div style={{
              position: "absolute", top: "50%", left: "50%",
              transform: "translate(-50%, -50%)",
              width: 20, height: 20, background: t.accent, borderRadius: 2,
            }}/>
          </div>
          {fieldBlock("VERIFY CODE", tfaCode, setTfaCode, "text", "000000")}
          {accentBtn("ENABLE 2FA →", () => {})}
        </div>
      )}

      {subHeader("Recovery Email")}
      <div style={{ maxWidth: 440, marginBottom: 32 }}>
        {fieldBlock("RECOVERY EMAIL", recoveryEmail, setRecoveryEmail, "email", "backup@example.com")}
        {accentBtn("UPDATE →", () => {})}
      </div>

      <button onClick={async () => {
        await db.auth.signOut({ scope: 'global' });
        navigate('login');
      }} style={{
        width: "100%", background: "transparent", color: "#FF4444",
        border: "1px solid rgba(255,68,68,0.4)", borderRadius: 4,
        padding: "13px 0", fontSize: 12, fontWeight: 700, cursor: "pointer",
        fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
        maxWidth: 440,
      }}>SIGN OUT ALL SESSIONS →</button>
    </div>
  );

  const notifRows = [
    { key: "emailNotifications",    label: "EMAIL NOTIFICATIONS",    desc: "Receive important account updates via email" },
    { key: "pushNotifications",     label: "PUSH NOTIFICATIONS",     desc: "Browser push notifications for real-time alerts" },
    { key: "newCommentAlerts",      label: "NEW COMMENT ALERTS",     desc: "Get notified when someone comments on your work" },
    { key: "collaboratorActivity",  label: "COLLABORATOR ACTIVITY",  desc: "Updates when collaborators edit your projects" },
    { key: "marketplaceUpdates",    label: "MARKETPLACE UPDATES",    desc: "New items and sales notifications from the marketplace" },
    { key: "weeklyDigest",          label: "WEEKLY DIGEST",          desc: "A weekly summary of your activity and highlights" },
  ];

  const renderNotifications = () => (
    <div>
      {sectionHeader("// NOTIFICATION PREFERENCES")}
      <div style={{ maxWidth: 560 }}>
        {notifRows.map((row) => (
          <div key={row.key} style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "16px 0", borderBottom: `1px solid ${t.panelLine}`,
          }}>
            <div style={{ flex: 1, marginRight: 20 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 4 }}>
                {row.label}
              </div>
              <div style={{ fontSize: 12, color: t.textDim, lineHeight: 1.5 }}>
                {row.desc}
              </div>
            </div>
            <SettingsToggle
              on={notifToggles[row.key]}
              onToggle={() => setNotifToggles(prev => ({ ...prev, [row.key]: !prev[row.key] }))}
              accent={t.accent}
            />
          </div>
        ))}
        <div style={{ paddingTop: 24 }}>
          <button
            onClick={() => { setNotifSaved(true); setTimeout(() => setNotifSaved(false), 2500); }}
            style={{
              background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
              padding: "12px 22px", fontSize: 12, fontWeight: 900, cursor: "pointer",
              fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
            }}
          >{notifSaved ? "✓ SAVED" : "SAVE PREFERENCES →"}</button>
        </div>
      </div>
    </div>
  );

  const sessions = [
    { device: "laptop",  name: "MacBook Pro 16\"", browser: "Chrome 124",  ip: "192.168.1.14",  location: "New York, US",    last: "Now",          current: true  },
    { device: "mobile",  name: "iPhone 15 Pro",    browser: "Safari 17",   ip: "192.168.1.21",  location: "New York, US",    last: "2 hours ago",  current: false },
    { device: "desktop", name: "Windows PC",       browser: "Firefox 126", ip: "10.0.0.44",     location: "Brooklyn, US",    last: "Yesterday",    current: false },
  ];

  const DeviceIcon = ({ type }) => {
    if (type === "laptop") return (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="4" width="20" height="14" rx="2"/>
        <path d="M1 20h22"/>
      </svg>
    );
    if (type === "mobile") return (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="5" y="1" width="14" height="22" rx="2"/>
        <circle cx="12" cy="19" r="1" fill="currentColor"/>
      </svg>
    );
    return (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="3" width="20" height="14" rx="2"/>
        <path d="M8 21h8M12 17v4"/>
      </svg>
    );
  };

  const renderSessions = () => (
    <div>
      {sectionHeader("// ACTIVE SESSIONS")}
      <div style={{ maxWidth: 600 }}>
        {sessions.map((s, i) => (
          <div key={i} style={{
            display: "flex", alignItems: "center", gap: 16,
            padding: "18px 20px",
            background: s.current ? `${t.accent}08` : t.panel,
            border: `1px solid ${s.current ? t.accent + "44" : t.panelLine}`,
            borderRadius: 4, marginBottom: 10,
          }}>
            <div style={{ color: s.current ? t.accent : t.textDim, flexShrink: 0 }}>
              <DeviceIcon type={s.device}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                <span style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, letterSpacing: 0.5, textTransform: "uppercase" }}>
                  {s.name}
                </span>
                <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1 }}>
                  {s.browser}
                </span>
                {s.current && (
                  <span style={{
                    background: t.accent, color: t.accentText,
                    fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 900, letterSpacing: 1.5,
                    padding: "3px 8px", borderRadius: 3,
                  }}>CURRENT</span>
                )}
              </div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1 }}>
                {s.ip} · {s.location} · Last active: {s.last}
              </div>
            </div>
            {!s.current && (
              <button style={{
                background: "transparent", color: t.textDim,
                border: `1px solid ${t.panelLine}`, borderRadius: 4,
                padding: "7px 14px", fontSize: 10, fontWeight: 700, cursor: "pointer",
                fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase", flexShrink: 0,
              }}>SIGN OUT</button>
            )}
          </div>
        ))}
      </div>
    </div>
  );

  const privacyRows = [
    { key: "profileVisibility", label: "PROFILE VISIBILITY",  desc: "Allow others to view your public profile" },
    { key: "showInDiscover",    label: "SHOW IN DISCOVER",    desc: "Appear in the discover feed for new creators" },
    { key: "analyticsSharing",  label: "ANALYTICS SHARING",   desc: "Share anonymous usage data to improve VLStudio" },
  ];

  const renderDataPrivacy = () => (
    <div>
      {sectionHeader("// DATA & PRIVACY")}

      {subHeader("Data Export")}
      <div style={{ maxWidth: 500, marginBottom: 32 }}>
        <p style={{ color: t.textDim, fontSize: 13, lineHeight: 1.6, margin: "0 0 16px" }}>
          Request a full export of all your account data including projects, settings, and activity logs.
        </p>
        {exportQueued ? (
          <div style={{
            fontFamily: DISPLAY_B, fontSize: 11, color: t.accent,
            letterSpacing: 2, textTransform: "uppercase",
            border: `1px solid ${t.accent}44`, borderRadius: 4,
            padding: "12px 18px", display: "inline-block",
          }}>
            // EXPORT QUEUED
          </div>
        ) : (
          <button
            onClick={async () => {
              if (!user) return;
              const { error } = await db.from('supportrequest').insert({
                user_id: user.id,
                name: profile?.username || '',
                email: user.email,
                subject: 'Data Export Request',
                message: 'User requested data export.',
                created_at: new Date().toISOString(),
              });
              if (!error) setExportQueued(true);
            }}
            style={{
              background: "transparent", color: t.text,
              border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "12px 22px", fontSize: 12, fontWeight: 700, cursor: "pointer",
              fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
            }}
          >REQUEST EXPORT →</button>
        )}
      </div>

      {subHeader("Privacy Settings")}
      <div style={{ maxWidth: 560 }}>
        {privacyRows.map((row) => (
          <div key={row.key} style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "16px 0", borderBottom: `1px solid ${t.panelLine}`,
          }}>
            <div style={{ flex: 1, marginRight: 20 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 4 }}>
                {row.label}
              </div>
              <div style={{ fontSize: 12, color: t.textDim, lineHeight: 1.5 }}>
                {row.desc}
              </div>
            </div>
            <SettingsToggle
              on={privacyToggles[row.key]}
              onToggle={() => setPrivacyToggles(prev => ({ ...prev, [row.key]: !prev[row.key] }))}
              accent={t.accent}
            />
          </div>
        ))}
      </div>
    </div>
  );

  const GoogleLogo = () => (
    <svg width="20" height="20" viewBox="0 0 18 18" style={{ flexShrink: 0 }}>
      <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z"/>
      <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z"/>
      <path fill="#FBBC05" d="M3.964 10.707c-.18-.54-.282-1.117-.282-1.707s.102-1.167.282-1.707V4.961H.957C.347 6.175 0 7.55 0 9s.348 2.825.957 4.039l3.007-2.332z"/>
      <path fill="#EA4335" d="M9 3.582c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.961L3.964 7.293C4.672 5.163 6.656 3.582 9 3.582z"/>
    </svg>
  );

  const YouTubeLogo = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" style={{ flexShrink: 0 }}>
      <rect width="24" height="24" rx="5" fill="#FF0000"/>
      <polygon points="10,8 17,12 10,16" fill="#fff"/>
    </svg>
  );

  const renderConnectedAccounts = () => (
    <div>
      {sectionHeader("// CONNECTED ACCOUNTS")}
      <div style={{ maxWidth: 520 }}>

        {/* Google */}
        <div style={{
          display: "flex", alignItems: "center", gap: 16,
          padding: "20px 22px",
          background: t.panel, border: `1px solid ${t.panelLine}`,
          borderRadius: 4, marginBottom: 12,
        }}>
          <GoogleLogo/>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 4 }}>
              Google
            </div>
            {(() => {
              const providers = user?.app_metadata?.providers || [];
              const isGoogleConnected = providers.includes('google');
              return isGoogleConnected ? (
                <>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 7, height: 7, borderRadius: 99, background: "#34A853", flexShrink: 0 }}/>
                    <span style={{ fontSize: 12, color: t.textDim }}>Connected as {user?.email}</span>
                  </div>
                </>
              ) : (
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{ width: 7, height: 7, borderRadius: 99, background: t.textDim, flexShrink: 0 }}/>
                  <span style={{ fontSize: 12, color: t.textDim }}>Not connected</span>
                </div>
              );
            })()}
          </div>
          {(() => {
            const providers = user?.app_metadata?.providers || [];
            const isGoogleConnected = providers.includes('google');
            return isGoogleConnected ? (
              <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", cursor: "default", textDecoration: "underline" }}>CONNECTED</span>
            ) : (
              <button onClick={() => signInWithGoogle()} style={{ background: "transparent", color: t.text, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "8px 14px", fontSize: 10, fontWeight: 700, cursor: "pointer", fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase" }}>
                CONNECT GOOGLE →
              </button>
            );
          })()}
        </div>

        {/* YouTube */}
        <div style={{
          display: "flex", alignItems: "center", gap: 16,
          padding: "20px 22px",
          background: t.panel, border: `1px solid ${t.panelLine}`,
          borderRadius: 4, marginBottom: 12,
        }}>
          <YouTubeLogo/>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 4 }}>
              YouTube
            </div>
            {youtubeConnected ? (
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 7, height: 7, borderRadius: 99, background: "#FF0000", flexShrink: 0 }}/>
                <span style={{ fontSize: 12, color: t.textDim }}>Connected</span>
              </div>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 7, height: 7, borderRadius: 99, background: t.textDim, flexShrink: 0 }}/>
                <span style={{ fontSize: 12, color: t.textDim }}>Not connected</span>
              </div>
            )}
          </div>
          {youtubeConnected ? (
            <span
              onClick={() => setYoutubeConnected(false)}
              style={{
                fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim,
                letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
                textDecoration: "underline",
              }}
            >DISCONNECT</span>
          ) : (
            <button
              onClick={() => setYoutubeConnected(true)}
              style={{
                background: "transparent", color: t.text,
                border: `1px solid ${t.panelLine}`, borderRadius: 4,
                padding: "8px 14px", fontSize: 10, fontWeight: 700, cursor: "pointer",
                fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
              }}
            >CONNECT →</button>
          )}
        </div>

      </div>
    </div>
  );

  const tabContent = {
    "PROFILE":            renderProfile(),
    "SECURITY":           renderSecurity(),
    "NOTIFICATIONS":      renderNotifications(),
    "SESSIONS":           renderSessions(),
    "DATA & PRIVACY":     renderDataPrivacy(),
    "CONNECTED ACCOUNTS": renderConnectedAccounts(),
  };

  return (
    <div style={{ background: t.bg, minHeight: "calc(100vh - 65px)", display: "flex" }}>
      <style>{`
        .settings-tab-btn:hover { background: rgba(255,255,255,0.05) !important; }
      `}</style>

      {/* ── LEFT TAB NAV ── */}
      <div style={{
        width: 200, flexShrink: 0,
        borderRight: `1px solid ${t.panelLine}`,
        position: "sticky", top: 65,
        height: "calc(100vh - 65px)",
        overflowY: "auto",
        paddingTop: 32,
      }}>
        <div style={{
          fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim,
          letterSpacing: 3, textTransform: "uppercase",
          padding: "0 20px 16px",
          borderBottom: `1px solid ${t.panelLine}`,
          marginBottom: 8,
        }}>// SETTINGS</div>
        {TABS.map(tab => {
          const isActive = activeTab === tab;
          return (
            <button
              key={tab}
              className="settings-tab-btn"
              onClick={() => setActiveTab(tab)}
              style={{
                display: "block", width: "100%", textAlign: "left",
                background: isActive ? `${t.accent}10` : "transparent",
                border: "none",
                borderLeft: `3px solid ${isActive ? t.accent : "transparent"}`,
                padding: "12px 18px 12px 17px",
                fontFamily: DISPLAY_B, fontSize: 10, fontWeight: isActive ? 800 : 500,
                letterSpacing: 1.5, textTransform: "uppercase",
                color: isActive ? t.accent : t.textDim,
                cursor: "pointer",
                transition: "all 0.15s ease",
              }}
            >{tab}</button>
          );
        })}
      </div>

      {/* ── MAIN CONTENT ── */}
      <div style={{ flex: 1, padding: "36px 48px", overflowY: "auto" }}>
        <div style={{ maxWidth: 680 }}>
          {tabContent[activeTab]}
        </div>
      </div>
    </div>
  );
}
function AdminScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile } = useAuth();

  // Admin guard — render in place to prevent flash
  if (profile !== null && profile?.role !== 'admin') {
    return (
      <div style={{ minHeight: 'calc(100vh - 65px)', background: t.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20 }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 64, fontWeight: 900, color: '#FF4444', letterSpacing: -2 }}>403</div>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 22, fontWeight: 900, color: '#FF4444', letterSpacing: -0.5 }}>// ACCESS DENIED</div>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: t.textDim, letterSpacing: 2 }}>ADMINISTRATOR ACCESS REQUIRED</div>
        <button onClick={() => navigate('dashboard')} style={{ background: t.accent, color: t.accentText, border: 'none', borderRadius: 4, padding: '12px 28px', fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 900, letterSpacing: 2, textTransform: 'uppercase', cursor: 'pointer' }}>
          ← BACK TO DASHBOARD
        </button>
      </div>
    );
  }

  const TABS = ["CONTENT REPORTS", "USER MANAGEMENT", "DISPUTES", "AUDIT LOG", "SECURITY"];
  const [activeTab, setActiveTab] = React.useState("CONTENT REPORTS");

  // ── CONTENT REPORTS state ──
  const [reports, setReports] = React.useState([
    { id: 1, type: "POST",    reason: "Spam / misleading content",      reporter: "@m_torres",   date: "Jun 03", status: "PENDING"  },
    { id: 2, type: "COMMENT", reason: "Harassment and hate speech",      reporter: "@j_reed",     date: "Jun 03", status: "PENDING"  },
    { id: 3, type: "PROFILE", reason: "Impersonation of another user",   reporter: "@ana_w",      date: "Jun 02", status: "RESOLVED" },
    { id: 4, type: "POST",    reason: "Copyright infringement",          reporter: "@theostyle",  date: "Jun 01", status: "DISMISSED"},
    { id: 5, type: "COMMENT", reason: "Explicit content / NSFW",         reporter: "@k_lang",     date: "May 31", status: "PENDING"  },
    { id: 6, type: "POST",    reason: "Misleading health information",    reporter: "@c_north",    date: "May 30", status: "RESOLVED" },
  ]);
  const [expandedReport, setExpandedReport] = React.useState(null);

  const reportExcerpts = {
    1: "\"Check out this tool that made me $5000 in 48 hours — it's completely free, just enter your card…\"",
    2: "\"You're an absolute moron and should be banned from posting. Nobody wants to see your garbage edits here.\"",
    3: "Profile name set to 'VLStudio Official Support' with logo copied from the platform.",
    4: "Entire soundtrack lifted from a commercially licensed album without attribution or permission.",
    5: "Thumbnail and first 10 seconds contain explicit nudity not marked as mature content.",
    6: "Post claims daily use of this supplement cures chronic illness — links to affiliate product.",
  };

  // Load real reports from DB
  React.useEffect(() => {
    if (!user) return;
    db.from('contentreport').select('*, profiles!reporter_id(username)').order('created_at', { ascending: false }).limit(50)
      .then(({ data }) => {
        if (data && data.length > 0) {
          setReports(data.map(r => ({
            id: r.id, type: (r.content_type || 'POST').toUpperCase(),
            reason: r.reason || '', reporter: '@' + (r.profiles?.username || 'user'),
            date: r.created_at?.slice(5, 10).replace('-', ' ') || '', status: (r.status || 'PENDING').toUpperCase(),
            details: r.details,
          })));
        }
      });
  }, [user?.id]);

  const updateReportStatus = async (id, status) => {
    setReports(prev => prev.map(r => r.id === id ? { ...r, status } : r));
    setExpandedReport(null);
    if (user && typeof id === 'number') {
      await db.from('contentreport').update({ status: status.toLowerCase(), reviewer_id: user.id, reviewed_at: new Date().toISOString() }).eq('id', id);
    }
  };

  // ── USER MANAGEMENT state ──
  const [userSearch, setUserSearch] = React.useState("");
  const [userRoleFilter, setUserRoleFilter] = React.useState("All");
  const [userStatusFilter, setUserStatusFilter] = React.useState("All");
  const [users, setUsers] = React.useState([
    { id: 1, initials: "MT", username: "m_torres",   role: "CREATOR", projects: 14, earnings: "$2,840", reports: 0, joined: "Jan 12", status: "ACTIVE"    },
    { id: 2, initials: "JR", username: "j_reed",     role: "CLIENT",  projects: 6,  earnings: "$740",   reports: 1, joined: "Feb 08", status: "ACTIVE"    },
    { id: 3, initials: "AW", username: "ana_w",      role: "CREATOR", projects: 22, earnings: "$5,190", reports: 0, joined: "Nov 04", status: "ACTIVE"    },
    { id: 4, initials: "TS", username: "theostyle",  role: "CREATOR", projects: 9,  earnings: "$1,630", reports: 2, joined: "Mar 17", status: "ACTIVE"    },
    { id: 5, initials: "KL", username: "k_lang",     role: "CLIENT",  projects: 3,  earnings: "$320",   reports: 0, joined: "Apr 29", status: "SUSPENDED" },
    { id: 6, initials: "CN", username: "c_north",    role: "ADMIN",   projects: 0,  earnings: "—",      reports: 0, joined: "Oct 01", status: "ACTIVE"    },
  ]);
  const [suspendModal, setSuspendModal] = React.useState(null); // userId
  const [suspendReason, setSuspendReason] = React.useState("");
  const [suspendDuration, setSuspendDuration] = React.useState("1 week");

  // Load real users from DB
  React.useEffect(() => {
    if (!user) return;
    db.from('profiles').select('id, username, role, created_at, suspended').order('created_at', { ascending: false }).limit(100)
      .then(({ data }) => {
        if (data && data.length > 0) {
          setUsers(data.map(u => ({
            id: u.id, initials: (u.username || '?')[0].toUpperCase() + (u.username?.[1] || '?').toUpperCase(),
            username: u.username || 'Unknown', role: (u.role || 'creator').toUpperCase(),
            projects: 0, earnings: '—', reports: 0,
            joined: u.created_at?.slice(0, 10) || '—',
            status: u.suspended ? 'SUSPENDED' : 'ACTIVE',
          })));
        }
      });
  }, [user?.id]);

  const filteredUsers = users.filter(u => {
    const matchSearch = !userSearch || u.username.toLowerCase().includes(userSearch.toLowerCase());
    const matchRole   = userRoleFilter === "All" || u.role === userRoleFilter.toUpperCase();
    const matchStatus = userStatusFilter === "All" || u.status === userStatusFilter.toUpperCase();
    return matchSearch && matchRole && matchStatus;
  });

  const confirmSuspend = async () => {
    setUsers(prev => prev.map(u => u.id === suspendModal ? { ...u, status: "SUSPENDED" } : u));
    if (suspendModal) {
      await db.from('profiles').update({ suspended: true, suspend_reason: suspendReason, suspend_until: suspendDuration }).eq('id', suspendModal);
    }
    setSuspendModal(null);
    setSuspendReason("");
    setSuspendDuration("1 week");
  };

  // ── DISPUTES state ──
  const [disputes, setDisputes] = React.useState([
    { id: 1, buyer: "@j_reed",    seller: "@m_torres",  reason: "Deliverable didn't match project brief",    amount: "$480",  date: "Jun 03", status: "OPEN",     resolved: false },
    { id: 2, buyer: "@c_north",   seller: "@theostyle", reason: "Work delivered 2 weeks late with no notice", amount: "$220",  date: "Jun 02", status: "OPEN",     resolved: false },
    { id: 3, buyer: "@k_lang",    seller: "@ana_w",     reason: "Final file missing promised assets",         amount: "$950",  date: "Jun 01", status: "RESOLVED", resolved: true  },
    { id: 4, buyer: "@v_jones",   seller: "@m_torres",  reason: "Revision requests ignored after payment",    amount: "$310",  date: "May 30", status: "OPEN",     resolved: false },
    { id: 5, buyer: "@p_chen",    seller: "@k_lang",    reason: "Incorrect format — can't use deliverable",   amount: "$175",  date: "May 29", status: "RESOLVED", resolved: true  },
    { id: 6, buyer: "@s_malik",   seller: "@ana_w",     reason: "Watermarked preview sent as final file",     amount: "$640",  date: "May 28", status: "OPEN",     resolved: false },
  ]);
  const [disputeModal, setDisputeModal] = React.useState(null); // { id, action }
  const [refundPct, setRefundPct] = React.useState(50);

  const resolveDispute = (id, resolution) => {
    setDisputes(prev => prev.map(d => d.id === id ? { ...d, status: resolution, resolved: true } : d));
    setDisputeModal(null);
    setRefundPct(50);
  };

  const getDisputeAmount = (dispute) => {
    if (!dispute) return "$0";
    const raw = parseFloat(dispute.amount.replace("$","").replace(",","")) || 0;
    return raw;
  };

  // ── SECURITY state ──
  const [enforce2FA, setEnforce2FA] = React.useState(false);
  const [ipWhitelist, setIpWhitelist] = React.useState("192.168.1.0/24\n10.0.0.1\n10.0.0.44");
  const [taxRate, setTaxRate] = React.useState("8.5");
  const [taxSaved, setTaxSaved] = React.useState(false);
  const [ipSaved, setIpSaved] = React.useState(false);

  const handleTaxUpdate = () => {
    setTaxSaved(true);
    setTimeout(() => setTaxSaved(false), 2000);
  };
  const handleIpSave = () => {
    setIpSaved(true);
    setTimeout(() => setIpSaved(false), 2000);
  };

  // ── style helpers ──
  const sectionHeader = (text) => (
    <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 3, textTransform: "uppercase", marginBottom: 20 }}>
      {text}
    </div>
  );

  const typeBadgeColor = { POST: "#7CD3FF", COMMENT: "#FFB347", PROFILE: "#C9A0FF" };
  const statusBadgeColor = {
    PENDING:   { color: "#FFD166", border: "rgba(255,209,102,0.35)" },
    RESOLVED:  { color: t.accent,  border: `${t.accent}44` },
    DISMISSED: { color: t.textDim, border: t.panelLine },
    SUSPENDED: { color: "#FF4444", border: "rgba(255,68,68,0.4)" },
    OPEN:      { color: "#FFD166", border: "rgba(255,209,102,0.35)" },
    "FAVOR BUYER":        { color: t.accent,  border: `${t.accent}44` },
    "FAVOR SELLER":       { color: t.accent,  border: `${t.accent}44` },
    "PARTIAL REFUND":     { color: "#FFD166", border: "rgba(255,209,102,0.35)" },
  };

  const StatusBadge = ({ status }) => {
    const sc = statusBadgeColor[status] || { color: t.textDim, border: t.panelLine };
    return (
      <span style={{
        fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1.5,
        textTransform: "uppercase", color: sc.color,
        border: `1px solid ${sc.border}`, borderRadius: 3, padding: "3px 7px",
        whiteSpace: "nowrap",
      }}>{status}</span>
    );
  };

  const adminInput = (value, onChange, type = "text", placeholder = "") => (
    <input
      type={type} value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        width: "100%", background: "#000", color: t.text,
        border: `1px solid ${t.panelLine}`, borderRadius: 4,
        padding: "10px 14px", fontSize: 13, fontFamily: "inherit",
        outline: "none", boxSizing: "border-box",
      }}
      onFocus={(e) => e.target.style.borderColor = t.accent}
      onBlur={(e) => e.target.style.borderColor = t.panelLine}
    />
  );

  // ── TAB: CONTENT REPORTS ──
  const renderContentReports = () => {
    const total    = reports.length;
    const pending  = reports.filter(r => r.status === "PENDING").length;
    const resolved = reports.filter(r => r.status === "RESOLVED").length;

    return (
      <div>
        {sectionHeader("// CONTENT REPORTS")}
        {/* Summary row */}
        <div style={{ display: "flex", gap: 12, marginBottom: 24 }}>
          {[
            { label: "TOTAL",          value: 142 },
            { label: "PENDING REVIEW", value: 28  },
            { label: "RESOLVED",       value: 114 },
          ].map(c => (
            <div key={c.label} style={{
              background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "14px 20px", minWidth: 120,
            }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 6 }}>
                {c.label}
              </div>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 26, fontWeight: 900, color: t.accent, letterSpacing: -0.5 }}>
                {c.value}
              </div>
            </div>
          ))}
        </div>

        {/* Table */}
        <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, overflow: "hidden" }}>
          {/* Header row */}
          <div style={{
            display: "grid", gridTemplateColumns: "90px 1fr 110px 80px 100px 90px",
            gap: 8, padding: "10px 16px",
            borderBottom: `1px solid ${t.panelLine}`,
            fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase",
          }}>
            <span>TYPE</span><span>REASON</span><span>REPORTER</span>
            <span>DATE</span><span>STATUS</span><span></span>
          </div>

          {reports.map(r => (
            <React.Fragment key={r.id}>
              <div style={{
                display: "grid", gridTemplateColumns: "90px 1fr 110px 80px 100px 90px",
                gap: 8, padding: "12px 16px", alignItems: "center",
                borderBottom: `1px solid ${t.panelLine}`,
                background: expandedReport === r.id ? `${t.accent}06` : "transparent",
              }}>
                {/* Type badge */}
                <span style={{
                  fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1.5,
                  textTransform: "uppercase", color: typeBadgeColor[r.type],
                  border: `1px solid ${typeBadgeColor[r.type]}55`, borderRadius: 3,
                  padding: "3px 7px", display: "inline-block",
                }}>{r.type}</span>
                {/* Reason */}
                <span style={{ fontSize: 12, color: t.text, lineHeight: 1.4 }}>{r.reason}</span>
                {/* Reporter */}
                <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 0.5 }}>{r.reporter}</span>
                {/* Date */}
                <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim }}>{r.date}</span>
                {/* Status */}
                <StatusBadge status={r.status}/>
                {/* Action */}
                <button
                  onClick={() => setExpandedReport(expandedReport === r.id ? null : r.id)}
                  style={{
                    background: "transparent", color: t.textDim,
                    border: `1px solid ${t.panelLine}`, borderRadius: 3,
                    padding: "5px 9px", fontSize: 10, fontWeight: 700, cursor: "pointer",
                    fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                    whiteSpace: "nowrap",
                  }}
                >REVIEW →</button>
              </div>

              {/* Inline detail panel */}
              {expandedReport === r.id && (
                <div style={{
                  borderBottom: `1px solid ${t.panelLine}`,
                  background: "#000", padding: "20px 24px",
                }}>
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 6 }}>
                      REPORTED CONTENT EXCERPT
                    </div>
                    <p style={{
                      fontStyle: "italic", color: t.textDim, fontSize: 13, lineHeight: 1.55,
                      margin: 0, borderLeft: `2px solid ${t.panelLine}`, paddingLeft: 14,
                    }}>
                      {reportExcerpts[r.id]}
                    </p>
                  </div>
                  <div style={{ marginBottom: 16, fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1 }}>
                    Reported by <span style={{ color: t.accent }}>{r.reporter}</span> · {r.date}
                  </div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button
                      onClick={() => updateReportStatus(r.id, "DISMISSED")}
                      style={{
                        background: "transparent", color: t.textDim,
                        border: `1px solid ${t.panelLine}`, borderRadius: 4,
                        padding: "8px 16px", fontSize: 10, fontWeight: 700, cursor: "pointer",
                        fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                      }}
                    >DISMISS</button>
                    <button
                      onClick={() => updateReportStatus(r.id, "RESOLVED")}
                      style={{
                        background: "transparent", color: "#FF4444",
                        border: "1px solid rgba(255,68,68,0.5)", borderRadius: 4,
                        padding: "8px 16px", fontSize: 10, fontWeight: 700, cursor: "pointer",
                        fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                      }}
                    >REMOVE CONTENT</button>
                    <button
                      onClick={() => updateReportStatus(r.id, "RESOLVED")}
                      style={{
                        background: "transparent", color: t.accent,
                        border: `1px solid ${t.accent}55`, borderRadius: 4,
                        padding: "8px 16px", fontSize: 10, fontWeight: 700, cursor: "pointer",
                        fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                      }}
                    >WARN USER</button>
                  </div>
                </div>
              )}
            </React.Fragment>
          ))}
        </div>
      </div>
    );
  };

  // ── TAB: USER MANAGEMENT ──
  const renderUserManagement = () => (
    <div>
      {sectionHeader("// USER MANAGEMENT")}

      {/* Search + filters */}
      <div style={{ display: "flex", gap: 10, marginBottom: 20, flexWrap: "wrap" }}>
        <input
          value={userSearch}
          onChange={e => setUserSearch(e.target.value)}
          placeholder="Search username…"
          style={{
            flex: 1, minWidth: 180, background: "#000", color: t.text,
            border: `1px solid ${t.panelLine}`, borderRadius: 4,
            padding: "9px 14px", fontSize: 12, fontFamily: DISPLAY_B,
            outline: "none", letterSpacing: 0.5,
          }}
          onFocus={e => e.target.style.borderColor = t.accent}
          onBlur={e => e.target.style.borderColor = t.panelLine}
        />
        {[
          { label: "ROLE", value: userRoleFilter, set: setUserRoleFilter, opts: ["All","Creator","Client","Admin"] },
          { label: "STATUS", value: userStatusFilter, set: setUserStatusFilter, opts: ["All","Active","Suspended"] },
        ].map(f => (
          <select
            key={f.label}
            value={f.value}
            onChange={e => f.set(e.target.value)}
            style={{
              background: "#000", color: t.textDim, border: `1px solid ${t.panelLine}`,
              borderRadius: 4, padding: "9px 12px", fontSize: 11, fontFamily: DISPLAY_B,
              letterSpacing: 1, textTransform: "uppercase", outline: "none", cursor: "pointer",
            }}
          >
            {f.opts.map(o => <option key={o}>{o}</option>)}
          </select>
        ))}
      </div>

      {/* Table */}
      <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, overflow: "hidden" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "36px 130px 80px 70px 90px 60px 70px 140px",
          gap: 8, padding: "10px 16px",
          borderBottom: `1px solid ${t.panelLine}`,
          fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase",
        }}>
          <span></span><span>USERNAME</span><span>ROLE</span><span>PROJECTS</span>
          <span>EARNINGS</span><span>REPORTS</span><span>JOINED</span><span>ACTIONS</span>
        </div>

        {filteredUsers.map(u => (
          <div
            key={u.id}
            style={{
              display: "grid", gridTemplateColumns: "36px 130px 80px 70px 90px 60px 70px 140px",
              gap: 8, padding: "11px 16px", alignItems: "center",
              borderBottom: `1px solid ${t.panelLine}`,
              opacity: u.status === "SUSPENDED" ? 0.6 : 1,
            }}
          >
            {/* Avatar */}
            <div style={{
              width: 28, height: 28, borderRadius: 99,
              background: `${t.accent}18`, border: `1px solid ${t.accent}44`,
              display: "flex", alignItems: "center", justifyContent: "center",
              fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 900, color: t.accent,
            }}>{u.initials}</div>
            {/* Username */}
            <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.text, letterSpacing: 0.5 }}>@{u.username}</span>
            {/* Role badge */}
            <span style={{
              fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1.5,
              textTransform: "uppercase", color: u.role === "ADMIN" ? "#C9A0FF" : u.role === "CREATOR" ? t.accent : "#7CD3FF",
              border: `1px solid ${u.role === "ADMIN" ? "#C9A0FF55" : u.role === "CREATOR" ? `${t.accent}44` : "#7CD3FF55"}`,
              borderRadius: 3, padding: "3px 7px", display: "inline-block",
            }}>{u.role}</span>
            {/* Projects */}
            <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim }}>{u.projects}</span>
            {/* Earnings */}
            <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent }}>{u.earnings}</span>
            {/* Reports */}
            <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: u.reports > 0 ? "#FF4444" : t.textDim }}>{u.reports}</span>
            {/* Joined */}
            <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim }}>{u.joined}</span>
            {/* Actions */}
            <div style={{ display: "flex", gap: 6 }}>
              {u.status === "SUSPENDED" ? (
                <span style={{
                  fontFamily: DISPLAY_B, fontSize: 9, fontWeight: 800, letterSpacing: 1,
                  textTransform: "uppercase", color: "#FF4444",
                  border: "1px solid rgba(255,68,68,0.4)", borderRadius: 3, padding: "3px 7px",
                }}>SUSPENDED</span>
              ) : (
                <>
                  <button style={{
                    background: "transparent", color: t.textDim, border: `1px solid ${t.panelLine}`,
                    borderRadius: 3, padding: "4px 8px", fontSize: 9, fontWeight: 700, cursor: "pointer",
                    fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                  }}>EDIT →</button>
                  <button
                    onClick={() => { setSuspendModal(u.id); setSuspendReason(""); setSuspendDuration("1 week"); }}
                    style={{
                      background: "transparent", color: "#FF4444",
                      border: "1px solid rgba(255,68,68,0.5)", borderRadius: 3,
                      padding: "4px 8px", fontSize: 9, fontWeight: 700, cursor: "pointer",
                      fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                    }}
                  >SUSPEND →</button>
                </>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Suspend Modal */}
      <Modal
        open={suspendModal !== null}
        onClose={() => setSuspendModal(null)}
        t={t}
        subtitle="// USER MANAGEMENT"
        title="SUSPEND USER?"
      >
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6 }}>
            REASON
          </div>
          <textarea
            value={suspendReason}
            onChange={e => setSuspendReason(e.target.value)}
            placeholder="Describe the reason for suspension…"
            rows={3}
            style={{
              width: "100%", background: "#000", color: t.text,
              border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "10px 14px", fontSize: 13, fontFamily: "inherit",
              outline: "none", resize: "none", boxSizing: "border-box",
            }}
            onFocus={e => e.target.style.borderColor = t.accent}
            onBlur={e => e.target.style.borderColor = t.panelLine}
          />
        </div>
        <div style={{ marginBottom: 20 }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 8 }}>
            DURATION
          </div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {["1 day", "1 week", "1 month", "Permanent"].map(d => (
              <button
                key={d}
                onClick={() => setSuspendDuration(d)}
                style={{
                  padding: "7px 14px", fontSize: 11, fontWeight: 700,
                  fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
                  cursor: "pointer", borderRadius: 3,
                  background: suspendDuration === d ? "rgba(255,68,68,0.15)" : "transparent",
                  border: `1px solid ${suspendDuration === d ? "rgba(255,68,68,0.6)" : t.panelLine}`,
                  color: suspendDuration === d ? "#FF4444" : t.textDim,
                }}
              >{d}</button>
            ))}
          </div>
        </div>
        <button
          onClick={confirmSuspend}
          style={{
            width: "100%", background: "rgba(255,68,68,0.12)", color: "#FF4444",
            border: "1px solid rgba(255,68,68,0.5)", borderRadius: 4,
            padding: "12px", fontSize: 12, fontWeight: 900, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
          }}
        >CONFIRM SUSPEND →</button>
      </Modal>
    </div>
  );

  // ── TAB: DISPUTES ──
  const renderDisputes = () => (
    <div>
      {sectionHeader("// DISPUTES")}
      <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, overflow: "hidden" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "100px 100px 1fr 80px 70px 90px 200px",
          gap: 8, padding: "10px 16px",
          borderBottom: `1px solid ${t.panelLine}`,
          fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase",
        }}>
          <span>BUYER</span><span>SELLER</span><span>REASON</span>
          <span>AMOUNT</span><span>DATE</span><span>STATUS</span><span>ACTIONS</span>
        </div>

        {disputes.map(d => (
          <div key={d.id} style={{
            display: "grid", gridTemplateColumns: "100px 100px 1fr 80px 70px 90px 200px",
            gap: 8, padding: "12px 16px", alignItems: "center",
            borderBottom: `1px solid ${t.panelLine}`,
            opacity: d.resolved ? 0.55 : 1,
          }}>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 0.5 }}>{d.buyer}</span>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 0.5 }}>{d.seller}</span>
            <span style={{ fontSize: 11, color: t.text, lineHeight: 1.4 }}>{d.reason}</span>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.accent, fontWeight: 700 }}>{d.amount}</span>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim }}>{d.date}</span>
            <StatusBadge status={d.status}/>
            <div style={{ display: "flex", gap: 4 }}>
              {["FAVOR BUYER", "FAVOR SELLER", "PARTIAL REFUND"].map(action => (
                <button
                  key={action}
                  disabled={d.resolved}
                  onClick={() => { if (!d.resolved) setDisputeModal({ id: d.id, action }); }}
                  style={{
                    background: "transparent",
                    color: d.resolved ? t.textDim : (action === "FAVOR BUYER" ? t.accent : action === "FAVOR SELLER" ? "#7CD3FF" : "#FFD166"),
                    border: `1px solid ${d.resolved ? t.panelLine : (action === "FAVOR BUYER" ? `${t.accent}44` : action === "FAVOR SELLER" ? "#7CD3FF44" : "rgba(255,209,102,0.4)")}`,
                    borderRadius: 3, padding: "4px 7px", fontSize: 9, fontWeight: 700,
                    cursor: d.resolved ? "default" : "pointer",
                    fontFamily: DISPLAY_B, letterSpacing: 0.8, textTransform: "uppercase",
                    whiteSpace: "nowrap",
                  }}
                >{action === "PARTIAL REFUND" ? "PARTIAL" : action.split(" ")[1]}</button>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Dispute action modal */}
      {disputeModal && (() => {
        const d = disputes.find(x => x.id === disputeModal.id);
        const isPartial = disputeModal.action === "PARTIAL REFUND";
        const rawAmt = getDisputeAmount(d);
        const refundAmt = ((rawAmt * refundPct) / 100).toFixed(2);
        return (
          <Modal
            open={true}
            onClose={() => { setDisputeModal(null); setRefundPct(50); }}
            t={t}
            subtitle="// DISPUTES"
            title={`CONFIRM: ${disputeModal.action}`}
          >
            <p style={{ color: t.textDim, fontSize: 13, lineHeight: 1.6, margin: "0 0 16px" }}>
              {isPartial
                ? `Issue a partial refund on the $${rawAmt} transaction between ${d.buyer} and ${d.seller}.`
                : `Resolve this dispute in ${disputeModal.action === "FAVOR BUYER" ? d.buyer + "'s" : d.seller + "'s"} favor. Transaction amount: ${d.amount}.`}
            </p>
            {isPartial && (
              <div style={{ marginBottom: 20 }}>
                <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 8 }}>
                  REFUND PERCENTAGE
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <input
                    type="number" min={0} max={100} value={refundPct}
                    onChange={e => setRefundPct(Math.max(0, Math.min(100, Number(e.target.value))))}
                    style={{
                      width: 80, background: "#000", color: t.text,
                      border: `1px solid ${t.panelLine}`, borderRadius: 4,
                      padding: "9px 12px", fontSize: 14, fontFamily: DISPLAY_B,
                      outline: "none", textAlign: "center",
                    }}
                    onFocus={e => e.target.style.borderColor = t.accent}
                    onBlur={e => e.target.style.borderColor = t.panelLine}
                  />
                  <span style={{ fontFamily: DISPLAY_B, fontSize: 13, color: t.textDim }}>%</span>
                  <span style={{ fontFamily: DISPLAY_B, fontSize: 18, fontWeight: 900, color: t.accent }}>
                    = ${refundAmt}
                  </span>
                </div>
              </div>
            )}
            <div style={{ display: "flex", gap: 10 }}>
              <button
                onClick={() => resolveDispute(disputeModal.id, disputeModal.action)}
                style={{
                  flex: 1, background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
                  padding: "12px", fontSize: 12, fontWeight: 900, cursor: "pointer",
                  fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                }}
              >CONFIRM →</button>
              <button
                onClick={() => { setDisputeModal(null); setRefundPct(50); }}
                style={{
                  flex: 1, background: "transparent", color: t.textDim,
                  border: `1px solid ${t.panelLine}`, borderRadius: 4,
                  padding: "12px", fontSize: 12, fontWeight: 700, cursor: "pointer",
                  fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
                }}
              >CANCEL</button>
            </div>
          </Modal>
        );
      })()}
    </div>
  );

  // ── TAB: AUDIT LOG ──
  const [auditLog, setAuditLog] = React.useState([
    { actor: "admin@vlstudio.io",  action: "Suspended user account",          target: "@k_lang",      time: "Jun 05 · 09:14" },
    { actor: "admin@vlstudio.io",  action: "Removed reported content (POST)",  target: "post#8812",    time: "Jun 04 · 16:47" },
    { actor: "c_north@vlstudio.io",action: "Updated platform tax rate → 8.5%", target: "system",       time: "Jun 04 · 11:22" },
    { actor: "admin@vlstudio.io",  action: "Resolved dispute (FAVOR BUYER)",   target: "dispute#1029", time: "Jun 03 · 15:09" },
    { actor: "c_north@vlstudio.io",action: "Dismissed content report",         target: "report#0441",  time: "Jun 03 · 10:54" },
    { actor: "admin@vlstudio.io",  action: "Warned user for policy violation",  target: "@theostyle",   time: "Jun 02 · 14:31" },
    { actor: "c_north@vlstudio.io",action: "Updated IP whitelist",              target: "system",       time: "Jun 01 · 09:05" },
    { actor: "admin@vlstudio.io",  action: "Enforced 2FA policy for all users", target: "system",       time: "May 30 · 17:42" },
  ]);
  React.useEffect(() => {
    if (!user) return;
    db.from('admin_audit_log').select('*, profiles!actor_id(username, email)').order('created_at', { ascending: false }).limit(50)
      .then(({ data }) => {
        if (data && data.length > 0) {
          setAuditLog(data.map(e => ({
            actor: e.profiles?.email || e.profiles?.username || 'admin',
            action: e.action || '', target: e.target || 'system',
            time: e.created_at?.slice(0, 16).replace('T', ' · ').replace(/-/g, '-') || '',
          })));
        }
      });
  }, [user?.id]);

  const renderAuditLog = () => (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
        {sectionHeader("// AUDIT LOG")}
        <button style={{
          background: "transparent", color: t.textDim, border: `1px solid ${t.panelLine}`,
          borderRadius: 4, padding: "8px 16px", fontSize: 10, fontWeight: 700, cursor: "pointer",
          fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase", marginTop: -20,
        }}>EXPORT LOG →</button>
      </div>
      <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, overflow: "hidden" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "180px 1fr 120px 140px",
          gap: 8, padding: "10px 16px",
          borderBottom: `1px solid ${t.panelLine}`,
          fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase",
        }}>
          <span>ACTOR</span><span>ACTION</span><span>TARGET</span><span>TIMESTAMP</span>
        </div>
        {auditLog.map((row, i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "180px 1fr 120px 140px",
            gap: 8, padding: "12px 16px", alignItems: "center",
            borderBottom: i < auditLog.length - 1 ? `1px solid ${t.panelLine}` : "none",
          }}>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 0.5 }}>{row.actor}</span>
            <span style={{ fontSize: 12, color: t.text }}>{row.action}</span>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim, letterSpacing: 0.5 }}>{row.target}</span>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 10, color: t.textDim }}>{row.time}</span>
          </div>
        ))}
      </div>
    </div>
  );

  // ── TAB: SECURITY ──
  const renderSecurity = () => (
    <div>
      {sectionHeader("// SECURITY")}

      {/* Three panels side by side */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginBottom: 24 }}>

        {/* 2FA Policy */}
        <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px" }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 14 }}>
            2FA POLICY
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
            <SettingsToggle on={enforce2FA} onToggle={() => setEnforce2FA(v => !v)} accent={t.accent}/>
            <span style={{ fontFamily: DISPLAY_B, fontSize: 11, fontWeight: 700, letterSpacing: 1, color: t.text }}>
              ENFORCE FOR ALL USERS
            </span>
          </div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 10, color: enforce2FA ? t.accent : t.textDim, letterSpacing: 1.5 }}>
            {enforce2FA ? "✓ ENFORCED" : "NOT ENFORCED"}
          </div>
        </div>

        {/* Active Sessions */}
        <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px" }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 14 }}>
            ACTIVE SESSIONS
          </div>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 40, fontWeight: 900, color: t.accent, letterSpacing: -1, lineHeight: 1, marginBottom: 10 }}>
            247
          </div>
          <span style={{
            fontFamily: DISPLAY_B, fontSize: 10, color: t.accent, letterSpacing: 1.5,
            textTransform: "uppercase", textDecoration: "underline", cursor: "pointer",
          }}>VIEW ALL →</span>
        </div>

        {/* IP Whitelist */}
        <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px", display: "flex", flexDirection: "column" }}>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 10 }}>
            IP WHITELIST
          </div>
          <textarea
            value={ipWhitelist}
            onChange={e => setIpWhitelist(e.target.value)}
            placeholder={"One IP per line…"}
            rows={3}
            style={{
              flex: 1, background: "#000", color: t.text,
              border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "8px 10px", fontSize: 11, fontFamily: DISPLAY_B,
              outline: "none", resize: "none", marginBottom: 10, letterSpacing: 0.5,
            }}
            onFocus={e => e.target.style.borderColor = t.accent}
            onBlur={e => e.target.style.borderColor = t.panelLine}
          />
          <button
            onClick={handleIpSave}
            style={{
              background: "transparent", color: ipSaved ? t.accent : t.text,
              border: `1px solid ${ipSaved ? t.accent : t.panelLine}`, borderRadius: 4,
              padding: "7px 12px", fontSize: 10, fontWeight: 700, cursor: "pointer",
              fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
            }}
          >{ipSaved ? "// SAVED" : "SAVE WHITELIST →"}</button>
        </div>
      </div>

      {/* Platform Tax Rate */}
      <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "24px", maxWidth: 360 }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 14 }}>
          PLATFORM TAX RATE (%)
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
          <input
            type="number" step="0.1" min={0} max={100}
            value={taxRate}
            onChange={e => setTaxRate(e.target.value)}
            style={{
              width: 100, background: "#000", color: t.text,
              border: `1px solid ${t.panelLine}`, borderRadius: 4,
              padding: "10px 14px", fontSize: 18, fontFamily: DISPLAY_B,
              fontWeight: 900, outline: "none", letterSpacing: 0.5, textAlign: "center",
            }}
            onFocus={e => e.target.style.borderColor = t.accent}
            onBlur={e => e.target.style.borderColor = t.panelLine}
          />
          <button
            onClick={handleTaxUpdate}
            style={{
              background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
              padding: "10px 20px", fontSize: 11, fontWeight: 900, cursor: "pointer",
              fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase",
            }}
          >UPDATE →</button>
          {taxSaved && (
            <span style={{
              fontFamily: DISPLAY_B, fontSize: 11, color: t.accent,
              letterSpacing: 2, textTransform: "uppercase",
              animation: "vlfade .2s ease",
            }}>// SAVED</span>
          )}
        </div>
      </div>

      {/* TEST ERROR PAGES — developer shortcut */}
      <div style={{ background: t.panel, border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px 24px", maxWidth: 540, marginTop: 12 }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 9, color: t.textDim, letterSpacing: 2, textTransform: "uppercase", marginBottom: 14 }}>
          // DEV · TEST ERROR PAGES
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {[404, 403, 408, 429, 500, 503].map(code => (
            <button
              key={code}
              onClick={() => navigate("error-" + code)}
              style={{
                background: code >= 500 ? "rgba(255,68,68,0.1)" : "transparent",
                color: code >= 500 ? "#FF4444" : t.textDim,
                border: `1px solid ${code >= 500 ? "rgba(255,68,68,0.4)" : t.panelLine}`,
                borderRadius: 3, padding: "5px 12px", fontSize: 11, fontWeight: 700,
                cursor: "pointer", fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase",
              }}
            >{code}</button>
          ))}
        </div>
      </div>
    </div>
  );

  const tabContent = {
    "CONTENT REPORTS": renderContentReports(),
    "USER MANAGEMENT":  renderUserManagement(),
    "DISPUTES":         renderDisputes(),
    "AUDIT LOG":        renderAuditLog(),
    "SECURITY":         renderSecurity(),
  };

  return (
    <div style={{ background: t.bg, minHeight: "calc(100vh - 65px)", display: "flex" }}>
      <style>{`
        .admin-tab-btn:hover { background: rgba(255,255,255,0.05) !important; }
      `}</style>

      {/* ── LEFT TAB NAV ── */}
      <div style={{
        width: 220, flexShrink: 0,
        borderRight: `1px solid ${t.panelLine}`,
        position: "sticky", top: 65,
        height: "calc(100vh - 65px)",
        overflowY: "auto",
        paddingTop: 32,
      }}>
        <div style={{
          fontFamily: DISPLAY_B, fontSize: 9, color: "#FF4444",
          letterSpacing: 3, textTransform: "uppercase",
          padding: "0 20px 16px",
          borderBottom: `1px solid ${t.panelLine}`,
          marginBottom: 8,
          display: "flex", alignItems: "center", gap: 8,
        }}>
          <span>// ADMIN PANEL</span>
        </div>
        {TABS.map(tab => {
          const isActive = activeTab === tab;
          return (
            <button
              key={tab}
              className="admin-tab-btn"
              onClick={() => setActiveTab(tab)}
              style={{
                display: "block", width: "100%", textAlign: "left",
                background: isActive ? "rgba(255,68,68,0.08)" : "transparent",
                border: "none",
                borderLeft: `3px solid ${isActive ? "#FF4444" : "transparent"}`,
                padding: "12px 18px 12px 17px",
                fontFamily: DISPLAY_B, fontSize: 10, fontWeight: isActive ? 800 : 500,
                letterSpacing: 1.5, textTransform: "uppercase",
                color: isActive ? "#FF4444" : t.textDim,
                cursor: "pointer",
                transition: "all 0.15s ease",
              }}
            >{tab}</button>
          );
        })}
      </div>

      {/* ── MAIN CONTENT ── */}
      <div style={{ flex: 1, padding: "36px 48px", overflowY: "auto" }}>
        <div style={{ maxWidth: 900 }}>
          {tabContent[activeTab]}
        </div>
      </div>
    </div>
  );
}
function SupportScreen({ t, navigate }) {
  useRequireAuth(navigate);
  const { user, profile } = useAuth();
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [subject, setSubject] = React.useState("");
  const [message, setMessage] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState("");
  const ticketNum = React.useRef("VLS-" + Date.now().toString(36).toUpperCase());

  // Pre-fill name and email from real profile
  React.useEffect(() => {
    if (profile?.username) setName(profile.username);
    if (user?.email) setEmail(user.email);
  }, [profile, user]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name || !email || !subject || !message) return;
    setSubmitting(true);
    setSubmitError("");
    const { error } = await db.from('supportrequest').insert({
      user_id: user?.id,
      name,
      email,
      subject,
      message,
      status: 'open',
      created_at: new Date().toISOString(),
    });
    setSubmitting(false);
    if (error) { setSubmitError('// ERROR: ' + error.message); }
    else { setSubmitted(true); }
  };

  return (
    <div style={{ minHeight: "calc(100vh - 65px)", overflowY: "auto", background: t.bg, padding: "64px 24px" }}>
      <div style={{ maxWidth: 600, margin: "0 auto" }}>
        {/* Header */}
        <h1 style={{
          fontFamily: DISPLAY_B, fontSize: 56, fontWeight: 900, letterSpacing: -2,
          margin: "0 0 48px", textTransform: "uppercase",
        }}>// SUPPORT</h1>

        {!submitted ? (
          <form onSubmit={handleSubmit} style={{ marginBottom: 56 }}>
            <FieldB t={t} label="Name" value={name} onChange={setName} placeholder="Your name"/>
            <FieldB t={t} label="Email" type="email" value={email} onChange={setEmail} placeholder="you@studio.com"/>
            <FieldB t={t} label="Subject" value={subject} onChange={setSubject} placeholder="Brief summary of your issue"/>
            <label style={{ display: "block", marginBottom: 24 }}>
              <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6 }}>
                Message
              </div>
              <textarea
                value={message} onChange={e => setMessage(e.target.value)}
                rows={6} placeholder="Describe your issue in detail…"
                style={{
                  width: "100%", background: "#000", color: t.text, border: `1px solid ${t.panelLine}`,
                  borderRadius: 4, padding: "12px 14px", fontSize: 14, fontFamily: "inherit",
                  outline: "none", resize: "vertical", boxSizing: "border-box",
                }}
                onFocus={e => e.target.style.borderColor = t.accent}
                onBlur={e => e.target.style.borderColor = t.panelLine}
              />
            </label>
            {submitError && <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: '#FF4444', marginBottom: 12 }}>{submitError}</div>}
            <button type="submit" disabled={submitting} style={{
              background: submitting ? t.panelLine : t.accent,
              color: submitting ? t.textDim : t.accentText,
              border: "none", borderRadius: 4,
              padding: "14px 24px", fontSize: 13, fontWeight: 900,
              cursor: submitting ? "default" : "pointer",
              fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase",
            }}>{submitting ? "// SUBMITTING…" : "SUBMIT REQUEST →"}</button>
          </form>
        ) : (
          <div style={{ marginBottom: 56 }}>
            <div style={{
              fontFamily: DISPLAY_B, fontSize: 18, fontWeight: 900, color: t.accent,
              letterSpacing: -0.5, margin: "0 0 12px", textTransform: "uppercase",
            }}>
              // REQUEST SUBMITTED · WE'LL RESPOND WITHIN 24H
            </div>
            <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 2, margin: "0 0 20px" }}>
              Ticket {ticketNum.current}
            </div>
            <span
              onClick={() => { setSubmitted(false); setName(profile?.username || ""); setSubject(""); setMessage(""); }}
              style={{
                fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1.5,
                textTransform: "uppercase", textDecoration: "underline", cursor: "pointer",
              }}
            >SUBMIT ANOTHER →</span>
          </div>
        )}

        {/* Info cards */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          {[
            { label: "DOCS →",      desc: "Guides, tutorials, and API reference for VLStudio." },
            { label: "CHANGELOG →", desc: "What's new in every release, from beta onwards." },
            { label: "STATUS →",    desc: "Real-time platform health and incident updates." },
          ].map(card => (
            <div key={card.label} style={{ border: `1px solid ${t.panelLine}`, borderRadius: 4, padding: "20px" }}>
              <div style={{
                fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 700, color: t.textDim,
                letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 8,
              }}>{card.label}</div>
              <div style={{ fontSize: 12, color: t.textDim, lineHeight: 1.5 }}>{card.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---- Reset Password Screen ----
function ResetPasswordScreen({ t, navigate }) {
  const params = new URLSearchParams(window.location.search);
  const tokenHash = params.get('token_hash');
  const tokenType = params.get('type');

  const [verifying, setVerifying] = React.useState(!!tokenHash);
  const [verified, setVerified] = React.useState(false);
  const [verifyError, setVerifyError] = React.useState("");
  const [newPassword, setNewPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [updating, setUpdating] = React.useState(false);
  const [updateError, setUpdateError] = React.useState("");
  const [updated, setUpdated] = React.useState(false);

  React.useEffect(() => {
    if (!tokenHash || !tokenType) { setVerifying(false); return; }
    db.auth.verifyOtp({ token_hash: tokenHash, type: 'recovery' })
      .then(({ error }) => {
        setVerifying(false);
        if (error) { setVerifyError('// INVALID OR EXPIRED LINK · ' + error.message); }
        else { setVerified(true); }
      });
  }, []);

  const handleSetPassword = async (e) => {
    e.preventDefault();
    if (newPassword.length < 8) { setUpdateError('// MIN 8 CHARACTERS'); return; }
    if (newPassword !== confirmPassword) { setUpdateError('// PASSWORDS DO NOT MATCH'); return; }
    setUpdating(true);
    setUpdateError("");
    const { error } = await db.auth.updateUser({ password: newPassword });
    setUpdating(false);
    if (error) { setUpdateError('// ERROR: ' + error.message); }
    else {
      setUpdated(true);
      setTimeout(() => navigate('login'), 2000);
    }
  };

  if (verifying) {
    return (
      <div style={{ minHeight: '100vh', background: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 13, color: t.accent, letterSpacing: 3 }}>// VERIFYING LINK…</div>
      </div>
    );
  }

  if (!tokenHash || !tokenType) {
    return (
      <div style={{ minHeight: '100vh', background: t.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20 }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 22, fontWeight: 900, color: '#FF4444', letterSpacing: -0.5 }}>// INVALID OR EXPIRED LINK</div>
        <button onClick={() => navigate('login')} style={{ background: t.accent, color: t.accentText, border: 'none', borderRadius: 4, padding: '12px 28px', fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 900, letterSpacing: 2, textTransform: 'uppercase', cursor: 'pointer' }}>
          REQUEST NEW LINK →
        </button>
      </div>
    );
  }

  if (verifyError) {
    return (
      <div style={{ minHeight: '100vh', background: t.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20 }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 16, color: '#FF4444', letterSpacing: 1 }}>{verifyError}</div>
        <button onClick={() => navigate('login')} style={{ background: t.accent, color: t.accentText, border: 'none', borderRadius: 4, padding: '12px 28px', fontFamily: DISPLAY_B, fontSize: 12, fontWeight: 900, letterSpacing: 2, textTransform: 'uppercase', cursor: 'pointer' }}>
          REQUEST NEW LINK →
        </button>
      </div>
    );
  }

  if (updated) {
    return (
      <div style={{ minHeight: '100vh', background: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ fontFamily: DISPLAY_B, fontSize: 22, fontWeight: 900, color: t.accent, letterSpacing: -0.5 }}>// PASSWORD UPDATED · REDIRECTING…</div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', background: t.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 24 }}>
      <div style={{ fontFamily: DISPLAY_B, fontSize: 32, fontWeight: 900, letterSpacing: -1, textTransform: 'uppercase' }}>SET NEW PASSWORD</div>
      <form onSubmit={handleSetPassword} style={{ display: 'flex', flexDirection: 'column', gap: 14, width: 360 }}>
        <FieldB t={t} label="New Password" type="password" value={newPassword} onChange={setNewPassword} placeholder="••••••••"/>
        <FieldB t={t} label="Confirm Password" type="password" value={confirmPassword} onChange={setConfirmPassword} placeholder="••••••••"/>
        {updateError && <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: '#FF4444' }}>{updateError}</div>}
        <button type="submit" disabled={updating} style={{
          background: updating ? t.panelLine : t.accent, color: updating ? t.textDim : t.accentText,
          border: 'none', borderRadius: 4, padding: '14px 20px',
          fontFamily: DISPLAY_B, fontSize: 14, fontWeight: 900, letterSpacing: 2,
          textTransform: 'uppercase', cursor: updating ? 'default' : 'pointer',
        }}>
          {updating ? '// UPDATING…' : 'SET PASSWORD →'}
        </button>
      </form>
    </div>
  );
}

// ---- Error Screen ----
function ErrorScreen({ code, title, message, t, navigate }) {
  const is5xx = code >= 500;
  const codeColor = is5xx ? "#FF4444" : t.accent;
  return (
    <div style={{
      minHeight: "calc(100vh - 65px)", background: t.bg,
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: "64px 24px", textAlign: "center",
    }}>
      <div style={{
        fontFamily: DISPLAY_B, fontSize: 180, fontWeight: 900, lineHeight: 1,
        color: codeColor, letterSpacing: -8, margin: "0 0 20px",
        textShadow: `0 0 120px ${codeColor}33`,
      }}>{code}</div>
      <div style={{
        fontFamily: DISPLAY_B, fontSize: 28, fontWeight: 900, letterSpacing: -0.5,
        margin: "0 0 12px", textTransform: "uppercase",
      }}>{title}</div>
      <p style={{ fontSize: 15, color: t.textDim, lineHeight: 1.6, maxWidth: 440, margin: "0 0 40px" }}>
        {message}
      </p>
      <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
        <button onClick={() => navigate("dashboard")} style={{
          background: "transparent", color: t.textDim,
          border: `1px solid ${t.panelLine}`, borderRadius: 4,
          padding: "12px 20px", fontFamily: DISPLAY_B, fontSize: 11,
          fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
        }}>← GO BACK</button>
        <button onClick={() => navigate("dashboard")} style={{
          background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
          padding: "12px 24px", fontFamily: DISPLAY_B, fontSize: 11,
          fontWeight: 900, letterSpacing: 1.5, textTransform: "uppercase", cursor: "pointer",
        }}>HOME →</button>
      </div>
    </div>
  );
}

// ---- Offline Screen ----
function OfflineScreen({ t, navigate }) {
  return (
    <div style={{
      minHeight: "calc(100vh - 65px)", background: t.bg,
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: "64px 24px", textAlign: "center", gap: 24,
    }}>
      {/* WiFi-slash icon */}
      <svg width="80" height="80" viewBox="0 0 80 80" fill="none" style={{ color: t.textDim }}>
        <path d="M10 30 Q40 8 70 30" stroke="currentColor" strokeWidth="5" strokeLinecap="round" fill="none" opacity="0.4"/>
        <path d="M20 42 Q40 28 60 42" stroke="currentColor" strokeWidth="5" strokeLinecap="round" fill="none" opacity="0.55"/>
        <path d="M30 54 Q40 47 50 54" stroke="currentColor" strokeWidth="5" strokeLinecap="round" fill="none" opacity="0.7"/>
        <circle cx="40" cy="64" r="5" fill="currentColor"/>
        <line x1="15" y1="15" x2="65" y2="65" stroke="currentColor" strokeWidth="5" strokeLinecap="round"/>
      </svg>
      <div style={{
        fontFamily: DISPLAY_B, fontSize: 32, fontWeight: 900, letterSpacing: -1,
        color: t.textDim, textTransform: "uppercase",
      }}>YOU'RE OFFLINE</div>
      <p style={{ fontSize: 14, color: t.textDim, lineHeight: 1.6, maxWidth: 380, margin: 0 }}>
        Check your connection and try again. Your work is saved locally.
      </p>
      <button
        onClick={() => window.location.reload()}
        style={{
          background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
          padding: "12px 28px", fontFamily: DISPLAY_B, fontSize: 12,
          fontWeight: 900, letterSpacing: 2, textTransform: "uppercase", cursor: "pointer",
        }}
      >↻ RETRY</button>
    </div>
  );
}

// ---- Session Expired Screen ----
function SessionExpiredScreen({ t, navigate }) {
  return (
    <div style={{
      minHeight: "calc(100vh - 65px)", background: t.bg,
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: "64px 24px", textAlign: "center", gap: 20,
    }}>
      {/* Lock icon */}
      <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
        <rect x="12" y="28" width="40" height="28" rx="4" stroke={t.textDim} strokeWidth="3" fill="none"/>
        <path d="M20 28v-8a12 12 0 0124 0v8" stroke={t.textDim} strokeWidth="3" strokeLinecap="round" fill="none"/>
        <circle cx="32" cy="42" r="4" fill={t.textDim}/>
        <line x1="32" y1="46" x2="32" y2="50" stroke={t.textDim} strokeWidth="3" strokeLinecap="round"/>
      </svg>
      <div style={{
        fontFamily: DISPLAY_B, fontSize: 32, fontWeight: 900, letterSpacing: -1,
        textTransform: "uppercase", margin: 0,
      }}>// SESSION EXPIRED</div>
      <p style={{ fontSize: 14, color: t.textDim, lineHeight: 1.6, maxWidth: 360, margin: 0 }}>
        Sign in again to continue
      </p>
      <button
        onClick={() => navigate("login")}
        style={{
          background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
          padding: "12px 28px", fontFamily: DISPLAY_B, fontSize: 12,
          fontWeight: 900, letterSpacing: 2, textTransform: "uppercase", cursor: "pointer",
        }}
      >SIGN IN →</button>
    </div>
  );
}

// ---- Payment Success Screen ----
function PaymentSuccessScreen({ t, navigate }) {
  const orderNum = React.useRef("ORD-" + String(Math.floor(Math.random() * 900000 + 100000)));
  return (
    <div style={{
      minHeight: "calc(100vh - 65px)", background: t.bg,
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: "64px 24px", textAlign: "center", gap: 20,
    }}>
      {/* Checkmark */}
      <svg width="80" height="80" viewBox="0 0 80 80">
        <circle cx="40" cy="40" r="37" fill="none" stroke={t.accent} strokeWidth="3"/>
        <path d="M22 40l12 14 24-26" fill="none" stroke={t.accent} strokeWidth="4" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      <div style={{
        fontFamily: DISPLAY_B, fontSize: 32, fontWeight: 900, color: t.accent,
        letterSpacing: -1, textTransform: "uppercase", margin: 0,
      }}>// PAYMENT SUCCESSFUL</div>
      <div style={{ fontFamily: DISPLAY_B, fontSize: 12, color: t.textDim, letterSpacing: 2, textTransform: "uppercase" }}>
        Order {orderNum.current}
      </div>
      <button
        onClick={() => navigate("dashboard")}
        style={{
          background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
          padding: "12px 28px", fontFamily: DISPLAY_B, fontSize: 12, marginTop: 8,
          fontWeight: 900, letterSpacing: 2, textTransform: "uppercase", cursor: "pointer",
        }}
      >GO TO DASHBOARD →</button>
    </div>
  );
}


// ---- Modals ----
function Modal({ open, onClose, t, children, title, subtitle }) {
  React.useEffect(() => {
    if (!open) return;
    window.__vlModalDepth = (window.__vlModalDepth || 0) + 1;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
      window.__vlModalDepth = Math.max(0, (window.__vlModalDepth || 1) - 1);
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(0,0,0,0.7)", backdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1000, padding: 24,
      animation: "vlfade .18s ease",
    }}>
      <style>{`@keyframes vlfade { from{opacity:0} to{opacity:1} } @keyframes vlpop { from{opacity:0; transform:translateY(8px) scale(.98)} to{opacity:1; transform:none} }`}</style>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: t.panel, border: `1px solid ${t.accent}55`, borderRadius: 8, padding: 36,
        width: "100%", maxWidth: 460, color: t.text, position: "relative",
        boxShadow: `0 30px 80px rgba(0,0,0,0.7), 0 0 0 1px ${t.panelLine}, 0 0 80px ${t.accent}22`,
        animation: "vlpop .22s ease",
      }}>
        <button onClick={onClose} aria-label="Close" style={{
          position: "absolute", top: 14, right: 14, width: 28, height: 28, borderRadius: 4,
          background: "transparent", color: t.textDim, border: `1px solid ${t.panelLine}`,
          cursor: "pointer", fontFamily: DISPLAY_B, fontSize: 12,
        }}>✕</button>
        <div style={{ fontFamily: DISPLAY_B, color: t.accent, fontSize: 11, letterSpacing: 2.5, textTransform: "uppercase", marginBottom: 10 }}>
          {subtitle}
        </div>
        <h3 style={{ fontFamily: DISPLAY_B, fontSize: 32, fontWeight: 900, letterSpacing: -1, margin: "0 0 20px", lineHeight: 1, textTransform: "uppercase" }}>
          {title}
        </h3>
        {children}
      </div>
    </div>
  );
}

function SigninModal({ open, onClose, t }) {
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const submit = (e) => { e.preventDefault(); if (email.includes("@")) setSent(true); };
  React.useEffect(() => { if (!open) { setSent(false); setEmail(""); setPw(""); } }, [open]);
  return (
    <Modal open={open} onClose={onClose} t={t} title={sent ? "Check your inbox" : "Welcome back"} subtitle={sent ? "// magic link sent" : "// sign in"}>
      {sent ? (
        <p style={{ color: t.textDim, fontSize: 14, lineHeight: 1.6, margin: 0 }}>
          We sent a magic link to <span style={{ color: t.accent, fontFamily: DISPLAY_B }}>{email}</span>. Click it to land back in your editor — no password to remember.
        </p>
      ) : (
        <form onSubmit={submit}>
          <FieldB t={t} label="Email" type="email" value={email} onChange={setEmail} placeholder="you@studio.com"/>
          <FieldB t={t} label="Password" type="password" value={pw} onChange={setPw} placeholder="••••••••"/>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18, fontSize: 12, fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase" }}>
            <label style={{ display: "inline-flex", alignItems: "center", gap: 6, color: t.textDim, cursor: "pointer" }}>
              <input type="checkbox" defaultChecked style={{ accentColor: t.accent }}/> Keep me signed in
            </label>
            <a style={{ color: t.accent, cursor: "pointer" }}>Forgot?</a>
          </div>
          <button type="submit" style={{
            width: "100%", background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "14px 20px", fontSize: 14, fontWeight: 900, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase",
          }}>→ Sign in</button>
          <div style={{ textAlign: "center", color: t.textDim, fontSize: 11, fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase", marginTop: 14 }}>
            No account? <span style={{ color: t.accent, cursor: "pointer" }}>Get the beta →</span>
          </div>
        </form>
      )}
    </Modal>
  );
}

function DownloadModal({ open, onClose, t }) {
  const platforms = [
    { key: "mac", label: "macOS",   sub: "Universal · 12+",     glyph: "⌘" },
    { key: "win", label: "Windows", sub: "x64 · 10/11",          glyph: "⊞" },
    { key: "web", label: "Web",     sub: "Chrome, Safari, Edge", glyph: "◎" },
  ];
  const [picked, setPicked] = React.useState("mac");
  const [stage, setStage] = React.useState("pick"); // pick | downloading
  const [pct, setPct] = React.useState(0);
  React.useEffect(() => {
    if (!open) { setStage("pick"); setPct(0); setPicked("mac"); }
  }, [open]);
  React.useEffect(() => {
    if (stage !== "downloading") return;
    const id = setInterval(() => {
      setPct(p => Math.min(100, p + Math.random() * 9 + 3));
    }, 220);
    return () => clearInterval(id);
  }, [stage]);
  return (
    <Modal open={open} onClose={onClose} t={t} title={stage === "pick" ? "Get the beta" : pct >= 100 ? "Done. Open it." : "Downloading…"} subtitle="// open beta · v0.9.2">
      {stage === "pick" ? (
        <>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 18 }}>
            {platforms.map(p => {
              const on = p.key === picked;
              return (
                <button key={p.key} onClick={() => setPicked(p.key)} style={{
                  display: "flex", alignItems: "center", gap: 14, padding: "14px 16px",
                  background: on ? `${t.accent}14` : "transparent",
                  border: `1px solid ${on ? t.accent : t.panelLine}`, borderRadius: 4,
                  color: t.text, cursor: "pointer", textAlign: "left", fontFamily: "inherit",
                }}>
                  <span style={{ fontSize: 22, color: t.accent, width: 22, textAlign: "center" }}>{p.glyph}</span>
                  <span style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 800, fontFamily: DISPLAY_B, letterSpacing: 1, textTransform: "uppercase" }}>{p.label}</div>
                    <div style={{ fontSize: 11, color: t.textDim, fontFamily: DISPLAY_B, letterSpacing: 0.5 }}>{p.sub}</div>
                  </span>
                  <span style={{
                    width: 16, height: 16, borderRadius: 99, border: `1.5px solid ${on ? t.accent : t.panelLine}`,
                    background: on ? t.accent : "transparent",
                  }}/>
                </button>
              );
            })}
          </div>
          <button onClick={() => setStage("downloading")} style={{
            width: "100%", background: t.accent, color: t.accentText, border: "none", borderRadius: 4,
            padding: "14px 20px", fontSize: 14, fontWeight: 900, cursor: "pointer",
            fontFamily: DISPLAY_B, letterSpacing: 2, textTransform: "uppercase",
          }}>↓ Download · 240 MB</button>
          <div style={{ textAlign: "center", color: t.textDim, fontSize: 11, fontFamily: DISPLAY_B, letterSpacing: 1.5, textTransform: "uppercase", marginTop: 14 }}>
            No card · free while in beta
          </div>
        </>
      ) : (
        <>
          <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1, marginBottom: 8, display: "flex", justifyContent: "space-between" }}>
            <span>VLStudio-{picked}-0.9.2.{picked === "win" ? "exe" : picked === "mac" ? "dmg" : "app"}</span>
            <span style={{ color: t.accent }}>{Math.floor(pct)}%</span>
          </div>
          <div style={{ height: 10, background: "rgba(255,255,255,0.06)", borderRadius: 4, overflow: "hidden", marginBottom: 18 }}>
            <div style={{ width: `${pct}%`, height: "100%", background: t.accent, transition: "width .2s ease", boxShadow: `0 0 12px ${t.accent}` }}/>
          </div>
          {pct >= 100 ? (
            <p style={{ color: t.textDim, fontSize: 14, lineHeight: 1.6, margin: 0 }}>
              Installer's in your Downloads folder. Open it, edit something, then send us a bug — we read every report.
            </p>
          ) : (
            <p style={{ color: t.textDim, fontSize: 13, lineHeight: 1.5, margin: 0, fontFamily: DISPLAY_B }}>
              Hang tight. Pulling {Math.round(240 * pct/100)} / 240 MB…
            </p>
          )}
        </>
      )}
    </Modal>
  );
}

function FieldB({ t, label, type = "text", value, onChange, placeholder }) {
  return (
    <label style={{ display: "block", marginBottom: 14 }}>
      <div style={{ fontFamily: DISPLAY_B, fontSize: 11, color: t.textDim, letterSpacing: 1.5, textTransform: "uppercase", marginBottom: 6 }}>
        {label}
      </div>
      <input
        type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
        style={{
          width: "100%", background: "#000", color: t.text, border: `1px solid ${t.panelLine}`, borderRadius: 4,
          padding: "12px 14px", fontSize: 14, fontFamily: "inherit", outline: "none", boxSizing: "border-box",
        }}
        onFocus={(e) => e.target.style.borderColor = t.accent}
        onBlur={(e) => e.target.style.borderColor = t.panelLine}
      />
    </label>
  );
}

Object.assign(window, { SigninModal, DownloadModal });
