const { Button: HB, Icon: HI, Logo: HLogo } = window.EPCMDesignSystem_e7f830;
const LOGO_LIGHT = '/assets/logo/epcm-logo-light.png';
const L = (en, fr) => ({ en, fr });

/* Service-type-first nav. Items route to the underlying service page. */
const MENU_DEFS = {
  repair: [
    { heading: L('Heating', 'Chauffage'), items: [ { id: 'heating', label: L('Heating Repair', 'Réparation chauffage') }, { id: 'furnace', label: L('Furnace Repair', 'Réparation fournaise') }, { id: 'boiler', label: L('Boiler Repair', 'Réparation chaudière') } ] },
    { heading: L('Cooling & Heat Pumps', 'Climatisation et thermopompes'), items: [ { id: 'cooling', label: L('AC Repair', 'Réparation climatisation') }, { id: 'heat-pump', label: L('Heat Pump Repair', 'Réparation thermopompe') }, { id: 'mini-split', label: L('Mini-Split Repair', 'Réparation mini-split') } ] },
  ],
  install: [
    { heading: L('Heating', 'Chauffage'), items: [ { id: 'furnace', label: L('Furnace Installation', 'Installation fournaise') }, { id: 'boiler', label: L('Boiler Installation', 'Installation chaudière') }, { id: 'oil-conversion', label: L('Oil Conversion', 'Conversion au mazout') }, { id: 'bi-energy', label: L('Bi-Energy System', 'Système biénergie') } ] },
    { heading: L('Cooling & Heat Pumps', 'Climatisation et thermopompes'), items: [ { id: 'wall-ac', label: L('Wall-Mounted AC', 'Climatiseur mural') }, { id: 'central-ac', label: L('Central AC', 'Climatisation centrale') }, { id: 'mini-split', label: L('Mini-Split Installation', 'Installation mini-split') }, { id: 'central-heat-pump', label: L('Central Heat Pump', 'Thermopompe centrale') }, { id: 'wall-heat-pump', label: L('Wall-Mounted Heat Pump', 'Thermopompe murale') } ] },
    { heading: L('More', 'Plus'), items: [ { id: 'air-duct-cleaning', label: L('Air Duct Cleaning', 'Nettoyage de conduits') }, { id: 'brands', label: L('Brands & Machines', 'Marques et appareils') } ] },
  ],
  all: [
    { heading: L('By System', 'Par système'), items: [ { id: 'heating' }, { id: 'cooling' }, { id: 'heat-pump' }, { id: 'air-duct-cleaning' } ] },
    { heading: L('More', 'Plus'), items: [ { id: 'services', label: L('All Services Overview', 'Aperçu des services') }, { id: 'air-duct-cleaning' }, { id: 'government-grants' }, { id: 'maintenance-plans', label: L('Protection Plans', 'Plans de protection') } ] },
  ],
};

function Header({ onNavigate, onBook, onGoPlumbing, page, lang, onLang }) {
  const t = (n) => window.EPCM_T(n, lang);
  const P = window.EPCM_PAGES;
  const S = window.EPCM_SHARED;
  const [open, setOpen] = React.useState(null);
  const [mobile, setMobile] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);

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

  const go = (id) => { setMobile(false); setOpen(null); onNavigate(id); };

  const topItems = [
    { key: 'repair', id: 'services', label: L('Repairs', 'Réparations'), menu: 'repair' },
    { key: 'install', id: 'services', label: L('Installations', 'Installations'), menu: 'install' },
    { key: 'memberships', id: 'maintenance-plans', label: L('Protection Plans', 'Plans de protection') },
    { key: 'financing', id: 'financing', label: L('Financing', 'Financement') },
    { key: 'plumbing', label: L('Plumbing', 'Plomberie'), plumbing: true },
  ];
  const navBtn = (active) => ({ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'none', border: 'none', cursor: 'pointer', font: 'inherit', fontSize: '0.92rem', fontWeight: 500, color: active ? 'var(--text)' : 'var(--text-secondary)', padding: '8px 10px', borderRadius: 'var(--radius-sm)', letterSpacing: '-0.01em', whiteSpace: 'nowrap' });
  const itemLink = (it) => (
    <button key={it.id + (it.label ? t(it.label) : '')} onClick={() => go(it.id)} style={{ display: 'block', width: '100%', textAlign: 'left', background: 'none', border: 'none', cursor: 'pointer', font: 'inherit', fontSize: '0.9rem', color: 'var(--text-secondary)', padding: '8px 12px', borderRadius: 'var(--radius-sm)' }}
      onMouseOver={(e) => { e.currentTarget.style.background = 'var(--surface-2)'; e.currentTarget.style.color = 'var(--text)'; }}
      onMouseOut={(e) => { e.currentTarget.style.background = 'none'; e.currentTarget.style.color = 'var(--text-secondary)'; }}>{it.label ? t(it.label) : t(P[it.id].nav)}</button>
  );

  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, background: scrolled ? 'rgba(16,16,20,0.85)' : 'rgba(16,16,20,0.55)', backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)', borderBottom: '1px solid ' + (scrolled ? 'var(--border)' : 'transparent'), transition: 'background var(--dur), border-color var(--dur)' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: '0 var(--gutter)', height: 78, display: 'flex', alignItems: 'center', gap: 16 }}>
        <a href="#" onClick={(e) => { e.preventDefault(); go('home'); }} style={{ flex: 'none', display: 'flex' }}><HLogo src={LOGO_LIGHT} height={29} /></a>

        <nav className="epcm-desktop-nav" style={{ display: 'flex', alignItems: 'center', gap: 0 }} onMouseLeave={() => setOpen(null)}>
          {topItems.map((it) => (
            it.plumbing ? (
              <button key="plumbing" onClick={onGoPlumbing} title={lang === 'fr' ? 'Visiter EPCM Plomberie' : 'Visit EPCM Plumbing'} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 6, background: 'var(--accent-soft)', border: '1px solid var(--accent-line)', cursor: 'pointer', font: 'inherit', fontSize: '0.92rem', fontWeight: 500, color: 'var(--arctic-blue)', padding: '7px 13px', borderRadius: 'var(--radius-pill)', whiteSpace: 'nowrap' }}
                onMouseOver={(e) => { e.currentTarget.style.background = 'var(--accent)'; e.currentTarget.style.color = 'var(--on-accent)'; }}
                onMouseOut={(e) => { e.currentTarget.style.background = 'var(--accent-soft)'; e.currentTarget.style.color = 'var(--arctic-blue)'; }}>
                <HI name="droplets" size={15} />{t(it.label)}<HI name="arrow-up-right" size={13} />
              </button>
            ) : (
            <div key={it.key} style={{ position: 'relative' }} onMouseEnter={() => setOpen(it.menu || null)}>
              <button onClick={() => go(it.id)} style={navBtn(page === it.id || page === it.key || (it.menu && open === it.menu))}>
                {t(it.label)}{it.menu && <HI name="chevron-down" size={13} strokeWidth={2} style={{ opacity: 0.7 }} />}
              </button>
              {it.menu && open === it.menu && (
                <div style={{ position: 'absolute', top: '100%', left: 0, paddingTop: 10 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: `repeat(${MENU_DEFS[it.menu].length}, minmax(190px, 1fr))`, gap: 6, background: 'var(--surface-1)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 14, width: MENU_DEFS[it.menu].length * 215 }}>
                    {MENU_DEFS[it.menu].map((col) => (
                      <div key={col.heading.en}>
                        <div style={{ fontSize: '0.7rem', textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--accent)', padding: '6px 12px 8px' }}>{t(col.heading)}</div>
                        {col.items.map(itemLink)}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
            )
          ))}
        </nav>

        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 12 }}>
          <a href={S.contact.phoneHref} className="epcm-phone-link" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'var(--text)', fontSize: '0.92rem', fontWeight: 500, whiteSpace: 'nowrap' }}><HI name="phone" size={16} color="var(--accent)" strokeWidth={2} />{S.contact.phone}</a>
          <button onClick={onLang} className="epcm-lang" style={{ whiteSpace: 'nowrap', background: 'none', border: '1px solid var(--border-strong)', color: 'var(--text-secondary)', borderRadius: 'var(--radius-sm)', cursor: 'pointer', font: 'inherit', fontSize: '0.8125rem', fontWeight: 500, padding: '6px 10px', letterSpacing: '0.04em' }}>{lang === 'en' ? 'FR' : 'EN'}</button>
          <span className="epcm-book-btn"><HB variant="primary" iconRight="calendar-check" onClick={onBook}>{t(S.ui.book)}</HB></span>
          <button className="epcm-burger" onClick={() => setMobile((m) => !m)} aria-label="Menu" style={{ display: 'none', background: 'var(--surface-2)', border: '1px solid var(--border-strong)', color: 'var(--text)', width: 44, height: 44, borderRadius: 'var(--radius-sm)', cursor: 'pointer', alignItems: 'center', justifyContent: 'center' }}><HI name={mobile ? 'x' : 'menu'} size={22} /></button>
        </div>
      </div>

      {mobile && (
        <div className="epcm-mobile-menu" style={{ borderTop: '1px solid var(--border)', background: 'var(--obsidian-900)', padding: 'var(--gutter)', maxHeight: '74vh', overflowY: 'auto' }}>
          {[['repair', L('Repairs', 'Réparations')], ['install', L('Installations', 'Installations')]].map(([menu, label]) => (
            <div key={menu} style={{ paddingTop: 14 }}>
              <div style={{ fontSize: '0.72rem', textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--accent)', marginBottom: 4, fontWeight: 600 }}>{t(label)}</div>
              {MENU_DEFS[menu].map((col) => col.items.map((it) => (
                <button key={menu + it.id + (it.label ? t(it.label) : '')} onClick={() => go(it.id)} style={{ display: 'block', width: '100%', textAlign: 'left', background: 'none', border: 'none', cursor: 'pointer', font: 'inherit', color: 'var(--text-secondary)', fontSize: '0.96rem', padding: '8px 4px' }}>{it.label ? t(it.label) : t(P[it.id].nav)}</button>
              )))}
            </div>
          ))}
          <div style={{ paddingTop: 14, display: 'grid', gap: 2, borderTop: '1px solid var(--border)', marginTop: 12 }}>
            <button onClick={() => { setMobile(false); onGoPlumbing(); }} style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left', background: 'var(--accent-soft)', border: '1px solid var(--accent-line)', borderRadius: 'var(--radius-md)', cursor: 'pointer', font: 'inherit', color: 'var(--arctic-blue)', fontSize: '1rem', fontWeight: 600, padding: '12px 12px', marginBottom: 6 }}><HI name="droplets" size={17} />{lang === 'fr' ? 'EPCM Plomberie' : 'EPCM Plumbing'}<HI name="arrow-up-right" size={14} /></button>
            {[['maintenance-plans', L('Protection Plans', 'Plans de protection')], ['financing', L('Financing', 'Financement')], ['about', L('About', 'À propos')], ['contact', L('Contact', 'Contact')]].map(([id, label]) => (
              <button key={id} onClick={() => go(id)} style={{ display: 'block', width: '100%', textAlign: 'left', background: 'none', border: 'none', cursor: 'pointer', font: 'inherit', color: 'var(--text)', fontSize: '1rem', fontWeight: 500, padding: '12px 4px' }}>{t(label)}</button>
            ))}
          </div>
          <div style={{ display: 'grid', gap: 10, marginTop: 16 }}>
            <HB variant="primary" full iconRight="calendar-check" onClick={() => { setMobile(false); onBook(); }}>{t(S.ui.book)}</HB>
            <a href={S.contact.phoneHref} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, minHeight: 48, background: 'var(--accent-soft)', border: '1px solid var(--accent-line)', borderRadius: 'var(--radius-md)', color: 'var(--arctic-blue)', fontSize: '1rem', fontWeight: 600, textDecoration: 'none' }}><HI name="phone" size={17} />{S.contact.phone}</a>
            <button onClick={() => { setMobile(false); onLang(); }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, minHeight: 48, width: '100%', background: 'none', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-md)', cursor: 'pointer', font: 'inherit', color: 'var(--text-secondary)', fontSize: '0.95rem', fontWeight: 500 }}><HI name="languages" size={16} />{lang === 'en' ? 'Français' : 'English'}</button>
          </div>
        </div>
      )}
    </header>
  );
}

function AnnouncementBar({ lang, onNavigate }) {
  const t = (n) => window.EPCM_T(n, lang);
  const msgs = [
    { icon: 'badge-percent', id: 'financing', text: L('Flexible monthly financing through Financeit — comfort now, pay over time', 'Financement mensuel flexible avec Financeit — le confort maintenant, payez plus tard') },
    { icon: 'calendar-check', id: 'maintenance-plans', text: L('Maintenance plans from $295/year — protect your system & save on repairs', 'Forfaits d’entretien dès 295 $/an — protégez votre système et économisez sur les réparations') },
    { icon: 'landmark', id: 'government-grants', text: L('Government grants & subventions on efficient systems — see if you qualify', 'Subventions gouvernementales sur les systèmes efficaces — voyez si vous êtes admissible') },
  ];
  const [i, setI] = React.useState(0);
  React.useEffect(() => { const tm = setInterval(() => setI((x) => (x + 1) % msgs.length), 4800); return () => clearInterval(tm); }, []);
  const m = msgs[i];
  return (
    <button onClick={() => onNavigate(m.id)} aria-label="Promotion" style={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center', gap: 10, background: 'var(--gradient-accent)', color: 'var(--on-accent)', border: 'none', cursor: 'pointer', font: 'inherit', fontSize: '0.85rem', fontWeight: 500, padding: '9px 16px', minHeight: 38 }}>
      <HI name={m.icon} size={15} color="var(--on-accent)" />
      <span key={i} className="epcm-anno" style={{ textAlign: 'center' }}>{t(m.text)}</span>
      <HI name="arrow-right" size={14} color="var(--on-accent)" />
    </button>
  );
}

window.AnnouncementBar = AnnouncementBar;
window.Header = Header;
window.LOGO_LIGHT = LOGO_LIGHT;
