// ────────────────────────────────────────────────────────────────────────
//  closing.jsx — final closing section. A full-bleed sunset-waves VIDEO fills
//  the whole section; the "Thank You" message is layered over it in luminous
//  ivory/gold, with a soft warm scrim for legibility.
//
//  Assets:
//   • assets/closing-waves.mp4 — sunset waves clip (full-section background)
//   • assets/emblem2.png       — actual transparent VR logo (unmodified)
//
//  • video shown uncropped on wide screens (contain) / full-bleed COVER on
//    portrait mobile so it fills the phone; warm dark fills any letterbox.
//  • blob-loaded so it plays even where the host lacks HTTP range support.
//  • staggered fade-up reveal; honors prefers-reduced-motion (clip pauses).
//
//  NOT an RSVP confirmation — no response language, no RSVP button.
// ────────────────────────────────────────────────────────────────────────
(function () {
  const { useState, useEffect, useRef } = React;

  const GOLD_LT = '#e3c172';
  const GOLD_HI = '#f3da97';
  const IVORY = '#fdf3df';
  const CREAM = '#f1e4c4';
  const A = (q) => window.asset ? window.asset(q) : q;

  const TS = '0 1px 3px rgba(24,10,2,0.6), 0 2px 18px rgba(24,10,2,0.45)';

  function useReducedMotion() {
    const [r, setR] = useState(false);
    useEffect(() => {
      const m = window.matchMedia('(prefers-reduced-motion: reduce)');
      const on = () => setR(!!m.matches);
      on();
      m.addEventListener ? m.addEventListener('change', on) : m.addListener(on);
      return () => {m.removeEventListener ? m.removeEventListener('change', on) : m.removeListener(on);};
    }, []);
    return r;
  }

  // ── ornamental dividers (light gold, for legibility over video) ─────────
  function HLine({ w = 60, side = 'l' }) {
    const grad = side === 'l' ?
    'linear-gradient(90deg, rgba(243,218,151,0) 0%, rgba(243,218,151,0.95) 100%)' :
    'linear-gradient(90deg, rgba(243,218,151,0.95) 0%, rgba(243,218,151,0) 100%)';
    return <span style={{ display: 'inline-block', width: w, height: 1, background: grad,
      boxShadow: '0 1px 2px rgba(20,8,2,0.4)' }} />;
  }
  function Divider({ motif }) {
    return (
      <div aria-hidden="true" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
        filter: 'drop-shadow(0 1px 2px rgba(20,8,2,0.45))' }}>
        <HLine w={'clamp(40px,12vw,72px)'} side="l" />
        {motif}
        <HLine w={'clamp(40px,12vw,72px)'} side="r" />
      </div>);

  }
  const HeartMotif = (
    <svg width="16" height="14" viewBox="0 0 16 14" fill="none" aria-hidden="true">
      <path d="M8 13 C 2 8.4 2.2 3 6 3 C 7.4 3 8 4.2 8 4.8 C 8 4.2 8.6 3 10 3 C 13.8 3 14 8.4 8 13 Z"
        fill="none" stroke={GOLD_HI} strokeWidth="1.3" />
    </svg>);

  const DiamondMotif = (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
      <span style={{ width: 4, height: 4, background: GOLD_HI, transform: 'rotate(45deg)', opacity: 0.7 }} />
      <span style={{ width: 7, height: 7, background: GOLD_HI, transform: 'rotate(45deg)' }} />
      <span style={{ width: 4, height: 4, background: GOLD_HI, transform: 'rotate(45deg)', opacity: 0.7 }} />
    </span>);

  const LotusMotif = (
    <svg width="34" height="16" viewBox="0 0 34 16" fill="none" aria-hidden="true">
      <g fill={GOLD_HI}>
        <path d="M17 15 C 17 8 17 4 17 2 C 19 5 20 9 19.6 14 Z" />
        <path d="M17 15 C 17 8 17 4 17 2 C 15 5 14 9 14.4 14 Z" />
        <path d="M17 15 C 19 9 22 6 26 5 C 25 10 22 13 19 15 Z" opacity="0.92" />
        <path d="M17 15 C 15 9 12 6 8 5 C 9 10 12 13 15 15 Z" opacity="0.92" />
        <path d="M17 15 C 21 11 27 9 32 10 C 29 14 24 15 19 15 Z" opacity="0.8" />
        <path d="M17 15 C 13 11 7 9 2 10 C 5 14 10 15 15 15 Z" opacity="0.8" />
      </g>
    </svg>);


  // ── a few slow drifting petals over the scene ──────────────────────────
  function Petals({ reduced }) {
    if (reduced) return null;
    const defs = [
    { l: '9%', dx: 24, dur: 17, delay: 0, s: 13, c: ['#d98a8f', '#f6dcd6'] },
    { l: '30%', dx: -18, dur: 20, delay: -7, s: 11, c: ['#c98fb0', '#f0d6e6'] },
    { l: '58%', dx: 26, dur: 18, delay: -12, s: 14, c: ['#d98a8f', '#f3cfcf'] },
    { l: '80%', dx: -20, dur: 19, delay: -4, s: 12, c: ['#cf8f6a', '#f2cda0'] }];

    return (
      <div aria-hidden="true" style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none', zIndex: 8 }}>
        {defs.map((p, i) =>
        <svg key={i} width={p.s} height={p.s * 1.3} viewBox="0 0 20 26"
          style={{ position: 'absolute', left: p.l, top: 0, '--dx': `${p.dx}px`, '--rot': `${180 + i * 40}deg`,
            animation: `clzPetal ${p.dur}s linear ${p.delay}s infinite`,
            filter: 'drop-shadow(0 1px 3px rgba(40,16,8,0.3))' }}>
            <defs><radialGradient id={`clzp${i}`} cx="0.5" cy="0.35" r="0.75">
              <stop offset="0" stopColor={p.c[1]} /><stop offset="1" stopColor={p.c[0]} />
            </radialGradient></defs>
            <path d="M10 0 C 18 8 18 18 10 26 C 2 18 2 8 10 0 Z" fill={`url(#clzp${i})`} fillOpacity="0.88" />
          </svg>
        )}
      </div>);

  }

  // ── full-bleed sunset video background ─────────────────────────────────
  function VideoBackdrop({ reduced }) {
    const vidRef = useRef(null);
    const [vsrc, setVsrc] = useState(null);

    // Load the clip as a Blob → object URL. Static hosts often serve video
    // without HTTP range support, which makes <video> fail with "source not
    // supported"; a blob URL is a complete, seekable local copy that plays
    // everywhere. Falls back to the direct path if the fetch fails.
    useEffect(() => {
      let alive = true, url = null;
      fetch(A('assets/closing-waves.mp4')).
      then((r) => r.ok ? r.blob() : Promise.reject(r.status)).
      then((b) => {if (!alive) return;url = URL.createObjectURL(b);setVsrc(url);}).
      catch(() => {if (alive) setVsrc(A('assets/closing-waves.mp4'));});
      return () => {alive = false;if (url) URL.revokeObjectURL(url);};
    }, []);

    useEffect(() => {
      const v = vidRef.current;
      if (!v || !vsrc) return;
      if (reduced) {try {v.pause();} catch (e) {}} else
      {const p = v.play();if (p && p.catch) p.catch(() => {});}
    }, [reduced, vsrc]);

    return (
      <div aria-hidden="true" style={{ position: 'absolute', inset: 0, overflow: 'hidden', zIndex: 0 }}>
        {/* Portrait viewport (mobile): COVER fills the screen edge-to-edge.
            Wide / landscape: CONTAIN so the whole vertical frame shows, with
            warm dark filling the sides — never a hard-cropped strip. */}
        <video ref={vidRef} className="clz-video"
          src={vsrc || undefined}
          autoPlay muted loop playsInline preload="auto"
          onLoadedData={(e) => {const p = e.target.play();if (p && p.catch) p.catch(() => {});}}
          style={{ position: 'absolute', inset: 0, display: 'block', width: '100%', height: '100%',
            objectFit: 'cover', objectPosition: 'center',
            // brightened to taste — lighter sunset feel
            filter: 'brightness(1.14) saturate(1.05)' }} />

        {/* warm scrim — lighter than before so the scene stays luminous;
            still enough contrast at top & bottom to keep text legible */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'linear-gradient(180deg, rgba(46,20,8,0.38) 0%, rgba(46,20,8,0.12) 26%, rgba(46,20,8,0.08) 52%, rgba(40,17,6,0.20) 78%, rgba(34,14,5,0.42) 100%)' }} />
        {/* soft focal halo behind the central message (lighter touch) */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'radial-gradient(120% 70% at 50% 44%, rgba(30,12,4,0.18) 0%, rgba(30,12,4,0) 60%)' }} />
        {/* gentle sunset glow pulse near the horizon */}
        <div style={{ position: 'absolute', left: '50%', top: '52%', width: '70%', height: '38%',
          transform: 'translate(-50%,-50%)', borderRadius: '50%', pointerEvents: 'none',
          background: 'radial-gradient(circle, rgba(255,228,168,0.30) 0%, rgba(255,222,150,0.10) 46%, rgba(255,222,150,0) 72%)',
          mixBlendMode: 'screen', animation: reduced ? 'none' : 'clzGlow 7s ease-in-out infinite' }} />
      </div>);

  }

  // ── section ────────────────────────────────────────────────────────────
  function ClosingSection() {
    const reduced = useReducedMotion();
    const [ref, inView] = window.useInView(0.2);
    const show = inView || reduced;

    const rise = (d, dist = 20) => ({
      opacity: show ? 1 : 0,
      transform: show ? 'none' : `translateY(${reduced ? 0 : dist}px)`,
      transition: reduced ? 'none' : `opacity .9s ease ${d}s, transform .9s cubic-bezier(.22,.61,.36,1) ${d}s`
    });

    return (
      <section id="closing" data-screen-label="Closing" ref={ref} style={{
        position: 'relative', minHeight: '100vh',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 'clamp(48px,10vh,110px) 7vw',
        background: '#2a1206', overflow: 'hidden'
      }}>
        {/* full-section video */}
        <VideoBackdrop reduced={reduced} />

        {/* soft ivory→scene blend so the flow dissolves in instead of cutting */}
        <div aria-hidden="true" style={{ position: 'absolute', left: 0, right: 0, top: 0,
          height: 'clamp(90px,18vh,190px)', zIndex: 6, pointerEvents: 'none',
          background: 'linear-gradient(180deg, #e4d4b1 0%, rgba(228,212,177,0.62) 34%, rgba(228,212,177,0.22) 66%, rgba(228,212,177,0) 100%)' }} />

        {/* drifting petals */}
        <Petals reduced={reduced} />

        {/* thin gold frame around the scene */}
        <div aria-hidden="true" style={{ position: 'absolute', inset: 'clamp(10px,2.6vw,18px)', zIndex: 7,
          border: '1px solid rgba(227,193,114,0.6)', borderRadius: 8, pointerEvents: 'none',
          boxShadow: 'inset 0 0 0 1px rgba(255,247,224,0.12), inset 0 0 60px rgba(20,8,2,0.3)' }} />

        {/* content over the video */}
        <div style={{ position: 'relative', zIndex: 7, display: 'flex', flexDirection: 'column',
          alignItems: 'center', textAlign: 'center', width: 'min(92vw, 460px)' }}>

          {/* emblem (actual transparent VR logo, unmodified) */}
          <img src={A('assets/emblem2.png')} alt="Vyshnavan &amp; Rathusaigini" draggable="false"
            style={{ ...rise(0.05, 14), width: 'clamp(86px,23vw,124px)', height: 'auto', display: 'block',
              marginBottom: 'clamp(8px,2vw,12px)', filter: 'drop-shadow(0 4px 16px rgba(0,0,0,0.5))' }} />

          {/* names */}
          <div style={{ ...rise(0.12), fontFamily: 'Marcellus, serif', color: GOLD_HI,
            fontSize: 'clamp(11px,3vw,15.5px)', letterSpacing: '0.16em', whiteSpace: 'nowrap', textShadow: TS }}>
            VYSHNAVAN <span style={{ color: GOLD_LT }}>&amp;</span> RATHUSAIGINI
          </div>

          <div style={{ ...rise(0.16), margin: 'clamp(10px,2.4vw,15px) 0 0' }}>
            <Divider motif={DiamondMotif} />
          </div>

          {/* Thank You */}
          <h2 style={{ ...rise(0.24), margin: 'clamp(10px,2.6vw,18px) 0 0', whiteSpace: 'nowrap',
            fontFamily: '"Cormorant Garamond", serif', fontStyle: 'italic', fontWeight: 600,
            color: IVORY, fontSize: 'clamp(42px,12vw,68px)', lineHeight: 1.0, letterSpacing: '0.01em',
            textShadow: '0 2px 22px rgba(0,0,0,0.5), 0 0 36px rgba(255,224,150,0.22)' }}>
            Thank You
          </h2>

          <div style={{ ...rise(0.32), margin: 'clamp(14px,3.2vw,22px) 0' }}>
            <Divider motif={HeartMotif} />
          </div>

          {/* message 1 */}
          <p style={{ ...rise(0.4), margin: 0, fontFamily: '"Cormorant Garamond", serif',
            color: IVORY, fontSize: 'clamp(15px,4vw,20px)', lineHeight: 1.55, maxWidth: '100%', textShadow: TS }}>
            Thank you for being a part of our journey.<br />
            Your love, blessings and presence<br />
            mean the world to us.
          </p>

          <div style={{ ...rise(0.46), margin: 'clamp(18px,4vw,28px) 0' }}>
            <Divider motif={DiamondMotif} />
          </div>

          {/* message 2 */}
          <p style={{ ...rise(0.52), margin: 0, fontFamily: '"Cormorant Garamond", serif',
            color: CREAM, fontSize: 'clamp(15px,4vw,20px)', lineHeight: 1.55, maxWidth: '100%', textShadow: TS }}>
            We can’t wait to celebrate<br />
            this beautiful new chapter with you.
          </p>

          <div style={{ ...rise(0.58), margin: 'clamp(20px,4.4vw,30px) 0 clamp(12px,2.6vw,16px)' }}>
            <Divider motif={LotusMotif} />
          </div>

          {/* sign-off */}
          <p style={{ ...rise(0.64), margin: 0, fontFamily: '"Cormorant Garamond", serif', fontStyle: 'italic',
            color: CREAM, fontSize: 'clamp(15px,3.8vw,19px)', whiteSpace: 'nowrap', textShadow: TS }}>
            With love,
          </p>
          <div style={{ ...rise(0.7), marginTop: 'clamp(4px,1.4vw,9px)', display: 'inline-flex', alignItems: 'center',
            justifyContent: 'center', gap: 'clamp(7px,2vw,12px)', flexWrap: 'nowrap', maxWidth: '100%' }}>
            <span style={{ fontFamily: '"Great Vibes", cursive', color: IVORY, fontSize: 'clamp(24px,6.6vw,36px)',
              lineHeight: 1.15, whiteSpace: 'nowrap', textShadow: '0 2px 14px rgba(0,0,0,0.5)' }}>Vyshnavan</span>
            <svg width="22" height="20" viewBox="0 0 26 23" fill="none" aria-hidden="true"
              style={{ flex: 'none', filter: 'drop-shadow(0 1px 4px rgba(0,0,0,0.5))' }}>
              <path d="M13 21 C 3 13.5 3.4 4 10 4 C 12.4 4 13 6.4 13 7.6 C 13 6.4 13.6 4 16 4 C 22.6 4 23 13.5 13 21 Z"
                fill="none" stroke={GOLD_HI} strokeWidth="1.7" />
            </svg>
            <span style={{ fontFamily: '"Great Vibes", cursive', color: IVORY, fontSize: 'clamp(24px,6.6vw,36px)',
              lineHeight: 1.15, whiteSpace: 'nowrap', textShadow: '0 2px 14px rgba(0,0,0,0.5)' }}>Rathusaigini</span>
          </div>
        </div>

        {/* component-scoped keyframes */}
        <style>{`
          @keyframes clzGlow { 0%,100% { opacity: .5; } 50% { opacity: .9; } }
          /* wide / landscape viewports: show whole portrait frame, no strip-crop */
          @media (min-aspect-ratio: 1/1) {
            #closing .clz-video { object-fit: contain !important; }
          }
          @keyframes clzPetal {
            0%   { transform: translate3d(0,-12%,0) rotate(0deg); opacity: 0; }
            12%  { opacity: .85; }
            88%  { opacity: .85; }
            100% { transform: translate3d(var(--dx,20px), 96vh, 0) rotate(var(--rot,200deg)); opacity: 0; }
          }
          @media (prefers-reduced-motion: reduce) {
            #closing [style*="animation"] { animation: none !important; }
          }
        `}</style>
      </section>);

  }

  window.ClosingSection = ClosingSection;
})();
