/* header-app.jsx — header for /app surface (dropdowns only; wallet
 * integration is stripped from this branch).
 *
 * No-bundler form: React globals, no react-router (we navigate via
 * full-page reloads with plain `<a href>`), Logo comes from
 * sections-top.jsx as a window global. */
const { useState, useRef, useEffect } = React;
// `useLocation` is replaced by reading window.location.pathname
// directly on render — full-page navigation between /app/* routes is
// the no-bundler default.

const APP_MENU = [
  { label: "Home",      to: "/" },
  // "Use" + "Dashboard" entries temporarily hidden to keep the app header
  // structurally aligned with the landing Nav (Home / Build / Tutorials
  // [/Rewards]). Pages at /app/live-apps and /app/dashboard still resolve
  // for direct URLs and for the Launch App / Apply for SDK CTAs.
  { label: "Build",     items: [{ label: "RFPs", href: "/rfp" }, { label: "Apply", href: "/build" }] },
  { label: "Tutorials", href: "/#playlists" },
  // Rewards is intentionally disabled for now — visible so users know
  // the section exists, but the dropdown + child links are suppressed
  // (see NavItem's `disabled` branch + the drawer rendering below).
  { label: "Rewards", disabled: true, items: [{ label: "Claim", href: "#claim" }, { label: "Surprise", href: "#surprise" }] },
];

function NavItem({ entry, isOpen, onEnter, onLeave }) {
  const hasDropdown = !!entry.items && !entry.disabled;
  const closeTimerRef = useRef(null);
  const handleEnter = () => {
    if (entry.disabled) return;
    if (closeTimerRef.current) { clearTimeout(closeTimerRef.current); closeTimerRef.current = null; }
    onEnter();
  };
  const handleLeave = () => {
    if (entry.disabled) return;
    closeTimerRef.current = setTimeout(() => { onLeave(); closeTimerRef.current = null; }, 140);
  };
  useEffect(() => () => { if (closeTimerRef.current) clearTimeout(closeTimerRef.current); }, []);

  // Match the landing-page Nav (sections-top.jsx) link styling exactly:
  // mono 13/0.14em uppercase, default text color, .footlink class so the
  // green hover transition comes through from sections-bottom.jsx.
  const labelStyle = {
    fontFamily: "var(--mono)", fontSize: 13, letterSpacing: "0.14em",
    textTransform: "uppercase", textDecoration: "none",
    color: entry.disabled ? "var(--dim)" : "var(--text)",
    opacity: entry.disabled ? 0.45 : 1,
    display: "inline-flex", alignItems: "center", gap: 6,
    cursor: entry.disabled ? "not-allowed" : (hasDropdown ? "default" : "pointer"),
    pointerEvents: entry.disabled ? "none" : "auto",
  };
  const labelInner = (
    <>
      {entry.label}
      {hasDropdown && (
        <span style={{ fontSize: 8, opacity: 0.6, transform: isOpen ? "rotate(180deg)" : "none",
          transition: "transform .18s ease-out" }}>▼</span>
      )}
    </>
  );

  const dropdownItemStyle = {
    display: "block", padding: "10px 18px", fontSize: 13,
    fontFamily: "var(--display)", textDecoration: "none",
  };

  // Disabled branch — render as a non-interactive span so it's visible
  // (so users know the section exists) but unclickable and the dropdown
  // arrow + popover are gone. The .footlink class is omitted so the
  // green hover never triggers.
  if (entry.disabled) {
    return (
      <span
        aria-disabled="true"
        title="Coming soon"
        style={labelStyle}
      >
        {entry.label}
      </span>
    );
  }

  return (
    <div
      onMouseEnter={handleEnter}
      onMouseLeave={handleLeave}
      style={{ position: "relative" }}
    >
      {entry.to ? (
        <a href={entry.to} className="footlink" style={labelStyle}>{labelInner}</a>
      ) : (
        <a href={hasDropdown ? undefined : entry.href} className="footlink" style={labelStyle}>{labelInner}</a>
      )}
      {hasDropdown && (
        <div style={{
          position: "absolute", top: "100%", left: "50%",
          transform: `translateX(-50%) translateY(${isOpen ? "0" : "-6px"})`,
          marginTop: 10, minWidth: 200,
          background: "rgba(13,13,13,0.94)", backdropFilter: "blur(14px)",
          border: "1px solid var(--line)", borderRadius: 8,
          padding: "6px 0", zIndex: 60,
          boxShadow: "0 16px 50px rgba(0,0,0,0.55)",
          opacity: isOpen ? 1 : 0,
          visibility: isOpen ? "visible" : "hidden",
          pointerEvents: isOpen ? "auto" : "none",
          transition: "opacity .18s ease-out, transform .22s cubic-bezier(.2,.7,.2,1), visibility .18s",
        }}>
          {/* invisible bridge so moving down doesn't close */}
          <div style={{ position: "absolute", top: -10, left: 0, right: 0, height: 10 }} />
          {entry.items.map((it) => (
            it.to ? (
              <a key={it.label} href={it.to} className="dropdown-link" style={dropdownItemStyle}>{it.label}</a>
            ) : (
              <a key={it.label} href={it.href} target={it.target} rel={it.rel} className="dropdown-link" style={dropdownItemStyle}>{it.label}</a>
            )
          ))}
        </div>
      )}
    </div>
  );
}

function HeaderApp() {
  const [openIdx, setOpenIdx] = useState(null);
  // Mobile drawer state — independent of desktop hover dropdowns.
  // Tracks which submenu group (Users / Builders / Rewards) is expanded
  // inline inside the drawer. -1 means none expanded.
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [drawerExpanded, setDrawerExpanded] = useState(-1);

  // Close the drawer on any external nav click (full-page reload won't
  // unmount before paint on some devices, so collapse first).
  const closeDrawer = () => { setDrawerOpen(false); setDrawerExpanded(-1); };

  return (
    <nav style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 50,
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "16px var(--gut)", pointerEvents: "none",
      overflow: "visible",
    }}>
      {/* Blur backdrop — extends below the nav and fades out via mask so
          the blur smoothly dissolves into the page content instead of
          ending at a hard line. */}
      <div aria-hidden="true" style={{
        position: "absolute", top: 0, left: 0, right: 0, height: 150,
        pointerEvents: "none", zIndex: -1,
        background: "linear-gradient(180deg, rgba(13,13,13,0.78) 0%, rgba(13,13,13,0) 100%)",
        backdropFilter: "blur(14px) saturate(140%)",
        WebkitBackdropFilter: "blur(14px) saturate(140%)",
        maskImage: "linear-gradient(180deg, rgba(0,0,0,1) 30%, rgba(0,0,0,0) 100%)",
        WebkitMaskImage: "linear-gradient(180deg, rgba(0,0,0,1) 30%, rgba(0,0,0,0) 100%)",
      }} />
      <a href="/" style={{
        display: "flex", alignItems: "center", pointerEvents: "auto",
        position: "relative", zIndex: 1,
        textDecoration: "none",
      }}>
        <Logo size={22} />
      </a>

      <div className="nav-menu app-nav-desk" style={{
        display: "flex", alignItems: "center",
        gap: "clamp(20px,2.6vw,44px)",
        pointerEvents: "auto",
        position: "relative", zIndex: 1,
      }}>
        {APP_MENU.map((entry, i) => (
          <NavItem
            key={entry.label}
            entry={entry}
            isOpen={openIdx === i}
            onEnter={() => setOpenIdx(i)}
            onLeave={() => setOpenIdx((cur) => (cur === i ? null : cur))}
          />
        ))}
      </div>

      {/* Right-side CTA — Apply for SDK. External cal.com booking page,
          same destination main's BuildPage uses for "Request SDK access".
          Opens in a new tab. Visible only on desktop; the mobile drawer
          carries the same link at the bottom. */}
      <a
        href="https://cal.com/adithyadinesh"
        target="_blank" rel="noopener noreferrer"
        className="app-nav-cta app-nav-desk btn btn-orange"
        style={{
          pointerEvents: "auto",
          position: "relative", zIndex: 1,
          padding: "10px 20px", fontSize: 13,
          // Belt-and-suspenders inline styles so the button looks right
          // even if .btn / .btn-orange CSS hasn't won the cascade by the
          // time HeaderApp paints on /app/* routes. Matches the rules
          // in styles.css for .btn + .btn-orange exactly.
          fontFamily: "var(--mono)",
          fontWeight: 600,
          letterSpacing: "0.04em",
          textTransform: "uppercase",
          background: "var(--orange, #c53400)",
          color: "#fff",
          border: "1px solid var(--orange, #c53400)",
          borderRadius: 2,
          textDecoration: "none",
          display: "inline-flex",
          alignItems: "center",
          whiteSpace: "nowrap",
        }}
      >
        Apply for SDK
      </a>

      {/* Mobile hamburger — same button styling as the landing-page Nav
          in sections-top.jsx so users get a consistent affordance across
          / and /app/*. Reuses the global .burger CSS classes defined
          there. Shown only when .app-nav-burger is :visible (≤760px). */}
      <button
        className="app-nav-burger"
        aria-label="Menu" aria-expanded={drawerOpen}
        onClick={() => setDrawerOpen((o) => !o)}
        style={{
          pointerEvents: "auto",
          position: "relative", zIndex: 2,
          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" + (drawerOpen ? " open" : "")}><i /><i /><i /></span>
      </button>

      {/* Mobile drawer — pinned below the nav. Two-level: top-level items
          with submenus expand inline rather than navigating, plain items
          link directly. Drawer auto-closes on outside tap and on plain
          link tap (the click bubbles to the wrapper). */}
      <div
        className={"app-nav-drawer" + (drawerOpen ? " open" : "")}
        onClick={(e) => {
          // Only close on actual link taps, not on submenu-header toggles.
          if (e.target.tagName === "A") closeDrawer();
        }}
      >
        {APP_MENU.map((entry, i) => {
          if (entry.disabled) {
            // Render disabled entries as non-interactive labels so users
            // see them but can't interact. Matches the desktop styling.
            return (
              <span
                key={entry.label}
                aria-disabled="true"
                title="Coming soon"
                style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  width: "100%", padding: "14px 12px",
                  color: "var(--dim)", opacity: 0.45,
                  cursor: "not-allowed", pointerEvents: "none",
                }}
              >{entry.label}</span>
            );
          }
          if (!entry.items) {
            // Plain link — Dashboard / Tutorials etc.
            return entry.to ? (
              <a key={entry.label} href={entry.to}>{entry.label}</a>
            ) : (
              <a key={entry.label} href={entry.href}>{entry.label}</a>
            );
          }
          // Collapsible submenu — tap header to expand, tap a child to navigate.
          const isExpanded = drawerExpanded === i;
          return (
            <div key={entry.label} className="app-nav-drawer__group">
              <button
                type="button"
                className="app-nav-drawer__group-head"
                aria-expanded={isExpanded}
                onClick={(e) => {
                  e.stopPropagation();
                  setDrawerExpanded((cur) => (cur === i ? -1 : i));
                }}
              >
                <span>{entry.label}</span>
                <span style={{
                  fontSize: 8, opacity: 0.6,
                  transform: isExpanded ? "rotate(180deg)" : "none",
                  transition: "transform .18s ease-out",
                }}>▼</span>
              </button>
              {isExpanded && (
                <div className="app-nav-drawer__sub">
                  {entry.items.map((it) => (
                    it.to ? (
                      <a key={it.label} href={it.to}>{it.label}</a>
                    ) : (
                      <a key={it.label} href={it.href} target={it.target} rel={it.rel}>{it.label}</a>
                    )
                  ))}
                </div>
              )}
            </div>
          );
        })}
        {/* Mirror the desktop right-side CTA at the bottom of the drawer
            so the action stays reachable on phones. */}
        <a href="https://cal.com/adithyadinesh" target="_blank" rel="noopener noreferrer" className="btn btn-orange" style={{ justifyContent: "center", marginTop: 6 }}>Apply for SDK</a>
      </div>

      {/* Wallet integration is out of scope for this branch — header
          intentionally has no Connect Wallet pill on the right side. */}

      <style>{`
        /* Top-level link hover is handled by .footlink (sections-bottom.jsx)
           so HeaderApp gets the exact same green-on-hover behaviour as the
           landing-page Nav. Dropdown items keep their own dim → green hover. */
        .dropdown-link { color: var(--dim); transition: color .15s, background .15s; }
        .dropdown-link:hover { color: var(--green); background: rgba(240,83,28,0.08); }

        /* Mobile hamburger + drawer — mirrors the .nav-burger / .nav-drawer
           pattern in sections-top.jsx. Different class names (.app-*) so
           the two headers can't accidentally style each other when both
           are mounted at once during route transitions. The .burger
           span inside the button needs its own CSS because the version
           in sections-top.jsx is only mounted on / (its <style> block
           lives inside that Nav component). */
        .app-nav-burger { display: none; }
        .app-nav-burger .burger {
          position: relative; display: inline-block;
          width: 18px; height: 12px;
        }
        .app-nav-burger .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;
        }
        .app-nav-burger .burger i:nth-child(1) { top: 0; }
        .app-nav-burger .burger i:nth-child(2) { top: 5px; }
        .app-nav-burger .burger i:nth-child(3) { top: 10px; }
        .app-nav-burger .burger.open i:nth-child(1) { top: 5px; transform: rotate(45deg); }
        .app-nav-burger .burger.open i:nth-child(2) { opacity: 0; }
        .app-nav-burger .burger.open i:nth-child(3) { top: 5px; transform: rotate(-45deg); }
        .app-nav-drawer { display: none; }
        @media (max-width: 760px) {
          .app-nav-desk { display: none !important; }
          .app-nav-burger { display: inline-flex !important; }
          .app-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);
            -webkit-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;
            z-index: 2;
            max-height: calc(100vh - 96px);
            overflow-y: auto;
          }
          .app-nav-drawer.open { display: flex; }
          .app-nav-drawer > a,
          .app-nav-drawer__group-head {
            display: flex; align-items: center; justify-content: space-between;
            width: 100%; padding: 14px 12px;
            color: var(--text); text-decoration: none;
            border-radius: 7px;
            background: transparent; border: none;
            font: inherit; letter-spacing: inherit; text-transform: inherit;
            cursor: pointer;
          }
          .app-nav-drawer > a:active,
          .app-nav-drawer__group-head:active { background: rgba(255,255,255,0.06); }
          .app-nav-drawer__sub {
            display: flex; flex-direction: column;
            padding: 2px 0 6px 14px;
            border-left: 1px solid var(--line);
            margin: 2px 0 6px 12px;
          }
          .app-nav-drawer__sub > a {
            padding: 10px 12px;
            color: var(--dim); text-decoration: none;
            font-size: 13px;
            border-radius: 7px;
          }
          .app-nav-drawer__sub > a:active { background: rgba(255,255,255,0.06); color: var(--text); }
        }
      `}</style>
    </nav>
  );
}

// No export — script-tag load makes HeaderApp a window global,
// consumed by app-page.jsx.
