/* global React */

// ===== PILOTOS FLASH (home) — 12 pilotos rotando determinísticamente en 6 slots =====
// Esquema: cola circular. 6 visibles + 6 en pool. Cada tick: cursor (round-robin)
// reemplaza el slot por la cabeza del pool; el desplazado va al final. Cero duplicados.
// Rotación: la rotación acumula (+180° cada flip), nunca vuelve hacia atrás.
const PILOTOS = [
  { id: 'colapinto',   name: 'Colapinto',   team: 'Alpine',     img: 'assets/pilotos/colapinto.jpg',   badge: '🇦🇷 ARG' },
  { id: 'verstappen',  name: 'Verstappen',  team: 'Red Bull',   img: 'assets/pilotos/verstappen.jpg' },
  { id: 'leclerc',     name: 'Leclerc',     team: 'Ferrari',    img: 'assets/pilotos/leclerc.jpg' },
  { id: 'hamilton',    name: 'Hamilton',    team: 'Ferrari',    img: 'assets/pilotos/hamilton.jpg' },
  { id: 'alonso',      name: 'Alonso',      team: 'Aston M.',   img: 'assets/pilotos/alonso.jpg' },
  { id: 'antonelli',   name: 'Antonelli',   team: 'Mercedes',   img: 'assets/pilotos/antonelli.jpg' },
  { id: 'norris',      name: 'Norris',      team: 'McLaren',    img: 'assets/pilotos/norris.jpg' },
  { id: 'gasly',       name: 'Gasly',       team: 'Alpine',     img: 'assets/pilotos/gasly.jpg' },
  { id: 'perez',       name: 'Pérez',       team: 'Red Bull',   img: 'assets/pilotos/perez.jpg' },
  { id: 'senna',       name: 'Senna',       team: 'Leyenda',    img: 'assets/pilotos/senna.jpg' },
  { id: 'schumacher',  name: 'Schumacher',  team: 'Leyenda',    img: 'assets/pilotos/schumacher.jpg' },
  { id: 'fangio',      name: 'Fangio',      team: 'Leyenda',    img: 'assets/pilotos/fangio.jpg',      badge: '🇦🇷 ARG' }
];

const SLOT_COUNT = 6;
const TICK_MS = 1500;
const PILOTOS_BY_ID = Object.fromEntries(PILOTOS.map(p => [p.id, p]));

// Devuelve true si en `rotation` está mirando la cara frontal (rotation % 360 === 0)
const isFrontVisible = (rotation) => Math.floor(rotation / 180) % 2 === 0;

function PilotoFace({ pilot }) {
  if (!pilot) return null;
  return (
    <>
      <img src={pilot.img} alt={pilot.name} loading="lazy" />
      {pilot.badge && <span className="piloto-badge">{pilot.badge}</span>}
      <div className="piloto-overlay">
        <span className="pn">{pilot.name}</span>
        <span className="pt">{pilot.team}</span>
      </div>
    </>
  );
}

function PilotosFlash() {
  // Cada slot: { frontId, backId, rotation (acumulado), flipping }
  const [slots, setSlots] = React.useState(() =>
    PILOTOS.slice(0, SLOT_COUNT).map(p => ({
      frontId: p.id,
      backId: null,
      rotation: 0,
      flipping: false
    }))
  );

  // Mirror del state para leer en closures de setTimeout
  const slotsRef = React.useRef(slots);
  slotsRef.current = slots;

  // Cola circular: cursor de slot + pool de ids fuera de pantalla
  const cycleRef = React.useRef({
    slotCursor: 0,
    pool: PILOTOS.slice(SLOT_COUNT).map(p => p.id)
  });

  // Preload de las 12 imágenes para que el flip no parpadee
  React.useEffect(() => {
    PILOTOS.forEach(p => { const img = new Image(); img.src = p.img; });
  }, []);

  // Loop determinístico
  React.useEffect(() => {
    let timeoutId;
    const tick = () => {
      const cycle = cycleRef.current;
      const slotIndex = cycle.slotCursor;
      const current = slotsRef.current[slotIndex];

      if (current.flipping) {
        timeoutId = setTimeout(tick, 600);
        return;
      }

      // Quien está visible ahora sale al pool; entra la cabeza del pool
      const visibleId = isFrontVisible(current.rotation) ? current.frontId : current.backId;
      const incomingId = cycle.pool.shift();
      cycle.pool.push(visibleId);
      cycle.slotCursor = (slotIndex + 1) % SLOT_COUNT;

      setSlots(prev => prev.map((s, i) => {
        if (i !== slotIndex) return s;
        const newRotation = s.rotation + 180;
        // El piloto nuevo va en la cara que será visible DESPUÉS del giro
        const showFrontAfter = isFrontVisible(newRotation);
        return {
          ...s,
          frontId: showFrontAfter ? incomingId : s.frontId,
          backId:  showFrontAfter ? s.backId    : incomingId,
          rotation: newRotation,
          flipping: true
        };
      }));

      timeoutId = setTimeout(tick, TICK_MS);
    };
    timeoutId = setTimeout(tick, 1400);
    return () => clearTimeout(timeoutId);
  }, []);

  // Al terminar el transform, marcamos como no-flipping (sin tocar rotación)
  const handleFlipEnd = (slotIndex) => (e) => {
    if (e.propertyName !== 'transform') return;
    if (e.target !== e.currentTarget) return;
    setSlots(prev => prev.map((s, i) =>
      i === slotIndex && s.flipping ? { ...s, flipping: false } : s
    ));
  };

  return (
    <section className="pilotos-flash">
      <video
        className="pilotos-flash-bg"
        src="assets/fondo-formula1.mp4"
        autoPlay
        loop
        muted
        playsInline
      />
      <div className="pilotos-flash-overlay" />
      <div className="container">
        <div className="section-head reveal centered">
          <span className="eyebrow" style={{ justifyContent: 'center' }}>Pilotos que nos inspiran</span>
          <h2 className="display"><span className="accent">Vamo Nene!!</span> te hace <span className="accent">sentir</span> piloto</h2>
        </div>

        <div className="pilotos-strip">
          {slots.map((s, i) => {
            const front = PILOTOS_BY_ID[s.frontId];
            const back  = s.backId ? PILOTOS_BY_ID[s.backId] : null;
            return (
              <div key={i} className="piloto-card">
                <div
                  className="piloto-inner"
                  style={{ transform: `rotateY(${s.rotation}deg)` }}
                  onTransitionEnd={handleFlipEnd(i)}
                >
                  <div className="piloto-face piloto-front"><PilotoFace pilot={front} /></div>
                  <div className="piloto-face piloto-back"><PilotoFace pilot={back} /></div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

window.PilotosFlash = PilotosFlash;
