function BeforeAfterSlider() {
  const { t } = window.useT();
  const [pos, setPos] = React.useState(50);
  const containerRef = React.useRef(null);
  const dragging = React.useRef(false);

  const updatePos = (clientX) => {
    if (!containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
    setPos((x / rect.width) * 100);
  };

  React.useEffect(() => {
    const onMove = (e) => { if (dragging.current) updatePos(e.clientX); };
    const onUp   = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
  }, []);

  return (
    <div ref={containerRef} className="ba-slider"
      onTouchStart={(e) => updatePos(e.touches[0].clientX)}
      onTouchMove={(e) => updatePos(e.touches[0].clientX)}
    >
      <img className="ba-img" src="assets/tot-3.webp" alt={t('stack.ba.after')} draggable="false" loading="lazy" />
      <img className="ba-img" src="assets/lebend-3.webp" alt={t('stack.ba.before')} draggable="false" loading="lazy"
        style={{ clipPath: `inset(0 ${(100 - pos).toFixed(1)}% 0 0)` }} />
      <div className="ba-handle" style={{ left: `${pos}%` }}
        onMouseDown={(e) => { dragging.current = true; e.preventDefault(); }}>
        <div className="ba-line" />
        <div className="ba-knob">
          <svg viewBox="0 0 32 16" width="28" height="14" fill="none">
            <path d="M11 2L4 8L11 14M21 2L28 8L21 14" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
      <div style={{ position:'absolute', inset:0, clipPath:`polygon(0 0,${pos}% 0,${pos}% 100%,0 100%)`, pointerEvents:'none', zIndex:5 }}>
        <span className="ba-label ba-label--l">{t('stack.ba.before')}</span>
      </div>
      <div style={{ position:'absolute', inset:0, clipPath:`polygon(${pos}% 0,100% 0,100% 100%,${pos}% 100%)`, pointerEvents:'none', zIndex:5 }}>
        <span className="ba-label ba-label--r">{t('stack.ba.after')}</span>
      </div>
    </div>
  );
}

function StackCards() {
  const { t } = window.useT();

  const CARDS = [
    {
      icon: 'shield',
      title: t('stack.card1.title'),
      features: [t('stack.card1.f1'), t('stack.card1.f2'), t('stack.card1.f3')],
    },
    {
      icon: 'hands',
      title: t('stack.card2.title'),
      features: [t('stack.card2.f1'), t('stack.card2.f2'), t('stack.card2.f3')],
    },
    {
      icon: 'pulse',
      title: t('stack.card3.title'),
      features: [t('stack.card3.f1'), t('stack.card3.f2'), t('stack.card3.f3')],
    },
  ];

  React.useEffect(() => {
    const cards = Array.from(document.querySelectorAll('.stack-card'));
    if (!cards.length) return;

    const onScroll = () => {
      for (let i = 0; i < cards.length; i++) {
        const card = cards[i];
        const next = cards[i + 1];
        if (!next) {
          card.style.transform = '';
          card.style.opacity = '';
          continue;
        }
        const cardRect = card.getBoundingClientRect();
        const nextRect = next.getBoundingClientRect();
        const nextStickyTop = parseFloat(getComputedStyle(next).top) || 0;
        const travel = cardRect.height;
        const distance = nextRect.top - nextStickyTop;
        let p = 1 - distance / travel;
        p = Math.max(0, Math.min(1, p));

        const scale = 1 - p * 0.08;
        const translateY = -p * 24;

        const fadeStart = 0.6;
        let opacity = 1;
        if (p > fadeStart) {
          opacity = 1 - (p - fadeStart) / (1 - fadeStart);
        }
        opacity = Math.max(0, Math.min(1, opacity));

        card.style.transform = `translateY(${translateY}px) scale(${scale})`;
        card.style.opacity = String(opacity);
      }
    };

    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    <section className="stack-section" id="about">
      <div className="stack-wrapper">
        {CARDS.map((card, i) => (
          <article className="stack-card" data-index={i} key={i}>
            <div className="card-left">
              <div className="card-head">
                <div className="card-icon card-icon-bare">{window.Icons[card.icon]}</div>
              </div>
              <h3>{card.title}</h3>
              <ul className="card-features">
                {card.features.map((f, j) => (
                  <li key={j}>
                    <svg className="feat-check" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                      <circle cx="10" cy="10" r="9" fill="currentColor" opacity="0.15"/>
                      <path d="M6 10.5 L9 13.5 L14.5 7.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    <span>{f}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div className="card-right">
              {i === 0 ? (
                <BeforeAfterSlider />
              ) : (
                <div className={`card-anim card-anim-${i}`}>
                  <div className="bubbles" aria-hidden="true">
                    {Array.from({ length: 6 }).map((_, k) => (
                      <span key={k} className="bubble" style={{
                        '--x': `${Math.random() * 100}%`,
                        '--size': `${12 + Math.random() * 48}px`,
                        '--delay': `${Math.random() * 6}s`,
                        '--dur': `${6 + Math.random() * 6}s`,
                        '--drift': `${(Math.random() - 0.5) * 40}px`,
                        '--opacity': `${0.25 + Math.random() * 0.35}`,
                      }} />
                    ))}
                  </div>
                  {i === 1 && (
                    <img
                      className="card-mouthpiece"
                      src="assets/mouthpiece_mit_grid.webp"
                      alt=""
                      aria-hidden="true"
                    />
                  )}
                  {i === 2 && (
                    <img
                      className="card-phone-mockup"
                      src="assets/iphone-mockup.webp"
                      alt=""
                      aria-hidden="true"
                      style={{ transform: 'translateX(-50%)' }}
                    />
                  )}
                </div>
              )}
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

window.StackCards = StackCards;
