/* global React, MagneticButton */
const { useState, useEffect } = React;

const NAV = [
  { label: "Productos", href: "#products" },
  { label: "Seguridad", href: "#security" },
  { label: "Clientes", href: "#testimonials" },
  { label: "Casos de uso", href: "#casos-uso" },
];

// mobileNav: "menu"  → hamburger that opens a full-width nav sheet
//            "fixed" → no hamburger; a persistent bottom CTA bar instead
// baseHref: prefix for the section anchors ("#products", "#top", ...) so the
//           header works unchanged on the landing page (baseHref="") and on
//           standalone pages like the legal docs (baseHref="Landing%20Page.html").
function Header({ mobileNav = "menu", baseHref = "" }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const homeHref = `${baseHref}#top`;

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Expose the active mobile-nav mode to CSS (for body offsets, visibility)
  useEffect(() => {
    document.documentElement.setAttribute("data-mobile-nav", mobileNav);
  }, [mobileNav]);

  // Lock body scroll while the mobile sheet is open
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  // Close the sheet whenever we leave the mobile breakpoint or switch variant
  useEffect(() => {
    if (mobileNav !== "menu") setOpen(false);
    const mq = window.matchMedia("(min-width: 761px)");
    const onChange = (e) => { if (e.matches) setOpen(false); };
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, [mobileNav]);

  return (
    <React.Fragment>
      <header className={`site-header${scrolled ? " is-scrolled" : ""}`}>
        <div className="wrap">
          <a href={homeHref} className="header-logo" style={{ display: "flex", alignItems: "center", textDecoration: "none" }} data-hover="1" onClick={() => setOpen(false)}>
            <img src="assets/meefi-logo-header.png" alt="Meefi" style={{ width: 92, height: 30, display: "block", objectFit: "cover", objectPosition: "center" }} />
          </a>

          <nav className="site-nav">
            {NAV.map((n) =>
              <a key={n.label} href={`${baseHref}${n.href}`} data-hover="1">{n.label}</a>
            )}
          </nav>

          <div className="header-actions" style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <div className="lang-toggle" role="group" aria-label="Idioma" style={{ display: "flex", alignItems: "center", gap: 2, padding: 2, border: "1px solid var(--border)", borderRadius: 999 }}>
              <span aria-current="true" style={{ fontSize: 12, fontWeight: 550, color: "var(--fg-1)", background: "var(--bg-3)", padding: "3px 8px", borderRadius: 999, lineHeight: 1 }}>ES</span>
              <a href="Landing%20Page%20EN.html" data-hover="1" onClick={(e) => { if (window.parent !== window) { e.preventDefault(); window.parent.postMessage({ type: "meefi-lang", lang: "en" }, "*"); } }} style={{ fontSize: 12, fontWeight: 450, color: "var(--fg-2)", padding: "3px 8px", borderRadius: 999, textDecoration: "none", lineHeight: 1 }}>EN</a>
            </div>
            <a
              href="#"
              data-hover="1"
              className="header-login"
              style={{
                fontSize: 14, fontWeight: 450, color: "var(--fg-1)",
                padding: "8px 12px", textDecoration: "none",
                borderRadius: 8
              }}>
              Iniciar sesión</a>
            <MagneticButton variant="primary" className="header-cta" onClick={trackLead} style={{ height: 36, padding: "0 18px", fontSize: 14, borderRadius: 999 }}>
              Aplica ahora
            </MagneticButton>

            {/* Hamburger — only rendered in "menu" variant; CSS shows it ≤760px */}
            {mobileNav === "menu" && (
              <button
                type="button"
                className={`nav-burger${open ? " is-open" : ""}`}
                aria-label={open ? "Cerrar menú" : "Abrir menú"}
                aria-expanded={open}
                aria-controls="mobile-sheet"
                onClick={() => setOpen((v) => !v)}>
                <span className="nav-burger-box">
                  <span className="nav-burger-line" />
                  <span className="nav-burger-line" />
                  <span className="nav-burger-line" />
                </span>
              </button>
            )}
          </div>
        </div>
      </header>

      {/* ── Mobile nav sheet (hamburger variant) ── */}
      {mobileNav === "menu" && (
        <React.Fragment>
          <div
            className={`mobile-scrim${open ? " is-open" : ""}`}
            onClick={() => setOpen(false)}
            aria-hidden="true" />
          <div id="mobile-sheet" className={`mobile-sheet${open ? " is-open" : ""}`} role="dialog" aria-modal="true" aria-label="Navegación">
            <nav className="mobile-sheet-nav">
              {NAV.map((n) =>
                <a key={n.label} href={`${baseHref}${n.href}`} onClick={() => setOpen(false)}>{n.label}</a>
              )}
            </nav>
            <div className="mobile-sheet-actions">
              <div className="lang-toggle" role="group" aria-label="Idioma" style={{ display: "flex", alignItems: "center", gap: 4, justifyContent: "center", marginBottom: 4 }}>
                <span aria-current="true" style={{ fontSize: 14, fontWeight: 550, color: "var(--fg-1)", background: "var(--bg-3)", padding: "6px 14px", borderRadius: 999, lineHeight: 1 }}>ES</span>
                <a href="Landing%20Page%20EN.html" onClick={(e) => { if (window.parent !== window) { e.preventDefault(); window.parent.postMessage({ type: "meefi-lang", lang: "en" }, "*"); } setOpen(false); }} style={{ fontSize: 14, fontWeight: 450, color: "var(--fg-2)", padding: "6px 14px", borderRadius: 999, textDecoration: "none", lineHeight: 1 }}>EN</a>
              </div>
              <a href="#" className="mobile-sheet-login" onClick={() => setOpen(false)}>Iniciar sesión</a>
              <MagneticButton variant="primary" className="mobile-sheet-cta" onClick={() => { trackLead(); setOpen(false); }}>
                Aplica ahora
              </MagneticButton>
            </div>
          </div>
        </React.Fragment>
      )}

      {/* ── Fixed CTA bar (fixed-button variant) ── */}
      {mobileNav === "fixed" && (
        <div className="mobile-cta-bar">
          <a href="#" className="mobile-cta-login">Iniciar sesión</a>
          <MagneticButton variant="primary" className="mobile-cta-btn" onClick={trackLead}>
            Aplica ahora
          </MagneticButton>
        </div>
      )}
    </React.Fragment>
  );
}
window.Header = Header;
