// ── BentoBivia — Desktop: 3-col grid | Mobile: sticky horizontal scroll ──
function BentoBivia() {
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' && window.innerWidth <= 768
  );

  const wrapperRef = useRef(null);
  const trackRef   = useRef(null);
  const stRef      = useRef(null);

  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  // Mobile horizontal scroll via GSAP ScrollTrigger
  useEffect(() => {
    if (!isMobile) return;
    const wrapper = wrapperRef.current;
    const track   = trackRef.current;
    if (!wrapper || !track) return;

    // Kill any existing ST on this wrapper
    if (stRef.current) { stRef.current.kill(); stRef.current = null; }

    const setup = () => {
      const totalScroll = track.scrollWidth - window.innerWidth;
      wrapper.style.height = 'calc(100vh + ' + totalScroll + 'px)';

      stRef.current = gsap.to(track, {
        x: -totalScroll,
        ease: 'none',
        scrollTrigger: {
          trigger: wrapper,
          start: 'top top',
          end: '+=' + totalScroll,
          scrub: 1,
          invalidateOnRefresh: true,
          onRefresh(self) {
            const ts = track.scrollWidth - window.innerWidth;
            wrapper.style.height = 'calc(100vh + ' + ts + 'px)';
            self.vars.end = '+=' + ts;
            gsap.set(track, { x: -ts * self.progress });
          },
        },
      });
    };

    requestAnimationFrame(setup);

    return () => {
      if (stRef.current) { stRef.current.scrollTrigger && stRef.current.scrollTrigger.kill(); stRef.current.kill(); stRef.current = null; }
      wrapper.style.height = '';
    };
  }, [isMobile]);

  // ── Shared styles ─────────────────────────────────────────────────────────
  const cardBase = {
    background: 'rgba(255,255,255,0.015)',
    border: '1px solid rgba(200,184,149,0.1)',
    borderRadius: '16px',
    overflow: 'hidden',
    padding: '28px',
    position: 'relative',
    boxSizing: 'border-box',
  };

  const headingStyle = {
    fontFamily: 'Sora,sans-serif',
    fontWeight: 600,
    fontSize: '16px',
    color: '#F2EFE8',
    letterSpacing: '-0.01em',
    marginBottom: '8px',
    marginTop: '20px',
  };

  const bodyStyle = {
    fontSize: '13px',
    color: 'var(--stone)',
    lineHeight: 1.75,
  };

  const iconCircle = (size) => ({
    width: size + 'px',
    height: size + 'px',
    borderRadius: '50%',
    border: '1px solid rgba(200,184,149,0.3)',
    background: 'rgba(200,184,149,0.04)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    flexShrink: 0,
  });

  const circleSize = isMobile ? 80 : 56;
  const svgSize    = isMobile ? 42 : 28;

  // ── Card contents ─────────────────────────────────────────────────────────
  const cardA = (
    <div style={{
      ...cardBase,
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      textAlign: 'center',
      ...(isMobile ? { width: 'calc(100vw - 60px)', height: 'calc(100vh - 200px)', flexShrink: 0 } : {}),
    }}>
      <div style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
        <svg width="252" height="106" viewBox="0 0 252 106" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ opacity: 0.55 }}>
          <path
            d="M112.891 97.7022C140.366 97.0802 171.004 94.6715 201.087 87.5116C210.43 85.2881 219.615 82.6412 228.284 78.2473C232.198 76.3179 235.905 73.9942 239.348 71.3124C241.85 69.2557 243.954 66.7571 245.555 63.9408C249.34 57.3235 248.281 50.5341 242.498 45.6109C239.033 42.7237 235.228 40.2703 231.169 38.3054C219.443 32.7209 207.141 28.4382 194.482 25.534C184.013 23.1927 173.358 21.7755 162.64 21.2989C161.376 21.3512 160.113 21.181 158.908 20.796C158.034 20.399 156.857 19.1682 156.962 18.4535C157.115 17.8927 157.381 17.3689 157.743 16.9139C158.104 16.4588 158.555 16.0821 159.067 15.8066C160.14 15.4683 161.274 15.3733 162.389 15.5286C179.805 15.3566 196.626 18.8373 212.998 24.462C220.978 27.2494 228.798 30.4747 236.423 34.1232C240.476 36.1159 244.202 38.7131 247.474 41.8258C254.342 48.2578 255.745 56.9397 251.841 65.4892C249.793 69.8582 246.736 73.6777 242.921 76.6327C236.224 82.0192 228.522 85.4602 220.502 88.2924C205.017 93.7847 188.964 96.9081 172.738 99.2109C153.442 101.949 133.993 103.478 114.506 103.79C91.1468 104.161 67.9334 102.97 45.1169 97.5831C36.0094 95.5616 27.2626 92.1655 19.1771 87.5116C13.839 84.5746 9.1557 80.5802 5.41318 75.7725C-0.54238 67.7259 -1.13794 59.1763 3.25594 50.2827C5.82447 45.3918 9.29572 41.0315 13.4863 37.4319C24.2989 27.5721 37.0438 20.9681 50.5431 15.7272C68.1451 8.8849 86.4883 5.1395 105.175 2.83669C129.045 0.0992292 153.151 0.134761 177.013 2.94256C197.672 5.23215 218.04 9.01724 237.588 16.3889C240.089 17.3418 242.498 18.5197 244.933 19.6446C246.627 20.4387 247.725 21.6695 246.997 23.615C246.455 25.1105 244.814 25.5605 242.63 24.5811C230.322 18.9961 217.233 16.1904 204.117 13.4376C188.761 10.3438 173.2 8.36665 157.558 7.52174C129.914 5.70776 102.154 8.06792 75.2124 14.5228C60.6177 17.8788 46.5758 23.2977 33.5102 30.6161C26.6595 34.3329 20.4123 39.0673 14.9818 44.658C12.9433 46.8071 11.1336 49.1622 9.58207 51.6855C4.87056 59.5336 5.61172 67.2494 11.9246 73.7608C15.2064 77.0494 18.8775 79.925 22.8564 82.3236C31.6176 87.7101 41.3848 90.5291 51.3902 92.5804C70.6068 96.5773 90.0219 97.7419 112.891 97.7022Z"
            stroke="#C8B895" strokeWidth="1" fill="none"
          />
        </svg>
        <div style={{
          position: 'absolute',
          fontFamily: 'Sora,sans-serif',
          fontWeight: 700,
          fontSize: '48px',
          color: '#C8B895',
          letterSpacing: '-0.02em',
          lineHeight: 1,
        }}>100+</div>
      </div>
      <h3 style={headingStyle}>Sistemas diseñados</h3>
      <p style={{ ...bodyStyle, maxWidth: '280px' }}>
        Cada arquitectura construida para la lógica específica de un negocio — nunca para una plantilla genérica.
      </p>
    </div>
  );

  const cardB = (
    <div style={{
      ...cardBase,
      ...(isMobile ? { width: 'calc(100vw - 60px)', height: 'calc(100vh - 200px)', flexShrink: 0 } : {}),
    }}>
      <div style={iconCircle(circleSize)}>
        <svg width={svgSize} height={svgSize} viewBox="0 0 24 24" fill="none" stroke="#C8B895" strokeWidth="1.2">
          <circle cx="12" cy="12" r="9" strokeDasharray="2 2" opacity="0.4" />
          <circle cx="12" cy="12" r="5.5" opacity="0.65" />
          <circle cx="12" cy="12" r="2" fill="#C8B895" stroke="none" />
          <line x1="12" y1="12" x2="19" y2="5" strokeWidth="1" opacity="0.8" />
          <circle cx="19" cy="5" r="1.2" fill="#C8B895" stroke="none" />
        </svg>
      </div>
      <h3 style={headingStyle}>Diagnóstico profundo</h3>
      <p style={bodyStyle}>
        Mapeamos cada proceso, fricción y dependencia del negocio antes de diseñar cualquier cosa.
      </p>
    </div>
  );

  const cardC = (
    <div style={{
      ...cardBase,
      ...(isMobile ? { width: 'calc(100vw - 60px)', height: 'calc(100vh - 200px)', flexShrink: 0 } : {}),
    }}>
      <div style={iconCircle(circleSize)}>
        <svg width={svgSize} height={svgSize} viewBox="0 0 24 24" fill="none">
          <rect x="10" y="2" width="4" height="4" rx="0.5" fill="rgba(200,184,149,0.15)" stroke="#C8B895" strokeWidth="1.2" />
          <rect x="2" y="10" width="4" height="4" rx="0.5" fill="rgba(200,184,149,0.15)" stroke="#C8B895" strokeWidth="1.2" />
          <rect x="18" y="10" width="4" height="4" rx="0.5" fill="rgba(200,184,149,0.15)" stroke="#C8B895" strokeWidth="1.2" />
          <rect x="10" y="18" width="4" height="4" rx="0.5" fill="rgba(200,184,149,0.15)" stroke="#C8B895" strokeWidth="1.2" />
          <line x1="12" y1="6" x2="4" y2="11" stroke="#C8B895" strokeWidth="1" opacity="0.7" />
          <line x1="12" y1="6" x2="20" y2="11" stroke="#C8B895" strokeWidth="1" opacity="0.7" />
          <line x1="4" y1="14" x2="12" y2="18" stroke="#C8B895" strokeWidth="1" opacity="0.7" />
          <line x1="20" y1="14" x2="12" y2="18" stroke="#C8B895" strokeWidth="1" opacity="0.7" />
        </svg>
      </div>
      <h3 style={headingStyle}>Arquitectura modular</h3>
      <p style={bodyStyle}>
        Diseñamos el ecosistema completo: plataformas, APIs y flujos de datos conectados desde el origen.
      </p>
    </div>
  );

  const cardD = (
    <div style={{
      ...cardBase,
      ...(isMobile ? { width: 'calc(100vw - 60px)', height: 'calc(100vh - 200px)', flexShrink: 0, display: 'flex', flexDirection: 'column', gap: '20px' } : {}),
    }}>
      {isMobile ? (
        // Mobile: stacked layout
        <>
          <div>
            <div style={iconCircle(circleSize)}>
              <svg width={svgSize} height={svgSize} viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="3" stroke="#C8B895" strokeWidth="1.3" />
                <path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"
                  stroke="#C8B895" strokeWidth="1.3" strokeLinecap="round" />
              </svg>
            </div>
            <h3 style={headingStyle}>Ejecución precisa</h3>
            <p style={bodyStyle}>
              Construimos lo que diseñamos. Integramos, operamos y entregamos cada sistema con exactitud quirúrgica.
            </p>
          </div>
          <div style={{
            border: '1px solid rgba(200,184,149,0.1)',
            background: 'rgba(0,0,0,0.35)',
            borderRadius: '8px',
            padding: '16px',
            flex: 1,
          }}>
            <div style={{ display: 'flex', gap: '6px', marginBottom: '14px' }}>
              {[0.25, 0.15, 0.1].map((op, i) => (
                <span key={i} style={{ width: '8px', height: '8px', borderRadius: '50%', background: `rgba(200,184,149,${op})`, display: 'inline-block' }} />
              ))}
            </div>
            {['CRM — integrado', 'Pipelines de datos', 'Flujos automáticos', 'Dashboard BI'].map((service, i, arr) => (
              <div key={service} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                fontSize: '11px',
                borderBottom: i < arr.length - 1 ? '1px solid rgba(200,184,149,0.06)' : 'none',
                padding: '7px 0',
                color: 'var(--stone)',
              }}>
                <span>{service}</span>
                <span style={{ color: '#6B9E6B', fontWeight: 500 }}>● activo</span>
              </div>
            ))}
          </div>
        </>
      ) : (
        // Desktop: 2-col layout
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
          <div>
            <div style={iconCircle(circleSize)}>
              <svg width={svgSize} height={svgSize} viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="3" stroke="#C8B895" strokeWidth="1.3" />
                <path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"
                  stroke="#C8B895" strokeWidth="1.3" strokeLinecap="round" />
              </svg>
            </div>
            <h3 style={headingStyle}>Ejecución precisa</h3>
            <p style={bodyStyle}>
              Construimos lo que diseñamos. Integramos, operamos y entregamos cada sistema con exactitud quirúrgica.
            </p>
          </div>
          <div style={{
            border: '1px solid rgba(200,184,149,0.1)',
            background: 'rgba(0,0,0,0.35)',
            borderRadius: '8px',
            padding: '16px',
          }}>
            <div style={{ display: 'flex', gap: '6px', marginBottom: '14px' }}>
              {[0.25, 0.15, 0.1].map((op, i) => (
                <span key={i} style={{ width: '8px', height: '8px', borderRadius: '50%', background: `rgba(200,184,149,${op})`, display: 'inline-block' }} />
              ))}
            </div>
            {['CRM — integrado', 'Pipelines de datos', 'Flujos automáticos', 'Dashboard BI'].map((service, i, arr) => (
              <div key={service} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                fontSize: '11px',
                borderBottom: i < arr.length - 1 ? '1px solid rgba(200,184,149,0.06)' : 'none',
                padding: '7px 0',
                color: 'var(--stone)',
              }}>
                <span>{service}</span>
                <span style={{ color: '#6B9E6B', fontWeight: 500 }}>● activo</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );

  // ── Mobile: sticky horizontal scroll ─────────────────────────────────────
  if (isMobile) {
    return (
      <div
        ref={wrapperRef}
        style={{
          width: '100vw',
          position: 'relative',
          left: '50%',
          transform: 'translateX(-50%)',
          marginTop: '40px',
          marginBottom: '40px',
        }}
      >
        <div style={{
          position: 'sticky',
          top: 0,
          height: '100vh',
          overflow: 'hidden',
          display: 'flex',
          alignItems: 'center',
        }}>
          <div
            ref={trackRef}
            style={{
              display: 'flex',
              gap: '16px',
              paddingLeft: '24px',
              paddingRight: '24px',
              willChange: 'transform',
              alignItems: 'center',
            }}
          >
            {cardA}
            {cardB}
            {cardC}
            {cardD}
          </div>
        </div>
      </div>
    );
  }

  // ── Desktop: CSS grid ─────────────────────────────────────────────────────
  return (
    <div className="bivia-bento">
      {cardA}
      {cardB}
      {cardC}
      {cardD}
    </div>
  );
}
