// Draggable before/after slider — mouse + touch.
// Bottom layer = viewport (input), top layer = render (output) clipped to handle position.

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

function BeforeAfter({ inputSrc, outputSrc, height = 620, initial = 50, glow = true }) {
  const { IconChevronLeft, IconChevronRight } = window.Icons;
  const [pct, setPct] = useState(initial);
  const [dragging, setDragging] = useState(false);
  const frameRef = useRef(null);

  const updateFromClientX = useCallback((clientX) => {
    const el = frameRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const x = clientX - rect.left;
    const next = Math.max(0, Math.min(100, (x / rect.width) * 100));
    setPct(next);
  }, []);

  useEffect(() => {
    if (!dragging) return;
    const onMove = (e) => {
      const cx = e.touches ? e.touches[0].clientX : e.clientX;
      updateFromClientX(cx);
      if (e.cancelable) e.preventDefault();
    };
    const onUp = () => setDragging(false);
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    window.addEventListener("touchmove", onMove, { passive: false });
    window.addEventListener("touchend", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
      window.removeEventListener("touchmove", onMove);
      window.removeEventListener("touchend", onUp);
    };
  }, [dragging, updateFromClientX]);

  const start = (e) => {
    setDragging(true);
    const cx = e.touches ? e.touches[0].clientX : e.clientX;
    updateFromClientX(cx);
  };

  // Label fade-out as handle approaches
  const leftFade = Math.max(0, Math.min(1, (pct - 8) / 14));
  const rightFade = Math.max(0, Math.min(1, (92 - pct) / 14));

  return (
    <div className="relative" style={{ width: "100%" }}>
      {glow && (
        <div
          aria-hidden
          className="absolute inset-0 pointer-events-none"
          style={{
            background:
              "radial-gradient(60% 55% at 50% 55%, rgba(29,158,117,0.18) 0%, rgba(29,158,117,0.04) 45%, rgba(29,158,117,0) 75%)",
            transform: "scale(1.25)",
            filter: "blur(20px)",
          }}
        />
      )}
      <div
        ref={frameRef}
        className="relative w-full overflow-hidden select-none"
        style={{
          height,
          borderRadius: 14,
          border: "0.6px solid #D0D0D0",
          background: "#0e0e0e",
          cursor: dragging ? "ew-resize" : "default",
        }}
        onMouseDown={start}
        onTouchStart={start}
      >
        {/* Bottom: viewport */}
        <img
          src={inputSrc}
          alt="SketchUp viewport"
          className="absolute inset-0 w-full h-full object-cover"
          draggable={false}
        />
        {/* Top: render, clipped to handle */}
        <div
          className="absolute inset-0 overflow-hidden"
          style={{ width: `${pct}%` }}
        >
          <img
            src={outputSrc}
            alt="Photoreal AI render"
            className="absolute inset-0 h-full object-cover"
            style={{ width: `${10000 / pct}%`, maxWidth: "none" }}
            draggable={false}
          />
        </div>

        {/* Labels */}
        <div
          className="absolute bottom-4 left-4 text-[11px] tracking-wide text-white/90 px-2.5 py-1.5"
          style={{
            background: "rgba(0,0,0,0.45)",
            backdropFilter: "blur(8px)",
            borderRadius: 999,
            border: "0.6px solid rgba(255,255,255,0.18)",
            opacity: rightFade,
            transition: "opacity 120ms linear",
            pointerEvents: "none",
          }}
        >
          Render
        </div>
        <div
          className="absolute bottom-4 right-4 text-[11px] tracking-wide text-white/90 px-2.5 py-1.5"
          style={{
            background: "rgba(0,0,0,0.45)",
            backdropFilter: "blur(8px)",
            borderRadius: 999,
            border: "0.6px solid rgba(255,255,255,0.18)",
            opacity: leftFade,
            transition: "opacity 120ms linear",
            pointerEvents: "none",
          }}
        >
          Viewport
        </div>

        {/* Handle */}
        <div
          className="absolute top-0 bottom-0"
          style={{
            left: `${pct}%`,
            width: 1,
            background: "rgba(255,255,255,0.95)",
            boxShadow: "0 0 0 0.5px rgba(0,0,0,0.2)",
            transform: "translateX(-0.5px)",
            pointerEvents: "none",
          }}
        >
          <div
            className="absolute left-1/2 top-1/2 flex items-center justify-center"
            style={{
              transform: "translate(-50%, -50%)",
              width: 44,
              height: 44,
              borderRadius: 999,
              background: "#1D9E75",
              color: "white",
              boxShadow:
                "0 8px 24px rgba(15,110,86,0.35), 0 0 0 4px rgba(255,255,255,0.9)",
              pointerEvents: "auto",
              cursor: "ew-resize",
            }}
            onMouseDown={start}
            onTouchStart={start}
          >
            <IconChevronLeft size={14} />
            <IconChevronRight size={14} />
          </div>
        </div>
      </div>
    </div>
  );
}

window.BeforeAfter = BeforeAfter;
