/* ============================================================
   Site chrome — Header, MobileNav, Footer, Sticky WhatsApp
   ============================================================ */
const { useState, useEffect, useRef } = React;
const NAV = [
  { id: 'home', label: 'Home' },
  { id: 'trips', label: 'Trips', children: [
    { id: 'snorkeling', label: 'Dolphin House Snorkeling' },
    { id: 'diving', label: 'Dolphin Snorkeling & Diving' },
    { id: 'speedboat', label: 'Speedboat Dolphin Trip' },
    { id: 'private_boat', label: 'Private Boat Dolphin Trip' },
  ]},
  { id: 'explained', label: 'Dolphin House Explained' },
  { id: 'faq', label: 'FAQ' },
  { id: 'contact', label: 'Book Now' },
];

function Logo({ white, icon, height = 38, onClick }) {
  const src = icon ? '/assets/logo-icon.png' : (white ? '/assets/logo-white.png' : '/assets/logo-color.png');
  return (
    <a href="#" onClick={(e) => { e.preventDefault(); onClick && onClick('home'); }} style={{ display: 'flex', alignItems: 'center' }} aria-label="Dolphin House Hurghada — home">
      <img src={src} alt="Dolphin House Hurghada logo" style={{ height, width: 'auto' }} draggable="false"/>
    </a>
  );
}

function LangSelect({ dark }) {
  const cur = (window.I18N && window.I18N.lang) || 'en';
  const opts = (window.I18N && window.I18N.langs) || [{ code: 'en', label: 'English' }];
  const switchLang = (code) => {
    if (!window.I18N || !window.I18N.isSupported(code)) return;
    // Rewrite ONLY the language prefix of the current page, keep the same
    // clean path + query string. Checkout/confirmation routes stay unprefixed.
    const path = window.location.pathname;
    const search = window.location.search || '';
    const isCheckout = path.indexOf('/book/') === 0 || path.indexOf('/booking-confirmation/') === 0;
    let target = path;
    if (!isCheckout) {
      const split = window.I18N.splitLangPath(path);
      target = window.I18N.withLangPrefix(split.cleanPath, code);
    }
    try { history.pushState(null, '', target + search); } catch (e) {}
    // setLang persists localStorage + sets <html lang> + triggers re-render.
    window.I18N.setLang(code);
  };
  return (
    <select aria-label={window.t('lang.select')} value={cur}
      onChange={(e) => switchLang(e.target.value)}
      style={{ fontFamily: 'var(--body)', fontWeight: 600, fontSize: 13.5, padding: '8px 10px', borderRadius: 10, cursor: 'pointer', maxWidth: '46vw',
        color: dark ? '#fff' : 'var(--ink)', background: dark ? 'rgba(255,255,255,.12)' : 'var(--ivory-2)', border: dark ? '1px solid rgba(255,255,255,.3)' : '1px solid var(--line)' }}>
      {opts.map(l => <option key={l.code} value={l.code} style={{ color: '#0e3a56', background: '#fff' }}>{l.code.toUpperCase()} · {l.label}</option>)}
    </select>
  );
}

function Header({ page, go, heroDark }) {
  const [scrolled, setScrolled] = useState(false);
  const [openMenu, setOpenMenu] = useState(false);
  const [tripsOpen, setTripsOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll(); window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setOpenMenu(false); }, [page]);

  const transparent = heroDark && !scrolled;
  const tripIds = ['snorkeling', 'diving', 'speedboat', 'private_boat'];

  return (
    <>
      <header style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 90,
        transition: 'background .3s ease, box-shadow .3s ease, padding .3s ease',
        background: transparent ? 'transparent' : 'rgba(252,247,237,.92)',
        backdropFilter: transparent ? 'none' : 'saturate(140%) blur(10px)',
        boxShadow: transparent ? 'none' : '0 1px 0 rgba(231,221,202,.9), 0 8px 24px -16px rgba(12,51,59,.3)',
        padding: scrolled ? '10px 0' : '16px 0',
      }}>
        <div className="wrap" style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
          <Logo white={transparent} onClick={go} height={transparent ? 42 : 38}/>
          <nav className="hide-mobile" style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 4 }}>
            {NAV.map(item => {
              const active = item.id === page || (item.id === 'trips' && tripIds.includes(page)) || (item.id === 'explained' && page === 'explained');
              const color = transparent ? '#fff' : 'var(--ink)';
              if (item.children) {
                return (
                  <div key={item.id} style={{ position: 'relative' }} onMouseEnter={() => setTripsOpen(true)} onMouseLeave={() => setTripsOpen(false)}>
                    <button onClick={() => go('home')} style={navLinkStyle(active, color)}>
                      {window.t('nav.' + item.id)}
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" style={{ marginLeft: 5, transform: tripsOpen ? 'rotate(180deg)' : 'none', transition: '.2s' }}><path d="M6 9l6 6 6-6"/></svg>
                    </button>
                    <div style={{
                      position: 'absolute', top: '100%', left: 0, paddingTop: 12, minWidth: 230,
                      opacity: tripsOpen ? 1 : 0, visibility: tripsOpen ? 'visible' : 'hidden',
                      transform: tripsOpen ? 'translateY(0)' : 'translateY(-6px)', transition: '.18s',
                    }}>
                      <div style={{ background: '#fff', borderRadius: 16, boxShadow: 'var(--shadow-md)', border: '1px solid var(--line)', padding: 8 }}>
                        {item.children.map(c => {
                          const t = DATA.trips[c.id];
                          return (
                            <Link key={c.id} to={c.id} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', padding: '11px 12px', borderRadius: 11, transition: '.15s' }}
                              onMouseEnter={e => e.currentTarget.style.background = 'var(--ivory-2)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                              <span style={{ width: 38, height: 38, borderRadius: 10, flex: 'none', overflow: 'hidden', background: `linear-gradient(140deg, ${t.g1}, ${t.g2})` }}>
                                <img src={t.imgSrc} alt="" loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
                              </span>
                              <span>
                                <span style={{ display: 'block', fontWeight: 700, fontFamily: 'var(--display)', fontSize: 15, color: 'var(--ink)' }}>{window.tt(t, 'name')}</span>
                                <span style={{ display: 'block', fontSize: 12.5, color: 'var(--ink-mute)' }}>{DATA.priceLabel(t).main} {DATA.priceLabel(t).note} · {t.duration}</span>
                              </span>
                            </Link>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                );
              }
              return <Link key={item.id} to={item.id} style={navLinkStyle(active, color)}>{window.t('nav.' + item.id)}</Link>;
            })}
            <div style={{ marginLeft: 12 }}><LangSelect dark={transparent}/></div>
            <div style={{ marginLeft: 8 }}>
              <Btn kind="wa" size="sm" href={DATA.waLink('Hi Dolphin House Hurghada! I would like to book a Dolphin House trip.')} newTab>{window.t('nav.bookWhatsapp')}</Btn>
            </div>
          </nav>
          {/* mobile burger */}
          <button className="only-mobile" onClick={() => setOpenMenu(true)} aria-label="Open menu"
            style={{ marginLeft: 'auto', width: 44, height: 44, borderRadius: 12, display: 'grid', placeItems: 'center', color: transparent ? '#fff' : 'var(--ink)', background: transparent ? 'rgba(255,255,255,.14)' : 'var(--ivory-2)', border: transparent ? '1px solid rgba(255,255,255,.3)' : '1px solid var(--line)' }}>
            <Ic.menu width="22" height="22"/>
          </button>
        </div>
      </header>

      {/* mobile drawer */}
      <div style={{ position: 'fixed', inset: 0, zIndex: 120, pointerEvents: openMenu ? 'auto' : 'none', overflow: 'hidden' }}>
        <div onClick={() => setOpenMenu(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(6,40,61,.5)', backdropFilter: 'blur(2px)', opacity: openMenu ? 1 : 0, transition: '.3s' }}></div>
        <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, width: 'min(86vw,340px)', background: 'var(--ivory)', boxShadow: 'var(--shadow-lg)', transform: openMenu ? 'none' : 'translateX(105%)', transition: 'transform .32s cubic-bezier(.2,.7,.3,1)', display: 'flex', flexDirection: 'column', padding: '20px 20px 24px' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
            <Logo onClick={(p) => { setOpenMenu(false); go(p); }} height={34}/>
            <button onClick={() => setOpenMenu(false)} aria-label="Close" style={{ width: 42, height: 42, borderRadius: 11, background: 'var(--ivory-2)', display: 'grid', placeItems: 'center', color: 'var(--ink)' }}><Ic.x width="20" height="20"/></button>
          </div>
          <div style={{ margin: '2px 0 14px' }}><LangSelect/></div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {NAV.map(item => (
              <div key={item.id}>
                <button onClick={() => { go(item.children ? 'home' : item.id); }} style={{ ...mobileLinkStyle, color: page === item.id ? 'var(--turq-deep)' : 'var(--ink)' }}>{window.t('nav.' + item.id)}</button>
                {item.children && (
                  <div style={{ paddingLeft: 14, display: 'flex', flexDirection: 'column' }}>
                    {item.children.map(c => (
                      <button key={c.id} onClick={() => go(c.id)} style={{ ...mobileLinkStyle, fontSize: 16, fontFamily: 'var(--body)', fontWeight: 600, color: page === c.id ? 'var(--turq-deep)' : 'var(--ink-soft)', padding: '10px 0' }}>{window.tt(DATA.trips[c.id], 'name')} <span style={{ color: 'var(--ink-mute)', fontWeight: 500 }}>· {DATA.priceLabel(DATA.trips[c.id]).main}</span></button>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
          <div style={{ marginTop: 'auto', paddingTop: 20 }}>
            <WAButton block msg={window.t('wa.generic')}>{window.t('nav.bookViaWhatsapp')}</WAButton>
            <p style={{ textAlign: 'center', fontSize: 12.5, color: 'var(--ink-mute)', marginTop: 12 }}>{window.t('nav.noPayEnquire')}</p>
          </div>
        </div>
      </div>
    </>
  );
}

function navLinkStyle(active, color) {
  return {
    display: 'inline-flex', alignItems: 'center', fontFamily: 'var(--body)', fontWeight: 600, fontSize: 15.5,
    padding: '9px 14px', borderRadius: 999, color: active ? 'var(--turq)' : color,
    opacity: active ? 1 : .9, transition: '.18s', letterSpacing: '-.01em',
  };
}
const mobileLinkStyle = { display: 'block', width: '100%', textAlign: 'left', fontFamily: 'var(--display)', fontWeight: 700, fontSize: 21, padding: '13px 0', color: 'var(--ink)' };

/* ---------- Sticky WhatsApp (mobile bottom bar + desktop float) ---------- */
function StickyCTA({ trip, page }) {
  const pl = trip ? DATA.priceLabel(trip) : null;
  const msg = trip
    ? window.t('wa.bookTrip', { name: window.tt(trip, 'name'), price: pl.main, note: pl.note })
    : window.t('wa.generic');
  return (
    <>
      {/* mobile bottom bar — hidden on contact page (has its own submit button) */}
      {page !== 'contact' && <div className="only-mobile" style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 95, padding: '10px 14px calc(10px + env(safe-area-inset-bottom))', background: 'rgba(252,247,237,.92)', backdropFilter: 'blur(12px)', borderTop: '1px solid var(--line)', boxShadow: '0 -8px 24px -16px rgba(12,51,59,.4)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {trip && (
            <div style={{ lineHeight: 1.1 }}>
              <div style={{ fontSize: 11, color: 'var(--ink-mute)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em' }}>{window.tt(trip, 'name')}</div>
              <div style={{ fontFamily: 'var(--display)', fontWeight: 800, fontSize: 21, color: 'var(--teal)' }}>{pl.main} <span style={{ fontSize: 13, color: 'var(--ink-mute)', fontWeight: 600, fontFamily: 'var(--body)' }}>{pl.note}</span></div>
            </div>
          )}
          <div style={{ flex: 1 }}><WAButton block size="lg" msg={msg}>{trip ? window.t('nav.bookThisTrip') : window.t('nav.bookViaWhatsapp')}</WAButton></div>
        </div>
      </div>}
      {/* desktop floating button */}
      <a className="hide-mobile" href={DATA.waLink(msg)} target="_blank" rel="noopener" aria-label="Book via WhatsApp"
        style={{ position: 'fixed', right: 24, bottom: 24, zIndex: 95, display: 'inline-flex', alignItems: 'center', gap: 11, background: 'var(--wa)', color: '#06351a', fontFamily: 'var(--body)', fontWeight: 700, padding: '15px 22px', borderRadius: 999, boxShadow: '0 14px 34px -8px rgba(37,211,102,.6)' }}
        onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; }} onMouseLeave={e => { e.currentTarget.style.transform = 'none'; }}>
        <Ic.wa width="22" height="22"/> {window.t('nav.bookViaWhatsapp')}
      </a>
    </>
  );
}

/* ---------- Footer ---------- */
function Footer({ go }) {
  return (
    <footer className="bg-deep" style={{ paddingTop: 72, paddingBottom: 120 }}>
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(240px,1.3fr) repeat(3, minmax(120px,1fr))', gap: 40 }} className="footer-grid">
          <div>
            <img src="/assets/logo-white.png" alt="Dolphin House Hurghada" style={{ height: 52, marginBottom: 18 }}/>
            <p className="on-dark-mute" style={{ fontSize: 15, maxWidth: '32ch' }}>{window.t('footer.tagline')}</p>
            <div style={{ marginTop: 20 }}>
              <WAButton size="md" msg={window.t('wa.generic')}>{window.t('footer.whatsappUs')}</WAButton>
            </div>
          </div>
          <FootCol title={window.t('footer.programs')} links={[
            [window.tt(DATA.trips.snorkeling, 'name'), 'snorkeling'],
            [window.tt(DATA.trips.diving, 'name'), 'diving'],
            [window.tt(DATA.trips.speedboat, 'name'), 'speedboat'],
            [window.tt(DATA.trips.private_boat, 'name'), 'private_boat'],
            [window.t('footer.dolphinExplained'), 'explained'],
          ]} go={go}/>
          <FootCol title={window.t('footer.plan')} links={[[window.t('nav.faq'), 'faq'], [window.t('footer.contact'), 'contact'], [window.t('footer.responsibleWatching'), 'home'], [window.t('footer.hotelPickup'), 'home']]} go={go}/>
          <div>
            <h4 style={{ fontFamily: 'var(--body)', fontWeight: 700, fontSize: 13, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--turq-bright)', marginBottom: 16 }}>{window.t('footer.reachUs')}</h4>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, color: 'rgba(234,246,247,.85)', fontSize: 15 }}>
              <span style={{ display: 'flex', gap: 9, alignItems: 'center' }}><Ic.wa width="17" height="17"/> +20 100 084 3745</span>
              <span style={{ display: 'flex', gap: 9, alignItems: 'center' }}><Ic.pin width="17" height="17"/> {window.t('footer.location')}</span>
              <span style={{ display: 'flex', gap: 9, alignItems: 'center' }}><Ic.clock width="17" height="17"/> {window.t('footer.daily')}</span>
            </div>
          </div>
        </div>
        <div style={{ borderTop: '1px solid rgba(255,255,255,.12)', marginTop: 48, paddingTop: 24, display: 'flex', flexWrap: 'wrap', gap: 14, justifyContent: 'space-between', color: 'rgba(234,246,247,.6)', fontSize: 13.5 }}>
          <span>{window.t('footer.copyright')}</span>
          <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Ic.dolphin width="15" height="15"/> {window.t('footer.respectNote')}</span>
        </div>
      </div>
    </footer>
  );
}
function FootCol({ title, links, go }) {
  return (
    <div>
      <h4 style={{ fontFamily: 'var(--body)', fontWeight: 700, fontSize: 13, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--turq-bright)', marginBottom: 16 }}>{title}</h4>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
        {links.map((l, i) => <Link key={i} to={l[1]} style={{ textAlign: 'left', color: 'rgba(234,246,247,.85)', fontSize: 15, padding: 0 }} onMouseEnter={e => e.currentTarget.style.color = '#fff'} onMouseLeave={e => e.currentTarget.style.color = 'rgba(234,246,247,.85)'}>{l[0]}</Link>)}
      </div>
    </div>
  );
}

Object.assign(window, { Header, Footer, StickyCTA, Logo, NAV });
