/* =========================================================
   Header fixo + menu mobile + barra fixa mobile
   Figma: 708:28 (header no hero) · 728:128 / 728:154 (desktop topo / após rolar)
          728:191 / 728:203 (mobile topo / após rolar) · 723:388 / 728:215 (menu aberto)
          723:382 / 728:237 / 728:841 (barra fixa mobile)
   ========================================================= */
CFG.images.headerEmblema = CFG.images.headerEmblema || "assets/header/emblema-marca.svg";
CFG.images.iconeWhatsapp = CFG.images.iconeWhatsapp || "assets/header/whatsapp.svg";

const HEADER_NAV_LINKS = [
  { id: "empreendimento", label: "O empreendimento" },
  { id: "casas", label: "As casas" },
  { id: "lazer", label: "Lazer" },
  { id: "localizacao", label: "Localização" },
];

const HEADER_SOLID_AFTER = 120; // px rolados até o header ficar sólido

function headerReducedMotion() {
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

function headerScrollTo(id) {
  const el = document.getElementById(id);
  if (!el) return;
  el.scrollIntoView({ behavior: "auto" });
}

function HeaderBrand({ onClick }) {
  return (
    <a href="#inicio" className="site-header__brand" aria-label="Moradas da Nova Cantareira — início" onClick={onClick}>
      <img className="site-header__emblema" src={CFG.images.headerEmblema} alt="" width="46" height="17" />
      <span className="site-header__marca" aria-hidden="true">
        <span className="site-header__marca-nome">MORADAS</span>
        <span className="site-header__marca-sub">da Nova Cantareira</span>
      </span>
    </a>
  );
}

function Header() {
  const [solid, setSolid] = useState(false);
  const [active, setActive] = useState("");
  const [menuOpen, setMenuOpen] = useState(false);
  const burgerRef = useRef(null);
  const menuId = useId();

  /* Sólido após 120px de rolagem */
  useEffect(() => {
    let raf = 0;
    const update = () => { raf = 0; setSolid(window.scrollY > HEADER_SOLID_AFTER); };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => { window.removeEventListener("scroll", onScroll); raf && cancelAnimationFrame(raf); };
  }, []);

  /* Link ativo = seção que ocupa a faixa central da tela */
  useEffect(() => {
    if (!("IntersectionObserver" in window)) return;
    const ids = ["inicio", ...HEADER_NAV_LINKS.map((l) => l.id),
      "seguranca", "planta"];
    const navIds = new Set(HEADER_NAV_LINKS.map((l) => l.id));
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (!e.isIntersecting) return;
        const id = e.target.id;
        // seções sem link no menu limpam o destaque
        setActive(navIds.has(id) ? id : "");
      });
    }, { rootMargin: "-45% 0px -54% 0px", threshold: 0 });
    // aguarda as demais seções montarem
    const t = setTimeout(() => {
      ids.forEach((id) => { const el = document.getElementById(id); el && io.observe(el); });
    }, 0);
    return () => { clearTimeout(t); io.disconnect(); };
  }, []);

  /* Trava a rolagem do body com o menu aberto; Esc fecha */
  useEffect(() => {
    document.body.classList.toggle("is-locked", menuOpen);
    if (!menuOpen) return;
    const onKey = (e) => {
      if (e.key === "Escape") {
        setMenuOpen(false);
        burgerRef.current && burgerRef.current.focus();
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [menuOpen]);

  /* Fecha o menu se a tela voltar ao desktop */
  useEffect(() => {
    const mq = window.matchMedia("(min-width: 961px)");
    const onChange = (e) => { if (e.matches) setMenuOpen(false); };
    mq.addEventListener ? mq.addEventListener("change", onChange) : mq.addListener(onChange);
    return () => { mq.removeEventListener ? mq.removeEventListener("change", onChange) : mq.removeListener(onChange); };
  }, []);

  const closeMenuNow = () => {
    document.body.classList.remove("is-locked");
    setMenuOpen(false);
  };

  const toggleMenu = () => {
    const next = !menuOpen;
    setMenuOpen(next);
  };

  const onNavClick = (e, id, origem) => {
    e.preventDefault();
    if (origem === "menu_mobile") {
      closeMenuNow();
      requestAnimationFrame(() => headerScrollTo(id));
    } else {
      headerScrollTo(id);
    }
  };

  const onBrandClick = (e) => {
    e.preventDefault();
    if (menuOpen) closeMenuNow();
    requestAnimationFrame(() => window.scrollTo({ top: 0, behavior: "auto" }));
  };

  const onMenuCta = () => {
    closeMenuNow();
    requestAnimationFrame(() => goToContato("menu_mobile"));
  };

  const cls = ["site-header", solid ? "is-solid" : "", menuOpen ? "is-menu-open" : ""].filter(Boolean).join(" ");

  return (
    <>
      <header className={cls}>
        <div className="container site-header__inner">
          <HeaderBrand onClick={onBrandClick} />
          <span className="site-header__spacer" />
          <nav className="site-header__nav" aria-label="Principal">
            <ul className="site-header__links">
              {HEADER_NAV_LINKS.map((l) => (
                <li key={l.id}>
                  <a
                    href={`#${l.id}`}
                    className={`site-header__link${active === l.id ? " is-active" : ""}`}
                    aria-current={active === l.id ? "true" : undefined}
                    onClick={(e) => onNavClick(e, l.id, "header")}
                  >
                    {l.label}
                  </a>
                </li>
              ))}
            </ul>
          </nav>
          <button type="button" className="btn btn--sm site-header__cta" onClick={() => goToContato("header")}>
            Entre em contato
          </button>
          <button
            type="button"
            ref={burgerRef}
            className="site-header__burger"
            aria-expanded={menuOpen}
            aria-controls={menuId}
            aria-label={menuOpen ? "Fechar menu" : "Abrir menu"}
            onClick={toggleMenu}
          >
            <span className="site-header__burger-linha" />
            <span className="site-header__burger-linha" />
          </button>
        </div>
      </header>

      <div
        id={menuId}
        className={`mobile-menu${menuOpen ? " is-open" : ""}`}
        aria-hidden={!menuOpen}
        role="dialog"
        aria-modal="true"
        aria-label="Menu"
      >
        <nav className="mobile-menu__inner" aria-label="Menu mobile">
          <ul className="mobile-menu__links">
            {HEADER_NAV_LINKS.map((l) => (
              <li key={l.id} className="mobile-menu__item">
                <a
                  href={`#${l.id}`}
                  className="mobile-menu__link"
                  tabIndex={menuOpen ? 0 : -1}
                  onClick={(e) => onNavClick(e, l.id, "menu_mobile")}
                >
                  {l.label}
                </a>
              </li>
            ))}
          </ul>
          <button
            type="button"
            className="btn btn--azul btn--block mobile-menu__cta"
            tabIndex={menuOpen ? 0 : -1}
            onClick={onMenuCta}
          >
            Entre em contato
          </button>
        </nav>
      </div>
    </>
  );
}

/* Barra fixa mobile: sobe ao passar 80% da altura do hero; some ao voltar ao topo */
function MobileBar() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const hero = document.getElementById("inicio");
      const limite = hero ? hero.offsetHeight * 0.8 : window.innerHeight * 0.8;
      setVisible(window.scrollY > limite);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      raf && cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div className={`mobile-bar${visible ? " is-visible" : ""}`} aria-hidden={!visible}>
      <button
        type="button"
        className="btn btn--azul mobile-bar__agendar"
        tabIndex={visible ? 0 : -1}
        onClick={() => goToContato("barra_fixa_mobile")}
      >
        Consultar financiamento
      </button>
      <button
        type="button"
        className="mobile-bar__whatsapp"
        aria-label="Falar pelo WhatsApp"
        tabIndex={visible ? 0 : -1}
        onClick={() => openWhatsApp("barra_fixa_mobile")}
      >
        <img src={CFG.images.iconeWhatsapp} alt="" width="22" height="22" />
      </button>
    </div>
  );
}

Object.assign(window, { Header, MobileBar });
