// v2/scene.jsx — Carousel with peeking side slides + per-slide caption below image.
// Pixel-based positioning (ResizeObserver) so translateX is always exact.
// Active slide: elevated card with shadow. Side slides: dimmed + faded at edges.

const CAROUSEL_SLIDES = [
  {
    img: 'v2/gallery/imagen1.webp',
    title: 'Panel de control en tiempo real',
    desc: 'Cuánto vendiste, qué producto está por agotarse y cuál te deja más ganancia. Todo en una sola pantalla.',
  },
  {
    img: 'v2/gallery/imagen2.webp',
    title: 'Inventario inteligente por sucursal',
    desc: 'Controla el stock de cada local, recibe alertas antes de quedarte sin producto y revisa el historial de entradas y salidas.',
  },
  {
    img: 'v2/gallery/imagen3.webp',
    title: 'Tu tienda online personalizada',
    desc: 'Tu catálogo con tu logo y colores. Los clientes ven tus productos y hacen pedidos desde cualquier dispositivo, sin descargar nada.',
  },
  {
    img: 'v2/gallery/imagen4.webp',
    title: 'Comisiones automáticas por vendedor',
    desc: 'Configura el porcentaje por rol, asigna cada venta a quien la cerró y genera el reporte sin una sola suma manual.',
  },
  {
    img: 'v2/gallery/imagen5.webp',
    title: 'Modo kiosco con gestión de turnos',
    desc: 'Cobra de forma autónoma, gestiona turnos por cajero, controla el efectivo y cierra caja en segundos con todo cuadrado.',
  },
  {
    img: 'v2/gallery/imagen6.webp',
    title: 'Restaurante: mesas a tu medida',
    desc: 'Diseña el plano de tu local, asigna mesas, envía comandas a cocina y divide la cuenta — sin papel ni hardware extra.',
  },
  {
    img: 'v2/gallery/imagen7.webp',
    title: 'Pantalla de cocina en vivo',
    desc: 'El chef ve los pedidos en pantalla en el instante en que se hacen. Sin comandas en papel, sin platos que se olvidan.',
  },
  {
    img: 'v2/gallery/imagen8.webp',
    title: 'Cobranzas: cero pagos perdidos',
    desc: 'Registra pagos parciales, lleva el saldo de cada cliente y consulta qué facturas están pendientes. Sin planillas ni Excel.',
  },
];

function V2ScrollScene() {
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [stageW, setStageW] = React.useState(0);
  const outerRef = React.useRef(null);
  const touchX = React.useRef(null);
  const n = CAROUSEL_SLIDES.length;

  // Pixel-exact measurement of the container width
  React.useLayoutEffect(function() {
    var el = outerRef.current;
    if (!el) return;
    function measure() { setStageW(el.offsetWidth); }
    measure();
    window.addEventListener('resize', measure);
    return function() { window.removeEventListener('resize', measure); };
  }, []);

  var prev = function() { setIdx(function(i) { return (i - 1 + n) % n; }); };
  var next = function() { setIdx(function(i) { return (i + 1) % n; }); };

  // Auto-advance, pause on hover
  React.useEffect(function() {
    if (paused) return;
    var t = setInterval(function() { setIdx(function(i) { return (i + 1) % n; }); }, 4800);
    return function() { clearInterval(t); };
  }, [paused]);

  var onTouchStart = function(e) { touchX.current = e.touches[0].clientX; };
  var onTouchEnd = function(e) {
    if (touchX.current === null) return;
    var dx = e.changedTouches[0].clientX - touchX.current;
    if (Math.abs(dx) > 50) { dx > 0 ? prev() : next(); }
    touchX.current = null;
  };

  // Layout math
  var ready = stageW > 0;
  var GAP = 14;
  var PEEK = !ready ? 0 : (stageW > 760 ? 64 : stageW > 520 ? 48 : 28);
  var SHAD_PAD = stageW > 760 ? 46 : 36;  // vertical room so the slide shadow isn't clipped
  var slideW = !ready ? 0 : stageW - 2 * PEEK;
  // Active slide always starts at x=PEEK from the left edge
  var trackOffset = !ready ? 0 : PEEK - idx * (slideW + GAP);

  var s = CAROUSEL_SLIDES[idx];

  return (
    React.createElement('section', { className: 'v-car-section', 'data-screen-label': '03 Carousel' },
      React.createElement('div', { className: 'v-wrap' },

        // Header
        React.createElement('div', { className: 'v-car-header' },
          React.createElement('span', { className: 'v-eyebrow' },
            React.createElement('span', { className: 'dot' }), 'Funcionalidades'
          ),
          React.createElement('h2', null,
            'Un panel. ',
            React.createElement('span', { className: 'v-gradient-text' }, 'Todas las herramientas.')
          )
        ),

        // Carousel outer (overflow: hidden INLINE so it cannot be overridden)
        React.createElement('div', {
          ref: outerRef,
          style: { overflow: 'hidden', position: 'relative', paddingTop: SHAD_PAD + 'px', paddingBottom: SHAD_PAD + 'px' },
          onMouseEnter: function() { setPaused(true); },
          onMouseLeave: function() { setPaused(false); },
          onTouchStart: onTouchStart,
          onTouchEnd: onTouchEnd,
        },

          // Sliding track
          React.createElement('div', {
            style: {
              display: 'flex',
              gap: GAP + 'px',
              transform: 'translateX(' + trackOffset + 'px)',
              transition: ready ? 'transform 0.5s cubic-bezier(0.4,0,0.2,1)' : 'none',
              willChange: 'transform',
              userSelect: 'none',
              WebkitUserSelect: 'none',
              alignItems: 'flex-start',
            }
          },
            CAROUSEL_SLIDES.map(function(sl, i) {
              var isActive = i === idx;
              return React.createElement('div', {
                key: i,
                className: 'v-car-slide' + (isActive ? ' active' : ''),
                style: {
                  flexShrink: 0,
                  width: ready ? slideW + 'px' : '100%',
                  transition: 'opacity 0.4s, transform 0.4s, box-shadow 0.4s',
                  opacity: isActive ? 1 : 0.42,
                  transform: isActive ? 'scale(1) translateY(0)' : 'scale(0.95) translateY(8px)',
                  boxShadow: isActive ? '0 6px 34px rgba(0,0,0,0.22)' : 'none',
                  borderRadius: '16px',
                  overflow: 'hidden',
                  pointerEvents: isActive ? 'auto' : 'none',
                }
              },
                React.createElement('img', {
                  src: sl.img,
                  alt: sl.title,
                  className: 'v-car-img',
                  loading: i === 0 ? 'eager' : 'lazy',
                  draggable: 'false',
                  style: { display: 'block', width: '100%' },
                })
              );
            })
          ),

          // Edge fades (left)
          React.createElement('div', {
            style: {
              position: 'absolute', top: 0, left: 0, bottom: 0,
              width: PEEK + 'px',
              background: 'linear-gradient(to right, var(--v-bg) 35%, transparent)',
              pointerEvents: 'none',
              zIndex: 4,
            }
          }),

          // Edge fades (right)
          React.createElement('div', {
            style: {
              position: 'absolute', top: 0, right: 0, bottom: 0,
              width: PEEK + 'px',
              background: 'linear-gradient(to left, var(--v-bg) 35%, transparent)',
              pointerEvents: 'none',
              zIndex: 4,
            }
          }),

          // Left arrow
          React.createElement('button', {
            className: 'v-car-arrow v-car-arrow--l',
            style: { zIndex: 10 },
            onClick: prev,
            'aria-label': 'Anterior',
          },
            React.createElement('svg', { viewBox: '0 0 24 24', fill: 'none', width: '20', height: '20' },
              React.createElement('path', { d: 'M15 18l-6-6 6-6', stroke: 'currentColor', strokeWidth: '2.5', strokeLinecap: 'round', strokeLinejoin: 'round' })
            )
          ),

          // Right arrow
          React.createElement('button', {
            className: 'v-car-arrow v-car-arrow--r',
            style: { zIndex: 10 },
            onClick: next,
            'aria-label': 'Siguiente',
          },
            React.createElement('svg', { viewBox: '0 0 24 24', fill: 'none', width: '20', height: '20' },
              React.createElement('path', { d: 'M9 18l6-6-6-6', stroke: 'currentColor', strokeWidth: '2.5', strokeLinecap: 'round', strokeLinejoin: 'round' })
            )
          )
        ),

        // Caption below the image (separate from the card, centered, soft tone)
        React.createElement('div', { className: 'v-car-caption', key: idx },
          React.createElement('strong', null, s.title),
          React.createElement('p', null, s.desc)
        ),

        // Dots row
        React.createElement('div', { className: 'v-car-dots', role: 'tablist', 'aria-label': 'Pantallas' },
          CAROUSEL_SLIDES.map(function(_, i) {
            return React.createElement('button', {
              key: i,
              role: 'tab',
              'aria-selected': i === idx,
              className: 'v-car-dot' + (i === idx ? ' active' : ''),
              onClick: function() { setIdx(i); setPaused(true); },
              'aria-label': 'Pantalla ' + (i + 1),
            });
          })
        )
      )
    )
  );
}

window.V2ScrollScene = V2ScrollScene;
