// Works v3 — dark gallery background, smooth crossfade, 2022—2026
const WORKS_V3 = [
  { id: 'radii8', title: 'RADII8', year: '2025',
    desc: 'a series of surreal characters drifting between worlds. each pulses from the inside out — sense it.',
    link: 'https://objkt.com/collections/KT1JVuvi262XUCLC9M8pUyLwaGrZuWL7mdfx',
    link2: { label: 'superrare ↗', url: 'https://superrare.com/petravoice' },
    images: ['radi-2.jpg', 'radi-4.jpg', 'radi-5.jpg', 'radi-6.jpg'],
    folder: 'radii8', accent: '#4d63d8', aspect: '4/5' },
  { id: 'angels', title: 'Online Angels', count: '222', year: '2025',
    desc: '222 PFPs where angelic power meets rebellious energy. angel or baddie — which calls to you?',
    link: 'https://og.rarible.com/collection/0xd51b912190d55f9e817ae9d1d33e747566011ab7/drops',
    images: ['angels-03.jpg', 'angels-115.jpg', 'angels-113.jpg', 'angels-65.jpg', 'angels-159.jpg', 'angels-181.jpg', 'angels-215.jpg'],
    folder: 'angels', accent: '#d99cb0', aspect: '1/1' },
  { id: 'boys', title: 'BOYS', count: '1,111', year: '2025',
    desc: '1,111 soft e-boy portraits — each with its own mood, radiating main character energy.',
    link: 'https://element.market/collections/boys',
    images: ['boys1.jpg', 'boys3.jpg', 'boys4.jpg', 'boys5.jpg', 'boys6.jpg', 'boys7.jpg'],
    folder: 'boys', accent: '#a8c4b6', aspect: '1/1' },
  { id: 'babes', title: 'Babes on Base', count: '333', year: '2024',
    desc: '333 creatures of inner being: from kindness to mischief, vulnerability to quiet joy.',
    link: 'https://opensea.io/collection/babes2024',
    images: ['babes-002.jpg', 'babes-021.jpg', 'babes-082.jpg', 'babes-120.jpg', 'babes-150.jpg', 'babes-209.jpg', 'babes-243.jpg', 'babes-275.jpg'],
    folder: 'babes', accent: '#f3b89a', aspect: '1/1' },
];

function WorksV3({ onLightbox }) {
  return (
    <section id="works" data-screen-label="03 Works" style={{
      position: 'relative',
      background: 'var(--paper)',
      overflow: 'hidden',
    }}>
      {/* Atmospheric blobs — large, asymmetric, dark under images / warm accents */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
        {/* RADII8 image row — dark blob right */}
        <div style={{ position: 'absolute', top: '26%', right: '-5%', width: '46vw', height: '52vw',
          borderRadius: '58% 42% 52% 48% / 44% 56% 38% 62%',
          background: 'radial-gradient(ellipse 60% 56% at 42% 44%, rgba(16,10,6,.62), transparent 68%)',
          filter: 'blur(75px)' }} />
        {/* Online Angels — warm peach right-center */}
        <div style={{ position: 'absolute', top: '38%', right: '6%', width: '40vw', height: '44vw',
          borderRadius: '45% 55% 62% 38% / 58% 42% 60% 40%',
          background: 'radial-gradient(ellipse 66% 58% at 50% 52%, rgba(208,172,148,.55), transparent 70%)',
          filter: 'blur(85px)' }} />
        {/* BOYS image row — dark blob right */}
        <div style={{ position: 'absolute', top: '57%', right: '-4%', width: '48vw', height: '50vw',
          borderRadius: '52% 48% 44% 56% / 62% 38% 56% 44%',
          background: 'radial-gradient(ellipse 58% 62% at 38% 46%, rgba(13,8,4,.65), transparent 66%)',
          filter: 'blur(80px)' }} />
        {/* Babes row — warm right */}
        <div style={{ position: 'absolute', top: '76%', right: '3%', width: '42vw', height: '46vw',
          borderRadius: '48% 52% 58% 42% / 42% 60% 44% 56%',
          background: 'radial-gradient(ellipse 64% 60% at 54% 46%, rgba(192,158,132,.58), transparent 72%)',
          filter: 'blur(90px)' }} />
        {/* Small dark accent left — only at BOYS/Babes level */}
        <div style={{ position: 'absolute', top: '60%', left: '-6%', width: '26vw', height: '34vw',
          borderRadius: '60% 40% 52% 48% / 48% 58% 42% 52%',
          background: 'radial-gradient(ellipse 68% 62% at 52% 48%, rgba(11,7,3,.48), transparent 70%)',
          filter: 'blur(85px)' }} />
      </div>

      <div className="works-inner" style={{ position: 'relative', zIndex: 1, padding: '140px 40px 60px' }}>
        <div className="reveal" style={{
          maxWidth: 1500, margin: '0 auto 80px',
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 40,
        }}>
          <div>
            <div className="mono-meta" style={{ marginBottom: 14, color: 'var(--vermilion)' }}>works · 2022—2026</div>
            <h2 style={{
              fontFamily: 'var(--display)', fontWeight: 300, fontStyle: 'italic',
              fontSize: 'clamp(56px, 8vw, 128px)', lineHeight: .9, letterSpacing: '-.04em',
              color: 'var(--ink)',
            }}>
              <span data-parallax="0.12" style={{ position: 'relative', display: 'inline-block' }}>
                <span style={{ position: 'absolute', inset: '-3px -10px', filter: 'blur(10px)', opacity: .28, color: 'var(--ash)' }}>collections</span>
                <span style={{ position: 'relative', display: 'inline-block', filter: 'blur(1.2px)', opacity: .88 }}>collections</span>
              </span>
            </h2>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 0, maxWidth: 1500, margin: '0 auto' }}>
          {WORKS_V3.map((w, i) => <WorkRowV3 key={w.id} w={w} idx={i} onLightbox={onLightbox} />)}
        </div>
      </div>

      {/* Bottom fade */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, height: '12vw',
        background: 'linear-gradient(to top, var(--paper), transparent)',
        pointerEvents: 'none', zIndex: 1,
      }}></div>
    </section>
  );
}

function WorkRowV3({ w, idx, onLightbox }) {
  const cols = 4;

  const startOffset = idx * 3;
  const [displayed, setDisplayed] = React.useState(() =>
    w.images.length <= cols
      ? [...w.images]
      : w.images.slice(startOffset % w.images.length, startOffset % w.images.length + cols)
          .concat(w.images.slice(0, Math.max(0, cols - (w.images.length - startOffset % w.images.length))))
          .slice(0, cols)
  );
  const [fadingSlot, setFadingSlot] = React.useState(-1);
  const displayedRef = React.useRef(displayed);

  // Keep ref in sync so interval can read current displayed without stale closure
  React.useEffect(() => { displayedRef.current = displayed; }, [displayed]);

  React.useEffect(() => {
    if (w.images.length <= cols) return;
    // Slow, staggered intervals — each row on its own rhythm
    const baseInterval = 6000 + idx * 1800 + [500, 1100, 300, 900][idx % 4];

    const t = setInterval(() => {
      // Pick 1 random slot to change
      const slot = Math.floor(Math.random() * cols);

      // Pick a random image NOT currently shown in any slot
      const current = displayedRef.current;
      const pool = w.images.filter(img => !current.includes(img));
      if (pool.length === 0) return;
      const nextImg = pool[Math.floor(Math.random() * pool.length)];

      setFadingSlot(slot);
      setTimeout(() => {
        setDisplayed(prev => {
          const n = [...prev];
          n[slot] = nextImg;
          return n;
        });
        setFadingSlot(-1);
      }, 500);
    }, baseInterval);
    return () => clearInterval(t);
  }, [cols, w.images, idx]);

  return (
    <div className="reveal" style={{
      padding: '52px 0',
      borderTop: '1px solid rgba(26,24,18,.08)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24,
        marginBottom: 6, flexWrap: 'wrap',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <span className="mono-meta" style={{ color: w.accent, fontSize: 10 }}>0{idx + 1}</span>
          <h3 style={{
            fontFamily: 'var(--mono)', fontWeight: 500,
            fontSize: 'clamp(18px, 2vw, 30px)', lineHeight: 1, letterSpacing: '.06em',
            textTransform: 'uppercase', color: 'var(--ink)',
          }}>{w.title}</h3>
          {w.count && <span className="mono-meta" style={{ opacity: .45, fontSize: 10, color: 'var(--ink)' }}>{w.count} · {w.year}</span>}
          {!w.count && <span className="mono-meta" style={{ opacity: .45, fontSize: 10, color: 'var(--ink)' }}>{w.year}</span>}
        </div>

        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <a href={w.link} target="_blank" data-hover style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.22em', textTransform: 'uppercase',
            padding: '9px 18px', borderRadius: 999,
            border: '1px solid rgba(26,24,18,.18)',
            color: 'var(--ink)', transition: 'background .25s',
          }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: w.accent }}></span>
            view ↗
          </a>
          {w.link2 && (
            <a href={w.link2.url} target="_blank" data-hover style={{
              fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.18em', textTransform: 'uppercase',
              color: 'var(--ash)',
            }}>{w.link2.label}</a>
          )}
        </div>
      </div>

      <div className="mono-meta" style={{ opacity: .45, fontSize: 10, marginBottom: 18, color: 'var(--ink)', paddingLeft: 2 }}>
        {w.desc}
      </div>

      <div className="works-img-grid" style={{
        display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 10,
      }}>
        {displayed.map((img, j) => (
          <WorkImgV3
            key={`${w.id}-slot-${j}`}
            src={`collections/${w.folder}/${img}`}
            label={`${String(j + 1).padStart(2, '0')}`}
            title={w.title}
            accent={w.accent}
            aspect={w.aspect}
            fading={fadingSlot === j}
            onLightbox={onLightbox}
          />
        ))}
      </div>
    </div>
  );
}

function WorkImgV3({ src, label, title, accent, aspect, fading, onLightbox }) {
  const ref = React.useRef(null);
  const [tilt, setTilt] = React.useState({ x: 0, y: 0 });
  const onMove = (e) => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    setTilt({
      x: ((e.clientX - r.left) / r.width - 0.5) * 6,
      y: ((e.clientY - r.top) / r.height - 0.5) * -6,
    });
  };
  return (
    <div ref={ref} data-hover
      onMouseMove={onMove} onMouseLeave={() => setTilt({ x: 0, y: 0 })}
      onClick={() => onLightbox({ src, title, label })}
      style={{
        position: 'relative', aspectRatio: aspect || '1/1',
        borderRadius: 4, overflow: 'hidden',
        transform: `perspective(1200px) rotateX(${tilt.y}deg) rotateY(${tilt.x}deg)`,
        transition: 'transform .5s var(--e-out)',
        boxShadow: '0 8px 28px rgba(26,20,14,.14)',
        cursor: 'pointer',
      }}>
      <img src={src} alt={title} style={{
        width: '100%', height: '100%', objectFit: 'cover',
        opacity: fading ? 0 : 1, transition: 'opacity .5s ease',
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(to top, rgba(0,0,0,.35) 0%, transparent 45%)',
        opacity: 0, transition: 'opacity .3s',
      }} className="work-img-overlay"></div>
    </div>
  );
}

window.WorksV3 = WorksV3;
