// ==================== MAGIC REVEAL ====================
// Plays when the user clicks "Open the Invitation" on the Cover screen.
// A four-beat sequence:
//   1. Marsala dim — the cover dims behind a warm portal field
//   2. Mandala portal — a gold mandala spirals open from the center
//   3. Marigold petals scatter outward + a soft ivory flash
//   4. Marsala curtains part vertically to reveal the invitation below
//
// Mid-animation we ask the parent to scroll to the invitation section so
// when the curtains part, the right content is already in view.

function MagicReveal({ active, onMidpoint, onDone }) {
  const { motion, AnimatePresence } = window.Motion;

  // 18 petals on a ring around center, scattered outward at varied delays.
  const petals = React.useMemo(
    () =>
      Array.from({ length: 18 }, (_, i) => {
        const angle = (i * Math.PI * 2) / 18;
        return {
          id: i,
          x: Math.cos(angle),
          y: Math.sin(angle),
          rot: Math.random() * 360,
          delay: 0.35 + Math.random() * 0.35,
          dist: 360 + Math.random() * 220,
          hue: i % 3, // 0 marigold, 1 saffron, 2 ivory
        };
      }),
    []
  );

  const petalColors = [
    'radial-gradient(circle at 30% 30%, #F7BE63 0%, #E89A2B 55%, #C68321 100%)',
    'radial-gradient(circle at 30% 30%, #F69A63 0%, #E85D1F 55%, #C44815 100%)',
    'radial-gradient(circle at 30% 30%, #FFFDF7 0%, #FAF2DF 60%, #EED9A9 100%)',
  ];

  return (
    <AnimatePresence>
      {active && (
        <motion.div
          key="reveal"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.35, ease: 'easeOut' }}
          style={{
            position: 'fixed', inset: 0, zIndex: 9999,
            pointerEvents: 'none',
            overflow: 'hidden',
            background:
              'radial-gradient(ellipse at center, rgba(74,17,25,.55) 0%, rgba(26,8,11,.92) 70%, rgba(15,5,8,.98) 100%)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
        >
          {/* Outer mandala — slow counter-rotation, larger, fainter */}
          <motion.div
            initial={{ scale: 0.2, rotate: 90, opacity: 0 }}
            animate={{ scale: [0.2, 1.35, 2.4], rotate: [90, 0, -60], opacity: [0, 0.55, 0] }}
            transition={{ duration: 1.9, ease: [0.2, 0.8, 0.2, 1], times: [0, 0.55, 1] }}
            style={{
              position: 'absolute', width: '90vmin', height: '90vmin',
              backgroundImage: 'url(assets/ornaments/mandala.svg)',
              backgroundSize: 'contain', backgroundRepeat: 'no-repeat',
              filter:
                'invert(.85) sepia(1) saturate(3) brightness(1.05) drop-shadow(0 0 40px rgba(229,193,104,.5))',
            }}
          />

          {/* Inner mandala — faster spin, sharper, smaller; emits the midpoint signal */}
          <motion.div
            initial={{ scale: 0, rotate: -200, opacity: 0 }}
            animate={{ scale: [0, 1, 1.6], rotate: [-200, 0, 120], opacity: [0, 1, 0] }}
            transition={{ duration: 1.6, ease: [0.2, 0.8, 0.2, 1], times: [0, 0.5, 1], delay: 0.1 }}
            onUpdate={(latest) => {
              if (latest.opacity > 0.95 && !MagicReveal._fired) {
                MagicReveal._fired = true;
                onMidpoint && onMidpoint();
              }
            }}
            style={{
              position: 'absolute', width: '52vmin', height: '52vmin',
              backgroundImage: 'url(assets/ornaments/mandala.svg)',
              backgroundSize: 'contain', backgroundRepeat: 'no-repeat',
              filter:
                'invert(.9) sepia(1) saturate(4) brightness(1.15) drop-shadow(0 0 28px rgba(229,193,104,.85))',
            }}
          />

          {/* Center golden flash — bright, screened, expands and dies */}
          <motion.div
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: [0, 3, 7], opacity: [0, 0.95, 0] }}
            transition={{ duration: 1.6, ease: 'easeOut', delay: 0.3 }}
            style={{
              position: 'absolute', width: 220, height: 220, borderRadius: '50%',
              background:
                'radial-gradient(circle, rgba(255,238,196,1) 0%, rgba(229,193,104,.55) 35%, rgba(229,193,104,0) 70%)',
              mixBlendMode: 'screen',
            }}
          />

          {/* Marigold petal storm */}
          {petals.map((p) => (
            <motion.div
              key={p.id}
              initial={{ x: 0, y: 0, scale: 0, opacity: 0, rotate: 0 }}
              animate={{
                x: p.x * p.dist,
                y: p.y * p.dist,
                scale: [0, 1.2, 0.7],
                opacity: [0, 1, 0],
                rotate: p.rot,
              }}
              transition={{ duration: 1.7, delay: p.delay, ease: [0.2, 0.7, 0.3, 1] }}
              style={{
                position: 'absolute',
                width: 22, height: 22,
                background: petalColors[p.hue],
                borderRadius: '60% 40% 60% 40% / 50% 50% 50% 50%',
                boxShadow: '0 0 14px rgba(242,169,59,.55)',
              }}
            />
          ))}

          {/* Gold sparkle dust — small, fast, twinkly */}
          {Array.from({ length: 26 }).map((_, i) => {
            const a = (i * Math.PI * 2) / 26 + 0.2;
            const d = 200 + Math.random() * 320;
            return (
              <motion.div
                key={'sp' + i}
                initial={{ x: 0, y: 0, opacity: 0, scale: 0 }}
                animate={{
                  x: Math.cos(a) * d,
                  y: Math.sin(a) * d,
                  opacity: [0, 1, 0],
                  scale: [0, 1, 0.4],
                }}
                transition={{ duration: 1.4, delay: 0.45 + Math.random() * 0.4, ease: 'easeOut' }}
                style={{
                  position: 'absolute', width: 4, height: 4, borderRadius: '50%',
                  background: '#FFE9B0',
                  boxShadow: '0 0 8px #F2D27E, 0 0 16px rgba(229,193,104,.6)',
                }}
              />
            );
          })}

          {/* CURTAINS — two marsala panels that part vertically to reveal the invitation */}
          <motion.div
            initial={{ y: 0 }}
            animate={{ y: '-100%' }}
            transition={{ duration: 0.9, delay: 1.55, ease: [0.7, 0, 0.2, 1] }}
            style={{
              position: 'absolute', top: 0, left: 0, right: 0, height: '50%',
              background:
                'linear-gradient(180deg, #1A080B 0%, #2A0F11 60%, #4F1820 100%)',
              boxShadow: '0 12px 24px rgba(0,0,0,.4)',
            }}
          >
            {/* gold trim along the bottom edge of the top curtain */}
            <div style={{
              position: 'absolute', left: 0, right: 0, bottom: 0, height: 2,
              background: 'linear-gradient(90deg, transparent, #C79A3A, #E5C168, #C79A3A, transparent)',
            }}/>
          </motion.div>

          <motion.div
            initial={{ y: 0 }}
            animate={{ y: '100%' }}
            transition={{ duration: 0.9, delay: 1.55, ease: [0.7, 0, 0.2, 1] }}
            onAnimationComplete={() => onDone && onDone()}
            style={{
              position: 'absolute', bottom: 0, left: 0, right: 0, height: '50%',
              background:
                'linear-gradient(0deg, #1A080B 0%, #2A0F11 60%, #4F1820 100%)',
              boxShadow: '0 -12px 24px rgba(0,0,0,.4)',
            }}
          >
            <div style={{
              position: 'absolute', left: 0, right: 0, top: 0, height: 2,
              background: 'linear-gradient(90deg, transparent, #C79A3A, #E5C168, #C79A3A, transparent)',
            }}/>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

// reset the midpoint guard when the overlay unmounts
MagicReveal._fired = false;

window.MagicReveal = MagicReveal;
