// ═══════════════════════════════════════════════════════════════════
// src/sections/BeforeAfter.jsx
// Interactive drag-to-compare before/after slider.
// All drag/touch logic is self-contained in this file.
// ═══════════════════════════════════════════════════════════════════

const { useState, useEffect, useRef, useCallback } = React;

function BeforeAfter() {
  const [pos, setPos]   = useState(50);
  const ref             = useRef(null);
  const dragging        = useRef(false);

  // Clamp pointer X to a percentage of the slider width
  const posFromClientX = useCallback((clientX) => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    const pct  = Math.max(2, Math.min(98, ((clientX - rect.left) / rect.width) * 100));
    setPos(pct);
  }, []);

  // Attach global move/up listeners so dragging outside the element still works
  useEffect(() => {
    const onMove = (e) => {
      if (!dragging.current) return;
      posFromClientX(e.clientX ?? e.touches?.[0]?.clientX);
    };
    const onUp = () => { dragging.current = false; };

    window.addEventListener("mousemove",  onMove);
    window.addEventListener("mouseup",    onUp);
    window.addEventListener("touchmove",  onMove, { passive: true });
    window.addEventListener("touchend",   onUp);
    return () => {
      window.removeEventListener("mousemove",  onMove);
      window.removeEventListener("mouseup",    onUp);
      window.removeEventListener("touchmove",  onMove);
      window.removeEventListener("touchend",   onUp);
    };
  }, [posFromClientX]);

  const onDragStart = (e) => {
    dragging.current = true;
    posFromClientX(e.clientX ?? e.touches?.[0]?.clientX);
  };

  const clipRight = `inset(0 0 0 ${pos}%)`;

  return (
    <section id="antes-depois" className="section">
      <div className="container">
        <div className="ba-wrap">

          {/* ── Copy ── */}
          <div className="ba-meta reveal">
            <div className="eyebrow" style={{ marginBottom: "16px" }}>Antes e depois</div>
            <h3 className="display">
              Resultados reais.<br/><em>Sorrisos transformados.</em>
            </h3>
            <p className="lede" style={{ marginTop: "16px", fontSize: "18px" }}>
              Arraste o controle para comparar a transformação.
              Cada caso é único — o seu também será.
            </p>
            <ul>
              <li><Icon.check/> Mais de 2.400 transformações realizadas</li>
              <li><Icon.check/> Garantia de satisfação em todos os tratamentos</li>
              <li><Icon.check/> Acompanhamento pós-procedimento gratuito</li>
            </ul>
            <a href={CONTACT.waLink} className="btn btn-primary"
               style={{ marginTop: "36px" }}
               target="_blank" rel="noopener noreferrer">
              <Icon.whatsapp className="wa-icon"/> Quero meu plano de tratamento
            </a>
          </div>

          {/* ── Slider ── */}
          <div
            ref={ref}
            className="ba-slider reveal d1"
            onMouseDown={onDragStart}
            onTouchStart={onDragStart}
            role="img"
            aria-label="Comparação antes e depois do tratamento"
          >
            {/* Fallback gradient layers (shown if photos fail to load) */}
            <div className="side before"><span>antes</span></div>
            <div className="ba-after-clip" style={{ clipPath: clipRight }}>
              <div className="side after" style={{ position: "absolute", inset: 0 }}>
                <span>depois</span>
              </div>
            </div>

            {/* Photo layers on top */}
            <Photo src={PHOTOS.before} alt="Sorriso antes do tratamento"  className="photo before-photo"/>
            <div className="ba-after-clip" style={{ clipPath: clipRight }}>
              <Photo src={PHOTOS.after} alt="Sorriso depois do tratamento" className="photo after-photo"/>
            </div>

            <span className="label l">Antes</span>
            <span className="label r">Depois</span>

            <div className="ba-handle" style={{ left: pos + "%" }}>
              <div className="knob">
                <Icon.handle/>
              </div>
            </div>
          </div>

        </div>
      </div>
    </section>
  );
}
