/* Events — Loncin op locatie: boottochten, exclusieve locaties en uw eigen evenement,
   met een scroll-gedreven fotoportfolio. */
function EventsScreen({ onNavigate }) {
  const { Eyebrow, Ornament, Button } = window.LoncinDesignSystem_6f2c51;
  const { PageHead, LINKS } = window;

  const offers = [
    ['Boottochten', 'Een diner aan boord op de Schelde. Wij varen uit met de keuken mee — aperitief op het dek, gangen onder weg, de skyline van Antwerpen als decor.'],
    ['Exclusieve locaties', 'Kastelen, herenhuizen, loodsen aan het water of een private zaal: wij koken op unieke, exclusieve plekken en brengen het volledige Loncin-restaurant naar de plaats van uw keuze.'],
    ['Uw eigen evenement', 'Een bedrijfsfeest, huwelijk of familiediner? Van intieme tafels tot grote gezelschappen — wij stellen samen met u een menu en beleving op maat samen.'],
  ];

  /* The portfolio: three parallax columns. Each column drifts at its own
     speed while every frame fades + lifts into view (IntersectionObserver). */
  const columns = [
    [
      { id: 'ev-festina', src: 'ev-festina-lente.jpg', label: 'Festina Lente', place: 'Aan boord op de Schelde', ratio: '3 / 2' },
      { id: 'ev-gala', src: 'ev-35jaar-gala.jpg', label: 'Galadiner', place: 'Exclusieve locatie', ratio: '2 / 3' },
      { id: 'ev-oesters', src: 'ev-oesters.jpg', label: 'Oesters', place: 'Apéro aan boord', ratio: '3 / 2' },
      { id: 'ev-receptie', src: 'ev-receptie.jpg', label: 'Receptie', place: 'Walking dinner', ratio: '3 / 2' },
      { id: 'ev-z9-nacht', src: 'ev-z9-nacht.jpg', label: 'De Z9 bij avond', place: 'Diner aan boord', ratio: '3 / 2' },
    ],
    [
      { id: 'ev-boot-dek', src: 'ev-boot-dek.jpg', label: 'Diner aan boord', place: 'Festina Lente', ratio: '3 / 2' },
      { id: 'ev-chef-boot', src: 'ev-chef-boot.jpg', label: 'De keuken vaart mee', place: 'Aan boord', ratio: '3 / 2' },
      { id: 'ev-staff', src: 'ev-35jaar-staff.jpg', label: 'Onze brigade', place: '35 jaar Loncin', ratio: '2 / 3' },
      { id: 'ev-caviar', src: 'ev-caviar.jpg', label: 'Caviar', place: 'Hapje op het dek', ratio: '3 / 2' },
      { id: 'ev-privefeest', src: 'ev-privefeest.jpg', label: 'Privéfeest in het herenhuis', place: 'Exclusieve locatie', ratio: '2 / 3' },
    ],
    [
      { id: 'ev-evanna', src: 'ev-evanna.jpg', label: 'Evanna bij avond', place: 'Yacht charter', ratio: '3 / 2' },
      { id: 'ev-scampi', src: 'ev-scampi.jpg', label: 'Scampi', place: 'Walking dinner', ratio: '3 / 2' },
      { id: 'ev-champagne', src: 'ev-champagne.jpg', label: 'Champagne Loncin', place: 'Een toost aan boord', ratio: '3 / 2' },
      { id: 'ev-sparkler', src: 'ev-35jaar-sparkler.jpg', label: 'Een feest om nooit te vergeten', place: '35 jaar Loncin', ratio: '3 / 2' },
      { id: 'ev-festina-oudjaar', src: 'ev-festina-oudjaar.jpg', label: 'Oudjaar aan boord', place: 'Festina Lente', ratio: '3 / 2' },
      { id: 'ev-tafel-kandelaar', src: 'ev-tafel-kandelaar.jpg', label: 'Gedekte tafel met kandelaars', place: 'Diner op locatie', ratio: '2 / 3' },
    ],
  ];
  const SPEEDS = [-34, 26, -18];

  const colRefs = React.useRef([]);

  React.useEffect(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    // Mark a figure revealed (records when, for the watchdog below).
    const seenAt = new WeakMap();
    const mark = (el) => { if (!seenAt.has(el)) seenAt.set(el, (window.performance && performance.now()) || Date.now()); el.classList.add('is-in'); };

    // Watchdog: in some embedding/capture/print contexts CSS transitions never
    // advance, which would freeze a revealed figure at opacity:0 (gallery shows
    // as a black band). If a figure has been revealed for longer than the
    // transition should take but is still transparent, kill its transition so
    // it snaps to the visible end-state. Working browsers finish the fade well
    // before this fires, so the animation is untouched there.
    let wTicks = 0;
    const watchdog = setInterval(() => {
      wTicks++;
      const now = (window.performance && performance.now()) || Date.now();
      document.querySelectorAll('.ev-reveal.is-in').forEach((el) => {
        const t = seenAt.get(el) || 0;
        if (now - t > 1100 && parseFloat(getComputedStyle(el).opacity) < 0.02) {
          el.style.transition = 'none';
          el.style.opacity = '1';
          el.style.transform = 'none';
        }
      });
      if (wTicks > 16) clearInterval(watchdog);
    }, 300);

    // Reveal on enter — IntersectionObserver, with a scroll-position fallback
    // (some capture/embedding contexts don't fire IO reliably).
    const reveal = () => {
      const vh = window.innerHeight || 800;
      document.querySelectorAll('.ev-reveal').forEach((el) => {
        if (el.getBoundingClientRect().top < vh * 0.9) mark(el);
      });
    };
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) mark(e.target); }),
      { threshold: 0.18 }
    );
    document.querySelectorAll('.ev-reveal').forEach((el) => io.observe(el));

    if (reduce) { reveal(); return () => { io.disconnect(); clearInterval(watchdog); }; }

    // Parallax drift per column + reveal fallback, throttled via rAF
    let raf = null;
    const update = () => {
      raf = null;
      const vh = window.innerHeight || 800;
      colRefs.current.forEach((el, i) => {
        if (!el) return;
        const rect = el.getBoundingClientRect();
        const center = rect.top + rect.height / 2;
        const offset = (center - vh / 2) / vh; // ~ -1 .. 1
        el.style.transform = `translate3d(0, ${(offset * SPEEDS[i]).toFixed(1)}px, 0)`;
      });
      reveal();
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    update();
    return () => {
      io.disconnect();
      clearInterval(watchdog);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <main style={{ paddingBottom: 'var(--space-9)' }}>
      <PageHead
        eyebrow="Events"
        title="Loncin op locatie"
        intro="Restaurant Loncin komt ook naar u toe. Wij organiseren events tijdens boottochten op de Schelde, op unieke en exclusieve locaties, en op uw eigen evenement — met dezelfde verse, klassieke keuken als in het herenhuis."
      />

      {/* Three offerings */}
      <section style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: 'var(--space-5) var(--gutter) var(--space-7)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 'clamp(1.5rem, 3vw, 2.6rem)' }}>
          {offers.map(([title, desc], i) => (
            <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: '0.9rem' }}>
              <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--text-caption)', letterSpacing: 'var(--tracking-caps)', textTransform: 'uppercase', color: 'var(--metal-gold)' }}>
                {String(i + 1).padStart(2, '0')}
              </span>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'var(--text-h2)', color: 'var(--text-primary)', margin: 0, letterSpacing: 'var(--tracking-display)' }}>{title}</h3>
              <p style={{ fontFamily: 'var(--font-serif)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-relaxed)', margin: 0 }}>{desc}</p>
            </div>
          ))}
        </div>
      </section>

      <div style={{ maxWidth: 460, margin: 'var(--space-6) auto var(--space-7)' }}><Ornament variant="diamond" /></div>

      {/* Scroll-driven portfolio */}
      <section style={{ padding: '0 var(--gutter)' }}>
        <div style={{ maxWidth: 'var(--container-prose)', margin: '0 auto var(--space-7)', textAlign: 'center' }}>
          <Eyebrow align="center" rule>Een greep uit onze events</Eyebrow>
          <p style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', color: 'var(--text-secondary)', fontSize: 'var(--text-body-lg)', marginTop: '1.2rem' }}>
            Scroll door de beelden — van het dek van een schip tot een private zaal.
          </p>
        </div>

        <div
          className="ev-gallery"
          style={{
            maxWidth: 'var(--container-max)',
            margin: '0 auto',
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 'clamp(0.8rem, 1.6vw, 1.4rem)',
            alignItems: 'start',
          }}
        >
          {columns.map((col, ci) => (
            <div
              key={ci}
              ref={(el) => (colRefs.current[ci] = el)}
              style={{
                display: 'flex',
                flexDirection: 'column',
                gap: 'clamp(0.8rem, 1.6vw, 1.4rem)',
                marginTop: ci === 1 ? 'clamp(1.5rem, 5vw, 4rem)' : 0,
                willChange: 'transform',
              }}
            >
              {col.map((it) => (
                <figure key={it.id} className="ev-reveal" style={{ margin: 0 }}>
                  <div style={{ width: '100%', aspectRatio: it.ratio, borderRadius: 'var(--radius-card)', overflow: 'hidden', background: 'var(--surface-raised, #1a1714)' }}>
                    <img
                      src={window.RES('assets/' + it.src)}
                      alt={it.label + ' — ' + it.place}
                      loading="lazy"
                      style={{ display: 'block', width: '100%', height: '100%', objectFit: 'cover' }}
                    />
                  </div>
                  <figcaption style={{ marginTop: '0.7rem', display: 'flex', flexDirection: 'column', gap: '0.15rem' }}>
                    <span style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-body-lg)', color: 'var(--text-primary)' }}>{it.label}</span>
                    <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--text-caption)', letterSpacing: 'var(--tracking-caps)', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{it.place}</span>
                  </figcaption>
                </figure>
              ))}
            </div>
          ))}
        </div>
      </section>

      <div style={{ maxWidth: 460, margin: 'var(--space-8) auto var(--space-7)' }}><Ornament variant="diamond" /></div>

      {/* CTA */}
      <section style={{ textAlign: 'center', padding: '0 var(--gutter)' }}>
        <p style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', color: 'var(--text-secondary)', fontSize: 'var(--text-body-lg)', maxWidth: '48ch', margin: '0 auto 1.8rem' }}>
          Een eigen feest, een boottocht of een diner op locatie? Vertel ons uw idee
          en wij stellen een voorstel op maat samen.
        </p>
        <div style={{ display: 'flex', gap: '1rem', justifyContent: 'center', flexWrap: 'wrap' }}>
          <Button variant="primary" href={LINKS.mail} target="_blank" rel="noopener noreferrer">Vraag een offerte</Button>
          <Button variant="ghost" onClick={() => onNavigate('contact')}>Contactgegevens</Button>
        </div>
      </section>
    </main>
  );
}
Object.assign(window, { EventsScreen });
