// ── PerspectiveMarquee — 3D tilted marquee band (GSAP infinite loop) ──────────
// Sits between <BentoBivia /> and la .bivia-grid. Dos filas de conceptos que se
// desplazan en sentidos opuestos sobre un plano inclinado en perspectiva.
//
// Estructura: el tilt 3D (rotateX/rotateY) vive en un contenedor propio para que
// GSAP pueda animar x / y / opacity del plano interior sin pisar la rotación.
function PerspectiveMarquee() {
  const wrapperRef = useRef(null);
  const planeRef   = useRef(null);
  const rowARef    = useRef(null);
  const rowBRef    = useRef(null);

  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' && window.innerWidth <= 768
  );

  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  // Palabras del ecosistema BIVIA
  const rowA = ['Diagnóstico', 'Arquitectura', 'Integración', 'Automatización', 'Datos', 'Estrategia'];
  const rowB = ['Sistemas', 'Ejecución', 'CRM', 'Pipelines', 'Dashboards', 'APIs', 'Software', 'ERP', 'Web', 'Ecommerce'];

  useEffect(() => {
    const wrapper = wrapperRef.current;
    const plane   = planeRef.current;
    const rowAEl  = rowARef.current;
    const rowBEl  = rowBRef.current;
    if (!wrapper || !plane || !rowAEl || !rowBEl) return;

    const tweens = [];

    // ── Fade + rise on scroll into view ──────────────────────────────────────
    tweens.push(
      gsap.fromTo(plane,
        { opacity: 0, y: 40 },
        {
          opacity: 1, y: 0, duration: 1, ease: 'power3.out',
          scrollTrigger: { trigger: wrapper, start: 'top 85%', toggleActions: 'play none none none' },
        }
      )
    );

    // ── Bucle infinito sin cortes ────────────────────────────────────────────
    // Cada fila lleva sus items duplicados (2 mitades idénticas); animar xPercent
    // 0 → -50 (o -50 → 0) sobre contenido duplicado da un loop perfectamente continuo.
    const speed = isMobile ? 26 : 40; // segundos por ciclo (menor = más rápido)
    tweens.push(
      gsap.to(rowAEl, { xPercent: -50, ease: 'none', duration: speed, repeat: -1 }),
      gsap.fromTo(rowBEl, { xPercent: -50 }, { xPercent: 0, ease: 'none', duration: speed * 1.18, repeat: -1 })
    );

    // ── Parallax sutil del plano al hacer scroll (x sobre el plano interior) ──
    tweens.push(
      gsap.fromTo(plane,
        { x: 24 },
        {
          x: -24, ease: 'none',
          scrollTrigger: { trigger: wrapper, start: 'top bottom', end: 'bottom top', scrub: 1.2 },
        }
      )
    );

    return () => {
      tweens.forEach((t) => {
        if (t.scrollTrigger) t.scrollTrigger.kill();
        t.kill();
      });
    };
  }, [isMobile]);

  // ── Estilos ────────────────────────────────────────────────────────────────
  const wordStyle = {
    fontFamily: 'Sora,sans-serif',
    fontWeight: 600,
    fontSize: isMobile ? '34px' : '58px',
    letterSpacing: '-0.02em',
    lineHeight: 1,
    whiteSpace: 'nowrap',
    color: '#C8B895',
    display: 'inline-flex',
    alignItems: 'center',
    flexShrink: 0,
  };

  const dotStyle = {
    width: isMobile ? '6px' : '9px',
    height: isMobile ? '6px' : '9px',
    borderRadius: '50%',
    background: 'rgba(200,184,149,0.4)',
    margin: isMobile ? '0 22px' : '0 40px',
    flexShrink: 0,
  };

  const rowBase = {
    display: 'flex',
    alignItems: 'center',
    width: 'max-content',
    willChange: 'transform',
  };

  // Una fila = items duplicados (2 mitades idénticas) para el loop continuo
  const buildRow = (words, opacity) => {
    const half = words.map((w, i) => (
      <React.Fragment key={i}>
        <span style={{ ...wordStyle, opacity }}>{w}</span>
        <span style={dotStyle} />
      </React.Fragment>
    ));
    return [...half, ...half.map((el, i) => React.cloneElement(el, { key: 'dup-' + i }))];
  };

  return (
    <div
      ref={wrapperRef}
      style={{
        position: 'relative',
        width: '100vw',
        left: '50%',
        transform: 'translateX(-50%)',
        marginTop: isMobile ? '72px' : '120px',
        marginBottom: isMobile ? '72px' : '120px',
        perspective: isMobile ? '900px' : '1200px',
        overflow: 'hidden',
      }}
    >
      {/* Máscaras de desvanecimiento en los bordes */}
      <div style={{
        position: 'absolute', inset: 0, zIndex: 2, pointerEvents: 'none',
        background: 'linear-gradient(90deg, var(--carbon) 0%, rgba(11,13,15,0) 14%, rgba(11,13,15,0) 86%, var(--carbon) 100%)',
      }} />

      {/* Contenedor del tilt 3D (estático) */}
      <div style={{
        transform: `rotateX(8deg) rotateY(${isMobile ? -16 : -26}deg)`,
        transformStyle: 'preserve-3d',
        transformOrigin: 'center center',
      }}>
        {/* Plano interior — GSAP anima aquí (opacity / y / x) */}
        <div
          ref={planeRef}
          style={{
            opacity: 0,
            display: 'flex',
            flexDirection: 'column',
            gap: isMobile ? '26px' : '44px',
            padding: isMobile ? '48px 0' : '80px 0',
          }}
        >
          <div ref={rowARef} style={rowBase}>{buildRow(rowA, 1)}</div>
          <div ref={rowBRef} style={rowBase}>{buildRow(rowB, 0.42)}</div>
        </div>
      </div>
    </div>
  );
}
