// ────────────────────────────────────────────────────────────────────────
//  hero.jsx — OpeningHero: one continuous scroll-driven sequence that
//  TRANSFORMS the opening into the Save-the-Date section (no page break).
//
//  Phase A  (opening, master p 0 → OPEN_END):
//    closed temple door → doors swing open revealing the Koneswaram/mandir
//    scene → Ganesha line-art blessing → golden bloom → VR emblem → names
//    reveal → welcome line → scroll cue.
//
//  Phase B  (save the date, master p OPEN_END → 1, sub-progress `sp`):
//    sp .00–.25  hold (logo + names centred, welcome visible)
//    sp .25–.45  logo + names shrink & rise into a top header
//    sp .40–.60  welcome line fades out
//    sp .10–.40  door cross-fades to a full-bleed Koneswaram backdrop
//                (same scene) with a warm-gold readability wash + vignette
//    sp .50–.80  Save the Date content fades / slides into centre
//    sp .66–.92  closing celebration line
// ────────────────────────────────────────────────────────────────────────
const { useState, useEffect, useRef } = React;

const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = (t) => t * t * (3 - 2 * t);
const seg = (p, a, b) => smooth(clamp((p - a) / (b - a), 0, 1));

const OPEN_END = 0.58; // master fraction at which the opening completes

// Scroll cue — `dark` for the door, light for the bright stage.
function ScrollCue({ label, dark, style }) {
  const c = dark ? '#fbe8c4' : '#9a6f33';
  const dot = dark ? '#ffe9b8' : '#b58a32';
  const sh = dark ? '0 1px 7px rgba(50,20,6,0.85)' : 'none';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9, ...style }}>
      <span style={{ fontFamily: 'Jost, sans-serif', fontSize: 11, letterSpacing: '0.36em',
                     textTransform: 'uppercase', color: c, textShadow: sh }}>{label}</span>
      <div style={{ position: 'relative', width: 1, height: 40,
                    background: dark ? 'rgba(251,232,196,0.55)' : 'rgba(154,111,51,0.4)' }}>
        <span style={{ position: 'absolute', left: '50%', top: 0, width: 5, height: 5, marginLeft: -2.5,
                       borderRadius: '50%', background: dot, boxShadow: `0 0 8px ${dot}`,
                       animation: 'scrolldot 2.2s ease-in-out infinite' }} />
      </div>
      <svg width="15" height="9" viewBox="0 0 16 10" style={{ opacity: 0.9 }}>
        <path d="M1 1 L8 8 L15 1" fill="none" stroke={dot} strokeWidth="1.6" strokeLinecap="round" />
      </svg>
    </div>
  );
}

// faint gold corner flourish — echoes the temple-frame border of the reference
function CornerFlourish({ pos, opacity }) {
  const flip = { tl: 'none', tr: 'scaleX(-1)', bl: 'scaleY(-1)', br: 'scale(-1,-1)' }[pos];
  const place = {
    tl: { top: 0, left: 0 }, tr: { top: 0, right: 0 },
    bl: { bottom: 0, left: 0 }, br: { bottom: 0, right: 0 },
  }[pos];
  return (
    <svg width="86" height="86" viewBox="0 0 86 86" style={{ position: 'absolute', ...place,
      transform: flip, opacity, transition: 'opacity .2s linear' }}>
      <g fill="none" stroke="#b58a32" strokeWidth="1.2" strokeLinecap="round">
        <path d="M10 10 L10 44 M10 10 L44 10" strokeOpacity="0.8" />
        <path d="M16 16 C 16 34 34 16 52 16" strokeOpacity="0.6" />
        <path d="M16 16 C 34 16 16 34 16 52" strokeOpacity="0.6" />
        <circle cx="10" cy="10" r="2.2" fill="#b58a32" stroke="none" />
      </g>
    </svg>
  );
}

function OpeningHero() {
  const wrapRef = useRef(null);
  const [p, setP] = useState(0);

  useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const el = wrapRef.current;
        if (!el) return;
        const total = el.offsetHeight - window.innerHeight;
        setP(clamp(-el.getBoundingClientRect().top / total, 0, 1));
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); };
  }, []);

  // sub-progress timelines
  const op = clamp(p / OPEN_END, 0, 1);          // opening 0→1
  const sp = seg(p, OPEN_END, 1);                // save-the-date 0→1

  // ── Phase A (opening) ──
  const enterHint  = 1 - seg(op, 0.0, 0.06);
  const doorAngle  = lerp(0, 110, seg(op, 0.05, 0.44));
  const doorPush   = lerp(0, 4, seg(op, 0.10, 0.46));
  const doorReveal = seg(op, 0.06, 0.20);
  const doorZoom   = lerp(1, 1.4, seg(op, 0.05, 0.86));

  const ganIn   = seg(op, 0.40, 0.50);
  const ganOut  = seg(op, 0.58, 0.68);
  const ganesha = ganIn * (1 - ganOut);

  const bloom       = seg(op, 0.60, 0.80) * (1 - seg(sp, 0.12, 0.38));
  const logoOpacity = seg(op, 0.66, 0.80);
  const logoScale   = lerp(0.9, 1, seg(op, 0.66, 0.90));
  const namesP      = seg(op, 0.80, 0.96);
  const invite      = seg(op, 0.88, 0.97);
  const beginCue    = seg(op, 0.92, 1.0);

  // ── Phase B (save the date) ──
  const headerMove  = seg(sp, 0.25, 0.45);            // logo+names rise & shrink
  const welcomeFade = seg(sp, 0.40, 0.60);            // welcome fades out
  const doorFade    = seg(sp, 0.10, 0.42);            // door → full-bleed scene
  const stdBgIn     = seg(sp, 0.08, 0.40);            // backdrop wash in
  const stdIn       = seg(sp, 0.50, 0.80);            // STD content in
  const celebrate   = seg(sp, 0.66, 0.92);
  const endCue      = seg(sp, 0.88, 1.0);

  const namesHeader = Math.max(namesP, headerMove > 0 ? 1 : 0);
  const petals = seg(op, 0.16, 0.40) * (1 - seg(sp, 0.86, 1.0));

  const DoorScene = window.DoorScene, WeddingEmblem = window.WeddingEmblem;
  const NamesReveal = window.NamesReveal, GaneshaBlessing = window.GaneshaBlessing;
  const PetalParticles = window.PetalParticles, OrnamentalDivider = window.OrnamentalDivider;
  const SaveTheDate = window.SaveTheDate;
  const A = (q) => (window.asset ? window.asset(q) : q);

  return (
    <section ref={wrapRef} style={{ position: 'relative', height: '900vh' }}>
      <div style={{ position: 'sticky', top: 0, height: '100vh', overflow: 'hidden',
                    background: 'radial-gradient(120% 100% at 50% 40%, #f6eede 0%, #efe2c9 60%, #e7d8ba 100%)' }}>

        {/* The temple-door portal + revealed Koneswaram scene */}
        <div style={{ position: 'absolute', inset: 0, opacity: 1 - doorFade }}>
          <DoorScene angle={doorAngle} push={doorPush} reveal={doorReveal} zoom={doorZoom} opacity={1} />
        </div>

        {/* Full-bleed Koneswaram backdrop for the Save-the-Date (same scene) */}
        <div style={{ position: 'absolute', inset: 0, zIndex: 15, opacity: stdBgIn, pointerEvents: 'none' }}>
          <img src={A('assets/reveal.jpg')} alt="" draggable="false" style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
            transform: `scale(${lerp(1.18, 1.06, stdBgIn)})`, filter: 'saturate(1.06) brightness(1.02) blur(2px)' }} />
          {/* warm-gold readability wash */}
          <div style={{ position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, rgba(58,18,16,0.30) 0%, rgba(120,70,26,0.10) 26%, rgba(120,70,26,0.06) 60%, rgba(58,18,16,0.34) 100%)' }} />
          {/* ivory centre glow so gold/maroon text reads */}
          <div style={{ position: 'absolute', inset: 0,
            background: 'radial-gradient(ellipse 78% 64% at 50% 54%, rgba(252,244,224,0.80) 0%, rgba(250,236,206,0.42) 40%, rgba(250,236,206,0) 72%)' }} />
          {/* vignette */}
          <div style={{ position: 'absolute', inset: 0,
            background: 'radial-gradient(130% 100% at 50% 46%, transparent 58%, rgba(70,32,12,0.30) 100%)' }} />
          {/* faint temple-gold corner frame */}
          <CornerFlourish pos="tl" opacity={0.5 * stdBgIn} />
          <CornerFlourish pos="tr" opacity={0.5 * stdBgIn} />
          <CornerFlourish pos="bl" opacity={0.5 * stdBgIn} />
          <CornerFlourish pos="br" opacity={0.5 * stdBgIn} />
        </div>

        {/* Ganesha blessing — appears in the revealed doorway, then fades */}
        <div style={{ position: 'absolute', left: '50%', top: '43%', zIndex: 20,
                      transform: `translate(-50%,-50%) scale(${lerp(0.9, 1, ganIn)})`,
                      width: 'min(54vw, 250px)', opacity: ganesha, pointerEvents: 'none' }}>
          <div style={{ position: 'absolute', left: '50%', top: '48%', width: '180%', height: '170%',
                        transform: 'translate(-50%,-50%)', borderRadius: '50%', pointerEvents: 'none',
                        background: 'radial-gradient(circle, rgba(255,244,214,0.85) 0%, rgba(255,236,196,0.4) 38%, rgba(255,236,196,0) 70%)' }} />
          <GaneshaBlessing style={{ position: 'relative' }} />
        </div>

        {/* Soft golden bloom — luminous stage for the emblem & names (opening) */}
        <div style={{ position: 'absolute', inset: 0, zIndex: 25, opacity: bloom, pointerEvents: 'none',
          background: 'radial-gradient(ellipse 72% 60% at 50% 50%, rgba(250,240,216,0.74) 0%, rgba(249,234,202,0.5) 42%, rgba(250,236,206,0) 74%)' }} />

        {/* Save the Date — centre content (sits below the header) */}
        <div style={{ position: 'absolute', inset: 0, zIndex: 32, display: 'flex',
                      alignItems: 'center', justifyContent: 'center', padding: '23vh 5vw 6vh',
                      pointerEvents: 'none' }}>
          <SaveTheDate reveal={stdIn} celebrate={celebrate} />
        </div>

        {/* Logo + names — centre during opening, rise into a header in Phase B */}
        <div style={{ position: 'absolute', left: '50%', top: `${lerp(43, 11, headerMove)}%`,
                      transform: 'translate(-50%,-50%)', zIndex: 36, width: '100%',
                      display: 'flex', flexDirection: 'column', alignItems: 'center',
                      gap: `${lerp(2.6, 0.8, headerMove)}vh`, pointerEvents: 'none' }}>
          <div style={{ width: `min(${lerp(62, 26, headerMove)}vw, ${lerp(300, 100, headerMove)}px, ${lerp(38, 17, headerMove)}vh)`,
                        opacity: logoOpacity, transform: `scale(${logoScale})`, transformOrigin: 'center' }}>
            <WeddingEmblem glow={logoOpacity} />
          </div>
          <div style={{ opacity: namesHeader > 0.02 ? 1 : 0,
                        transform: `scale(${lerp(1, 0.6, headerMove)})`, transformOrigin: 'center' }}>
            <NamesReveal progress={namesHeader} />
          </div>
        </div>

        {/* Welcome line + divider — well below the names, fades out in Phase B */}
        <div style={{ position: 'absolute', left: '50%', top: '75%', transform: 'translate(-50%,-50%)',
                      zIndex: 34, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
                      opacity: invite * (1 - welcomeFade), pointerEvents: 'none' }}>
          <OrnamentalDivider width={210} reveal={invite} />
          <p style={{ fontFamily: 'Marcellus, serif', color: '#6e4a22', margin: 0,
                      fontSize: 'clamp(12.5px,3.2vw,17px)', letterSpacing: '0.12em', textAlign: 'center' }}>
            We invite you to celebrate our wedding
          </p>
        </div>

        {/* Petals & gold dust */}
        <PetalParticles intensity={petals} />

        {/* warm vignette over the door phase */}
        <div style={{ position: 'absolute', inset: 0, zIndex: 50, pointerEvents: 'none', opacity: 1 - doorFade,
          background: 'radial-gradient(135% 100% at 50% 46%, transparent 62%, rgba(110,62,24,0.18) 100%)' }} />

        {/* scroll cues */}
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 'max(28px, env(safe-area-inset-bottom))',
                      zIndex: 60, display: 'flex', justifyContent: 'center', opacity: enterHint,
                      pointerEvents: 'none', transition: 'opacity .3s' }}>
          <ScrollCue label="Scroll to enter" dark />
        </div>
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 'max(28px, env(safe-area-inset-bottom))',
                      zIndex: 60, display: 'flex', justifyContent: 'center',
                      opacity: beginCue * (1 - seg(sp, 0.0, 0.12)), pointerEvents: 'none' }}>
          <ScrollCue label="Scroll to continue" />
        </div>
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 'max(26px, env(safe-area-inset-bottom))',
                      zIndex: 60, display: 'flex', justifyContent: 'center', opacity: endCue, pointerEvents: 'none' }}>
          <ScrollCue label="Scroll" />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { OpeningHero, ScrollCue });
