// Header — sticky bar + 6 mega menus + mobile nav. Ported 1:1 from
// src/components/Header.tsx. Mega-menu bodies live in MegaMenus.jsx /
// MegaContact.jsx; the mobile drawer in MobileNav.jsx.
(function () {
  const { useState, useEffect, useRef } = React;
  const D = window.REA_DATA;

  function Header({ alwaysShowLogo = false, hideQuoteBar = false }) {
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
    const [openMenu, setOpenMenu] = useState(null);
    const [quoteOpen, setQuoteOpen] = useState(false);
    const [modalOpen, setModalOpen] = useState(false);
    const [isScrolled, setIsScrolled] = useState(false);
    const headerRef = useRef(null);

    // Any in-page CTA can open the quote modal via window.openQuoteModal().
    useEffect(() => {
      const onOpen = () => setQuoteOpen(true);
      window.addEventListener('rea:open-quote', onOpen);
      return () => window.removeEventListener('rea:open-quote', onOpen);
    }, []);

    // Hide the sticky mobile CTA bar while ANY modal is open (incl. ones opened
    // from the page), so it doesn't show through the blurred backdrop.
    useEffect(() => {
      const onState = (e) => setModalOpen(!!(e.detail && e.detail.open));
      window.addEventListener('rea:modal-state', onState);
      return () => window.removeEventListener('rea:modal-state', onState);
    }, []);

    // Track scroll (works whether the page scrolls window or a .rea-scroll host)
    useEffect(() => {
      const SCROLL_THRESHOLD = 180;
      const scroller = document.querySelector('.rea-scroll') || window;
      let ticking = false;
      const update = () => {
        const y = scroller === window ? window.scrollY : scroller.scrollTop;
        setIsScrolled(y > SCROLL_THRESHOLD);
        ticking = false;
      };
      const onScroll = () => { if (!ticking) { window.requestAnimationFrame(update); ticking = true; } };
      update();
      scroller.addEventListener('scroll', onScroll, { passive: true });
      return () => scroller.removeEventListener('scroll', onScroll);
    }, []);

    const closeNow = () => setOpenMenu(null);
    const toggleMenu = (menu) => setOpenMenu((cur) => (cur === menu ? null : menu));

    useEffect(() => {
      if (openMenu === null) return;
      const handleClick = (e) => { if (headerRef.current && !headerRef.current.contains(e.target)) setOpenMenu(null); };
      document.addEventListener('mousedown', handleClick);
      return () => document.removeEventListener('mousedown', handleClick);
    }, [openMenu]);

    useEffect(() => {
      if (openMenu === null) return;
      const handleKey = (e) => { if (e.key === 'Escape') setOpenMenu(null); };
      document.addEventListener('keydown', handleKey);
      return () => document.removeEventListener('keydown', handleKey);
    }, [openMenu]);

    const menuTriggers = [
      { key: 'products', label: 'Produse' },
      { key: 'services', label: 'Servicii' },
      { key: 'partners', label: 'Parteneri' },
      { key: 'about', label: 'Despre' },
      { key: 'careers', label: 'Cariere' },
      { key: 'contact', label: 'Contact' }
    ];

    return (
      <header ref={headerRef} className="sticky top-0 z-50 w-full border-b border-border bg-background">
        <div className="container mx-auto px-4 h-20 flex items-center justify-between">
          <a href="../acasa/index.html" className={`flex items-center transition-opacity duration-200 ${alwaysShowLogo || isScrolled ? 'xl:opacity-100' : 'xl:opacity-0 xl:pointer-events-none'}`} aria-label="Rom Energy Armstrong - acasă">
            <img src={D.logo} alt="Rom Energy Armstrong" className="h-9 w-auto" />
          </a>

          <nav className="hidden xl:flex items-center gap-7">
            {menuTriggers.map((t) => {
              const isActive = openMenu === t.key;
              return (
                <div key={t.key} className="relative h-20 flex items-center">
                  <button onClick={() => toggleMenu(t.key)}
                    className={`flex items-center gap-1.5 text-sm font-semibold transition-colors ${isActive ? 'text-primary' : 'text-foreground/80 hover:text-primary'}`}
                    aria-expanded={isActive} aria-haspopup="true">
                    {t.label}
                    <Icon name="chevron-down" className={`w-3.5 h-3.5 transition-transform ${isActive ? 'rotate-180' : ''}`} strokeWidth={2.5} />
                  </button>
                </div>
              );
            })}
          </nav>

          <div className="hidden xl:flex items-center gap-6">
            <a href="tel:+40212323884" className="flex items-center gap-2 text-sm font-semibold text-foreground hover:text-primary transition-colors">
              <Icon name="phone" className="w-4 h-4 text-accent" />
              <span>+40 21 232 38 84</span>
            </a>
            <button onClick={() => setQuoteOpen(true)} className="group inline-flex items-center gap-2 bg-accent hover:bg-accent/90 text-accent-foreground px-5 py-2.5 rounded-sm font-semibold text-sm transition-all">
              Cere ofertă
              <Icon name="arrow-right" className="w-4 h-4 group-hover:translate-x-1 transition-transform" strokeWidth={2.5} />
            </button>
          </div>

          <button className="xl:hidden p-2 text-foreground" onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)} aria-label="Toggle menu">
            {isMobileMenuOpen ? <Icon name="x" className="w-6 h-6" /> : <Icon name="menu" className="w-6 h-6" />}
          </button>
        </div>

        {/* Backdrop overlay */}
        <div onClick={closeNow} aria-hidden="true"
          className={`fixed inset-x-0 top-20 bottom-0 bg-foreground/30 backdrop-blur-[2px] transition-opacity duration-200 ${openMenu !== null ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`} />

        {/* Mega menus (desktop) */}
        {openMenu === 'products' && <MegaMenuProducts onClose={closeNow} />}
        {openMenu === 'services' && <MegaMenuServices onClose={closeNow} />}
        {openMenu === 'partners' && <MegaMenuPartners onClose={closeNow} />}
        {openMenu === 'about' && <MegaMenuAbout onClose={closeNow} />}
        {openMenu === 'careers' && <MegaMenuCareers onClose={closeNow} />}
        {openMenu === 'contact' && <MegaMenuContact onClose={closeNow} />}

        {/* Mobile nav */}
        <MobileNav isOpen={isMobileMenuOpen} onClose={() => setIsMobileMenuOpen(false)} />

        {/* Quote modal — opened by the header button or any in-page "Cere ofertă" CTA */}
        <ContactModal open={quoteOpen} onClose={() => setQuoteOpen(false)} />

        {/* Sticky mobile contact bar — always-available lead path on phones/tablets.
            paddingBottom adds the iOS safe-area inset so the buttons clear Safari's
            bottom toolbar / home-indicator gesture zone (where taps get swallowed). */}
        {!hideQuoteBar && (
        <div style={{ paddingBottom: 'calc(0.625rem + env(safe-area-inset-bottom))' }}
          className={`xl:hidden fixed bottom-0 inset-x-0 z-40 flex px-3 pt-2.5 bg-background/95 backdrop-blur border-t border-border transition-transform duration-300 ${(isScrolled && !isMobileMenuOpen && !modalOpen) ? 'translate-y-0' : 'translate-y-full'}`}>
          <button type="button" onClick={() => setQuoteOpen(true)} className="w-full inline-flex items-center justify-center gap-2 bg-accent hover:bg-accent/90 text-accent-foreground px-4 py-3 rounded-sm font-semibold text-sm transition-colors">
            Cere ofertă
            <Icon name="arrow-right" className="w-4 h-4" strokeWidth={2.5} />
          </button>
        </div>
        )}
      </header>
    );
  }

  window.Header = Header;
})();
