// ==================== GALLERY ====================
function Gallery() {
  const { motion, AnimatePresence } = window.Motion;

  // Pre-classified by orientation so wide slots only get landscape photos
  // and tall slots only get portrait photos — no awkward stretching/cropping.
  const LANDSCAPE = React.useMemo(
    () => [
      ...[1,4,5,6,9,11,16,17,19,20,21,22,23,24,25,26,27,28]
        .map(n => `wedding/wed-${String(n).padStart(2, '0')}.jpg`),
      'couple-3.jpeg',
      'family.jpeg',
      'ring-ceremony.jpeg',
    ],
    []
  );
  const PORTRAIT = React.useMemo(
    () => [
      ...[10,12,13]
        .map(n => `wedding/wed-${String(n).padStart(2, '0')}.jpg`),
      'couple-1.jpeg',
      'couple-2.jpeg',
    ],
    []
  );

  // 6 fixed mosaic slots — same shape as the original gallery.
  // Top half above the video, bottom half below.
  const SLOTS_TOP = [
    { span: 'tall', orient: 'P', pos: 'center 25%' },
    { span: 'wide', orient: 'L', pos: 'center 35%' },
    { span: 'tall', orient: 'P', pos: 'center 20%' },
  ];
  const SLOTS_BOTTOM = [
    { span: 'tall', orient: 'P', pos: 'center 30%' },
    { span: 'wide', orient: 'L', pos: 'center 40%' },
    { span: 'tall', orient: 'P', pos: 'center 25%' },
  ];

  const pick = (pool, taken) => {
    const free = pool.filter(p => !taken.has(p));
    const list = free.length ? free : pool;
    return list[Math.floor(Math.random() * list.length)];
  };

  const initSlots = (slots) => {
    const taken = new Set();
    return slots.map(s => {
      const src = pick(s.orient === 'P' ? PORTRAIT : LANDSCAPE, taken);
      taken.add(src);
      return { ...s, src };
    });
  };

  const [topTiles,    setTopTiles]    = React.useState(() => initSlots(SLOTS_TOP));
  const [bottomTiles, setBottomTiles] = React.useState(() => initSlots(SLOTS_BOTTOM));

  // Every 3.5s, pick one slot at random (across both halves) and swap its
  // photo for another random one of the same orientation that isn't on screen.
  React.useEffect(() => {
    const id = setInterval(() => {
      const half = Math.random() < 0.5;
      const setter = half ? setTopTiles : setBottomTiles;
      setter(prev => {
        const all = new Set([
          ...topTiles.map(t => t.src),
          ...bottomTiles.map(t => t.src),
        ]);
        const idx = Math.floor(Math.random() * prev.length);
        const slot = prev[idx];
        // Don't repeat the slot's current photo
        all.add(slot.src);
        const pool = slot.orient === 'P' ? PORTRAIT : LANDSCAPE;
        const next = pick(pool, all);
        if (!next || next === slot.src) return prev;
        const out = [...prev];
        out[idx] = { ...slot, src: next };
        return out;
      });
    }, 3500);
    return () => clearInterval(id);
  }, [topTiles, bottomTiles, PORTRAIT, LANDSCAPE]);

  // Tap-to-unmute on the featured video.
  const videoRef = React.useRef(null);
  const [muted, setMuted] = React.useState(true);
  const toggleMute = () => {
    const v = videoRef.current;
    if (!v) return;
    v.muted = !v.muted;
    setMuted(v.muted);
    if (!v.muted) v.play().catch(() => {});
  };

  const headerVar = {
    hidden:  { opacity: 0, y: 30 },
    visible: { opacity: 1, y: 0, transition: { duration: 0.7, ease: [0.2, 0.8, 0.2, 1] } },
  };
  const grid = {
    hidden:  {},
    visible: { transition: { staggerChildren: 0.08, delayChildren: 0.15 } },
  };
  const tile = {
    hidden:  { opacity: 0, scale: 0.6, y: 60, rotate: -2, filter: 'blur(8px)' },
    visible: {
      opacity: 1, scale: 1, y: 0, rotate: 0, filter: 'blur(0px)',
      transition: { type: 'spring', stiffness: 80, damping: 14 },
    },
  };

  // Each slot is a stable container; the photo INSIDE crossfades on change.
  const renderTile = (t, key) => (
    <motion.div key={key} className={`gallery-tile ${t.span}`}
      variants={tile}
      whileHover={{ y: -6, scale: 1.02, transition: { type:'spring', stiffness:200, damping:18 } }}
      style={{
        background: 'var(--ivory-300)',
        transformOrigin: '50% 80%',
        position: 'relative', overflow: 'hidden',
      }}>
      <AnimatePresence mode="wait">
        <motion.div
          key={t.src}
          initial={{ opacity: 0, scale: 1.06 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.97 }}
          transition={{ duration: 0.9, ease: [0.2, 0.8, 0.2, 1] }}
          style={{
            position: 'absolute', inset: 0,
            backgroundImage: `url(../../assets/photos/${t.src})`,
            backgroundSize: 'cover',
            backgroundPosition: t.pos,
          }}
        />
      </AnimatePresence>
      <div className="gallery-frame"/>
    </motion.div>
  );

  return (
    <section className="screen" style={{
      minHeight:'100vh', padding:'80px 16px',
      background:'var(--ivory-300)',
      position:'relative', overflow:'hidden',
    }}>
      <div style={{
        position:'absolute', inset:0,
        backgroundImage:'url(../../assets/patterns/kolam-tile.svg)',
        backgroundSize:'180px', opacity:.18, pointerEvents:'none',
      }} />
      <div style={{ position:'relative', maxWidth:1100, margin:'0 auto', textAlign:'center' }}>
        <motion.div initial="hidden" whileInView="visible" viewport={{ once:false, amount:0.4 }} variants={headerVar}>
          <div style={{ fontFamily:'var(--font-ui)', fontSize:12, letterSpacing:'.4em', textTransform:'uppercase', color:'var(--gold-700)' }}>
            ✦ Moments ✦
          </div>
          <h2 className="section-h2" style={{
            fontFamily:'var(--font-display)', fontStyle:'italic', fontWeight:500,
            color:'var(--marsala-700)', margin:'16px 0 8px', lineHeight:1,
          }}>
            A Little Joy
          </h2>
          <Divider width={220} />
        </motion.div>

        <motion.div className="gallery-grid"
          initial="hidden" whileInView="visible" viewport={{ once:false, amount:0.05 }} variants={grid}>
          {topTiles.map((t, i) => renderTile(t, 'top-' + i))}
        </motion.div>

        {/* ── Featured video — sits in the middle of "A Little Joy" ── */}
        <motion.div
          initial={{ opacity: 0, y: 60, scale: 0.85, filter:'blur(8px)' }}
          whileInView={{ opacity: 1, y: 0, scale: 1, filter:'blur(0px)' }}
          viewport={{ once:false, amount:0.3 }}
          transition={{ type:'spring', stiffness:80, damping:16, delay:0.1 }}
          style={{
            position:'relative',
            margin:'40px auto 8px',
            width:'min(720px, 96%)',
            padding: 14,
            background:'var(--marsala-700)',
            borderRadius: 22,
            border:'1.5px solid var(--gold-500)',
            boxShadow:'0 20px 50px rgba(122,31,43,.28), 0 6px 16px rgba(58,26,28,.18)',
          }}
        >
          <div style={{
            fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'.4em',
            textTransform:'uppercase', color:'var(--gold-300)',
            textAlign:'center', marginBottom:10,
          }}>
            ✦ A Cherished Moment ✦
          </div>
          <div style={{
            position:'relative', overflow:'hidden',
            borderRadius: 14, border:'1px solid var(--gold-500)',
            boxShadow:'inset 0 0 0 4px rgba(251,243,227,.15)',
            background:'#0a0508',
            aspectRatio: '16 / 9',
          }}>
            <video
              ref={videoRef}
              src="assets/video/joy-moment.mp4"
              autoPlay muted loop playsInline preload="metadata"
              onClick={toggleMute}
              style={{
                display:'block', width:'100%', height:'100%',
                objectFit:'cover', objectPosition:'center',
                cursor:'pointer',
              }}
            />
            <button
              type="button"
              onClick={toggleMute}
              aria-label={muted ? 'Unmute video' : 'Mute video'}
              style={{
                position:'absolute', right:10, bottom:10,
                padding:'7px 12px', borderRadius:999,
                background:'rgba(26,8,11,.7)', color:'var(--gold-200)',
                border:'1px solid var(--gold-500)', cursor:'pointer',
                fontFamily:'var(--font-ui)', fontSize:10, letterSpacing:'.22em',
                textTransform:'uppercase', backdropFilter:'blur(6px)',
                touchAction:'manipulation',
              }}>
              {muted ? '🔇 tap for sound' : '🔊 sound on'}
            </button>
          </div>
        </motion.div>

        <motion.div className="gallery-grid"
          initial="hidden" whileInView="visible" viewport={{ once:false, amount:0.05 }} variants={grid}
          style={{ marginTop: 24 }}>
          {bottomTiles.map((t, i) => renderTile(t, 'bot-' + i))}
        </motion.div>

        <motion.p
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once:false, amount:0.5 }}
          transition={{ duration: 0.8, delay: 0.2, ease:[0.2, 0.8, 0.2, 1] }}
          style={{
            fontFamily:'var(--font-body)', fontStyle:'italic', fontSize:18,
            color:'var(--ink-700)', maxWidth:560, margin:'40px auto 0', lineHeight:1.6,
          }}>
          The best part of any celebration is the people in it. We can't wait to add your face to these.
        </motion.p>
      </div>
    </section>
  );
}

window.Gallery = Gallery;
