// Before/After slider for refurbishment section.

const { useState, useRef, useEffect } = React;

function BeforeAfter({ before, after, beforeLabel = "Before", afterLabel = "After" }) {
  const [pos, setPos] = useState(50);
  const ref = useRef(null);
  const dragging = useRef(false);

  useEffect(() => {
    const onMove = (e) => {
      if (!dragging.current || !ref.current) return;
      const rect = ref.current.getBoundingClientRect();
      const x = (e.touches ? e.touches[0].clientX : e.clientX) - rect.left;
      const pct = Math.max(0, Math.min(100, (x / rect.width) * 100));
      setPos(pct);
    };
    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);
    };
  }, []);

  return (
    <div
      ref={ref}
      className="ba-slider"
      style={{ "--pos": pos + "%" }}
      onMouseDown={() => { dragging.current = true; }}
      onTouchStart={() => { dragging.current = true; }}
    >
      <div className="ba-layer" style={{ backgroundImage: `url(${before})` }} />
      <div className="ba-layer after" style={{ backgroundImage: `url(${after})` }} />
      <div className="ba-label before">{beforeLabel}</div>
      <div className="ba-label after">{afterLabel}</div>
      <div className="ba-handle">
        <div className="ba-handle-knob" aria-label="Drag to compare">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M6 3 L2 8 L6 13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M10 3 L14 8 L10 13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

window.BeforeAfter = BeforeAfter;
