// 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;

// Brand logo with graceful fallback to the text wordmark.
// TODO: this is Futura's hosted logo; swap to a locally hosted asset before launch.
const LOGO_SRC = 'https://futuraplanning.co.uk/wp-content/uploads/2026/05/Color-logo-with-background-scaled.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 (
    <span className="inline-flex items-center rounded-xl bg-white shadow-[0_6px_16px_-8px_rgba(15,26,60,0.5)]" style={{ padding: scrolled ? '5px 10px' : '7px 12px', transition: 'padding 350ms ' + EASE }}>
      <img
        src={LOGO_SRC}
        alt="Futura Planning"
        referrerPolicy="no-referrer"
        onError={() => setFailed(true)}
        style={{ height: scrolled ? 30 : 38, width: 'auto', maxWidth: 200, objectFit: 'contain', display: 'block', transition: 'height 350ms ' + EASE }}
      />
    </span>
  );
}

function smoothTo(e, hash) {
  if (!hash || hash[0] !== '#') return;
  const el = document.querySelector(hash);
  if (!el) return;
  e.preventDefault();
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const y = el.getBoundingClientRect().top + window.pageYOffset - 88;
  window.scrollTo({ top: y, behavior: reduce ? 'auto' : 'smooth' });
}

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}
              href="#services"
              onClick={(e) => { smoothTo(e, '#services'); setOpen(false); }}
              className="block rounded-xl px-4 py-2.5 text-[15px] font-sans text-ink hover:bg-blue-light hover:text-navy transition-colors"
            >
              {s}
            </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="#top" onClick={(e) => smoothTo(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="https://futuraplanning.co.uk/news/" target="_blank" rel="noopener noreferrer" className="text-white/90 hover:text-white font-sans font-medium text-[15px] transition-colors py-2">News</a>
            <a
              href="#contact"
              onClick={(e) => smoothTo(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>
            <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} />
              {PHONE_DISPLAY}
            </a>
            <a href="#will-finder" onClick={(e) => smoothTo(e, '#will-finder')} className="text-white/80 hover:text-white font-sans font-medium text-[15px] transition-colors underline-offset-4 hover:underline">Online Will</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">
            <span className="font-display font-medium text-white text-[20px]">Futura Planning</span>
            <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} href="#services" onClick={(e) => { smoothTo(e, '#services'); setMenuOpen(false); }} className="py-2.5 text-white/90 font-sans text-[16px] border-b border-white/10">{s}</a>
              ))}
            </div>
          </div>

          <div className="mt-6 flex flex-col gap-2">
            <a href="https://futuraplanning.co.uk/news/" target="_blank" rel="noopener noreferrer" className="py-2.5 text-white font-sans font-medium text-[17px]">News</a>
            <a href="#will-finder" onClick={(e) => { smoothTo(e, '#will-finder'); setMenuOpen(false); }} className="py-2.5 text-white font-sans font-medium text-[17px]">Online Will</a>
          </div>

          <a
            href="#contact"
            onClick={(e) => { smoothTo(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 });
