// Gallery.jsx — Results grid + Before/After slider + Differentials

let ALL_ITEMS = [];
const FILTERS = ["Todos", "Design Natural", "Henna e Tintura", "Brow Lamination", "Lash Lifting"];

// Fetch dynamic data if available
fetch('api.php')
  .then(res => res.json())
  .then(data => {
    const results = [
      ...(data.design || []),
      ...(data.brow || []),
      ...(data.henna || [])
    ];
    const lash = data.lash || [];
    ALL_ITEMS = [...results, ...lash];
  })
  .catch(err => {
    console.log("Using fallback static data.");
    const RESULTS = [
      { src: "https://imagedelivery.net/mYdfeAeRRdkIXG5w7XJhtQ/724fce1a-bbec-4f69-6dcd-324211594d00/public", label: "Design Natural" },
      { src: "https://imagedelivery.net/mYdfeAeRRdkIXG5w7XJhtQ/e6091403-28a5-4e71-8834-5841bf3b6600/public", label: "Brow Lamination", span: true },
      { src: "https://imagedelivery.net/mYdfeAeRRdkIXG5w7XJhtQ/1738ec87-9e58-4aff-be33-1fead70eef00/public", label: "Henna" }
    ];
    ALL_ITEMS = RESULTS;
  });

/* ── Before/After Slider ─────────────────────────── */
function BeforeAfter({ before, after }) {
  const [pos, setPos] = React.useState(50);
  const containerRef = React.useRef(null);
  const dragging = React.useRef(false);

  const updatePos = React.useCallback((clientX) => {
    const rect = containerRef.current.getBoundingClientRect();
    const x = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
    setPos(x * 100);
  }, []);

  const onMouseDown = (e) => { dragging.current = true; updatePos(e.clientX); };
  const onMouseMove = (e) => { if (dragging.current) updatePos(e.clientX); };
  const onMouseUp = () => { dragging.current = false; };
  const onTouchStart = (e) => { dragging.current = true; updatePos(e.touches[0].clientX); };
  const onTouchMove = (e) => { if (dragging.current) updatePos(e.touches[0].clientX); };
  const onTouchEnd = () => { dragging.current = false; };

  React.useEffect(() => {
    window.addEventListener("mouseup", onMouseUp);
    window.addEventListener("mousemove", onMouseMove);
    window.addEventListener("touchend", onTouchEnd);
    window.addEventListener("touchmove", onTouchMove, { passive: true });
    return () => {
      window.removeEventListener("mouseup", onMouseUp);
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("touchend", onTouchEnd);
      window.removeEventListener("touchmove", onTouchMove);
    };
  }, []);

  return (
    <div
      ref={containerRef}
      className="ba-slider-wrap"
      style={{ height: 520, position: "relative" }}
      onMouseDown={onMouseDown}
      onTouchStart={onTouchStart}>

      {/* After (Background) */}
      <div className="ba-before" style={{ zIndex: 1 }}>
        <img src={after} alt="Depois" style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center center" }} />
        <div className="ba-after-label">Depois</div>
      </div>

      {/* Before (Clipped on top) */}
      <div className="ba-after" style={{ width: `${pos}%`, zIndex: 2 }}>
        <img src={before} alt="Antes" style={{ width: containerRef.current ? containerRef.current.offsetWidth + "px" : "720px", height: "100%", objectFit: "cover", objectPosition: "center 72%", maxWidth: "none" }} />
        <div className="ba-before-label">Antes</div>
      </div>

      {/* Handle */}
      <div className="ba-handle" style={{ left: `${pos}%`, transform: "translateX(-50%)", zIndex: 10 }}>
        <div className="ba-handle-circle">
          <span style={{ display: "flex", alignItems: "center", gap: 2 }}>
            <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor">
              <path d="M3 1L0 5L3 9M7 1L10 5L7 9" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round" />
            </svg>
          </span>
        </div>
      </div>
    </div>);

}

/* ── Gallery ─────────────────────────────────────── */
function Gallery() {
  const [items, setItems] = React.useState(ALL_ITEMS);

  React.useEffect(() => {
    fetch('api.php')
      .then(res => res.json())
      .then(data => {
        const results = [
          ...(data.design || []),
          ...(data.brow || []),
          ...(data.henna || [])
        ];
        const lash = data.lash || [];
        setItems([...results, ...lash].slice(0, 9)); // Show some items
      })
      .catch(err => {
        setItems(ALL_ITEMS);
      });
  }, []);

  return (
    <section id="results">
      <div className="container">
        {/* Before / After */}
        <div className="ba-section">
          <div className="ba-title">
            <div className="eyebrow reveal" style={{ justifyContent: "center", marginBottom: 16 }}>Transformação</div>
            <h3 className="section-title reveal d1" style={{ fontSize: "clamp(24px,3vw,38px)" }}>
              Antes e <span className="hl" style={{ fontSize: "45px" }}>depois</span>
            </h3>
            <p className="section-sub reveal d2" style={{ marginBottom: 40 }}>
              Arraste para ver a diferença que um design preciso faz.
            </p>
          </div>
          <div className="reveal d3">
            <BeforeAfter
              before="https://imagedelivery.net/mYdfeAeRRdkIXG5w7XJhtQ/5e7a84f2-7539-433d-c0e6-f43f9cce5900/public"
              after="https://imagedelivery.net/mYdfeAeRRdkIXG5w7XJhtQ/e6091403-28a5-4e71-8834-5841bf3b6600/public" />

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

}

/* ── Differentials ───────────────────────────────── */
const DIFFS = [
  { title: "Atendimento cuidadoso", desc: "Cada cliente recebe atenção personalizada do início ao fim do procedimento." },
  { title: "Foco total na qualidade", desc: "Resultado impecável em cada serviço, sem pressa e sem concessões." },
  { title: "Design para cada rosto", desc: "Nenhum design é igual. Cada traçado é pensado para a sua fisionomia." },
  { title: "Técnicas atualizadas", desc: "Constante aperfeiçoamento com as melhores técnicas do mercado." },
  { title: "Ambiente acolhedor", desc: "Um espaço pensado para você se sentir bem e à vontade." },
  { title: "Resultado natural", desc: "Beleza sem exagero — sobrancelhas que parecem sempre suas." }];


function Differentials() {
  return (
    <section id="differentials">
      <div className="container">
        <div className="diff-grid">
          <div className="diff-text">
            <div className="eyebrow reveal">Por que a Essenza Glow</div>
            <div className="gold-line reveal d1" style={{ marginTop: 20, marginBottom: 24 }} />
            <h2 className="section-title reveal d2" style={{ textAlign: "left", margin: 0 }}>
              O detalhe<br />
              <span className="hl" style={{ fontSize: "45px" }}>muda tudo.</span>
            </h2>
            <div className="diff-list">
              {DIFFS.map((d, i) =>
                <div className={`diff-item reveal d${Math.min(i + 1, 6)}`} key={d.title}>
                  <div className="diff-dot" />
                  <div>
                    <div className="diff-item-title">{d.title}</div>
                    <div className="diff-item-desc">{d.desc}</div>
                  </div>
                </div>
              )}
            </div>
          </div>

          <div className="diff-img-wrap reveal-right d2">
            <img
              src="https://imagedelivery.net/mYdfeAeRRdkIXG5w7XJhtQ/d3aecb59-88df-4dba-c0c8-06cf39c0ed00/public"
              alt="Resultado Essenza Glow"
              className="diff-photo" />

            <div className="diff-frame" />
          </div>
        </div>
      </div>
    </section>);

}

Object.assign(window, { Gallery, Differentials });