// components/header.jsx
// <SiteHeader>. Round 11 Block B/C:
//   LEFT: fanish-wordmark.svg
//   RIGHT (desktop): Get fanish. CTA pill + hamburger
//   RIGHT (mobile): hamburger only
//   Hamburger menu = right-anchored popover with: How it works, Examples,
//     What you get, FAQ.

function SiteHeader({ onIntent, isLaunched, onHowItWorks }) {
  const C = window.COPY;
  const [open, setOpen] = React.useState(false);

  const triggerCta = (origin) => {
    setOpen(false);
    const ua = navigator.userAgent || "";
    const isIOS = /iPhone|iPad|iPod/i.test(ua);
    const isAndroid = /Android/i.test(ua);
    // iPhone + iOS live → straight to the App Store.
    if (isIOS && C.iosLaunched && C.cta.appStoreUrl) {
      window.trackEvent("header_cta_click", { source: "header", origin, platform: "ios" });
      window.trackEvent("app_store_redirect", { source: "header", origin, platform: "ios" });
      window.location.href = C.cta.appStoreUrl;
      return;
    }
    // Android device, once live → Play (future).
    if (isAndroid && C.androidLaunched && C.cta.googlePlayUrl) {
      window.trackEvent("header_cta_click", { source: "header", origin, platform: "android" });
      window.trackEvent("app_store_redirect", { source: "header", origin, platform: "android" });
      window.location.href = C.cta.googlePlayUrl;
      return;
    }
    // Android device, not yet live → coming-soon modal.
    if (isAndroid) {
      window.trackEvent("header_cta_click", { source: "header", origin, platform: "android" });
      onIntent("header", "android");
      return;
    }
    // Desktop / anything else: iOS is the live product → App Store listing.
    if (C.iosLaunched && C.cta.appStoreUrl) {
      window.trackEvent("header_cta_click", { source: "header", origin, platform: "desktop" });
      window.trackEvent("app_store_redirect", { source: "header", origin, platform: "ios" });
      window.location.href = C.cta.appStoreUrl;
      return;
    }
    // Fully pre-launch fallback.
    window.trackEvent("header_cta_click", { source: "header", origin });
    onIntent("header", "android");
  };

  const navClick = (label, href, e) => {
    window.trackEvent(label === "How it works" ? "nav_how_click" : "nav_faq_click", { source: "header" });
    setOpen(false);
    // The "How it works" interception only makes sense when the FAQ
    // section actually exists on the current page (i.e. we're on home).
    // On supplemental pages, the href has already been rewritten to
    // "/#faq-how-it-works" so the browser will navigate naturally.
    if (label === "How it works" && onHowItWorks && document.getElementById("faq")) {
      e && e.preventDefault();
      onHowItWorks();
      history.pushState(null, "", "#faq-how-it-works");
      const faqSection = document.getElementById("faq");
      if (faqSection) {
        setTimeout(() => faqSection.scrollIntoView({ behavior: "smooth", block: "start" }), 50);
      }
    }
  };

  // Close popover on outside click / Escape
  const popRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDocClick = (e) => {
      if (popRef.current && !popRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  return (
    <header className="site-header" role="banner">
      <a href="#main" className="skip-link">Skip to main content</a>

      <div className="site-header-inner">
        <a href="/" className="wordmark wordmark-header" aria-label="Fanish home">
          <img src="fanish-wordmark.svg" alt="fanish." className="wordmark-img" />
        </a>

        <div className="header-actions" ref={popRef}>
          <button
            type="button"
            className="hamburger"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
          >
            {open ? <IconClose size={28} /> : <IconMenu size={28} />}
          </button>

          {open && (
            <div className="header-menu-popover" role="dialog" aria-label="Navigation menu">
              {C.header.nav.map((item) => {
                // If we're not on the home page, in-page anchor hrefs
                // ("#faq", "#what-you-get", etc.) need to be rewritten to
                // absolute paths ("/#faq") so they navigate back to the
                // home page AND scroll to the target. Otherwise the link
                // becomes "<currentpage>.html#faq" which has no target
                // and just appends the hash to the URL.
                const onHome =
                  window.location.pathname === "/" ||
                  window.location.pathname.endsWith("/index.html") ||
                  window.location.pathname.endsWith("index.html");
                const isAnchor = item.href && item.href.startsWith("#");
                const effectiveHref = !onHome && isAnchor ? "/" + item.href : item.href;
                return (
                  <a
                    key={item.label}
                    href={effectiveHref}
                    className="header-menu-item"
                    data-track={item.trackEvent}
                    onClick={(e) => navClick(item.label, effectiveHref, e)}
                  >
                    {item.label}
                  </a>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </header>
  );
}

window.SiteHeader = SiteHeader;
