// ────────────────────────────────────────────────────────────────────────
//  invitation.jsx — Formal Invitation section. Shows the real wedding card
//  art with a Tamil / English toggle at the top (matching the RSVP page's
//  language switch). The English card has the Mr./Mrs./Miss line removed.
//
//  Also exports the shared window.useInView helper used by other sections.
// ────────────────────────────────────────────────────────────────────────
(function () {
  const { useState, useEffect, useRef } = React;

  const GOLD = '#a9802f';
  const GOLD_LT = '#c9a24b';
  const GOLD_HI = '#e3c172';
  const MAROON = '#6e1f22';
  const A = (q) => window.asset ? window.asset(q) : q;

  // Shared: reveal a node once it scrolls into view. Returns [ref, inView].
  function useInView(threshold = 0.28, once = true) {
    const ref = useRef(null);
    const [seen, setSeen] = useState(false);
    useEffect(() => {
      const el = ref.current;
      if (!el) return;
      const io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) {setSeen(true);if (once) io.disconnect();} else
            if (!once) setSeen(false);
          });
        },
        { threshold }
      );
      io.observe(el);
      return () => io.disconnect();
    }, [threshold, once]);
    return [ref, seen];
  }
  window.useInView = useInView;

  const CARDS = {
    ta: { src: 'assets/invite-tamil.png', ratio: 1575 / 2175,
      alt: 'திருமண அழைப்பிதழ் — Vyshnavan & Rathusaigini wedding invitation (Tamil)' },
    en: { src: 'assets/invite-english.png', ratio: 1595 / 2185,
      alt: 'Wedding Invitation — Vyshnavan & Rathusaigini (English)' } };


  // Hoisted to module scope so the button nodes stay stable across renders
  // (keeps focus after activation and lets the .inv-tab CSS transitions run).
  function Tab({ id, label, lang, setLang }) {
    const on = lang === id;
    return (
      <button type="button" onClick={() => setLang(id)} aria-pressed={on}
        className={'inv-tab' + (on ? ' is-on' : '')}>
        <span className="inv-tab__label">{label}</span>
      </button>);

  }

  function InvitationSection() {
    const [ref, inView] = useInView(0.16);
    const [lang, setLang] = useState('ta');
    const OD = window.OrnamentalDivider;
    const card = CARDS[lang];
    const cardRef = useRef(null);
    // scroll-linked: the card drifts up as you travel through the section
    const p = window.useScrollProgress ? window.useScrollProgress(cardRef) : 0;

    // staggered fade-up so the section flows in as you scroll
    const rise = (d, dist = 18) => ({
      opacity: inView ? 1 : 0,
      transform: inView ? 'translateY(0)' : `translateY(${dist}px)`,
      transition: `opacity .9s cubic-bezier(.22,.61,.36,1) ${d}s, transform .9s cubic-bezier(.22,.61,.36,1) ${d}s`
    });

    // keep both files warm so switching never flashes an empty frame
    useEffect(() => {
      Object.values(CARDS).forEach((c) => {const i = new Image();i.src = A(c.src);});
    }, []);


    return (
      <section id="invitation" data-screen-label="Invitation" style={{
        position: 'relative', minHeight: '100vh',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: 'clamp(46px,9vh,104px) 4vw clamp(52px,10vh,110px)',
        background: 'transparent', overflow: 'hidden'
      }}>
        <div aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'radial-gradient(120% 92% at 50% 46%, transparent 72%, rgba(110,62,24,0.07) 100%)' }} />

        <div ref={ref} style={{ position: 'relative', zIndex: 2, width: 'min(92vw, 560px)',
          display: 'flex', flexDirection: 'column', alignItems: 'center' }}>

          {/* language toggle */}
          <div className="inv-toggle" role="group" aria-label="Invitation language"
            style={{ ...rise(0.02, 16) }}>
            <Tab id="ta" label="தமிழ்" lang={lang} setLang={setLang} />
            <Tab id="en" label="English" lang={lang} setLang={setLang} />
          </div>

          {/* the card */}
          <div ref={cardRef} style={{ position: 'relative', width: '100%',
            marginTop: 'clamp(18px,3.8vw,26px)',
            aspectRatio: String(card.ratio),
            borderRadius: 3,
            boxShadow: '0 30px 70px -28px rgba(70,34,10,0.5), 0 0 0 1px rgba(169,128,47,0.45), 0 0 0 7px rgba(255,252,244,0.6), 0 0 0 8px rgba(169,128,47,0.28)',
            background: '#f6ead0', overflow: 'hidden',
            opacity: inView ? 1 : 0,
            transform: inView ?
            `translate3d(0,${(-p * 26).toFixed(2)}px,0) scale(1)` :
            'translate3d(0,34px,0) scale(0.985)',
            transition: inView ?
            'opacity 1.05s cubic-bezier(.22,.61,.36,1) .14s, transform .35s linear' :
            'opacity 1.05s cubic-bezier(.22,.61,.36,1) .14s, transform 1.15s cubic-bezier(.22,.61,.36,1) .14s' }}>
            {Object.keys(CARDS).map((k) =>
            <img key={k} src={A(CARDS[k].src)} alt={CARDS[k].alt} draggable="false"
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
                objectFit: 'contain', display: 'block',
                opacity: lang === k ? 1 : 0, transition: 'opacity .5s ease',
                pointerEvents: lang === k ? 'auto' : 'none' }} />
            )}
          </div>

          {/* open full size */}
          <a href={A(card.src)} target="_blank" rel="noopener noreferrer" className="inv-full"
            style={{ ...rise(0.34, 12) }}>
            View full size
          </a>
        </div>

        <style>{`
          .inv-toggle { display:flex; gap:6px; padding:5px; border:1px solid rgba(169,128,47,0.5);
            border-radius:999px; background:rgba(255,252,244,0.72);
            box-shadow:0 6px 18px -12px rgba(70,34,10,0.5), inset 0 1px 0 rgba(255,255,255,0.7); }
          .inv-tab { appearance:none; cursor:pointer; border:1px solid transparent; border-radius:999px;
            background:transparent; padding:8px 24px; min-height:44px; display:flex;
            align-items:center; justify-content:center; color:#8a6526;
            transition:background .28s ease, color .28s ease, border-color .28s ease, box-shadow .28s ease; }
          .inv-tab__label { font-family:Marcellus, serif; font-size:clamp(13px,3.4vw,15px); letter-spacing:0.04em; line-height:1.15; }
          .inv-tab:hover { color:#6e1f22; background:rgba(201,162,75,0.12); }
          .inv-tab.is-on { color:#fdf3df; border-color:${GOLD_HI};
            background:linear-gradient(168deg, #8d5a1e 0%, #6e1f22 100%);
            box-shadow:0 8px 18px -10px rgba(70,20,14,0.6), inset 0 1px 0 rgba(255,224,160,0.28); }
          .inv-tab:focus-visible { outline:2px solid ${GOLD_LT}; outline-offset:2px; }
          .inv-full { margin-top:clamp(14px,3vw,20px); font-family:Jost, sans-serif;
            font-size:clamp(10px,2.6vw,11.5px); letter-spacing:0.22em; text-transform:uppercase;
            color:#9a6f33; text-decoration:none; border-bottom:1px solid rgba(169,128,47,0.45);
            padding-bottom:3px; transition:color .25s ease, border-color .25s ease; }
          .inv-full:hover { color:#6e1f22; border-color:#6e1f22; }
          @media (prefers-reduced-motion: reduce) { .inv-tab, .inv-full { transition:none; } }
        `}</style>
      </section>);

  }

  window.InvitationSection = InvitationSection;
  window.InvitationPlaceholder = InvitationSection; // keep old mount name working
})();
