// Pages of the wedding invitation
const { useState, useEffect, useRef } = React;

// Module-level audio — lives outside React so it survives component unmounts
const bgAudio = window.bgAudio = new Audio('audio/background.mp3');
bgAudio.loop = true;

// Start music on first user gesture of any kind (browser autoplay policy)
const startAudio = () => bgAudio.play().catch(() => {});
['click', 'touchstart', 'keydown', 'scroll'].forEach(evt =>
  window.addEventListener(evt, startAudio, { once: true, passive: true })
);

// ─── i18n ────────────────────────────────────────────────────────────────────
const _p = new URLSearchParams(window.location.search);
const _pathLang = /\/en(\/|$)/.test(window.location.pathname) ? 'en'
                : /\/de(\/|$)/.test(window.location.pathname) ? 'de' : null;
const lang = _pathLang || _p.get('lang') || 'de';
window.lang = lang;

const TRANSLATIONS = {
  de: {
    saveTheDate:      'SAVE THE DATE',
    tapToOpen:        'TIPPEN ZUM ÖFFNEN',
    nikkahDate:       '18. JULI 2026',
    weAreMarrying:    'WIR HEIRATEN',
    daughterOf:       'Tochter von Ahmad Shah Syed',
    sonOf:            'Sohn von Abdul Ahad Muslim Zai',
    inThisWorld:      'In dieser Welt — und in der nächsten.',
    countdown:        'Countdown',
    countdownUntil:   'BIS ZUM 18. JULI 2026',
    days:             'TAGE',
    hours:            'STUNDEN',
    minutes:          'MINUTEN',
    seconds:          'SEKUNDEN',
    welcome:          'Willkommen!',
    welcomeBody:      'Wir laden Euch von Herzen ein, unseren Nikkah-Tag mit uns zu feiern. Wir freuen uns darauf, diesen unvergesslichen Moment mit unseren liebsten Menschen zu teilen.',
    verseTranslation: '„Und zu Seinen Zeichen gehört es, dass Er für euch aus euch selbst Gattinnen erschaffen hat, damit ihr bei ihnen Ruhe findet. Und Er hat Zuneigung und Barmherzigkeit zwischen euch gesetzt. Darin sind wahrlich Zeichen für ein Volk, das nachdenkt."',
    verseRef:         'Sure Ar-Rum 30:21',
    onDate:           'AM SAMSTAG, 18. JULI 2026',
    islamicDate:      '3. MUḤARRAM 1448 AH',
    atTime:           'UM 18:00 UHR',
    openInMaps:       'IN KARTE ÖFFNEN',
    presenceText:     'Eure Anwesenheit ist das schönste Geschenk, das wir uns wünschen können.',
    duaText:          'Möge Allah euch segnen, Seinen Segen auf euch herabschicken und euch in Güte vereinen.',
    withLove:         'MIT LIEBE,',
    rsvpSubtitle:     'BITTE GEBT UNS BIS ZUM 18.06.2026 BESCHEID',
    namePlaceholder:  'Euer Name',
    attendingBtn:     'Ich werde dabei sein',
    notAttendingBtn:  'Ich kann leider nicht kommen',
    lookingForward:   'Wir freuen uns auf euch, inshallah.',
    thankYou:         'Vielen Dank',
    attendingMsg:     'Wir freuen uns sehr, euch an unserem Tag willkommen zu heißen.',
    notAttendingMsg:  'Schade, dass ihr nicht dabei sein könnt. Ihr seid in unseren Gedanken.',
  },
  en: {
    saveTheDate:      'SAVE THE DATE',
    tapToOpen:        'TAP TO OPEN',
    nikkahDate:       'JULY 18, 2026',
    weAreMarrying:    'WE ARE GETTING MARRIED',
    daughterOf:       'Daughter of Ahmad Shah Syed',
    sonOf:            'Son of Abdul Ahad Muslim Zai',
    inThisWorld:      'In this world — and the next.',
    countdown:        'Countdown',
    countdownUntil:   'UNTIL JULY 18, 2026',
    days:             'DAYS',
    hours:            'HOURS',
    minutes:          'MINUTES',
    seconds:          'SECONDS',
    welcome:          'Welcome!',
    welcomeBody:      'We warmly invite you to celebrate our Nikkah with us. We look forward to sharing this unforgettable moment with our dearest family and friends.',
    verseTranslation: '"And of His signs is that He created for you from yourselves mates that you may find tranquility in them; and He placed between you affection and mercy. Indeed in that are signs for a people who give thought."',
    verseRef:         'Surah Ar-Rum 30:21',
    onDate:           'ON SATURDAY, JULY 18, 2026',
    islamicDate:      '3 Muḥarram 1448 AH',
    atTime:           'AT 6:00 PM',
    openInMaps:       'OPEN IN MAPS',
    presenceText:     'Your presence is the greatest gift we could wish for.',
    duaText:          'May Allah bless you, shower His blessings upon you, and unite you in goodness.',
    withLove:         'WITH LOVE,',
    rsvpSubtitle:     'PLEASE LET US KNOW BY JUNE 18, 2026',
    namePlaceholder:  'Your Name',
    attendingBtn:     'I will be there',
    notAttendingBtn:  'I am unable to attend',
    lookingForward:   'We look forward to seeing you, inshallah.',
    thankYou:         'Thank You',
    attendingMsg:     'We are so happy to welcome you on our special day.',
    notAttendingMsg:  'We are sorry you cannot make it. You are in our thoughts.',
  },
};
const tr = TRANSLATIONS[lang] || TRANSLATIONS.de;

// ─── Page 1: Cover — seal splits open (top half up, bottom half down) ──────
function CoverPage({ onOpen, tweaks }) {
  const [sealBroken, setSealBroken] = useState(false);
  const [opening,    setOpening]    = useState(false);
  const [ringActive, setRingActive] = useState(false);
  const [ringDone,   setRingDone]   = useState(false);
  const openedRef  = useRef(false);

  const handleOpen = (withMusic = false) => {
    if (openedRef.current) return;
    openedRef.current = true;
    if (withMusic) bgAudio.play().catch(() => {});
    setSealBroken(true);
    onOpen();
    setTimeout(() => setOpening(true), 140);
  };

  useEffect(() => {
    // Micro-scroll to fire the 'scroll' event and unlock browser autoplay
    const ts = setTimeout(() => {
      window.scrollTo(0, 1);
      requestAnimationFrame(() => window.scrollTo(0, 0));
    }, 200);

    const t1 = setTimeout(() => setRingActive(true), 60);
    const t2 = setTimeout(() => setRingDone(true), 1000);
    const t3 = setTimeout(() => handleOpen(false), 2000);
    return () => { clearTimeout(ts); clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);

  const easing = 'cubic-bezier(0.65, 0, 0.35, 1)';

  const damask = (
    <div style={{
      position: 'absolute', inset: 0, opacity: 0.07, pointerEvents: 'none',
      backgroundImage: `radial-gradient(circle at 22% 30%, ${tweaks.gold} 1px, transparent 1.5px),
                        radial-gradient(circle at 72% 68%, ${tweaks.gold} 1px, transparent 1.5px)`,
      backgroundSize: '58px 58px, 74px 74px',
    }} />
  );

  // Renders the full page design at 200% height of the panel (= 100% viewport).
  // forTop=true  → top:0       → panel clips the first half (top 50% of viewport)
  // forTop=false → top:-100%   → panel clips the second half (bottom 50% of viewport)
  // The wax seal is placed at top:50% of this full-height div, so it sits exactly
  // on the boundary and gets naturally torn apart as the two panels slide away.
  const pageContent = (forTop) => (
    <div style={{
      position: 'absolute',
      left: 0, right: 0,
      height: '200%',
      top: forTop ? 0 : '-100%',
      background: `linear-gradient(175deg, ${tweaks.bgLight} 0%, ${tweaks.bgBase} 100%)`,
    }}>
      {damask}

      {/* Decorative border */}
      <div style={{ position: 'absolute', left: 14, right: 14, top: 14, height: 1, background: `${tweaks.gold}40`, pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', left: 14, right: 14, bottom: 14, height: 1, background: `${tweaks.gold}40`, pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', left: 14, top: 14, bottom: 14, width: 1, background: `${tweaks.gold}40`, pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', right: 14, top: 14, bottom: 14, width: 1, background: `${tweaks.gold}40`, pointerEvents: 'none' }} />

      {/* Bismillah + header — flex-centred in the upper viewport half */}
      <div style={{
        position: 'absolute', top: 0, bottom: '50%', left: 0, right: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', paddingBottom: '8%',
        pointerEvents: 'none',
      }}>
        <Bismillah color={tweaks.gold} width={148} />
        <div style={{
          fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
          fontSize: 10.5, letterSpacing: '0.44em', color: tweaks.ink,
          opacity: 0.45, marginTop: 10, whiteSpace: 'nowrap',
        }}>{ tr.saveTheDate }</div>
      </div>

      {/* Date + Nikkah — anchored below the seal regardless of screen height.
          Seal tip is at 50vh+60px, ring bottom ≈ 50vh+127px → start at 50%+155px */}
      <div style={{
        position: 'absolute', top: 'calc(50% + 155px)', left: 0, right: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
        pointerEvents: 'none',
      }}>
        <div style={{
          fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
          fontSize: 13, letterSpacing: '0.34em', color: tweaks.ink,
          fontWeight: 600, opacity: 0.78, whiteSpace: 'nowrap',
        }}>{ tr.nikkahDate }</div>
        <div style={{
          fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
          fontSize: 28, color: tweaks.ink, whiteSpace: 'nowrap',
        }}>Nikkah</div>
      </div>

    </div>
  );

  return (
    <div
      onClick={() => handleOpen(true)}
      style={{ position: 'absolute', inset: 0, cursor: sealBroken ? 'default' : 'pointer' }}
    >
      {/* Top half — V dips 60px down at centre, slides up on open */}
      <div style={{
        position: 'absolute',
        top: 0, left: 0, right: 0, height: '50%',
        background: `linear-gradient(175deg, ${tweaks.bgLight} 0%, ${tweaks.bgBase} 100%)`,
        clipPath:        'polygon(0% 0%, 100% 0%, 100% 100%, calc(100% - 14px) 100%, 50% calc(100% + 60px), 14px 100%, 0% 100%)',
        WebkitClipPath:  'polygon(0% 0%, 100% 0%, 100% 100%, calc(100% - 14px) 100%, 50% calc(100% + 60px), 14px 100%, 0% 100%)',
        transform: opening ? 'translateY(calc(-100% - 70px))' : 'translateY(0)',
        transition: opening ? `transform 1.1s ${easing}` : 'none',
        zIndex: 5,
      }}>
        {pageContent(true)}
      </div>

      {/* Bottom half — matching 60px notch at top centre, slides down on open */}
      <div style={{
        position: 'absolute',
        top: '50%', left: 0, right: 0, height: '50%',
        background: `linear-gradient(175deg, ${tweaks.bgLight} 0%, ${tweaks.bgBase} 100%)`,
        clipPath:        'polygon(0% 0%, 14px 0%, 50% 60px, calc(100% - 14px) 0%, 100% 0%, 100% 100%, 0% 100%)',
        WebkitClipPath:  'polygon(0% 0%, 14px 0%, 50% 60px, calc(100% - 14px) 0%, 100% 0%, 100% 100%, 0% 100%)',
        transform: opening ? 'translateY(calc(100% + 70px))' : 'translateY(0)',
        transition: opening ? `transform 1.1s ${easing}` : 'none',
        zIndex: 5,
      }}>
        {pageContent(false)}
      </div>

      {/* Wax seal — sits at the V-tip, exactly where a letter seal closes the flap */}
      <div style={{
        position: 'absolute',
        top: 'calc(50% + 60px)', left: '50%',
        transform: 'translate(-50%, -50%)',
        zIndex: 7,
        pointerEvents: sealBroken ? 'none' : 'auto',
        cursor: sealBroken ? 'default' : 'pointer',
      }}>
        <div
          className={ringDone && !sealBroken ? 'seal-pulse' : ''}
          style={{ position: 'relative', display: 'inline-block' }}
        >
          <WaxSeal size={120} broken={sealBroken} />
          {!sealBroken && (
            <svg
              style={{ position: 'absolute', top: 0, left: 0, pointerEvents: 'none', overflow: 'visible' }}
              width={120} height={120} viewBox="0 0 140 140"
            >
              <path
                pathLength="1"
                d="M 70 8 C 88 6 102 14 110 26 C 124 30 132 44 130 58 C 138 70 134 88 122 96 C 124 112 110 124 96 122 C 88 134 70 134 60 128 C 46 134 30 124 30 110 C 14 106 8 90 16 78 C 6 66 12 48 26 42 C 24 26 38 14 54 16 C 60 8 70 8 70 8 Z"
                fill="none"
                stroke={tweaks.gold}
                strokeWidth="3"
                strokeDasharray="1"
                strokeDashoffset={ringActive ? 0 : 1}
                strokeLinecap="round"
                transform="translate(70 70) scale(1.12) translate(-70 -70)"
                style={{ transition: ringActive ? 'stroke-dashoffset 0.94s linear' : 'none', opacity: 0.85 }}
              />
            </svg>
          )}
        </div>
      </div>

      {/* Animations */}
      <style>{`
        @keyframes sealPulse {
          0%, 100% { transform: scale(1); }
          50%       { transform: scale(1.06); }
        }
        @keyframes hintFade {
          from { opacity: 0; transform: translateY(5px); }
          to   { opacity: 1; }
        }
        .seal-pulse { animation: sealPulse 1.8s ease-in-out infinite; }
      `}</style>

      {/* "Tap to open" hint — appears after ring completes */}
      {ringDone && !sealBroken && (
        <div style={{
          position: 'absolute',
          bottom: '8%', left: 0, right: 0,
          textAlign: 'center',
          fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
          fontSize: 10, letterSpacing: '0.32em', color: tweaks.ink,
          opacity: 0.45, pointerEvents: 'none', zIndex: 7,
          whiteSpace: 'nowrap',
          animation: 'hintFade 0.7s ease forwards',
        }}>{ tr.tapToOpen }</div>
      )}

      {/* Gold V-line overlay — covers clip-path anti-aliasing artefacts */}
      {/* Gold V-line — height matches clip depth exactly so it sits on the seam */}
      <svg style={{
        position: 'absolute',
        top: '50%', left: 0,
        width: '100%', height: 60,
        pointerEvents: 'none',
        zIndex: 6,
        opacity: opening ? 0 : 1,
        transition: opening ? 'opacity 0.12s' : 'none',
      }}
        viewBox="0 0 390 60"
        preserveAspectRatio="none"
      >
        <polyline
          points="0,0 14,0 195,60 376,0 390,0"
          fill="none"
          stroke={tweaks.gold}
          strokeWidth="1.5"
          opacity="0.55"
          style={{ vectorEffect: 'non-scaling-stroke' }}
        />
      </svg>
    </div>
  );
}

// ─── Page 2: Main / Hero ──────────────────────────────
function MainPage({ tweaks, bgSrc, visible }) {
  const [ready, setReady] = useState(false);
  const wrapRef = useRef(null);

  useEffect(() => {
    if (ready) return;

    if (typeof visible === 'boolean') {
      // Mobile: parent tells us exactly when we're shown
      if (!visible) return;
      const t = setTimeout(() => setReady(true), 120);
      return () => clearTimeout(t);
    } else {
      // Desktop: fire when the section scrolls into view
      const el = wrapRef.current;
      if (!el) return;
      const io = new IntersectionObserver(
        ([e]) => { if (e.isIntersecting) { setReady(true); io.disconnect(); } },
        { threshold: 0.25 }
      );
      io.observe(el);
      return () => io.disconnect();
    }
  }, [visible, ready]);

  // fly(direction, delay): slides in from left (-) or right (+)
  const fly = (dx, delay) => ({
    opacity: ready ? 1 : 0,
    transform: ready ? 'translateX(0px)' : `translateX(${dx}px)`,
    transition: `opacity 0.9s cubic-bezier(0.22,1,0.36,1) ${delay}s,
                 transform 0.9s cubic-bezier(0.22,1,0.36,1) ${delay}s`,
  });

  return (
    <div ref={wrapRef} style={{
      position: 'absolute', inset: 0,
      overflow: 'hidden',
      background: '#E0E6DE',
    }}>
      {/* background image */}
      <picture>
        <source media="(max-width: 768px)" srcSet="images/background_image_mobile.jpeg" />
        <img
          src="images/background_image.png"
          alt=""
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%',
            objectFit: 'cover',
            objectPosition: '50% 40%',
          }}
        />
      </picture>

      {/* dark overlay + vignette */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(10,12,20,0.55) 0%, rgba(10,12,20,0.30) 25%, rgba(10,12,20,0.30) 55%, rgba(10,12,20,0.65) 100%)',
        pointerEvents: 'none',
      }} />

      <div style={{
        position: 'relative', height: '100%',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        padding: '44px 28px 44px', boxSizing: 'border-box',
        color: '#f7f3eb',
        textAlign: 'center',
      }}>
        <Bismillah color="#f0e2c0" width={200} />

        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 4, width: '100%' }}>
          {/* Khadija — flies in from left */}
          <div style={{
            fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
            fontSize: 64, lineHeight: 0.95,
            color: '#fff',
            textShadow: '0 2px 12px rgba(0,0,0,0.3)',
            ...fly(-80, 0.5),
          }}>Khadija</div>
          <div style={{
            fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
            fontSize: 11, letterSpacing: '0.2em', fontStyle: 'italic',
            opacity: ready ? 0.85 : 0, marginTop: 10,
            whiteSpace: 'nowrap',
            transition: `opacity 0.7s ease 0.65s`,
          }}>{ tr.daughterOf }</div>

          <div style={{
            fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
            fontSize: 52, color: '#f0e2c0',
            margin: '6px 0',
            opacity: ready ? 1 : 0,
            transition: 'opacity 0.6s ease 0.8s',
          }}>&</div>

          {/* Aziz — flies in from right */}
          <div style={{
            fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
            fontSize: 64, lineHeight: 0.95,
            color: '#fff',
            textShadow: '0 2px 12px rgba(0,0,0,0.3)',
            ...fly(80, 0.65),
          }}>Aziz</div>
          <div style={{
            fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
            fontSize: 10.5, letterSpacing: '0.18em', fontStyle: 'italic',
            opacity: ready ? 0.85 : 0, marginTop: 10,
            whiteSpace: 'nowrap',
            transition: 'opacity 0.7s ease 0.8s',
          }}>{ tr.sonOf }</div>
        </div>

        <div style={{
          fontFamily: "'Amiri Quran', 'Amiri', serif",
          fontSize: 18, color: '#f0e2c0',
          direction: 'rtl', marginBottom: 4,
        }}>فِي الدُّنْيَا وَالْآخِرَة</div>

        <div style={{
          fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
          fontStyle: 'italic', fontSize: 13,
          opacity: 0.9, marginBottom: 22,
        }}>{ tr.inThisWorld }</div>

        <div style={{
          width: 50, height: 1, background: '#f0e2c0', opacity: 0.5, marginBottom: 14,
        }} />

        <div style={{
          fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
          fontSize: 22, letterSpacing: '0.35em', fontWeight: 700,
          whiteSpace: 'nowrap', fontVariantNumeric: 'lining-nums',
        }}>{ tr.nikkahDate }</div>

        <div style={{
          fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
          fontSize: 28, color: '#f0e2c0', marginTop: 6,
          whiteSpace: 'nowrap',
        }}>Nikkah</div>
      </div>
    </div>
  );
}

// ─── Page 3: Countdown + Welcome ─────────────────────
function useCountdown(target) {
  const [t, setT] = useState(() => diff(target));
  useEffect(() => {
    const id = setInterval(() => setT(diff(target)), 1000);
    return () => clearInterval(id);
  }, [target]);
  return t;
}
function diff(target) {
  const ms = Math.max(0, target - Date.now());
  const s = Math.floor(ms / 1000);
  return {
    days: Math.floor(s / 86400),
    hours: Math.floor((s % 86400) / 3600),
    mins: Math.floor((s % 3600) / 60),
    secs: s % 60,
  };
}

function CountdownPage({ tweaks, desktop = false }) {
  const target = new Date('2026-07-18T18:00:00').getTime();
  const t = useCountdown(target);
  const cell = (n, lbl) => (
    <div style={{ textAlign: 'center', flex: 1 }}>
      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 40, fontWeight: 600, color: tweaks.ink,
        letterSpacing: '0.02em', fontVariantNumeric: 'lining-nums',
      }}>{String(n).padStart(2, '0')}</div>
      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 9, letterSpacing: '0.3em', color: tweaks.ink, opacity: 0.55,
        marginTop: 2,
      }}>{lbl}</div>
    </div>
  );
  const wrapStyle = desktop
    ? { position: 'relative', width: '100%', minHeight: '100dvh', background: tweaks.bgBase,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        color: tweaks.ink, textAlign: 'center' }
    : { position: 'absolute', inset: 0, background: tweaks.bgBase, overflowY: 'auto',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        color: tweaks.ink, textAlign: 'center' };
  const innerStyle = desktop
    ? { width: '100%', maxWidth: 640, padding: '80px 32px 80px', boxSizing: 'border-box',
        display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1 }
    : { width: '100%', padding: '44px 32px 44px', boxSizing: 'border-box',
        display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1 };
  return (
    <div style={wrapStyle}>
    <div style={innerStyle}>
      <div style={{
        fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
        fontSize: 38, color: tweaks.ink,
      }}>{ tr.countdown }</div>

      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 15, letterSpacing: '0.3em', fontWeight: 600, opacity: 0.85,
        marginTop: 14, marginBottom: 24,
        whiteSpace: 'nowrap', fontVariantNumeric: 'lining-nums',
      }}>{ tr.countdownUntil }</div>

      <div style={{
        display: 'flex', alignItems: 'flex-start', width: '100%',
        padding: '16px 0',
        borderTop: `1px solid ${tweaks.gold}66`,
        borderBottom: `1px solid ${tweaks.gold}66`,
      }}>
        {cell(t.days, tr.days)}
        <Sep />
        {cell(t.hours, tr.hours)}
        <Sep />
        {cell(t.mins, tr.minutes)}
        <Sep />
        {cell(t.secs, tr.seconds)}
      </div>

      <div style={{
        fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
        fontSize: 44, color: tweaks.ink,
        marginTop: 40,
      }}>{ tr.welcome }</div>

      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 14.5, lineHeight: 1.6,
        color: tweaks.ink, opacity: 0.85,
        marginTop: 18, fontStyle: 'italic',
        maxWidth: 300, textWrap: 'pretty',
      }}>{ tr.welcomeBody }</div>

      <div style={{
        width: 40, height: 1, background: tweaks.gold, opacity: 0.4,
        margin: '30px auto 0',
      }} />

      <div style={{
        fontFamily: "'Amiri Quran', 'Amiri', serif",
        fontSize: 17, lineHeight: 1.9,
        color: tweaks.ink, opacity: 0.88,
        direction: 'rtl', marginTop: 22,
        maxWidth: 300, textWrap: 'pretty',
      }}>
        وَمِنْ آيَاتِهِ أَنْ خَلَقَ لَكُم مِّنْ أَنفُسِكُمْ أَزْوَاجًا لِّتَسْكُنُوا إِلَيْهَا وَجَعَلَ بَيْنَكُم مَّوَدَّةً وَرَحْمَةً ۚ إِنَّ فِي ذَٰلِكَ لَآيَاتٍ لِّقَوْمٍ يَتَفَكَّرُونَ
      </div>

      <div style={{
        fontFamily: "'Amiri', serif",
        fontSize: 12, letterSpacing: '0.15em',
        color: tweaks.ink, opacity: 0.5,
        direction: 'rtl', marginTop: 8,
      }}>سورة الروم ٣٠:٢١</div>

      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontStyle: 'italic', fontSize: 13.5, lineHeight: 1.65,
        color: tweaks.ink, opacity: 0.72,
        marginTop: 14, maxWidth: 300, textWrap: 'pretty',
      }}>
        { tr.verseTranslation }
      </div>
      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 11, letterSpacing: '0.2em', opacity: 0.45,
        marginTop: 6,
      }}>{ tr.verseRef }</div>

      <div style={{ marginTop: 'auto', paddingTop: 30 }}>
        <VaseOrnament color={tweaks.gold} width={64} />
      </div>
    </div>
    </div>
  );
}
function Sep() {
  return <div style={{ width: 1, alignSelf: 'stretch', background: 'currentColor', opacity: 0.18 }} />;
}

// ─── Page 4: Location ─────────────────────────────────
function LocationPage({ tweaks, desktop = false }) {
  const wrapStyle = desktop
    ? { position: 'relative', width: '100%', minHeight: '100dvh', background: tweaks.bgBase,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        color: tweaks.ink, textAlign: 'center' }
    : { position: 'absolute', inset: 0, background: tweaks.bgBase, overflowY: 'auto',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        color: tweaks.ink, textAlign: 'center' };
  const innerStyle = desktop
    ? { width: '100%', maxWidth: 640, padding: '80px 32px 80px', boxSizing: 'border-box',
        display: 'flex', flexDirection: 'column', alignItems: 'center' }
    : { width: '100%', padding: '40px 32px 44px', boxSizing: 'border-box',
        display: 'flex', flexDirection: 'column', alignItems: 'center' };
  return (
    <div style={wrapStyle}>
    <div style={innerStyle}>
      <ArchOrnament color={tweaks.gold} width={180} />

      <div style={{
        fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
        fontSize: 40, marginTop: 14, color: tweaks.ink,
      }}>LaViva Events</div>

      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 16, letterSpacing: '0.3em', fontWeight: 600, opacity: 0.88,
        marginTop: 28, whiteSpace: 'nowrap', fontVariantNumeric: 'lining-nums',
      }}>{ tr.onDate }</div>
      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 16, letterSpacing: '0.3em', marginTop: 14, fontWeight: 500,
        whiteSpace: 'nowrap', fontVariantNumeric: 'lining-nums',
      }}>{ tr.atTime }</div>

      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontSize: 13.5, lineHeight: 1.55, opacity: 0.78,
        marginTop: 26, fontStyle: 'italic',
      }}>
        LaViva Events &amp; More<br/>
        Raiffeisenstraße 24–26<br/>
        61191 Rosbach vor der Höhe
      </div>

      {/* stylized map */}
      <div style={{
        marginTop: 26, width: '100%', height: 180,
        borderRadius: 10, overflow: 'hidden',
        border: `1px solid ${tweaks.gold}44`,
        boxShadow: '0 4px 14px rgba(0,0,0,0.06)',
      }}>
        <StylizedMap accent={tweaks.gold} />
      </div>

      <a
        href="https://maps.google.com/?q=Raiffeisenstraße+24-26+61191+Rosbach"
        target="_blank"
        rel="noreferrer"
        style={{
          marginTop: 22,
          fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
          fontSize: 12, letterSpacing: '0.25em',
          color: tweaks.ink, textDecoration: 'none',
          display: 'flex', alignItems: 'center', gap: 8,
          paddingBottom: 4,
          borderBottom: `1px solid ${tweaks.gold}88`,
        }}
      >
        <svg width="11" height="13" viewBox="0 0 11 13" fill="none">
          <path d="M5.5 0C2.46 0 0 2.46 0 5.5 0 8.94 5.5 13 5.5 13S11 8.94 11 5.5C11 2.46 8.54 0 5.5 0Zm0 7.5a2 2 0 110-4 2 2 0 010 4Z" fill={tweaks.gold}/>
        </svg>
        { tr.openInMaps }
      </a>

      {/* ── Merged closing section ── */}
      <div style={{
        width: 60, height: 1, background: tweaks.gold, opacity: 0.45,
        margin: '36px 0 28px',
      }} />

      <div style={{
        fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
        fontStyle: 'italic', fontSize: 14.5, lineHeight: 1.65,
        opacity: 0.82, maxWidth: 300, textWrap: 'pretty', textAlign: 'center',
      }}>
        { tr.presenceText }
      </div>

      <div style={{ marginTop: 32, paddingBottom: 8 }}>
        <div style={{
          fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
          fontSize: 12, letterSpacing: '0.3em', opacity: 0.6,
          whiteSpace: 'nowrap',
        }}>{ tr.withLove }</div>
        <div style={{
          fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
          fontSize: 28, color: tweaks.ink, marginTop: 4,
          whiteSpace: 'nowrap',
        }}>Syed &amp; Muslim Zai</div>
      </div>
    </div>
    </div>
  );
}

function StylizedMap({ accent }) {
  return (
    <svg viewBox="0 0 320 180" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="320" height="180" fill="#eaeae0" />
      {/* blocks */}
      <rect x="0" y="0" width="120" height="80" fill="#f2efe6" />
      <rect x="160" y="0" width="160" height="60" fill="#f2efe6" />
      <rect x="0" y="100" width="100" height="80" fill="#f2efe6" />
      <rect x="140" y="80" width="80" height="60" fill="#e5e9d8" />
      <rect x="240" y="80" width="80" height="100" fill="#f2efe6" />
      <rect x="120" y="140" width="120" height="40" fill="#f2efe6" />

      {/* roads */}
      <g stroke="#fff" strokeWidth="14" fill="none" opacity="0.95">
        <path d="M 0 90 Q 80 88 140 92 Q 200 96 320 92" />
        <path d="M 130 0 L 134 90 L 142 140 L 220 180" />
      </g>
      <g stroke="#fff" strokeWidth="8" fill="none" opacity="0.95">
        <path d="M 0 30 L 320 38" />
        <path d="M 60 0 L 64 100 L 80 180" />
        <path d="M 240 0 L 244 180" />
      </g>

      {/* highlighted route */}
      <path d="M 30 170 L 90 110 L 140 95 L 175 100" stroke={accent} strokeWidth="3.5" fill="none" strokeLinecap="round" opacity="0.85" />

      {/* pin */}
      <g transform="translate(175, 95)">
        <circle r="10" fill={accent} />
        <path d="M 0 8 L -7 22 L 7 22 Z" fill={accent} />
        <circle r="4" fill="#fff" />
      </g>
    </svg>
  );
}

// ─── Page 5: RSVP ────────────────────────────────────────
// Replace YOUR_FORMSPREE_ID with your form ID from formspree.io
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/xlgvjjpj';

function RSVPPage({ tweaks, desktop = false }) {
  const params   = new URLSearchParams(window.location.search);
  const urlGuest = params.get('guest') || '';

  const [nameInput, setNameInput] = useState('');
  const [sent,      setSent]      = useState(false);
  const [attending, setAttending] = useState(null);
  const [sending,   setSending]   = useState(false);

  const guestName = urlGuest || nameInput.trim();
  const canSubmit = guestName.length > 0;

  const handleRSVP = async (isAttending) => {
    if (!canSubmit || sending) return;
    if (!urlGuest && nameInput.trim()) {
      const url = new URL(window.location);
      url.searchParams.set('guest', nameInput.trim());
      window.history.replaceState({}, '', url);
    }
    setSending(true);
    setAttending(isAttending);
    try {
      await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name:    guestName,
          antwort: isAttending ? 'Kommt' : 'Kommt nicht',
        }),
      });
    } catch (_) {}
    setSending(false);
    setSent(true);
  };

  const wrapStyle = desktop
    ? { position: 'relative', width: '100%', minHeight: '100dvh', background: tweaks.bgLight,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        color: tweaks.ink, textAlign: 'center' }
    : { position: 'absolute', inset: 0, background: tweaks.bgLight, overflowY: 'auto',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        color: tweaks.ink, textAlign: 'center' };
  const innerStyle = desktop
    ? { width: '100%', maxWidth: 560, padding: '60px 48px', boxSizing: 'border-box',
        display: 'flex', flexDirection: 'column', alignItems: 'center' }
    : { width: '100%', padding: '52px 40px', boxSizing: 'border-box',
        display: 'flex', flexDirection: 'column', alignItems: 'center' };

  const btn = (label, onClick, disabled) => (
    <button onClick={onClick} disabled={disabled} style={{
      width: '100%', maxWidth: 340,
      padding: '16px 28px',
      background: 'transparent',
      border: `1px solid ${tweaks.gold}${disabled ? '33' : '88'}`,
      fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
      fontSize: 13.5, letterSpacing: '0.22em',
      color: disabled ? `${tweaks.ink}55` : tweaks.ink,
      cursor: disabled ? 'default' : 'pointer',
      transition: 'border-color 0.2s, background 0.2s',
      outline: 'none',
    }}
      onMouseEnter={e => { if (!disabled) e.currentTarget.style.background = `${tweaks.gold}12`; }}
      onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
    >{label}</button>
  );

  return (
    <div style={wrapStyle}>
    <div style={innerStyle}>

      {sent ? (
        <>
          <div style={{
            fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
            fontSize: 52, color: tweaks.gold, lineHeight: 1, marginBottom: 28,
            opacity: 0.85,
          }}>{attending ? '✦' : '◇'}</div>

          <div style={{
            fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
            fontSize: 52, color: tweaks.ink,
          }}>{ tr.thankYou }{guestName ? `, ${guestName}` : ''}!</div>

          <div style={{
            fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
            fontStyle: 'italic', fontSize: 16, lineHeight: 1.75,
            opacity: 0.72, marginTop: 24, maxWidth: 340, textWrap: 'pretty',
          }}>
            {attending
              ? tr.attendingMsg
              : tr.notAttendingMsg}
          </div>
        </>
      ) : (
        <>
          <div style={{
            fontFamily: "var(--script-font, 'Pinyon Script'), cursive",
            fontSize: 62, color: tweaks.ink,
          }}>RSVP</div>

          <div style={{
            fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
            fontSize: 14, letterSpacing: '0.22em', opacity: 0.7,
            marginTop: 14, fontVariantNumeric: 'lining-nums',
          }}>{ tr.rsvpSubtitle }</div>

          <div style={{ width: 50, height: 1, background: tweaks.gold, opacity: 0.4, margin: '36px 0' }} />

          {urlGuest ? (
            <div style={{
              fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
              fontStyle: 'italic', fontSize: 22, opacity: 0.7, marginBottom: 40,
            }}>{urlGuest}</div>
          ) : (
            <input
              value={nameInput}
              onChange={e => setNameInput(e.target.value)}
              placeholder={ tr.namePlaceholder }
              style={{
                width: '100%', maxWidth: 300,
                background: 'transparent',
                border: 'none', borderBottom: `1px solid ${tweaks.gold}77`,
                fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
                fontSize: 18, letterSpacing: '0.06em',
                textAlign: 'center', color: tweaks.ink,
                padding: '10px 4px', outline: 'none',
                marginBottom: 40,
              }}
            />
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, width: '100%', alignItems: 'center' }}>
            {btn(sending ? '…' : tr.attendingBtn, () => handleRSVP(true), !canSubmit || sending)}
            {btn(tr.notAttendingBtn, () => handleRSVP(false), !canSubmit || sending)}
          </div>

          <div style={{
            fontFamily: "var(--serif-font, 'Cormorant Garamond'), serif",
            fontStyle: 'italic', fontSize: 15, opacity: 0.55,
            marginTop: 36,
          }}>{ tr.lookingForward }</div>
        </>
      )}

    </div>
    </div>
  );
}

Object.assign(window, { CoverPage, MainPage, CountdownPage, LocationPage, RSVPPage });
