// NO-SIGN4L web kit — app shell + state
const { useState } = React;

function BootScreen({ enter }) {
  const lines = [
    "> user@NO-SIGN4L:~$",
    "> signal ................. NONE",
    "> uplink ................. FAIL",
    "> channel ................ NULL",
    "> status ................. DISCONNECTED",
    "> SYSTEM OFFLINE.",
  ];
  const [shown, setShown] = useState(0);
  React.useEffect(() => {
    if (shown >= lines.length) return;
    const id = setTimeout(() => setShown(shown + 1), shown === 0 ? 200 : 400);
    return () => clearTimeout(id);
  }, [shown]);
  const ready = shown >= lines.length;
  React.useEffect(() => {
    if (!ready) return;
    const handler = (e) => { if (e.key === "Enter") enter(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [ready]);
  return (
    <div className="boot">
      <img src={MARK_HEADER} style={{width:280,marginBottom:6}} alt="" />
      <Lab>SYSTEM OFFLINE // NULL SURFACE</Lab>
      <div className="log">
        {lines.slice(0, shown).map((l, i) => (
          <div key={i} className={i === lines.length - 1 ? "" : "ok"}>{l}</div>
        ))}
        {!ready && <div>&gt;<span className="cursor"></span></div>}
      </div>
      {ready && <Btn variant="primary" onClick={enter}>Enter</Btn>}
    </div>
  );
}

function App() {
  const [booted, setBooted] = useState(() => !!localStorage.getItem("ns_booted"));
  const [route, setRoute] = useState("shop");
  const [active, setActive] = useState(null);
  const [cart, setCart] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [waitlistOpen, setWaitlistOpen] = useState(false);
  const [contactOpen, setContactOpen] = useState(false);
  const [loginOpen, setLoginOpen] = useState(false);
  const [user, setUser] = useState(null);
  const [theme, setTheme] = useState(() => localStorage.getItem("ns_theme") || "dark");

  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    document.body.classList.toggle("light-mode", theme === "light");
    localStorage.setItem("ns_theme", theme);
  }, [theme]);

  const toggleTheme = () => setTheme(t => t === "dark" ? "light" : "dark");

  // Restore session on load + handle OAuth redirect
  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get("oauth") === "success" || params.get("order") === "success") {
      window.history.replaceState({}, "", "/");
    }
    sb.auth.getSession().then(({ data }) => {
      const u = data?.session?.user;
      if (u) setUser({ id: u.id, username: u.user_metadata?.username || u.email.split("@")[0], email: u.email });
    });
    sb.auth.onAuthStateChange((_event, session) => {
      const u = session?.user;
      if (u) setUser({ id: u.id, username: u.user_metadata?.username || u.email.split("@")[0], email: u.email });
      else setUser(null);
    });
  }, []);

  const go = (r) => {
    if (r === "contact") { setContactOpen(true); return; }
    setActive(null); setRoute(r); window.scrollTo(0, 0);
  };
  const open = (p) => { setActive(p); window.scrollTo(0, 0); };
  const add = (p, size) => { setCart([...cart, { ...p, size }]); setActive(null); setCartOpen(true); };
  const remove = (ix) => setCart(cart.filter((_, i) => i !== ix));

  // if (!booted) return <BootScreen enter={() => { localStorage.setItem("ns_booted","1"); setBooted(true); }} />;

  const ContactLink = () => <a href="#" style={{color:"var(--fg1)",fontFamily:"var(--font-mono)",fontSize:13}} onClick={e => { e.preventDefault(); setContactOpen(true); }}>Contact us →</a>;

  let body;
  if (active) body = <ProductDetail p={active} back={() => setActive(null)} add={add} onWaitlist={() => setWaitlistOpen(true)} />;
  else if (route === "shop") body = <><Hero go={go} onWaitlist={() => setWaitlistOpen(true)} /><Grid open={open} /></>;
  else if (route === "system") body = (
    <StaticPage kicker="SYS.DOC / INFO" title="System Info">
      <p>Coming Soon.</p>
    </StaticPage>
  );
  else if (route === "sizing") body = <SizingPage />;
  else if (route === "archive") body = (
    <StaticPage kicker="SYS.DOC / ARCHIVE" title="Closed Channels">
      <p>Previous drops are decommissioned once they sell through. No restocks, no reruns. Once a transmission ends, it’s gone.</p>
      <p>TRANSMISSION 000 — CLOSED.<br/>STATIC — CLOSED.</p>
    </StaticPage>
  );
  else if (route === "privacy") body = (
    <StaticPage kicker="LEGAL / PRIVACY POLICY" title="Privacy Policy">
      <p>Last updated: June 2026</p>
      <p>NO-SIGN4L™ ("we", "us") operates nosign4l.com. This policy explains how we handle your information.</p>
      <p><strong style={{color:"var(--fg1)"}}>What We Collect</strong><br/>
      We do not store your personal data on our servers. All order information — name, address, email, and payment details — is collected and processed directly by Stripe. We never see or store your payment information. If you join the waitlist, your email is collected solely to notify you of new drops and is not shared with any third party.</p>
      <p><strong style={{color:"var(--fg1)"}}>Cookies and Analytics</strong><br/>
      This site uses Cloudflare for hosting and basic traffic analytics (page views, general location, device type). No advertising or tracking cookies are used.</p>
      <p><strong style={{color:"var(--fg1)"}}>Third Parties</strong><br/>
      We use Stripe for payment processing. Their privacy policy governs how your order data is handled. We do not sell, rent, or share your information with any other third parties.</p>
      <p><strong style={{color:"var(--fg1)"}}>Your Rights</strong><br/>
      You may request removal of your email from our waitlist at any time by contacting support@nosign4l.com. If you are in the EU, you have rights under GDPR including the right to access, correction, and erasure of your data held by Stripe.</p>
      <p><strong style={{color:"var(--fg1)"}}>Contact</strong><br/>
      <ContactLink /></p>
    </StaticPage>
  );
  else if (route === "terms") body = (
    <StaticPage kicker="LEGAL / TERMS OF SERVICE" title="Terms of Service">
      <p>Last updated: June 2026</p>
      <p>By accessing nosign4l.com or placing an order, you agree to these terms. If you do not agree, do not use this site.</p>
      <p><strong style={{color:"var(--fg1)"}}>Products</strong><br/>
      All items sold on this site are referred to as objects (apparel and accessories) or surfaces (skateboards). All objects and surfaces are limited edition. We reserve the right to cancel or limit orders at our discretion.</p>
      <p><strong style={{color:"var(--fg1)"}}>Pricing</strong><br/>
      All prices are listed in USD. We reserve the right to change prices at any time. Orders placed before a price change will be honored at the price shown at time of purchase.</p>
      <p><strong style={{color:"var(--fg1)"}}>Payment</strong><br/>
      Payments are processed securely through Stripe. We do not store your payment information. By submitting an order you authorize the charge to your provided payment method.</p>
      <p><strong style={{color:"var(--fg1)"}}>Shipping</strong><br/>
      We ship to the address provided at checkout. We are not responsible for delays caused by carriers or incorrect addresses submitted by the buyer. Risk of loss passes to the buyer upon handoff to the carrier.</p>
      <p><strong style={{color:"var(--fg1)"}}>Intellectual Property</strong><br/>
      All branding, graphics, and content on this site are original works and the property of NO-SIGN4L™. Any resemblance to existing trademarks or logos is unintentional. NO-SIGN4L™ has made reasonable efforts to ensure its marks do not conflict with existing registered trademarks. In the event a conflict is identified, NO-SIGN4L™ will cooperate in good faith to resolve it. You may not reproduce, copy, or use any content from this site without written permission.</p>
      <p><strong style={{color:"var(--fg1)"}}>No Warranty</strong><br/>
      All objects and surfaces are sold as-is. NO-SIGN4L™ makes no warranties, express or implied, beyond what is described in each product listing. We are not responsible for damage resulting from misuse, improper care, or normal wear.</p>
      <p><strong style={{color:"var(--fg1)"}}>Right to Refuse Service</strong><br/>
      NO-SIGN4L™ reserves the right to refuse, cancel, or limit any order at any time for any reason, including suspected fraud or abuse.</p>
      <p><strong style={{color:"var(--fg1)"}}>Limitation of Liability</strong><br/>
      NO-SIGN4L™ is not liable for any indirect, incidental, or consequential damages arising from use of this site or purchase of our products beyond the amount paid for the order in question.</p>
      <p><strong style={{color:"var(--fg1)"}}>Dispute Resolution</strong><br/>
      Any disputes arising from a purchase will be resolved through binding arbitration rather than in court, except where prohibited by law. You waive the right to participate in a class action lawsuit against NO-SIGN4L™.</p>
      <p><strong style={{color:"var(--fg1)"}}>Jurisdiction</strong><br/>
      These terms are governed by the laws of the United States. By using this site you agree that any legal proceedings will take place in the jurisdiction where NO-SIGN4L™ operates.</p>
      <p><strong style={{color:"var(--fg1)"}}>Age</strong><br/>
      This site is intended for users 18 and older. By placing an order you confirm you are at least 18 years of age. NO-SIGN4L™ is not liable for purchases made by minors without parental consent.</p>
      <p><strong style={{color:"var(--fg1)"}}>Policy Changes</strong><br/>
      We reserve the right to update these terms at any time. Continued use of this site after changes are posted constitutes acceptance of the updated terms.</p>
      <p><strong style={{color:"var(--fg1)"}}>Contact</strong><br/>
      <ContactLink /></p>
    </StaticPage>
  );
  else if (route === "returns") body = (
    <StaticPage kicker="LEGAL / RETURNS & REFUNDS" title="Returns & Refunds">
      <p>Last updated: June 2026</p>
      <p><strong style={{color:"var(--fg1)"}}>All Sales Final</strong><br/>
      All objects and surfaces are sold as final sale. We do not accept returns or exchanges unless the item arrives damaged or defective.</p>
      <p><strong style={{color:"var(--fg1)"}}>Damaged or Defective Items</strong><br/>
      If your order arrives damaged or defective, contact us within 7 days of delivery with your order number and photos of the issue. We will replace the item or issue a refund at our discretion.</p>
      <p><strong style={{color:"var(--fg1)"}}>Wrong Item Received</strong><br/>
      If you receive the wrong item, contact us within 7 days of delivery. We will cover return shipping and send the correct item.</p>
      <p><strong style={{color:"var(--fg1)"}}>Sizing</strong><br/>
      We are not responsible for sizing issues. Please refer to the size guide before ordering. Size-related returns will not be accepted.</p>
      <p><strong style={{color:"var(--fg1)"}}>Lost or Stolen Packages</strong><br/>
      Once an order is handed to the carrier and tracking shows delivered, we are not responsible for lost or stolen packages. Contact your carrier directly or file a claim with the shipping provider.</p>
      <p><strong style={{color:"var(--fg1)"}}>Contact</strong><br/>
      <ContactLink /></p>
    </StaticPage>
  );
  else body = (
    <StaticPage kicker="SYS.DOC / CONTACT" title="Open Channel">
      <p>This terminal does not accept inbound calls. For wholesale, press, or grid-down logistics, transmit to:</p>
      <p style={{fontFamily:"var(--font-mono)",color:"var(--fg1)"}}>null@no-sign4l.offline</p>
    </StaticPage>
  );

  return (
    <ThemeContext.Provider value={theme}>
    <div className="app">
      <SysBar />
      <Nav route={active ? "shop" : route} go={go} cartCount={cart.length} openCart={() => setCartOpen(true)} openLogin={() => setLoginOpen(true)} user={user} theme={theme} toggleTheme={toggleTheme} />
      {body}
      <Footer go={go} onWaitlist={() => setWaitlistOpen(true)} />
      <CartDrawer open={cartOpen} items={cart} close={() => setCartOpen(false)} remove={remove} userId={user?.id ?? null} />
      {waitlistOpen && <WaitlistPopup onClose={() => setWaitlistOpen(false)} />}
      {contactOpen && <ContactPopup onClose={() => setContactOpen(false)} />}
      {loginOpen && <LoginPopup onClose={() => setLoginOpen(false)} onLogin={(u) => setUser(u)} />}
      <CookieBanner />
    </div>
    </ThemeContext.Provider>
  );
}

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