// Sticky header: navy→blue gradient, condenses on scroll. Desktop nav with Services
// dropdown + gold "Get in touch" + click-to-call + Online Will. Mobile hamburger panel
// + a sticky bottom Call/WhatsApp bar.
const { useState: useStateHd, useRef: useRefHd } = React;
const useEffectHd = React.useLayoutEffect;

// The same header serves the home page and every subpage. On the home page
// (window.__IS_HOME) brand/contact links smooth-scroll to in-page sections;
// on subpages they navigate to the home page or the contact page instead.
const IS_HOME = !!window.__IS_HOME;
const NAV_HOME_HREF = IS_HOME ? '#top' : 'index.html';
// "Get in touch" always goes to the dedicated contact page, never an anchor.
const NAV_CONTACT_HREF = 'contact.html';
const navSmooth = (e, hash) => { if (IS_HOME && hash !== '#contact') smoothTo(e, hash); };

// Brand logo: the white-on-transparent wordmark sits straight on the navy
// header. Graceful fallback to a text wordmark if the image ever fails.
const LOGO_SRC = 'images/logo-white.png';
function Logo({ scrolled }) {
  const [failed, setFailed] = useStateHd(false);
  if (failed) {
    return (
      <span className="flex flex-col leading-none">
        <span className="font-display font-medium text-white text-[21px] sm:text-[23px] tracking-[-0.01em]">Futura Planning</span>
        <span className="font-sans font-medium text-[9px] uppercase mt-1" style={{ letterSpacing: '0.22em', color: 'rgba(255,255,255,0.7)' }}>
          Your Legacy. Our Expertise
        </span>
      </span>
    );
  }
  return (
    <img
      src={LOGO_SRC}
      alt="Futura Planning — Your Legacy. Our Expertise"
      onError={() => setFailed(true)}
      style={{ height: scrolled ? 36 : 46, width: 'auto', maxWidth: 230, objectFit: 'contain', display: 'block', transition: 'height 350ms ' + EASE }}
    />
  );
}

// Scroll to a target Y, smooth where possible. Some rendering contexts freeze
// CSS smooth-scroll animations entirely (the same frozen-clock issue
// useStaticRender guards against), so if the page has not moved shortly after
// starting, jump there instantly instead of silently going nowhere.
function scrollToY(y) {
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  if (reduce) { window.scrollTo({ top: y, behavior: 'auto' }); return; }
  const startY = window.pageYOffset;
  window.scrollTo({ top: y, behavior: 'smooth' });
  setTimeout(() => {
    if (Math.abs(window.pageYOffset - startY) < 2 && Math.abs(startY - y) > 2) {
      window.scrollTo({ top: y, behavior: 'auto' });
    }
  }, 180);
}

function smoothTo(e, hash) {
  if (!hash || hash[0] !== '#') return;
  const el = document.querySelector(hash);
  if (!el) return;
  e.preventDefault();
  scrollToY(el.getBoundingClientRect().top + window.pageYOffset - 88);
}

function ServicesMenu({ scrolled }) {
  const [open, setOpen] = useStateHd(false);
  const ref = useRefHd(null);
  const closeT = useRefHd(null);
  const enter = () => { clearTimeout(closeT.current); setOpen(true); };
  const leave = () => { closeT.current = setTimeout(() => setOpen(false), 120); };
  return (
    <div className="relative" ref={ref} onMouseEnter={enter} onMouseLeave={leave}>
      <button
        type="button"
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
        className="flex items-center gap-1.5 text-white/90 hover:text-white font-sans font-medium text-[15px] transition-colors py-2"
      >
        Services
        <Icon name="chevronDown" size={16} strokeWidth={2} style={{ transition: 'transform 300ms ' + EASE, transform: open ? 'rotate(180deg)' : 'none' }} />
      </button>
      <div
        className="absolute left-1/2 top-full pt-3"
        style={{
          transform: 'translateX(-50%)',
          opacity: open ? 1 : 0,
          pointerEvents: open ? 'auto' : 'none',
          transition: 'opacity 220ms ' + EASE,
        }}
      >
        <div
          className="w-64 rounded-2xl bg-paper p-2 shadow-[0_24px_60px_-18px_rgba(26,48,102,0.35)] ring-1 ring-navy/5"
          style={{ transform: open ? 'translateY(0)' : 'translateY(-6px)', transition: 'transform 260ms ' + EASE }}
        >
          {SERVICES.map((s) => (
            <a
              key={s.label}
              href={s.hash}
              onClick={() => setOpen(false)}
              className={
                'block rounded-xl px-4 py-2.5 text-[15px] font-sans transition-colors ' +
                (s.highlight
                  ? 'font-semibold text-navy bg-gold/20 hover:bg-gold/35'
                  : 'text-ink hover:bg-blue-light hover:text-navy')
              }
            >
              {s.label}
              {s.highlight ? <span className="ml-2 rounded-full bg-gold px-2 py-0.5 font-sans font-semibold uppercase text-navy" style={{ fontSize: 9, letterSpacing: '0.08em' }}>48hr</span> : null}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

function Header() {
  const [scrolled, setScrolled] = useStateHd(false);
  const [menuOpen, setMenuOpen] = useStateHd(false);
  const staticRender = useStaticRender();
  useEffectHd(() => {
    const on = () => setScrolled(window.pageYOffset > 40);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  useEffectHd(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  return (
    <React.Fragment>
      <header
        className="fixed inset-x-0 top-0 z-50"
        style={{
          background: scrolled
            ? 'linear-gradient(100deg, rgba(20,36,80,0.92), rgba(40,66,135,0.90))'
            : 'linear-gradient(100deg, #1A3066, #2C4A8F)',
          backdropFilter: scrolled ? 'blur(10px)' : 'none',
          WebkitBackdropFilter: scrolled ? 'blur(10px)' : 'none',
          boxShadow: scrolled ? '0 10px 30px -16px rgba(15,26,60,0.55)' : 'none',
          transition: 'background 350ms ' + EASE + ', box-shadow 350ms ' + EASE,
        }}
      >
        <div
          className="mx-auto flex max-w-[1280px] items-center justify-between gap-6 px-5 sm:px-7"
          style={{ height: scrolled ? 64 : 80, transition: 'height 350ms ' + EASE }}
        >
          {/* Logo */}
          <a href={NAV_HOME_HREF} onClick={(e) => navSmooth(e, '#top')} className="flex items-center" aria-label="Futura Planning, home">
            <Logo scrolled={scrolled} />
          </a>

          {/* Desktop nav */}
          <nav className="hidden lg:flex items-center gap-7">
            <ServicesMenu scrolled={scrolled} />
            <a href="wills.html" className="text-white/90 hover:text-white font-sans font-medium text-[15px] transition-colors py-2">Wills</a>
            <a href="lasting-power-of-attorney.html" className="text-white/90 hover:text-white font-sans font-medium text-[15px] transition-colors py-2">Lasting Power of Attorney</a>
            <a href="trusts.html" className="text-white/90 hover:text-white font-sans font-medium text-[15px] transition-colors py-2">Trusts</a>
            <a href={PHONE_TEL} className="flex items-center gap-2 text-white/90 hover:text-white font-sans font-medium text-[15px] transition-colors">
              <Icon name="phone" size={17} strokeWidth={2} className="ico-ring" />
              {PHONE_DISPLAY}
            </a>
            <a
              href={NAV_CONTACT_HREF}
              onClick={(e) => navSmooth(e, '#contact')}
              className="rounded-full bg-gold px-5 py-2.5 font-sans font-semibold text-[15px] text-navy shadow-[0_8px_20px_-8px_rgba(240,184,60,0.8)] hover:bg-gold-deep transition-colors"
            >
              Get in touch
            </a>
          </nav>

          {/* Mobile hamburger */}
          <button
            type="button"
            onClick={() => setMenuOpen(true)}
            aria-label="Open menu"
            className="lg:hidden inline-flex h-11 w-11 items-center justify-center rounded-full text-white ring-1 ring-white/25"
          >
            <Icon name="menu" size={24} strokeWidth={2} />
          </button>
        </div>
      </header>

      {/* Mobile full-screen panel */}
      <div
        className="fixed inset-0 z-[60] lg:hidden"
        style={{ pointerEvents: menuOpen ? 'auto' : 'none' }}
        aria-hidden={!menuOpen}
      >
        <div
          onClick={() => setMenuOpen(false)}
          className="absolute inset-0"
          style={{ background: 'rgba(15,26,60,0.5)', opacity: menuOpen ? 1 : 0, transition: staticRender ? 'none' : 'opacity 300ms ' + EASE }}
        />
        <div
          data-dark="true"
          className="absolute inset-y-0 right-0 w-full max-w-[400px] overflow-y-auto px-6 pt-6 pb-10"
          style={{
            background: 'linear-gradient(160deg, #1A3066, #2C4A8F)',
            transform: menuOpen ? 'translateX(0)' : 'translateX(100%)',
            transition: staticRender ? 'none' : 'transform 420ms ' + EASE,
          }}
        >
          <div className="flex items-center justify-between">
            <a href={NAV_HOME_HREF} onClick={(e) => { navSmooth(e, '#top'); setMenuOpen(false); }} aria-label="Futura Planning, home">
              <Logo scrolled={true} />
            </a>
            <button type="button" onClick={() => setMenuOpen(false)} aria-label="Close menu" className="inline-flex h-11 w-11 items-center justify-center rounded-full text-white ring-1 ring-white/25">
              <Icon name="x" size={22} strokeWidth={2} />
            </button>
          </div>

          <div className="mt-8">
            <p className="font-sans font-medium text-[11px] uppercase tracking-[0.18em] text-white/50 mb-3">Services</p>
            <div className="flex flex-col">
              {SERVICES.map((s) => (
                <a
                  key={s.label}
                  href={s.hash}
                  onClick={() => setMenuOpen(false)}
                  className={'py-2.5 font-sans text-[16px] border-b border-white/10 ' + (s.highlight ? 'text-gold font-semibold' : 'text-white/90')}
                >
                  {s.label}
                  {s.highlight ? <span className="ml-2 rounded-full bg-gold px-2 py-0.5 font-sans font-semibold uppercase text-navy" style={{ fontSize: 9, letterSpacing: '0.08em' }}>48hr</span> : null}
                </a>
              ))}
            </div>
          </div>

          <div className="mt-6 flex flex-col gap-2">
            <a href="wills.html" className="py-2.5 text-white font-sans font-medium text-[17px]">Wills</a>
            <a href="lasting-power-of-attorney.html" className="py-2.5 text-white font-sans font-medium text-[17px]">Lasting Power of Attorney</a>
            <a href="trusts.html" className="py-2.5 text-white font-sans font-medium text-[17px]">Trusts</a>
            <a href={IS_HOME ? '#will-finder' : 'index.html#will-finder'} onClick={(e) => { navSmooth(e, '#will-finder'); setMenuOpen(false); }} className="py-2.5 text-white font-sans font-medium text-[17px]">Which Will do I need?</a>
          </div>

          <a
            href={NAV_CONTACT_HREF}
            onClick={(e) => { navSmooth(e, '#contact'); setMenuOpen(false); }}
            className="mt-8 flex w-full items-center justify-center rounded-full bg-gold px-6 py-4 font-sans font-semibold text-[17px] text-navy shadow-[0_10px_24px_-10px_rgba(240,184,60,0.9)]"
          >
            Get in touch
          </a>
          <a href={PHONE_TEL} className="mt-3 flex w-full items-center justify-center gap-2 rounded-full px-6 py-4 font-sans font-medium text-[16px] text-white ring-1 ring-white/30">
            <Icon name="phone" size={18} strokeWidth={2} />
            {PHONE_DISPLAY}
          </a>
        </div>
      </div>
    </React.Fragment>
  );
}

// Sticky bottom Call / WhatsApp bar — mobile only. Exposes its visibility so the
// floating WhatsApp circle can hide behind it.
function MobileBottomBar() {
  return (
    <div
      className="fixed inset-x-0 bottom-0 z-50 grid grid-cols-2 gap-2 p-3 lg:hidden"
      style={{ background: 'rgba(253,251,246,0.92)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)', borderTop: '1px solid rgba(26,48,102,0.08)', paddingBottom: 'calc(0.75rem + env(safe-area-inset-bottom))' }}
    >
      <a href={PHONE_TEL} className="flex items-center justify-center gap-2 rounded-full bg-gold py-3.5 font-sans font-semibold text-[16px] text-navy shadow-[0_8px_18px_-10px_rgba(240,184,60,0.9)]">
        <Icon name="phone" size={18} strokeWidth={2} /> Call us
      </a>
      <a href={WHATSAPP_URL} target="_blank" rel="noopener noreferrer" className="flex items-center justify-center gap-2 rounded-full py-3.5 font-sans font-semibold text-[16px] text-white" style={{ background: '#25D366', boxShadow: '0 8px 18px -10px rgba(37,211,102,0.9)' }}>
        <Icon name="whatsapp" size={19} /> WhatsApp
      </a>
    </div>
  );
}

Object.assign(window, { Header, MobileBottomBar, smoothTo, scrollToY });
