/* ============================================================
   PRODUCT PAGE — reusable, distinct personality per trip
   ============================================================ */

function FactRow({ trip }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 1, background: 'var(--line)', borderRadius: 18, overflow: 'hidden', border: '1px solid var(--line)' }} className="factrow">
      {(window.tt(trip, 'quickFacts') || trip.quickFacts).slice(0,4).map(([l, v], i) => (
        <div key={i} style={{ background: '#fff', padding: '18px 20px', display: 'flex', gap: 13, alignItems: 'center' }}>
          <span style={{ width: 42, height: 42, borderRadius: 11, flex: 'none', display: 'grid', placeItems: 'center', background: 'var(--ivory-2)', color: 'var(--turq-deep)' }}><Ic.anchor width="21" height="21"/></span>
          <span style={{ lineHeight: 1.2 }}>
            <span style={{ display: 'block', fontSize: 11.5, color: 'var(--ink-mute)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em' }}>{l}</span>
            <span style={{ display: 'block', fontFamily: 'var(--display)', fontWeight: 700, fontSize: 16, color: 'var(--ink)', marginTop: 2 }}>{v}</span>
          </span>
        </div>
      ))}
    </div>
  );
}

function ProductHero({ trip, go }) {
  const coral = trip.accent === 'coral';
  const pl = DATA.priceLabel(trip);
  return (
    <section style={{ position: 'relative', overflow: 'hidden', paddingTop: 132, paddingBottom: 56 }}>
      <PhotoSlot label={trip.heroLabel} g1={trip.g1} g2="#06283d" radius="0" className="fill-abs" imgSrc={trip.imgSrc}
        overlay={<div style={{ position: 'absolute', inset: 0, zIndex: 1, background: 'linear-gradient(110deg, rgba(6,40,61,.9) 0%, rgba(6,40,61,.6) 45%, rgba(6,40,61,.2) 100%)' }}/>}/>
      <div className="wrap" style={{ position: 'relative', zIndex: 2 }}>
        <button onClick={() => go('home')} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'rgba(234,246,247,.8)', fontSize: 14, fontWeight: 600, marginBottom: 22 }}><Ic.arrow width="16" height="16" style={{ transform: 'rotate(180deg)' }}/> {window.t('prod.allTrips')}</button>
        <div style={{ maxWidth: 720 }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginBottom: 18 }}>
            <span className="tag" style={{ background: coral ? 'rgba(255,106,67,.92)' : 'rgba(39,205,226,.2)', color: coral ? '#fff' : '#bdf4fb', backdropFilter: 'blur(4px)' }}>{window.tt(trip, 'pace')}</span>
            {((window.tt(trip, 'personality') || trip.personality).slice(0, 2)).map((p, i) => <span key={i} className="pill dark">{p}</span>)}
          </div>
          <h1 className="h-hero" style={{ color: '#fff', fontSize: 'clamp(38px,5.6vw,68px)' }}>{window.tt(trip, 'h1') || window.tt(trip, 'name')}</h1>
          <p className="lead" style={{ color: 'rgba(234,246,247,.9)', marginTop: 18, maxWidth: '44ch' }}>{window.tt(trip, 'blurb')}</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 18, marginTop: 28 }}>
            <span style={{ display: 'flex', alignItems: 'baseline', gap: 8, color: '#fff' }}>
              <span style={{ fontSize: 13, color: 'rgba(234,246,247,.7)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em' }}>{pl.isFixed ? window.t('prod.flat') : window.t('prod.from')}</span>
              <span style={{ fontFamily: 'var(--display)', fontWeight: 800, fontSize: 46, lineHeight: 1 }}>{pl.main}</span>
              <span style={{ fontSize: 16, color: 'rgba(234,246,247,.75)' }}>{pl.note}</span>
            </span>
            <button onClick={() => window.goPath && window.goPath('/book/' + window.KEY_TO_PATH[trip.key].replace(/^\//, ''))} className="btn btn-coral btn-lg">{window.t('prod.continueBooking')}</button>
            <WAButton size="lg" msg={window.t('wa.bookTrip', { name: window.tt(trip, 'name'), price: pl.main, note: pl.note })}>{window.t('prod.askWa')}</WAButton>
          </div>
        </div>
        <div style={{ marginTop: 44 }}><FactRow trip={trip}/></div>
      </div>
    </section>
  );
}

function IncExc({ trip }) {
  return (
    <div className="grid g-2" style={{ gap: 22 }}>
      <div className="surface" style={{ padding: 28 }}>
        <h3 className="h-3" style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 10 }}><span style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(16,182,205,.14)', color: 'var(--turq-deep)', display: 'grid', placeItems: 'center' }}><Ic.check width="18" height="18"/></span> {window.t('prod.included')}</h3>
        <ul className="ticks">{(window.tt(trip, 'includes') || []).map((x, i) => <li key={i}><Ic.check className="tick-yes"/>{x}</li>)}</ul>
      </div>
      <div className="surface" style={{ padding: 28 }}>
        <h3 className="h-3" style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 10 }}><span style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(194,112,90,.14)', color: '#c2705a', display: 'grid', placeItems: 'center' }}><Ic.x width="18" height="18"/></span> {window.t('prod.notIncluded')}</h3>
        <ul className="ticks">{(window.tt(trip, 'excludes') || []).map((x, i) => <li key={i}><Ic.x className="tick-no"/>{x}</li>)}</ul>
      </div>
    </div>
  );
}

function RelatedTrips({ current, go }) {
  // Show at most 2 related trips — prefer non-identical type
  const others = DATA.tripOrder.filter(k => k !== current).slice(0, 2).map(k => DATA.trips[k]);
  return (
    <section className="bg-ivory2 sec-sm">
      <div className="wrap">
        <SecHead kicker={window.t('prod.otherKicker')} title={window.t('prod.compareOther')}/>
        <div className="grid g-2" style={{ marginTop: 32 }}>
          {others.map(t => (
            <button key={t.key} onClick={() => go(t.key)} className="surface" style={{ display: 'flex', gap: 16, padding: 16, alignItems: 'center', textAlign: 'left', boxShadow: 'var(--shadow-sm)', transition: '.18s' }}
              onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-3px)'} onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
              <span style={{ width: 84, height: 84, borderRadius: 14, flex: 'none', position: 'relative', overflow: 'hidden', background: `linear-gradient(140deg, ${t.g1}, ${t.g2})` }}>
                {t.imgSrc && <img src={t.imgSrc} alt={window.tt(t, 'name')} loading="lazy" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} onError={e => { e.currentTarget.style.display = 'none'; }}/>}
              </span>
              <span style={{ flex: 1 }}>
                <Tag tone={t.accent === 'coral' ? 'coral' : 'turq'}>{window.tt(t, 'bestForShort')}</Tag>
                <span style={{ display: 'block', fontFamily: 'var(--display)', fontWeight: 700, fontSize: 20, color: 'var(--ink)', marginTop: 7 }}>{window.tt(t, 'name')}</span>
                <span style={{ display: 'block', fontSize: 14, color: 'var(--ink-mute)', marginTop: 3 }}>{DATA.priceLabel(t).main} {DATA.priceLabel(t).note} · {window.tt(t, 'duration')}</span>
              </span>
              <span style={{ width: 42, height: 42, borderRadius: 11, background: 'var(--ivory-2)', color: 'var(--teal)', display: 'grid', placeItems: 'center', flex: 'none' }}><Ic.arrow width="19" height="19"/></span>
            </button>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 28 }}><Btn kind="ghost" onClick={() => go('home')} icon="arrow">{window.t('prod.fullComparison')}</Btn></div>
      </div>
    </section>
  );
}

function InternalLinks({ current, go }) {
  const links = {
    snorkeling: [
      { to: 'diving', label: window.t('il.snorkeling.diving') },
      { to: 'speedboat', label: window.t('il.snorkeling.speedboat') },
      { to: 'private_boat', label: window.t('il.snorkeling.private_boat') },
    ],
    diving: [
      { to: 'snorkeling', label: window.t('il.diving.snorkeling') },
      { to: 'private_boat', label: window.t('il.diving.private_boat') },
      { to: 'speedboat', label: window.t('il.diving.speedboat') },
    ],
    speedboat: [
      { to: 'private_boat', label: window.t('il.speedboat.private_boat') },
      { to: 'snorkeling', label: window.t('il.speedboat.snorkeling') },
    ],
    private_boat: [
      { to: 'diving', label: window.t('il.private_boat.diving') },
      { to: 'speedboat', label: window.t('il.private_boat.speedboat') },
    ],
  };
  const seen = {};
  const tripLinks = [];
  (links[current] || []).concat([
    { to: 'explained', label: window.t('il.explained') },
    { to: 'contact', label: window.t('il.book') },
  ]).forEach(l => { if (l.to !== current && !seen[l.to]) { seen[l.to] = 1; tripLinks.push(l); } });
  if (!tripLinks.length) return null;
  return (
    <section className="bg-ivory2 sec-sm">
      <div className="wrap" style={{ maxWidth: 700 }}>
        <h3 className="h-3" style={{ marginBottom: 18 }}>{window.t('prod.alsoSee')}</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {tripLinks.map(l => (
            <button key={l.to} onClick={() => go(l.to)} style={{ textAlign: 'left', padding: '13px 16px', background: '#fff', border: '1px solid var(--line)', borderRadius: 12, fontWeight: 600, fontSize: 15, color: 'var(--turq-deep)', transition: '.15s' }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--ivory-2)'} onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
              → {l.label}
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

/* Matches a media query and re-renders on viewport change (mobile gallery layout). */
function useMediaQuery(query) {
  const get = () => (typeof window !== 'undefined' && window.matchMedia ? window.matchMedia(query).matches : false);
  const [matches, setMatches] = React.useState(get);
  React.useEffect(() => {
    const mq = window.matchMedia(query);
    const onChange = () => setMatches(mq.matches);
    onChange();
    if (mq.addEventListener) mq.addEventListener('change', onChange); else mq.addListener(onChange);
    return () => { if (mq.removeEventListener) mq.removeEventListener('change', onChange); else mq.removeListener(onChange); };
  }, [query]);
  return matches;
}

/* Editorial gallery grid + accessible lightbox (no external library). */
function TripGallery({ trip }) {
  const gallery = (trip && trip.gallery) || [];
  const isMobile = useMediaQuery('(max-width: 760px)');
  const [open, setOpen] = React.useState(null); // active index, or null when closed
  const tx = (k, fb) => { const v = window.t(k); return v === k ? fb : v; };
  const name = window.tt(trip, 'name') || 'Hurghada Dolphin House and Snorkeling';
  const photoAlt = (i) => name + ' — Red Sea trip photo ' + (i + 1);

  const isOpen = open !== null;
  const show = (i) => setOpen(((i % gallery.length) + gallery.length) % gallery.length);
  const close = () => setOpen(null);
  const next = () => setOpen((o) => (o + 1) % gallery.length);
  const prev = () => setOpen((o) => (o - 1 + gallery.length) % gallery.length);

  React.useEffect(() => {
    if (!isOpen) return undefined;
    const onKey = (e) => {
      if (e.key === 'Escape') close();
      else if (e.key === 'ArrowRight') next();
      else if (e.key === 'ArrowLeft') prev();
    };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prevOverflow; };
  }, [isOpen]);

  if (!gallery.length) return null;

  // Mobile shows a compact 4-tile grid (1 wide + 2 + 1 wide "+N"); desktop shows the 5-tile feature grid.
  const shots = gallery.slice(0, isMobile ? 4 : 5);
  const more = gallery.length - shots.length;

  return (
    <section className="bg-ivory" style={{ paddingTop: 28, paddingBottom: 8 }}>
      <div className="wrap">
        <div className="trip-gallery">
          {shots.map((src, i) => {
            const last = i === shots.length - 1 && more > 0;
            const target = last ? shots.length : i; // "+N" opens the first hidden image
            return (
              <button type="button" key={i} className={'tg-cell' + (i === 0 ? ' tg-feature' : '') + (last ? ' tg-last' : '')}
                onClick={() => show(target)}
                aria-label={last ? tx('prod.galleryViewAll', 'View all photos') + ' (' + gallery.length + ')' : photoAlt(i)}>
                <img className="tg-img" src={src} loading={i === 0 ? 'eager' : 'lazy'} alt={photoAlt(i)}/>
                {last && <span className="tg-more" aria-hidden="true">+{more} {tx('prod.galleryMore', 'photos')}</span>}
              </button>
            );
          })}
        </div>
      </div>

      {isOpen && (
        <div className="lb" role="dialog" aria-modal="true" aria-label={tx('prod.galleryTitle', 'Trip photos')}
          onClick={(e) => { if (e.target === e.currentTarget) close(); }}>
          <div className="lb-top">
            <span className="lb-count">{open + 1} / {gallery.length}</span>
            <button type="button" className="lb-btn lb-close" onClick={close} aria-label={tx('prod.galleryClose', 'Close')}>
              <Ic.x width="22" height="22"/>
            </button>
          </div>
          <button type="button" className="lb-btn lb-nav lb-prev" onClick={prev} aria-label={tx('prod.galleryPrev', 'Previous photo')}>
            <Ic.arrow width="24" height="24" style={{ transform: 'rotate(180deg)' }}/>
          </button>
          <img className="lb-img" src={gallery[open]} alt={photoAlt(open)}/>
          <button type="button" className="lb-btn lb-nav lb-next" onClick={next} aria-label={tx('prod.galleryNext', 'Next photo')}>
            <Ic.arrow width="24" height="24"/>
          </button>
        </div>
      )}
    </section>
  );
}

function ProductPage({ tripKey, go }) {
  const trip = DATA.trips[tripKey];
  // Before-you-book FAQs (per trip)
  const faqPicks = (trip.faqs || []).filter(Boolean);
  return (
    <main>
      <ProductHero trip={trip} go={go}/>

      {/* Editorial photo gallery + lightbox — directly after hero */}
      <TripGallery trip={trip}/>

      {/* personality strip */}
      <section className="bg-ivory" style={{ paddingTop: 56, paddingBottom: 24 }}>
        <div className="wrap">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'center' }}>
            {trip.personality.map((p, i) => (
              <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 9, background: 'var(--ivory-2)', border: '1px solid var(--line)', borderRadius: 999, padding: '11px 18px', fontWeight: 600, fontSize: 15, color: 'var(--teal-800)' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: trip.accent === 'coral' ? 'var(--coral)' : 'var(--turq)' }}/>{(window.tt(trip, 'personality') || [])[i] || p}
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* description + highlights */}
      <section className="bg-ivory2 sec-sm">
        <div className="wrap prod-grid" style={{ display: 'grid', gridTemplateColumns: '1.25fr 0.95fr', gap: 48, alignItems: 'start' }}>
          <div>
            <SecHead kicker={window.t('prod.aboutKicker')} title={window.tt(trip, 'h1') || window.tt(trip, 'name')}/>
            <div style={{ marginTop: 22 }}>
              {(window.tt(trip, 'description') || [window.tt(trip, 'blurb')]).map((p, i) => (
                <p key={i} style={{ fontSize: 16, color: 'var(--ink-soft)', lineHeight: 1.7, marginBottom: 14 }}>{p}</p>
              ))}
            </div>
          </div>
          <div className="surface" style={{ padding: 28 }}>
            <h3 className="h-3" style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 10 }}><Ic.star width="20" height="20" style={{ color: 'var(--turq-deep)' }}/> {window.t('prod.highlights')}</h3>
            <ul className="ticks">{(window.tt(trip, 'highlights') || []).map((x, i) => <li key={i}><Ic.check className="tick-yes"/>{x}</li>)}</ul>
          </div>
        </div>
      </section>

      {/* Route + sticky booking */}
      <section className="bg-ivory sec-sm">
        <div className="wrap prod-grid" style={{ display: 'grid', gridTemplateColumns: '1.4fr 0.9fr', gap: 48, alignItems: 'start' }}>
          <div className="prod-main">
            <SecHead kicker={window.t('prod.routeKicker')} title={window.t('prod.route')} lead={window.t('prod.routeLead', { name: window.tt(trip, 'name').toLowerCase() })}/>
            <div style={{ marginTop: 34 }}><RouteMap stops={window.tt(trip, 'route')}/></div>
          </div>
          <aside style={{ position: 'sticky', top: 100 }} className="prod-aside">
            <div className="bk-card">
              <AvailabilityCalendar tripKey={tripKey} trip={trip} go={go}/>
            </div>
          </aside>
        </div>
      </section>

      {/* inclusions / exclusions */}
      <section className="bg-ivory2 sec-sm">
        <div className="wrap">
          <SecHead kicker={window.t('prod.detailsKicker')} title={window.t('prod.includedShort')}/>
          <div style={{ marginTop: 28 }}><IncExc trip={trip}/></div>
          <div className="surface" style={{ padding: 24, marginTop: 22, display: 'flex', gap: 16, alignItems: 'flex-start' }}>
            <Ic.dolphin width="24" height="24" style={{ color: 'var(--turq-deep)', flex: 'none', marginTop: 2 }}/>
            <div>
              <h3 style={{ fontSize: 17, marginBottom: 6 }}>{window.t('prod.policyTitle')}</h3>
              <p style={{ fontSize: 14.5, color: 'var(--ink-soft)', lineHeight: 1.6 }}>{window.t('prod.policyBody')}</p>
            </div>
          </div>
          {trip.key === 'diving' && (
            <div className="surface" style={{ padding: 20, marginTop: 22, background: 'rgba(16,182,205,.06)', border: '1px solid rgba(16,182,205,.2)' }}>
              <h3 style={{ fontSize: 16, marginBottom: 6, color: 'var(--turq-deep)' }}>{window.t('prod.divingTitle')}</h3>
              <p style={{ fontSize: 14, color: 'var(--ink-soft)' }}>{window.t('prod.divingBody')}</p>
            </div>
          )}
        </div>
      </section>

      {/* bring + who for */}
      <section className="bg-ivory sec-sm">
        <div className="wrap bring-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
          <div className="surface" style={{ padding: 28 }}>
            <h3 className="h-3" style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 10 }}><Ic.bag width="22" height="22" style={{ color: 'var(--turq-deep)' }}/> {window.t('prod.bring')}</h3>
            <ul className="ticks">{(window.tt(trip, 'bring') || []).map((x, i) => <li key={i}><Ic.check className="tick-yes"/>{x}</li>)}</ul>
          </div>
          <div style={{ background: 'linear-gradient(150deg, var(--teal-700), var(--teal-950))', color: '#fff', borderRadius: 'var(--r-md)', padding: 28 }}>
            <h3 className="h-3" style={{ color: '#fff', marginBottom: 14, display: 'flex', alignItems: 'center', gap: 10 }}><Ic.star width="20" height="20" style={{ color: 'var(--turq-bright)' }}/> {window.t('prod.bestForTitle')}</h3>
            <p style={{ color: 'rgba(234,246,247,.88)', fontSize: 16 }}>{window.tt(trip, 'forWho')}</p>
            <div style={{ marginTop: 18 }}><WAButton size="md" msg={window.t('wa.suitsGroup', { name: window.tt(trip, 'name') })}>{window.t('prod.askSuits')}</WAButton></div>
          </div>
        </div>
      </section>

      {/* responsible + weather notes */}
      <section className="bg-ivory2 sec-sm">
        <div className="wrap bring-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 22 }}>
          <div className="surface" style={{ padding: 26, display: 'flex', gap: 16 }}>
            <span style={{ width: 46, height: 46, borderRadius: 12, flex: 'none', background: 'rgba(16,182,205,.12)', color: 'var(--turq-deep)', display: 'grid', placeItems: 'center' }}><Ic.dolphin width="24" height="24"/></span>
            <div><h3 style={{ fontSize: 18, marginBottom: 6 }}>{window.t('prod.respTitle')}</h3><p style={{ fontSize: 14.5, color: 'var(--ink-soft)' }}>{window.t('prod.respBody')}</p></div>
          </div>
          <div className="surface" style={{ padding: 26, display: 'flex', gap: 16 }}>
            <span style={{ width: 46, height: 46, borderRadius: 12, flex: 'none', background: 'rgba(16,182,205,.12)', color: 'var(--turq-deep)', display: 'grid', placeItems: 'center' }}><Ic.wave width="24" height="24"/></span>
            <div><h3 style={{ fontSize: 18, marginBottom: 6 }}>{window.t('prod.weatherTitle')}</h3><p style={{ fontSize: 14.5, color: 'var(--ink-soft)' }}>{window.t('prod.weatherBody')}</p></div>
          </div>
        </div>
      </section>

      {/* What you will see — dolphin type */}
      <section className="bg-ivory sec-sm">
        <div className="wrap" style={{ maxWidth: 900 }}>
          <div className="surface" style={{ padding: 30, display: 'flex', gap: 18, alignItems: 'flex-start' }}>
            <span style={{ width: 48, height: 48, borderRadius: 13, flex: 'none', background: 'rgba(16,182,205,.12)', color: 'var(--turq-deep)', display: 'grid', placeItems: 'center' }}><Ic.dolphin width="25" height="25"/></span>
            <div>
              <SecHead kicker={window.t('prod.seeKicker')} title={window.t('prod.seeTitle')}/>
              <p style={{ fontSize: 15.5, color: 'var(--ink-soft)', lineHeight: 1.7, marginTop: 14 }}>{window.tt(trip, 'whatYouWillSee')}</p>
            </div>
          </div>
        </div>
      </section>

      {/* FAQs */}
      <section className="bg-ivory2 sec-sm">
        <div className="wrap" style={{ maxWidth: 820 }}>
          <SecHead center kicker={window.t('prod.beforeBook')} title={window.t('prod.yourQuestions', { name: window.tt(trip, 'h1') || window.tt(trip, 'name') })}/>
          <div style={{ marginTop: 28 }}>{(window.tt(trip, 'faqs') || faqPicks).filter(Boolean).map(([q, a], i) => <Accordion key={i} q={q} a={a} defaultOpen={i === 0}/>)}</div>
          <div style={{ textAlign: 'center', marginTop: 26 }}><Btn kind="ghost" onClick={() => go('faq')} icon="arrow">{window.t('prod.allFaqs')}</Btn></div>
        </div>
      </section>

      <RelatedTrips current={trip.key} go={go}/>
      <InternalLinks current={trip.key} go={go}/>
      <FinalCTA go={go} trip={trip}/>
    </main>
  );
}

Object.assign(window, { ProductPage, InternalLinks });
