/* ZOOM PARALLAX — "Quiénes somos".
   Adapted from the framer-motion zoom-parallax pattern using native scroll
   and CSS transforms. As the user scrolls past a 300vh container, 7 images
   zoom outward at different rates from a central tile, revealing context
   layered around. We use IntersectionObserver + scroll listener to drive
   per-image scale. Lightweight, no external libs. */

const ZoomParallax = ({ images, t, lang = 'es', setActiveProduct }) => {
  const containerRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const onScroll = () => {
      if (!containerRef.current) return;
      const rect = containerRef.current.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / total));
      setProgress(p);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Same scale curves as original component
  const scales = [4, 5, 6, 5, 6, 8, 9];

  // Per-index positioning (mirrors framer version)
  const positions = [
    { top: '0', left: '0', width: '25vw', height: '25vh' }, // center default
    { top: '-30vh', left: '5vw', width: '35vw', height: '30vh' },
    { top: '-10vh', left: '-25vw', width: '20vw', height: '45vh' },
    { top: '0', left: '27.5vw', width: '25vw', height: '25vh' },
    { top: '27.5vh', left: '5vw', width: '20vw', height: '25vh' },
    { top: '27.5vh', left: '-22.5vw', width: '30vw', height: '25vh' },
    { top: '22.5vh', left: '25vw', width: '15vw', height: '15vh' },
  ];

  return (
    <section id="nosotros" style={{ background: 'var(--bg)', position: 'relative' }}>
      {/* Intro panel */}
      <div className="wrap" style={{ paddingTop: 'clamp(80px, 12vw, 160px)', paddingBottom: 64 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 24 }}>
          <span className="eyebrow">{t('— 01 / Quiénes somos', '— 01 / Who we are')}</span>
          <h2 className="display display-lg" style={{ maxWidth: '14ch', textWrap: 'balance' }}>
            {t('Más de tres décadas haciéndolo todo en metal.', '30+ years doing everything in metal.')}
          </h2>
          <p style={{ fontSize: 18, color: 'var(--ink-2)', maxWidth: 720, lineHeight: 1.6 }}>
            {t(
              'AceroLab es una planta de fabricación metálica en Tlalnepantla, Estado de México, operando desde 1992. Trabajamos B2B, B2C y gobierno: cadenas de restaurantes, retail, despachos de arquitectura, operadores de espacio público y proyectos residenciales premium. Si tiene metal, lo hacemos. Hemos fabricado para Telmex, Chili\'s, Cheesecake Factory, Toks y el Gobierno de la Ciudad de México, entre otros. Visitas a planta bienvenidas.',
              "AceroLab is a metal fabrication plant in Tlalnepantla, Estado de México, operating since 1992. We work B2B, B2C and government: restaurant chains, retail, architecture firms, public-space operators and premium residential. If it has metal, we make it. We have built for Telmex, Chili's, Cheesecake Factory, Toks and the Mexico City Government, among others. Plant visits welcome."
            )}
          </p>
          <p className="mono" style={{ color: 'var(--ink-3)', marginTop: 8 }}>
            {t('Desplaza ↓ ', 'Scroll ↓ ')}
            <span style={{ color: 'var(--ink-4)' }}>
              {t('para conocer la planta', 'to meet the plant')}
            </span>
          </p>
        </div>
      </div>

      {/* Parallax stage — 300vh tall */}
      <div ref={containerRef} style={{ position: 'relative', height: '300vh' }}>
        <div style={{
          position: 'sticky',
          top: 0,
          height: '100vh',
          overflow: 'hidden',
          background: 'var(--bg-1)',
        }}>
          {images.map((img, idx) => {
            const scale = 1 + (scales[idx % scales.length] - 1) * progress;
            const pos = positions[idx];
            const src = typeof img === 'string' ? img : img.src;
            const data = window.productData?.[src];
            const pick = (field) => (typeof field === 'string' ? field : (field && (field[lang] || field.es)) || '');
            const isCentral = idx === 0;
            return (
              <div
                key={idx}
                style={{
                  position: 'absolute',
                  top: 0, left: 0,
                  width: '100%', height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transform: `scale(${scale})`,
                  willChange: 'transform',
                }}
              >
                <div style={{
                  position: 'relative',
                  width: pos.width,
                  height: pos.height,
                  top: pos.top,
                  left: pos.left,
                  cursor: isCentral && setActiveProduct ? 'pointer' : 'default',
                }}
                  onClick={isCentral && setActiveProduct ? () => setActiveProduct(src) : undefined}
                >
                  <img
                    src={src}
                    alt={data ? pick(data.title) : (typeof img === 'string' ? '' : (img.alt || ''))}
                    style={{
                      width: '100%', height: '100%',
                      objectFit: 'cover',
                      filter: 'contrast(1.05) saturate(0.85)',
                    }}
                  />
                  {/* Overlay info on the central image */}
                  {isCentral && (
                    <div style={{
                      position: 'absolute',
                      bottom: 12, left: 12, right: 12,
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'flex-end',
                      pointerEvents: 'none',
                      opacity: Math.max(0, 1 - progress * 2),
                    }}>
                      <span style={{
                        fontFamily: 'var(--mono)',
                        fontSize: 9,
                        color: '#fff',
                        background: 'rgba(0,0,0,0.7)',
                        padding: '4px 8px',
                        letterSpacing: '0.1em',
                        maxWidth: '70%',
                        textOverflow: 'ellipsis',
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                      }}>
                        {data ? `${pick(data.category).toUpperCase()} · ${pick(data.title)}` : 'AL · CDMX · 19.4326°N'}
                      </span>
                      <span style={{
                        fontFamily: 'var(--mono)',
                        fontSize: 9,
                        color: '#fff',
                        background: 'rgba(255,106,31,0.92)',
                        padding: '4px 8px',
                        letterSpacing: '0.1em',
                      }}>
                        {data?.measures || 'REC · 30Y'}
                      </span>
                    </div>
                  )}
                </div>
              </div>
            );
          })}

          {/* Caption that fades as you scroll */}
          <div style={{
            position: 'absolute',
            bottom: 32,
            left: 0, right: 0,
            textAlign: 'center',
            opacity: Math.max(0, 1 - progress * 3),
            pointerEvents: 'none',
            zIndex: 5,
          }}>
            <span className="mono" style={{ color: '#fff', background: 'rgba(0,0,0,0.5)', padding: '6px 12px', fontSize: 11 }}>
              {t('PLANTA · TLALNEPANTLA · EDOMEX', 'PLANT · TLALNEPANTLA · EDOMEX')}
            </span>
          </div>
        </div>
      </div>

      {/* Outro stats — appears after the zoom */}
      <div className="wrap" style={{ paddingTop: 64, paddingBottom: 'clamp(60px, 8vw, 120px)' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
          gap: 1,
          background: 'var(--hairline)',
          border: '1px solid var(--hairline)',
        }}>
          {[
            { k: 'B2B', v: t('Exclusivamente', 'Exclusively') },
            { k: 'EDOMEX', v: t('Planta propia', 'Own plant') },
            { k: 'T304/T316', v: t('Inox calidad alimenticia', 'Food-grade stainless') },
            { k: '8 procesos', v: t('Bajo un mismo techo', 'Under one roof') },
          ].map((s, i) => (
            <div key={i} style={{ background: 'var(--bg)', padding: 24 }}>
              <div className="display" style={{ fontSize: 22, marginBottom: 8 }}>{s.k}</div>
              <div className="mono" style={{ color: 'var(--ink-3)', fontSize: 10, textTransform: 'uppercase' }}>{s.v}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

window.ZoomParallax = ZoomParallax;
