/* global React */
const { useState, useRef, useCallback, useEffect } = React;

// Before/After slider. Pass `beforeSrc` / `afterSrc` for real images,
// or omit for labeled placeholder panels.
function BeforeAfter({
  beforeSrc,
  afterSrc,
  beforeLabel = "BEFORE",
  afterLabel = "AFTER",
  beforeNote = "Dim, wide-angle, cluttered",
  afterNote = "Bright, balanced, listing-ready",
  aspect = "16 / 10",
  initial = 50,
  rounded = true,
}) {
  const [pct, setPct] = useState(initial);
  const wrapRef = useRef(null);
  const draggingRef = useRef(false);

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

  useEffect(() => {
    const onMove = (e) => {
      if (!draggingRef.current) return;
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      handleMove(x);
      if (e.cancelable) e.preventDefault();
    };
    const onUp = () => { draggingRef.current = 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);
    };
  }, [handleMove]);

  const startDrag = (e) => {
    draggingRef.current = true;
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    handleMove(x);
  };

  const onKey = (e) => {
    if (e.key === "ArrowLeft") setPct((p) => Math.max(0, p - 2));
    if (e.key === "ArrowRight") setPct((p) => Math.min(100, p + 2));
  };

  return (
    <div
      ref={wrapRef}
      className="ba-wrap"
      style={{
        aspectRatio: aspect,
        borderRadius: rounded ? "var(--radius-lg)" : 0,
      }}
      onMouseDown={startDrag}
      onTouchStart={startDrag}
    >
      {/* AFTER (full) */}
      <div className="ba-layer ba-after">
        {afterSrc ? (
          <img src={afterSrc} alt="After" draggable="false" loading="lazy" decoding="async" />
        ) : (
          <Placeholder tone="after" label={afterLabel} note={afterNote} />
        )}
      </div>

      {/* BEFORE (clipped) */}
      <div className="ba-layer ba-before" style={{ clipPath: `inset(0 ${100 - pct}% 0 0)` }}>
        {beforeSrc ? (
          <img src={beforeSrc} alt="Before" draggable="false" loading="lazy" decoding="async" />
        ) : (
          <Placeholder tone="before" label={beforeLabel} note={beforeNote} />
        )}
      </div>

      {/* labels */}
      <div className="ba-tag ba-tag-before" style={{ opacity: pct > 12 ? 1 : 0 }}>{beforeLabel}</div>
      <div className="ba-tag ba-tag-after" style={{ opacity: pct < 88 ? 1 : 0 }}>{afterLabel}</div>

      {/* divider + handle */}
      <div className="ba-divider" style={{ left: `${pct}%` }} aria-hidden="true" />
      <button
        type="button"
        className="ba-handle"
        style={{ left: `${pct}%` }}
        onKeyDown={onKey}
        aria-label="Drag to compare before and after"
        aria-valuenow={Math.round(pct)}
        aria-valuemin={0}
        aria-valuemax={100}
        role="slider"
      >
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
          <path d="M7 5L3 10L7 15" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          <path d="M13 5L17 10L13 15" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
    </div>
  );
}

function Placeholder({ tone, label, note }) {
  const isBefore = tone === "before";
  return (
    <div className={`ph ph-${tone}`}>
      <div className="ph-stripes" />
      <div className="ph-meta">
        <div className="ph-label">{label}</div>
        <div className="ph-note">{note}</div>
        <div className="ph-dims">[ photo placeholder · 1600 × 1000 ]</div>
      </div>
      {isBefore && <div className="ph-grain" />}
    </div>
  );
}

window.BeforeAfter = BeforeAfter;
