/* Aevitan website — chrome: minimal header + rich footer (Beauty-In-Stem structure). */
const DS = window.AevitanDesignSystem_6a042d;
// The account area is the authenticated portal (separate origin); the header account icon signs in there.
const PORTAL_URL = (typeof location !== 'undefined' && location.hostname === 'localhost')
  ? 'http://localhost:3001'
  : 'https://portal.aevitan.com';

// B33: the /api/me fetch is hoisted to MODULE scope so window.__aevitanMeReady is assigned synchronously at
// script eval — BEFORE first paint or any CTA click — closing the pre-effect auth race. Every reader (the
// header icon AND Club.jsx's routePath) awaits/reads this ONE shared result. Fetch failure => signed-out.
if (typeof window !== 'undefined' && !window.__aevitanMeReady) {
  window.__aevitanMeReady = fetch(PORTAL_URL + '/api/me', { credentials: 'include' })
    .then((r) => (r.ok ? r.json() : null))
    .then((d) => { const v = d && d.firstName ? { firstName: d.firstName } : false; window.__aevitanMe = v; return v; })
    .catch(() => { window.__aevitanMe = false; return false; });
}

const ICON = {
  account: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm-7 8a7 7 0 0 1 14 0',
};
// Root-relative URL per route (lc-store.js) so nav anchors are REAL links — open-in-new-tab,
// copy-link and a11y semantics work; onClick preventDefaults into the SPA's go().
const RPATHS = (window.AEV_ROUTES || {}).paths || {};
const spaNav = (fn) => (e) => { e.preventDefault(); fn(); };
function Glyph({ d }) {
  return (
    <svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
      <path d={d} />
    </svg>
  );
}

// Login-aware account state (owner-defined): the web stays secret-free and asks the portal who you are via a
// credentialed same-site fetch to /api/me. CONSUMES the single module-level promise above (no per-mount fetch,
// no race) — the desktop icon, the mobile drawer row and Club.jsx's routePath all read the same result.
function useAccountMe() {
  const [me, setMe] = React.useState(window.__aevitanMe); // undefined until resolved, {firstName}|false after
  React.useEffect(() => {
    let alive = true;
    window.__aevitanMeReady.then((v) => { if (alive) setMe(v); });
    return () => { alive = false; };
  }, []);
  return me;
}

// Renders the account affordance in one of two variants from the shared `me` state (no own fetch, no nested anchors).
// Signed in -> "Hi, <first name>" + tip "Your dashboard", opens the portal. Signed out -> the portal SIGN-IN
// screen (owner-defined): the icon signs you in; new professionals reach onboarding via the portal login's
// "New to Aevitan? Request access ->" link, which lands on /account.
function AccountEntry({ me, go, variant, onNavigate }) {
  const signedIn = !!(me && me.firstName);
  const signInUrl = PORTAL_URL + '/login';
  if (variant === 'drawer') {
    return signedIn ? (
      // Signed-in: a real external link to the portal — default navigation, just close the drawer.
      <a className="is-in" href={PORTAL_URL} title="Your dashboard" onClick={() => { if (onNavigate) onNavigate(); }}>Hi, {me.firstName}<span aria-hidden="true">→</span></a>
    ) : (
      <a href={signInUrl} title="Sign in" onClick={() => { if (onNavigate) onNavigate(); }}>Sign in<span aria-hidden="true">→</span></a>
    );
  }
  return signedIn ? (
    <a className="aev-hd__acct is-in" href={PORTAL_URL} title="Your dashboard" aria-label={'Your dashboard, ' + me.firstName}>
      <Glyph d={ICON.account} /><span className="aev-hd__hi">Hi, {me.firstName}</span>
    </a>
  ) : (
    <a className="aev-hd__acct" href={signInUrl} title="Sign in" aria-label="Sign in">
      <Glyph d={ICON.account} />
    </a>
  );
}

// Owner-reported (2026-08-04): the wordmark is centred, so the two nav groups must balance around
// it. The right side carried 4 links PLUS the account entry against 2 on the left; 'About us' moves
// left to even the visual weight (3 + 3-with-account). The drawer keeps its own single ordered list.
const MENU_L = [
  ['science', 'Science'],
  ['club', 'Longevity Club'],
  ['about', 'About us'],
];
const MENU_R = [
  ['shop', 'Products'],
  ['verify', 'Verify'],
  ['faq', 'FAQ'],
];

function Header({ route, go, transparent }) {
  const ref = React.useRef(null);
  const me = useAccountMe();
  const [menuOpen, setMenuOpen] = React.useState(false);
  const ALL = [...MENU_L, ...MENU_R];
  const nav = (id) => { setMenuOpen(false); go(id); };
  // Shared, ref-counted body scroll-lock (lc-store.js) so the mobile menu and the Home product drawer never fight.
  React.useEffect(() => {
    if (!menuOpen) return undefined;
    const lock = window.aevScrollLock;
    if (lock) lock.acquire();
    return () => { if (lock) lock.release(); };
  }, [menuOpen]);
  React.useEffect(() => { setMenuOpen(false); }, [route]);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const apply = () => {
      const y = window.scrollY || 0;
      // home: start slightly translucent, ramp to fully opaque white over ~60% of a screen.
      // other pages: solid immediately.
      const p = transparent ? Math.max(0, Math.min(1, y / (window.innerHeight * 0.6))) : 1;
      const a = (0.10 + p * 0.90) * 0.7;
      el.style.background = `rgba(255,255,255,${a.toFixed(3)})`;
      el.style.borderBottomColor = `rgba(231,233,238,${(p * 0.7).toFixed(3)})`;
      el.style.boxShadow = p > 0.5 ? '0 1px 0 rgba(12,26,51,0.04)' : 'none';
    };
    apply();
    window.addEventListener('scroll', apply, { passive: true });
    window.addEventListener('resize', apply);
    return () => { window.removeEventListener('scroll', apply); window.removeEventListener('resize', apply); };
  }, [transparent]);
  return (
    <React.Fragment>
    <header className="aev-hd" ref={ref}>
      <div className="aev-hd__in">
        <div className="aev-hd__left">
          <button className={`aev-hd__burger ${menuOpen ? 'is-open' : ''}`} aria-label="Menu" aria-expanded={menuOpen} onClick={() => setMenuOpen((o) => !o)}>
            <span></span><span></span><span></span>
          </button>
          <nav className="aev-hd__nav aev-hd__nav--l">
            {MENU_L.map(([id, label]) => (
              <a key={id} href={RPATHS[id]} className={route === id ? 'on' : ''} onClick={spaNav(() => go(id))}>{label}</a>
            ))}
          </nav>
        </div>
        <a className="aev-hd__logo" href="/" onClick={spaNav(() => go('home'))}>
          <img src="../../assets/aevitan-wordmark-transparent.png" alt="Aevitan" />
        </a>
        <nav className="aev-hd__nav aev-hd__nav--r">
          {MENU_R.map(([id, label]) => (
            <a key={id} href={RPATHS[id]} className={route === id ? 'on' : ''} onClick={spaNav(() => go(id))}>{label}</a>
          ))}
          <AccountEntry me={me} go={go} variant="desktop" />
        </nav>
      </div>
    </header>
      {/* Drawer lives OUTSIDE <header> so the header's backdrop-filter (which establishes a
          containing block for position:fixed) doesn't clip it — it stays viewport-fixed. */}
      <div className={`aev-hd__mobile ${menuOpen ? 'is-open' : ''}`}>
        <nav>
          {ALL.map(([id, label]) => (
            <a key={id} href={RPATHS[id]} className={route === id ? 'on' : ''} onClick={spaNav(() => nav(id))}>{label}<span aria-hidden="true">→</span></a>
          ))}
          <AccountEntry me={me} go={go} variant="drawer" onNavigate={() => setMenuOpen(false)} />
        </nav>
      </div>
    </React.Fragment>
  );
}

function Footer({ go }) {
  return (
    <footer className="aev-ft">
      <div className="aev-ft__top">
        <a className="aev-ft__logo" href="/" onClick={spaNav(() => go('home'))}>
          <img src="../../assets/aevitan-wordmark-transparent.png" alt="Aevitan" />
        </a>
        <div className="aev-ft__explore">
          <span className="aev-ft__nav-h">Explore</span>
          <nav className="aev-ft__nav">
            <a href={RPATHS.science} onClick={spaNav(() => go('science'))}>Science</a>
            <a href={RPATHS.club} onClick={spaNav(() => go('club'))}>Longevity Club</a>
            <a href={RPATHS.about} onClick={spaNav(() => go('about'))}>About us</a>
            <a href={RPATHS.shop} onClick={spaNav(() => go('shop'))}>Products</a>
            <a href={RPATHS.verify} onClick={spaNav(() => go('verify'))}>Verify</a>
            <a href={RPATHS.faq} onClick={spaNav(() => go('faq'))}>FAQ</a>
          </nav>
        </div>
      </div>

      <div className="aev-ft__bot">
        <span>© 2026 Aevitan. Verified longevity &amp; wellness.</span>
        <nav className="aev-ft__legal">
          <a href={RPATHS.returns} onClick={spaNav(() => go('returns'))}>Return Policy</a>
          <a href={RPATHS.terms} onClick={spaNav(() => go('terms'))}>Terms &amp; Conditions</a>
          <a href={RPATHS.privacy} onClick={spaNav(() => go('privacy'))}>Privacy Policy</a>
        </nav>
        <span className="aev-ft__cur">Region: United States (USD)</span>
      </div>
    </footer>
  );
}

window.Header = Header;
window.Footer = Footer;
