// MOODBOARD — direct expansion of page 5 of PDF: collage of objects over water,
// with hover labels (Japón love, Expresar fuerte y claro, etc.)
// Items now drift autonomously across the water with random accelerations and
// decelerations — each object picks a slow-current target, eases toward it,
// then picks a new one. Hover pauses that single fragment for selection.
const MOODBOARD_ITEMS = [
  { src: 'assets/moodboard/sushi.png',      name: 'Japón love',         left: 6,  top: 14, w: 130, rot: -4 },
  { src: 'assets/moodboard/mochi.png',      name: 'Dulzura práctica',   left: 18, top: 56, w: 120, rot: 3 },
  { src: 'assets/moodboard/milanesa.png',   name: 'Mesa familiar',      left: 32, top: 12, w: 150, rot: -8 },
  { src: 'assets/moodboard/tiramisu.png',   name: 'Nostalgia',          left: 46, top: 62, w: 140, rot: 6 },
  { src: 'assets/moodboard/queen-card.png', name: 'Reina de corazones', left: 60, top: 18, w: 130, rot: -3 },
  { src: 'assets/moodboard/crown.png',      name: 'Corona',             left: 72, top: 66, w: 150, rot: 4 },
  { src: 'assets/moodboard/scorpion.png',   name: 'Impaciencia',        left: 84, top: 22, w: 130, rot: 12 },
  { src: 'assets/moodboard/grapes.png',     name: 'Abundancia',         left: 8,  top: 72, w: 140, rot: -6 },
  { src: 'assets/moodboard/surfboard.png',  name: 'Agua',               left: 52, top: 8,  w: 90,  rot: 10 },
  { src: 'assets/moodboard/plant.png',      name: 'Verde cortinado',    left: 72, top: 4,  w: 110, rot: -2 },
  { src: 'assets/moodboard/toblerone.png',  name: 'Geometría',          left: 86, top: 72, w: 130, rot: -4 },
  { src: 'assets/moodboard/madrileno.png',  name: 'Retrato en rojo',    left: 22, top: 30, w: 110, rot: 2 },
  { src: 'assets/moodboard/wassily.png',    name: 'Wassily',            left: 60, top: 44, w: 130, rot: -2 },
  { src: 'assets/moodboard/plane.png',      name: 'Viaje',              left: 38, top: 46, w: 130, rot: 8 },
  { src: 'assets/moodboard/degas.png',      name: 'Danza — Degas',      left: 2,  top: 42, w: 120, rot: -3 },
  { src: 'assets/moodboard/magnifier.png',  name: 'Selector',           left: 44, top: 28, w: 70,  rot: 14 },
];

function Moodboard() {
  const [active, setActive] = React.useState(null);
  const activeRef = React.useRef(null);
  React.useEffect(() => { activeRef.current = active; }, [active]);

  const containerRef = React.useRef(null);
  const itemRefs = React.useRef([]);

  // Per-item motion state. Each fragment has:
  //   x, y         — current position offset (% of container)
  //   vx, vy       — velocity (% per second)
  //   tx, ty       — target position (% of container)
  //   rot, vr      — current rotation, angular velocity
  //   trot         — target rotation
  //   nextPick     — timestamp at which to pick a new target
  //   home{X,Y}    — original anchor; targets drift around this point
  const motionRef = React.useRef(null);
  if (motionRef.current === null) {
    motionRef.current = MOODBOARD_ITEMS.map((m) => ({
      x: m.left, y: m.top,
      vx: 0, vy: 0,
      tx: m.left, ty: m.top,
      rot: m.rot, vr: 0, trot: m.rot,
      nextPick: 0,
      homeX: m.left, homeY: m.top, homeRot: m.rot,
    }));
  }

  React.useEffect(() => {
    let raf = 0;
    let last = performance.now();

    const pickNewTarget = (s, now) => {
      // Drift target stays within ±wander of the home anchor so the
      // collage composition is preserved over time.
      const wander = 12; // % of container
      s.tx = s.homeX + (Math.random() * 2 - 1) * wander;
      s.ty = s.homeY + (Math.random() * 2 - 1) * wander;
      // Clamp so objects never escape past the visible water area.
      s.tx = Math.max(1, Math.min(92, s.tx));
      s.ty = Math.max(1, Math.min(85, s.ty));
      // Rotation wobble around home rotation
      s.trot = s.homeRot + (Math.random() * 2 - 1) * 10;
      // Time until the next target — randomised so all 16 items
      // never re-target on the same frame.
      s.nextPick = now + 2200 + Math.random() * 3800;
    };

    const tick = (now) => {
      const dt = Math.min(0.05, (now - last) / 1000); // seconds, capped
      last = now;
      const motion = motionRef.current;
      const activeIdx = activeRef.current;

      for (let i = 0; i < motion.length; i++) {
        const s = motion[i];
        const isHovered = activeIdx === i;

        if (now >= s.nextPick) pickNewTarget(s, now);

        // Spring-damper toward target produces natural accel/decel:
        //   stiffness pulls toward target, damping bleeds velocity.
        // Hovered items get harder damping so they settle quickly.
        const stiffness = isHovered ? 6.0 : 0.9;   // accel strength
        const damping   = isHovered ? 4.0 : 1.6;   // friction
        const ax = (s.tx - s.x) * stiffness - s.vx * damping;
        const ay = (s.ty - s.y) * stiffness - s.vy * damping;
        s.vx += ax * dt;
        s.vy += ay * dt;
        s.x  += s.vx * dt;
        s.y  += s.vy * dt;

        // Rotation tracks its own gentler spring.
        const ar = (s.trot - s.rot) * 1.4 - s.vr * 1.8;
        s.vr  += ar * dt;
        s.rot += s.vr * dt;

        const el = itemRefs.current[i];
        if (el) {
          el.style.left = s.x + '%';
          el.style.top  = s.y + '%';
          el.style.transform = `rotate(${s.rot}deg) translateZ(0)`;
        }
      }

      raf = requestAnimationFrame(tick);
    };

    // Stagger initial target picks so motion starts varied.
    const now0 = performance.now();
    motionRef.current.forEach((s, i) => {
      s.nextPick = now0 + i * 120 + Math.random() * 800;
    });

    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <section id="moodboard" data-screen-label="06 Moodboard" style={{
      position: 'relative', padding: '140px 48px 0',
      background: 'var(--paper)'
    }}>
      <PageNumber n={6} label="COLLAGE" />
      <SectionLabel idx={5} title="Moodboard" kicker="Memoria visual · Fragmentos cotidianos que conviven." />

      <div ref={containerRef} style={{
        position: 'relative', height: '88vh', minHeight: 640,
        background: 'linear-gradient(to bottom, #A8C4D2 0%, #4A7A94 40%, #1F4E6B 100%)',
        overflow: 'hidden', marginBottom: 0,
        boxShadow: 'inset 0 0 200px rgba(0,0,0,.2)'
      }}>
        {/* Water surface texture using the ocean image as overlay */}
        <img src="assets/moodboard/wave.png" alt=""
             style={{
               position: 'absolute', inset: 0, width: '100%', height: '100%',
               objectFit: 'cover', opacity: .85
             }}/>

        {/* Subtle horizontal lines removed — water texture comes from wave.png alone */}

        {/* Collage items — positions/rotations driven by rAF loop above */}
        {MOODBOARD_ITEMS.map((m, i) => (
          <div key={i}
            ref={(el) => { itemRefs.current[i] = el; }}
            data-name={m.name}
            onMouseEnter={() => setActive(i)}
            onMouseLeave={() => setActive(null)}
            style={{
              position: 'absolute',
              left: m.left + '%', top: m.top + '%',
              width: m.w,
              transform: `rotate(${m.rot}deg) translateZ(0)`,
              transition: 'filter .3s',
              zIndex: active === i ? 10 : 1,
              filter: active === i ? 'none' : (active !== null ? 'saturate(.7) brightness(.95)' : 'none'),
              cursor: 'pointer',
              willChange: 'transform, left, top'
            }}
          >
            <img src={m.src} alt={m.name}
                 style={{
                   width: '100%', height: 'auto', display: 'block',
                   transform: active === i ? 'scale(1.1)' : 'scale(1)',
                   transition: 'transform .4s ease',
                   filter: 'drop-shadow(0 18px 24px rgba(0,40,60,.35))'
                 }}/>
            {/* Red frame around active */}
            {active === i && (
              <div style={{
                position: 'absolute', inset: -8,
                border: '1.5px solid var(--red)', pointerEvents: 'none',
                transform: 'scale(1.1)', transformOrigin: 'center'
              }}/>
            )}
          </div>
        ))}

        {/* Drifting NOMEN wordmark watermark */}
        <img src="assets/logo/nomen-wordmark.png" alt=""
             style={{
               position: 'absolute',
               right: '3%', bottom: '4%', width: 220, opacity: .92,
               mixBlendMode: 'multiply', pointerEvents: 'none'
             }}/>

        {/* Floating phrase */}
        <div style={{
          position: 'absolute', left: 24, top: 24,
          background: 'rgba(255,255,255,.92)', padding: '10px 14px',
          fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', fontWeight: 600
        }}>
          Inspiración personal
        </div>

        {/* Selector indicator — bottom caption */}
        <div style={{
          position: 'absolute', left: 24, bottom: 24,
          padding: '10px 14px', background: 'var(--red)', color: '#fff',
          fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', fontWeight: 600,
          minWidth: 240
        }}>
          {active !== null ? `Nombrado: ${MOODBOARD_ITEMS[active].name}` : 'Seleccioná un fragmento →'}
        </div>
      </div>

      {/* Caption strip below water */}
      <div style={{
        padding: '22px 0 0',
        display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16,
        borderTop: '1px solid var(--ink)'
      }}>
        <span className="eyebrow">Pl. 05 · Moodboard vivo — 16 fragmentos</span>
        <span className="eyebrow" style={{ opacity: .55 }}>Todas las imágenes: extraídas del portfolio NOMEN</span>
      </div>
    </section>
  );
}

Object.assign(window, { Moodboard });
