// NO-SIGN4L web kit — primitives + chrome
const ThemeContext = React.createContext('dark');
const MARK_W = "/assets/logo-main.png";
const MARK_B = "/assets/logomark-black.svg";
const MARK_HEADER = "/assets/logo-header.png";

// ---- Supabase client ----
const SUPABASE_URL = "https://wbqccwpmbekpgiqvvfvx.supabase.co";
const SUPABASE_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6IndicWNjd3BtYmVrcGdpcXZ2ZnZ4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA2MTA2NDEsImV4cCI6MjA5NjE4NjY0MX0.6rEmnZ9MQQNL79Loz2svLDEC2_Uuc-mmdAeI4F4nm5k";
const API = "https://api.nosign4l.com";

const sb = supabase.createClient(SUPABASE_URL, SUPABASE_ANON);

/* ---- scramble-on-hover
   A 3-char wide glitch window sweeps left→right across the word, resolving each
   character back to the original as it passes. Gentle — not full-word chaos.      ---- */
const SCRAMBLE_GLYPHS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#*+=/·";
const SCRAMBLE_WINDOW = 3;

function useScramble(text) {
  const [out, setOut] = React.useState(text);
  const timer = React.useRef(null);
  const textRef = React.useRef(text);
  // keep ref in sync so run() always reads the latest label (e.g. cart count)
  React.useEffect(() => {
    textRef.current = text;
    if (!timer.current) setOut(text);
  }, [text]);
  // cleanup on unmount
  React.useEffect(() => () => clearInterval(timer.current), []);

  const run = React.useCallback(() => {
    const orig = String(textRef.current);
    const len = orig.length;
    let it = 0;
    clearInterval(timer.current);
    timer.current = setInterval(() => {
      let s = "";
      for (let i = 0; i < len; i++) {
        const ch = orig[i];
        if (ch === " " || i < it || i >= it + SCRAMBLE_WINDOW) {
          s += ch; // resolved, spaces, or past window
        } else {
          s += SCRAMBLE_GLYPHS[(Math.random() * SCRAMBLE_GLYPHS.length) | 0];
        }
      }
      setOut(s);
      it += 1;
      if (it >= len) {
        clearInterval(timer.current);
        timer.current = null;
        setOut(String(textRef.current));
      }
    }, 38);
  }, []); // intentionally empty — reads live from textRef

  return [out, run];
}

/* ---- primitives ---- */
function Lab({children, bright, style, className}) {
  return <span className={"lab" + (bright ? " bright" : "") + (className ? " " + className : "")} style={style}>{children}</span>;
}

function Btn({children, variant, ...rest}) {
  const isStr = typeof children === "string";
  const [out, run] = useScramble(isStr ? children : "");
  return (
    <button
      className={"btn" + (variant ? " " + variant : "")}
      onMouseEnter={isStr ? run : undefined}
      {...rest}
    >
      {isStr ? out : children}
    </button>
  );
}

// Generic scramble element — nav links, cart, back, footer links
function ScrButton({txt, className, tag = "button", ...rest}) {
  const [out, run] = useScramble(txt);
  const Tag = tag;
  return <Tag className={className} onMouseEnter={run} {...rest}>{out}</Tag>;
}

/* ---- chrome ---- */
function CookieBanner() {
  const [dismissed, setDismissed] = React.useState(() => !!localStorage.getItem("ns_cookie_ok"));
  if (dismissed) return null;
  return (
    <div className="cookie-bar">
      <span>This site does not use tracking or advertising cookies.</span>
      <button onClick={() => { localStorage.setItem("ns_cookie_ok","1"); setDismissed(true); }}>Got it</button>
    </div>
  );
}

function SysBar() {
  const [t, setT] = React.useState("");
  React.useEffect(() => {
    const f = () => setT(new Date().toISOString().slice(11, 19));
    f();
    const id = setInterval(f, 1000);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="sysbar">
      <div><span className="blink"></span>SYS.STATE: OFFLINE</div>
      <div>{t} UTC</div>
    </div>
  );
}

function Nav({route, go, cartCount, openCart, openLogin, user, theme, toggleTheme}) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const navLinks = [
    { txt: "Drop",    r: "shop" },
    { txt: "Archive", r: "archive" },
    { txt: "System",  r: "system" },
    { txt: "Contact", r: "contact" },
  ];
  return (
    <>
      <div className="nav">
        <span className="brand" style={{cursor:"pointer"}} onClick={() => go("shop")}>NO-SIGN4L™</span>
        <div className="links">
          {navLinks.map(({txt, r}) => (
            <ScrButton key={r} txt={txt} className={route === r ? "on" : ""} onClick={() => go(r)} />
          ))}
        </div>
        <div className="right">
          {user
            ? <ScrButton txt={user.username} className="login-btn" onClick={() => window.location.href="/account"} />
            : <ScrButton txt="LOGIN" className="login-btn" onClick={openLogin} />
          }
          <ScrButton txt={"CART (" + cartCount + ")"} className="cart" onClick={openCart} />
          <button className="hamburger" onClick={() => setMenuOpen(o => !o)}>
            {menuOpen ? "✕" : "≡"}
          </button>
        </div>
      </div>
      <button className="theme-icon-btn" onClick={toggleTheme}>
        {theme === 'dark' ? '☀' : '☽'}
      </button>
      {menuOpen && (
        <div className="mobile-menu">
          {navLinks.map(({txt, r}) => (
            <button key={r} className={route === r ? "on" : ""} onClick={() => { go(r); setMenuOpen(false); }}>{txt}</button>
          ))}
        </div>
      )}
    </>
  );
}

function Footer({go, onWaitlist}) {
  const bin = "01001110 01001111 00101101 01010011 01001001 01000111 01001110 00110100 01001100 00100000 01010011 01011001 01010011 01010100 01000101 01001101 00100000 01001111 01000110 01000110 01001100 01001001 01001110 01000101";

  const navGo  = (r) => () => go && go(r);
  const navUrl = (url) => () => window.open(url, "_blank", "noopener");
  const navWL  = () => onWaitlist && onWaitlist();

  const links = [
    { txt: "Sizing",            act: navGo("sizing") },
    { txt: "Returns", act: navGo("returns") },
    { txt: "Privacy Policy",    act: navGo("privacy") },
    { txt: "Terms of Service",  act: navGo("terms") },
    { txt: "Instagram",         act: navUrl("https://instagram.com/nosign4l.shop") },
    { txt: "TikTok",            act: navUrl("https://tiktok.com/@no.sign4l") },
    { txt: "Twitter",           act: navUrl("https://twitter.com/SIGN4LONLINE") },
    { txt: "Contact",           act: navGo("contact") },
  ];

  return (
    <footer className="foot-main">
      <div className="foot-links">
        {links.map(({txt, act}, i) => (
          <React.Fragment key={txt}>
            {i > 0 && <span className="foot-sep">//</span>}
            <ScrButton tag="a" txt={txt} onClick={(e) => { e.preventDefault(); act(); }} href="#" />
          </React.Fragment>
        ))}
      </div>
      <div className="bin-strip">
        <Lab className="bin-label">© 2026 NO-SIGN4L™ · ALL RIGHTS RESERVED · MADE OFFLINE</Lab>
        <span className="bin-text">{bin}</span>
      </div>
    </footer>
  );
}

/* ---- portal helper for modals ---- */
function Portal({children}) {
  return ReactDOM.createPortal(children, document.body);
}

/* ---- waitlist popup ---- */
function WaitlistPopup({onClose}) {
  const FORMSPREE = "https://formspree.io/f/mjgdvpdn";
  const [email, setEmail] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState("");

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim()) { setError("Email is required."); return; }
    setError("");
    try {
      const res = await fetch(FORMSPREE, {
        method: "POST",
        headers: {"Content-Type": "application/json", "Accept": "application/json"},
        body: JSON.stringify({ email, _subject: "New Waitlist Signup" }),
      });
      if (res.ok) setSent(true);
      else setError("Something went wrong. Try again.");
    } catch { setError("Connection error."); }
  };

  return (
    <Portal>
      <div className="popup-scrim" onClick={onClose}>
        <div className="popup" onClick={e => e.stopPropagation()}>
          <div className="ph">
            <div>
              <Lab style={{display:"block",marginBottom:4}}>NO-SIGN4L // UPLINK</Lab>
              <div className="ptitle">Waitlist</div>
            </div>
            <button onClick={onClose}>✕</button>
          </div>
          <div className="pbody">
            {sent ? (
              <div style={{fontFamily:"var(--font-mono)",fontSize:13,color:"var(--fg2)",lineHeight:1.8}}>
                <div style={{color:"var(--fg1)",marginBottom:8}}>&gt; TRANSMISSION RECEIVED.</div>
                <div>You're on the list.</div>
              </div>
            ) : (
              <form onSubmit={submit}>
                <div className="psub" style={{marginBottom:16}}>Drop your email. We'll hit you when the next drop goes live.</div>
                <div className="prow single" style={{marginBottom:12}}>
                  <input type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} required />
                </div>
                {error && <div style={{fontFamily:"var(--font-mono)",fontSize:11,color:"#f44",marginBottom:8}}>{error}</div>}
                <Btn variant="primary" type="submit" style={{width:"100%"}}>Join Waitlist</Btn>
              </form>
            )}
          </div>
        </div>
      </div>
    </Portal>
  );
}

/* ---- contact popup ---- */
function ContactPopup({onClose}) {
  const FORMSPREE = "https://formspree.io/f/mjgdvpdn"; // nosign4l contact → support@nosign4l.com
  const types = ["Customer Support","General Inquiry","Partnership"];
  const [checked, setChecked] = React.useState([]);
  const [form, setForm]       = React.useState({name:"",email:"",social:"",date:"",message:""});
  const [sent, setSent]       = React.useState(false);
  const [error, setError]     = React.useState("");
  const toggle = (t) => setChecked(c => c.includes(t) ? c.filter(x => x!==t) : [...c, t]);
  const set    = (k) => (e) => setForm(f => ({...f, [k]: e.target.value}));
  const submit = async (e) => {
    e.preventDefault();
    if (!form.name.trim())    { setError("Name is required."); return; }
    if (!form.email.trim())   { setError("Email is required."); return; }
    if (!form.message.trim()) { setError("Message is required."); return; }
    setError("");
    try {
      const res = await fetch(FORMSPREE, {
        method: "POST",
        headers: {"Content-Type": "application/json", "Accept": "application/json"},
        body: JSON.stringify({
          name: form.name, email: form.email,
          social: form.social, date: form.date,
          inquiry: checked.join(", "),
          message: form.message,
          _replyto: form.email,
          _subject: "NO-SIGN4L Contact: " + (checked[0] || "General"),
        })
      });
      if (res.ok) { setSent(true); }
      else { setError("Transmission failed. Try again."); }
    } catch(err) { setError("Transmission failed. Try again."); }
  };
  return (
    <Portal>
      <div className="popup-scrim" onClick={onClose}>
        <div className="popup" style={{maxWidth:560}} onClick={e => e.stopPropagation()}>
          <div className="ph">
            <div>
              <Lab style={{display:"block",marginBottom:4}}>SYS.DOC // CONTACT</Lab>
              <div className="ptitle"></div>
            </div>
            <button onClick={onClose}>✕</button>
          </div>
          <div className="pbody">
            {sent ? (
              <div style={{fontFamily:"var(--font-mono)",fontSize:13,color:"var(--fg2)",lineHeight:1.8}}>
                <div style={{color:"var(--fg1)",marginBottom:8}}>&gt; MESSAGE TRANSMITTED.</div>
                <div>Channel open. We will respond when the system reconnects.</div>
                <div style={{marginTop:8,color:"var(--fg3)"}}>STATUS: SENT · UPLINK: NULL</div>
              </div>
            ) : (
              <form onSubmit={submit}>
                <div className="inquiry">
                  <div className="inq-label">Inquiry Type *</div>
                  <div className="inq-grid" style={{gridTemplateColumns:"1fr 1fr 1fr"}}>
                    {types.map(t => (
                      <label className="inq-opt" key={t}>
                        <input type="checkbox" checked={checked.includes(t)} onChange={() => toggle(t)} />
                        {t}
                      </label>
                    ))}
                  </div>
                </div>
                <div className="prow" style={{marginBottom:10}}>
                  <input placeholder="Name"  value={form.name}  onChange={set("name")}  required />
                  <input type="email" placeholder="Email" value={form.email} onChange={set("email")} required />
                </div>
                <div className="prow" style={{marginBottom:10}}>
                  <input placeholder="Website // Social" value={form.social} onChange={set("social")} />
                  <input placeholder="Today's Date"      value={form.date}   onChange={set("date")}   />
                </div>
                <div className="prow single" style={{marginBottom:0}}>
                  <textarea placeholder="Message *" rows={4} value={form.message} onChange={set("message")} required />
                </div>
                {error && <div style={{fontFamily:"var(--font-mono)",fontSize:11,color:"#f44",marginTop:10}}>{error}</div>}
              </form>
            )}
          </div>
          {!sent && (
            <div className="pfoot">
              <Btn variant="primary" onClick={submit}>Send →</Btn>
            </div>
          )}
        </div>
      </div>
    </Portal>
  );
}

/* ---- login popup ---- */
function EyeIcon({show}) {
  return show
    ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
    : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>;
}

function PwField({placeholder, value, onChange, autoComplete}) {
  const [show, setShow] = React.useState(false);
  return (
    <div className="pw-wrap">
      <input type={show ? "text" : "password"} placeholder={placeholder} value={value} onChange={onChange} autoComplete={autoComplete} />
      <button type="button" className="eye" onClick={() => setShow(s => !s)} tabIndex={-1}><EyeIcon show={show} /></button>
    </div>
  );
}

function LoginPopup({onClose, onLogin}) {
  const [mode, setMode] = React.useState("login"); // "login" | "register" | "forgot" | "verify-otp"
  const [form, setForm] = React.useState({username:"", email:"", password:"", confirmPassword:""});
  const [error, setError] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [resetSent, setResetSent] = React.useState(false);
  const [pendingEmail, setPendingEmail] = React.useState("");
  const [pendingUser, setPendingUser] = React.useState(null);
  const [otpCode, setOtpCode] = React.useState("");
  const set = (k) => (e) => setForm(f => ({...f, [k]: e.target.value}));

  const validPassword = (p) => p.length >= 8 && /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(p);

  const handleLogin = async (e) => {
    e.preventDefault(); setError(""); setLoading(true);
    if (!form.email) { setError("Enter your email."); setLoading(false); return; }
    if (!form.password) { setError("Enter your password."); setLoading(false); return; }
    const { data, error } = await sb.auth.signInWithPassword({ email: form.email, password: form.password });
    if (error) { setError(error.message || "Login failed."); setLoading(false); return; }
    const u = data.user;
    onLogin({ id: u.id, username: u.user_metadata?.username || u.email.split("@")[0], email: u.email });
    onClose();
  };

  const handleRegister = async (e) => {
    e.preventDefault(); setError(""); setLoading(true);
    if (!form.username) { setError("Choose a username."); setLoading(false); return; }
    if (!form.email) { setError("Enter your email."); setLoading(false); return; }
    if (!validPassword(form.password)) { setError("Password must be 8+ characters and include a special character."); setLoading(false); return; }
    if (form.password !== form.confirmPassword) { setError("Passwords don't match."); setLoading(false); return; }
    const { data, error } = await sb.auth.signUp({
      email: form.email,
      password: form.password,
      options: {
        data: { username: form.username },
        emailRedirectTo: "https://nosign4l.com/verify",
      },
    });
    if (error) { setError(error.message || "Registration failed."); setLoading(false); return; }
    // Supabase sends the verification code email automatically via our custom SMTP
    setPendingEmail(form.email);
    setPendingUser({ id: data.user.id, username: form.username, email: form.email });
    setLoading(false);
    setMode("verify-otp");
  };

  const handleVerifyOtp = async (e) => {
    e.preventDefault(); setError(""); setLoading(true);
    if (!otpCode || otpCode.length < 8) { setError("Enter the 6-digit code from your email."); setLoading(false); return; }
    const { error } = await sb.auth.verifyOtp({ email: pendingEmail, token: otpCode, type: "email" });
    if (error) { setError("Invalid or expired code. Check your email and try again."); setLoading(false); return; }
    setMode("verified");
    setTimeout(() => { onLogin(pendingUser); onClose(); }, 2000);
  };

  const handleForgot = async (e) => {
    e.preventDefault(); setError(""); setLoading(true);
    if (!form.email) { setError("Enter your email."); setLoading(false); return; }
    const { error } = await sb.auth.resetPasswordForEmail(form.email, {
      redirectTo: "https://nosign4l.com/reset",
    });
    setLoading(false);
    if (error) { setError(error.message || "Failed to send reset email."); return; }
    setResetSent(true);
  };

  const switchMode = (m) => { setMode(m); setError(""); setResetSent(false); setOtpCode(""); setForm({username:"",email:"",password:"",confirmPassword:""}); };

  const titles = { login:"CONNECT // AUTHENTICATE", register:"CONNECT // NEW USER", forgot:"CONNECT // RESET", "verify-otp":"CONNECT // VERIFY", "verified":"CONNECT // SUCCESS" };
  const subtitles = { login:"Login", register:"Register", forgot:"Forgot Password", "verify-otp":"Verify Email", "verified":"Verified" };
  const monoLink = (label, onClick) => (
    <button type="button" onClick={onClick}
      style={{background:"none",border:"none",color:"var(--fg1)",fontFamily:"var(--font-mono)",fontSize:11,cursor:"pointer",textDecoration:"underline",padding:0}}>{label}</button>
  );

  return (
    <Portal>
      <div className="popup-scrim">
        <div className="popup" style={{maxWidth:400}} onClick={e => e.stopPropagation()}>
          <div className="ph">
            <div>
              <Lab style={{display:"block",marginBottom:4}}>{titles[mode]}</Lab>
              <div className="ptitle">{subtitles[mode]}</div>
            </div>
            <button onClick={onClose}>✕</button>
          </div>
          <div className="pbody">

            {mode === "verified" ? (
              <div style={{textAlign:"center",padding:"20px 0"}}>
                <div style={{fontFamily:"var(--font-display)",fontSize:32,fontWeight:800,marginBottom:12}}>✓</div>
                <div style={{fontFamily:"var(--font-display)",fontSize:16,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",marginBottom:8}}>Email Verified</div>
                <div style={{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--fg3)"}}>Logging you in...</div>
              </div>
            ) : mode === "verify-otp" ? (
              <form onSubmit={handleVerifyOtp}>
                <div className="psub" style={{marginBottom:16}}>We sent a 6-digit code to <strong>{pendingEmail}</strong>. Enter it below to activate your account.</div>
                <div className="prow single" style={{marginBottom:10}}>
                  <input
                    type="text"
                    placeholder="00000000"
                    maxLength={8}
                    value={otpCode}
                    onChange={e => setOtpCode(e.target.value.replace(/\D/g, ""))}
                    autoComplete="one-time-code"
                    style={{textAlign:"center",fontSize:22,letterSpacing:"0.3em"}}
                  />
                </div>
                {error && <div style={{fontFamily:"var(--font-mono)",fontSize:11,color:"#f44",marginBottom:10}}>{error}</div>}
                <Btn variant="primary" type="submit" style={{width:"100%",marginBottom:12}} disabled={loading}>
                  {loading ? "VERIFYING..." : "Verify Email →"}
                </Btn>
                <div style={{textAlign:"center",marginTop:4,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg3)"}}>
                  Didn't get it? Check your spam folder.
                </div>
              </form>
            ) : mode === "forgot" ? (
              resetSent ? (
                <div style={{fontFamily:"var(--font-mono)",fontSize:13,color:"var(--fg2)",lineHeight:1.8}}>
                  <div style={{color:"var(--fg1)",marginBottom:8}}>&gt; RESET LINK SENT.</div>
                  <div>Check your email for a password reset link.</div>
                  <div style={{marginTop:14}}>
                    <span style={{fontSize:11,color:"var(--fg3)"}}>Back to </span>{monoLink("Login", () => switchMode("login"))}
                  </div>
                </div>
              ) : (
                <form onSubmit={handleForgot}>
                  <div className="psub">Enter your email and we'll send you a reset link.</div>
                  <div className="prow single" style={{marginBottom:10}}>
                    <input type="email" placeholder="Email" value={form.email} onChange={set("email")} autoComplete="email" />
                  </div>
                  {error && <div style={{fontFamily:"var(--font-mono)",fontSize:11,color:"#f44",marginBottom:10}}>{error}</div>}
                  <Btn variant="primary" type="submit" style={{width:"100%",marginBottom:12}} disabled={loading}>
                    {loading ? "SENDING..." : "Send Reset Link →"}
                  </Btn>
                  <div style={{textAlign:"center",marginTop:4}}>
                    <span style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg3)"}}>Back to </span>{monoLink("Login", () => switchMode("login"))}
                  </div>
                </form>
              )
            ) : mode === "login" ? (
              <form onSubmit={handleLogin}>
                <div className="prow single" style={{marginBottom:10}}>
                  <input type="email" placeholder="Email" value={form.email} onChange={set("email")} autoComplete="email" />
                </div>
                <div className="prow single" style={{marginBottom:10}}>
                  <PwField placeholder="Password" value={form.password} onChange={set("password")} autoComplete="current-password" />
                </div>
                {error && <div style={{fontFamily:"var(--font-mono)",fontSize:11,color:"#f44",marginBottom:10}}>{error}</div>}
                <Btn variant="primary" type="submit" style={{width:"100%",marginBottom:10}} disabled={loading}>
                  {loading ? "AUTHENTICATING..." : "Login →"}
                </Btn>
                <button type="button" className="gmail-btn" onClick={() => sb.auth.signInWithOAuth({ provider: "google", options: { redirectTo: "https://nosign4l.com?oauth=success" } })} style={{marginBottom:14}}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18A10.96 10.96 0 001 12c0 1.77.42 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
                  Continue with Google
                </button>
                <div style={{textAlign:"center",display:"flex",flexDirection:"column",gap:8}}>
                  <div>
                    <span style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg3)"}}>No account? </span>{monoLink("Register", () => switchMode("register"))}
                  </div>
                  <div>{monoLink("Forgot password?", () => switchMode("forgot"))}</div>
                </div>
              </form>
            ) : (
              <form onSubmit={handleRegister}>
                <div className="prow single" style={{marginBottom:10}}>
                  <input placeholder="Username" value={form.username} onChange={set("username")} autoComplete="username" />
                </div>
                <div className="prow single" style={{marginBottom:10}}>
                  <input type="email" placeholder="Email" value={form.email} onChange={set("email")} autoComplete="email" />
                </div>
                <div className="prow single" style={{marginBottom:10}}>
                  <PwField placeholder="Password" value={form.password} onChange={set("password")} autoComplete="new-password" />
                </div>
                <div className="prow single" style={{marginBottom:10}}>
                  <PwField placeholder="Confirm Password" value={form.confirmPassword} onChange={set("confirmPassword")} autoComplete="new-password" />
                </div>
                {error && <div style={{fontFamily:"var(--font-mono)",fontSize:11,color:"#f44",marginBottom:10}}>{error}</div>}
                <Btn variant="primary" type="submit" style={{width:"100%",marginBottom:10}} disabled={loading}>
                  {loading ? "CREATING..." : "Create Account →"}
                </Btn>
                <button type="button" className="gmail-btn" onClick={() => sb.auth.signInWithOAuth({ provider: "google", options: { redirectTo: "https://nosign4l.com?oauth=success" } })} style={{marginBottom:14}}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18A10.96 10.96 0 001 12c0 1.77.42 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
                  Sign up with Google
                </button>
                <div style={{textAlign:"center",marginTop:4}}>
                  <span style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg3)"}}>Have an account? </span>{monoLink("Login", () => switchMode("login"))}
                </div>
              </form>
            )}

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

Object.assign(window, {
  MARK_W, MARK_B, MARK_HEADER,
  useScramble, Lab, Btn, ScrButton,
  CookieBanner, SysBar, Nav, Footer,
  Portal, WaitlistPopup, ContactPopup, LoginPopup,
});
