/* sections-top.jsx — Nav + Hero */
const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

/* GTM/GA4 CTA tracking — pushes a cta_click event to the dataLayer.
 * GTM (GTM-K6LVSCS9) picks it up and forwards to GA4. Fires before
 * navigation since dataLayer.push is synchronous. */
function track(cta, location) {
  try {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event: "cta_click", cta_name: cta, cta_location: location });
  } catch (e) { /* never block navigation on tracking */ }
}

const LOGO_URL = "https://framerusercontent.com/images/KHsTqzcNJn981dsR0vwIJ6vDD0.png";

function Logo({ size = 20 }) {
  return (
    <img src={LOGO_URL} alt="strk20" style={{ height: size, width: "auto", display: "block" }} />
  );
}

function Nav() {
  const [open, setOpen] = useStateT(false);
  // Which top-level dropdown is open on desktop (Build menu). Tracking
  // by label keeps the API consistent if more dropdowns are added later.
  const [openMenu, setOpenMenu] = useStateT(null);
  // Which submenu is expanded inline inside the mobile drawer.
  const [drawerExpanded, setDrawerExpanded] = useStateT(null);
  const closeBurger = (e) => { if (e.target.tagName === "A") setOpen(false); };
  // The /app/* surface (shown after Launch App) renders this same Nav.
  // On those routes we surface the Rewards entry and swap the Launch App
  // CTA for "Apply for SDK". Computed per-render — navigation is a full
  // page reload, so Nav remounts and this re-evaluates on every route.
  const isApp = typeof window !== "undefined" && window.location.pathname.startsWith("/app");
  return (
    <nav style={{
      position: "fixed", top: "var(--promo-h, 0px)", left: 0, right: 0, zIndex: 50,
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "16px var(--gut)", pointerEvents: "none",
    }}>
      <a
        href="/"
        aria-label="strk20 home"
        onClick={(e) => {
          // Already on landing → suppress the navigation (full-page
          // reload during which Babel re-transforms every JSX file,
          // causing a brief blank screen) and just glide back to top.
          const p = window.location.pathname;
          if (p === "/" || p === "") {
            e.preventDefault();
            window.smoothScrollToTop?.();
          }
        }}
        style={{ display: "flex", alignItems: "center", pointerEvents: "auto" }}
      >
        <Logo size={22} />
      </a>

      {/* desktop links */}
      <div className="nav-desk" style={{ display: "flex", alignItems: "center", gap: "clamp(20px,2.6vw,44px)", pointerEvents: "auto",
        // Absolute-center the link row regardless of how wide the logo
        // (or any future right-side CTA) ends up — keeps the navbar
        // visually balanced on every page.
        position: "absolute", left: "50%", top: "50%",
        transform: "translate(-50%, -50%)",
        fontFamily: "var(--mono)", fontSize: 13, letterSpacing: "0.14em", textTransform: "uppercase" }}>
        <a
          href="/"
          className="footlink"
          style={{ color: "var(--text)" }}
          onClick={(e) => {
            const p = window.location.pathname;
            if (p === "/" || p === "") { e.preventDefault(); window.smoothScrollToTop?.(); }
          }}
        >Home</a>
        <a href="/app/live-apps" onClick={() => track("use", "nav")} className="footlink" style={{ color: "var(--text)" }}>Use</a>
        {/* Build → /apply (SDK application) and RFPs → /rfp as separate
            top-level links (the old Build dropdown was split into these). */}
        <a href="/apply" onClick={() => track("build", "nav")} className="footlink" style={{ color: "var(--text)" }}>Build</a>
        <a href="/rfp" onClick={() => track("rfps", "nav")} className="footlink" style={{ color: "var(--text)" }}>RFPs</a>
        <a
          href="#playlists"
          onClickCapture={() => track("tutorials", "nav")}
          className="footlink"
          style={{ color: "var(--text)" }}
          onClick={(e) => {
            // Already on landing → smooth scroll in place (no reload).
            // Otherwise let the browser navigate to /#playlists; the
            // post-mount handler in App() will scroll after Babel mounts
            // the Playlists section.
            const p = window.location.pathname;
            if (p === "/" || p === "") {
              e.preventDefault();
              window.smoothScrollToId?.("playlists");
              history.replaceState(null, "", "#playlists");
            }
          }}
        >Tutorials</a>
        {/* Dashboard from landing keeps the user in the unlaunched header
            (Nav). /dashboard is a dedicated route that renders Nav +
            Dashboard. /app/dashboard (HeaderApp + Dashboard) is what the
            HeaderApp uses after the app has been launched. */}
        {/* Dashboard keeps you in your current surface: inside the app
            (/app/*) it routes to /app/dashboard so you stay "launched";
            from the landing it routes to the landing /dashboard. */}
        <a href={isApp ? "/app/dashboard" : "/dashboard"} onClick={() => track("dashboard", "nav")} className="footlink" style={{ color: "var(--text)" }}>Dashboard</a>
        {/* Shield Rush — direct link to the live rewards app (no dropdown;
            the Claim page doesn't exist yet). */}
        {isApp && (
          <a href="/shield-rush" onClick={() => track("shield_rush", "nav")} className="footlink" style={{ color: "var(--text)" }}>Shield Rush</a>
        )}
      </div>
      <div className="nav-desk" style={{ position: "relative", pointerEvents: "auto" }}>
        {isApp ? (
          <a href="/build" onClick={() => track("apply_sdk", "nav")} className="btn btn-orange" style={{ padding: "10px 20px", fontSize: 13 }}>
            Apply for SDK
          </a>
        ) : (
          <a href="/shield-rush" onClick={() => track("launch_app", "nav")} className="btn btn-orange" style={{ padding: "10px 20px", fontSize: 13 }}>
            Launch App
          </a>
        )}
      </div>

      {/* mobile hamburger */}
      <button className="nav-burger" aria-label="Menu" aria-expanded={open} onClick={() => setOpen((o) => !o)}
        style={{ pointerEvents: "auto", background: "rgba(12,12,16,0.55)", backdropFilter: "blur(8px)",
          border: "1px solid var(--line)", borderRadius: 7, width: 42, height: 42,
          alignItems: "center", justifyContent: "center", cursor: "pointer", padding: 0 }}>
        <span className={"burger" + (open ? " open" : "")}><i /><i /><i /></span>
      </button>

      {/* mobile drawer */}
      <div className={"nav-drawer" + (open ? " open" : "")} onClick={closeBurger}>
        <a href="/">Home</a>
        <a href="/app/live-apps" onClick={() => track("use", "nav_mobile")}>Use</a>
        {/* Build → /apply and RFPs → /rfp as separate top-level links. */}
        <a href="/apply" onClick={() => track("build", "nav_mobile")}>Build</a>
        <a href="/rfp" onClick={() => track("rfps", "nav_mobile")}>RFPs</a>
        <a
          href="#playlists"
          onClick={(e) => {
            const p = window.location.pathname;
            if (p === "/" || p === "") {
              e.preventDefault();
              setOpen(false);
              window.smoothScrollToId?.("playlists");
              history.replaceState(null, "", "#playlists");
            }
          }}
        >Tutorials</a>
        <a href={isApp ? "/app/dashboard" : "/dashboard"} onClick={() => track("dashboard", "nav_mobile")}>Dashboard</a>
        {/* Shield Rush — direct link to the live rewards app. */}
        {isApp && (
          <a href="/shield-rush" onClick={() => track("shield_rush", "nav_mobile")}>Shield Rush</a>
        )}
        {isApp ? (
          <a href="/build" onClick={() => track("apply_sdk", "nav_mobile")} className="btn btn-orange" style={{ justifyContent: "center", marginTop: 6 }}>Apply for SDK</a>
        ) : (
          <a href="/shield-rush" onClick={() => track("launch_app", "nav_mobile")} className="btn btn-orange" style={{ justifyContent: "center", marginTop: 6 }}>Launch App</a>
        )}
      </div>

      <style>{`
        .pfp-pill{transition:background .2s,border-color .2s,box-shadow .2s}
        .pfp-pill:hover{background:rgba(197, 52, 0,0.2);border-color:var(--green);box-shadow:0 0 22px -4px var(--green-glow)}
        .nav-dropdown__label{transition:color .18s ease}
        .nav-dropdown:hover .nav-dropdown__label{color:var(--green)}
        .nav-dropdown__menu{
          position:absolute;top:100%;left:50%;
          min-width:200px;width:max-content;margin-top:10px;padding:6px 0;
          background:rgba(13,13,13,0.94);backdrop-filter:blur(14px);
          border:1px solid var(--line);border-radius:8px;
          box-shadow:0 16px 50px rgba(0,0,0,0.55);
          z-index:60;
          opacity:0;visibility:hidden;pointer-events:none;
          transform:translateX(-50%) translateY(-6px);
          transition:opacity .18s ease-out,transform .22s cubic-bezier(.2,.7,.2,1),visibility .18s;
        }
        .nav-dropdown__menu[data-open="true"]{
          opacity:1;visibility:visible;pointer-events:auto;
          transform:translateX(-50%) translateY(0);
        }
        .nav-dropdown__menu>a{
          display:block;padding:10px 18px;font-size:13px;white-space:nowrap;
          font-family:var(--display);color:var(--dim);text-decoration:none;
          transition:color .15s, background .15s;
        }
        .nav-dropdown__menu>a:hover{color:var(--green);background:rgba(240,83,28,0.08)}
        /* Greyed, unclickable Claim / Surprise — rewards not live yet.
           Same layout as a dropdown link / drawer sub-link, but dim and
           inert (no pointer events, no hover). */
        .rewards-soon{
          display:block;padding:10px 18px;font-size:13px;
          font-family:var(--display);color:var(--dim);
          opacity:0.4;cursor:not-allowed;pointer-events:none;user-select:none;
        }
        .nav-burger{display:none}
        .burger{position:relative;display:inline-block;width:18px;height:12px}
        .burger i{position:absolute;left:0;width:100%;height:2px;background:var(--text);border-radius:2px;transition:transform .25s ease,opacity .2s ease,top .25s ease}
        .burger i:nth-child(1){top:0}.burger i:nth-child(2){top:5px}.burger i:nth-child(3){top:10px}
        .burger.open i:nth-child(1){top:5px;transform:rotate(45deg)}
        .burger.open i:nth-child(2){opacity:0}
        .burger.open i:nth-child(3){top:5px;transform:rotate(-45deg)}
        .nav-drawer{display:none}
        @media(max-width:760px){
          .nav-desk{display:none!important}
          .nav-burger{display:inline-flex!important}
          .nav-drawer{position:absolute;top:calc(100% + 8px);left:var(--gut);right:var(--gut);
            flex-direction:column;gap:2px;padding:10px;border:1px solid var(--line);border-radius:12px;
            background:rgba(9,9,11,0.94);backdrop-filter:blur(14px);pointer-events:auto;
            box-shadow:0 24px 50px -20px rgba(0,0,0,0.8);
            font-family:var(--mono);font-size:14px;letter-spacing:0.12em;text-transform:uppercase;
            max-height:calc(100vh - 80px);overflow-y:auto}
          .nav-drawer.open{display:flex}
          .nav-drawer>a,.nav-drawer__group-head{
            display:flex;align-items:center;justify-content:space-between;
            width:100%;padding:14px 12px;
            color:var(--text);text-decoration:none;
            background:transparent;border:none;border-radius:7px;
            font:inherit;letter-spacing:inherit;text-transform:inherit;
            cursor:pointer
          }
          .nav-drawer>a:active,.nav-drawer__group-head:active{background:rgba(255,255,255,0.06)}
          .nav-drawer__sub{display:flex;flex-direction:column;padding:2px 0 6px 14px;
            border-left:1px solid var(--line);margin:2px 0 6px 12px}
          .nav-drawer__sub>a{padding:10px 12px;color:var(--dim);text-decoration:none;font-size:13px;border-radius:7px}
          .nav-drawer__sub>a:active{background:rgba(255,255,255,0.06);color:var(--text)}
        }
      `}</style>
    </nav>
  );
}

function Hero() {
  const { canvasRef } = usePoolCanvas("hero");
  const [vid, setVid] = useStateT(false);
  return (
    <header id="top" style={{ position: "relative", minHeight: "calc(100vh - var(--promo-h, 0px))", display: "flex",
      flexDirection: "column", justifyContent: "center", alignItems: "center", overflow: "hidden" }}>
      {/* subtle ambient bg video — shielded-page treatment (luminosity blend + low opacity keeps it abstract, not distracting) */}
      <video src="uploads/bg.mp4" autoPlay muted loop playsInline aria-hidden="true"
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover",
          zIndex: 0, mixBlendMode: "luminosity", opacity: 0.35, pointerEvents: "none" }} />
      {/* ambient funnel */}
      <canvas ref={canvasRef} style={{
        position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.8, zIndex: 1,
      }} />
      {/* strk20-style background gradient + video darkening */}
      <div style={{ position: "absolute", inset: 0, zIndex: 2,
        background: "radial-gradient(ellipse 70% 55% at 50% 60%, rgba(197, 52, 0,0.13), transparent 60%), radial-gradient(ellipse at 50% 48%, rgba(13,13,13,0.45) 20%, var(--bg) 78%)" }} />

      <div className="wrap" style={{ position: "relative", zIndex: 3, width: "100%",
        display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center" }}>
        <Reveal>
          <a href="#" onClick={(e) => { e.preventDefault(); track("watch_explainer", "hero"); setVid(true); }} className="hero-play"
            style={{ display: "inline-flex", alignItems: "center", gap: 9, cursor: "pointer",
            border: "1px solid var(--line)", borderRadius: 999, padding: "4px 5px 4px 13px",
            background: "rgba(12,12,16,0.5)", backdropFilter: "blur(6px)" }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.18em",
              color: "var(--dim)", textTransform: "uppercase" }}>Watch the 25-second explainer</span>
            <span style={{ width: 22, height: 22, borderRadius: "50%", background: "var(--green)",
              color: "#fff", display: "grid", placeItems: "center", fontSize: 8 }}>▶</span>
          </a>
        </Reveal>

        <Reveal delay={0.08} style={{ width: "100%" }}>
          <h1 style={{ fontSize: "clamp(22px,5.6vw,62px)", marginTop: 22, letterSpacing: "-0.025em",
            maxWidth: "min(94vw,1100px)", marginInline: "auto", textAlign: "center", lineHeight: 0.98, textTransform: "uppercase", fontWeight: 800,
            background: "linear-gradient(178deg, #fffdf1 0%, #f4ece8 50%, #ffcdb6 100%)",
            WebkitBackgroundClip: "text", backgroundClip: "text",
            WebkitTextFillColor: "transparent", color: "transparent" }}>
            Privacy that<br/>works for<br/>crypto.
          </h1>
        </Reveal>

        <Reveal delay={0.16}>
          <p style={{ marginTop: 22, fontSize: "clamp(14px,1.15vw,17px)", color: "var(--dim)",
            maxWidth: 480, lineHeight: 1.6, fontFamily: "var(--body)", fontWeight: 400 }}>
            Shield any tokens. Move them privately. Use them anywhere in DeFi. Compliant for regulators.
          </p>
        </Reveal>

        <Reveal delay={0.22}>
          <a href="#story" className="btn btn-orange" style={{ marginTop: 36 }}>
            Enter the pool <span className="arrow">↓</span>
          </a>
        </Reveal>
      </div>

      {/* ecosystem ticker — above the fold */}
      <div style={{ position: "absolute", bottom: 34, left: 0, right: 0, zIndex: 4 }}>
        <LogoTicker compact />
      </div>
      {vid && (
        <div onClick={() => setVid(false)} style={{ position: "fixed", inset: 0, zIndex: 100,
          background: "rgba(5,5,5,0.9)", backdropFilter: "blur(8px)", display: "flex",
          alignItems: "center", justifyContent: "center", padding: "clamp(16px,5vw,60px)" }}>
          <div onClick={(e) => e.stopPropagation()} style={{ position: "relative", width: "min(960px,100%)" }}>
            <button onClick={() => setVid(false)} style={{ position: "absolute", top: -40, right: 0,
              background: "none", border: "1px solid var(--line)", color: "var(--dim)",
              fontFamily: "var(--mono)", fontSize: 12, padding: "6px 12px", cursor: "pointer", borderRadius: 3 }}>
              ESC ✕
            </button>
            <video src="uploads/strk20-explainer.mp4" controls autoPlay playsInline
              style={{ width: "100%", borderRadius: 8, border: "1px solid var(--line)", background: "#000",
                display: "block", boxShadow: "0 40px 120px -40px rgba(197, 52, 0,0.4)" }} />
          </div>
        </div>
      )}
      <style>{`.hero-play{transition:border-color .2s,background .2s}.hero-play:hover{border-color:var(--green)}@media(max-width:760px){.hero-br{display:none}}`}</style>
    </header>
  );
}

Object.assign(window, { Nav, Hero, Logo, LOGO_URL });
