// ─────────────────────────────────────────────────────────────────────────────
// WORLDLINESS — Before / After slider
// - Dedicated expand button (top-right of frame) opens fullscreen overlay
// - Fullscreen overlay has the same drag slider
// - Click on frame moves slider (not open lightbox — that's the expand btn)
// ─────────────────────────────────────────────────────────────────────────────

function BeforeAfter() {
  const [idx, setIdx]         = useState(0);
  const [pos, setPos]         = useState(50);
  const [fullscreen, setFullscreen] = useState(false);
  const frameRef    = useRef(null);
  const fsFrameRef  = useRef(null);
  const dragging    = useRef(false);
  const project     = window.BEFORE_AFTER[idx];

  const makeMove = (ref) => (clientX) => {
    const frame = ref.current;
    if (!frame) return;
    const r = frame.getBoundingClientRect();
    const p = ((clientX - r.left) / r.width) * 100;
    setPos(Math.max(0, Math.min(100, p)));
  };

  const moveInline   = makeMove(frameRef);
  const moveFullscreen = makeMove(fsFrameRef);

  // Shared global mouse/touch listeners for drag
  useEffect(() => {
    const activeMove = fullscreen ? moveFullscreen : moveInline;
    const onMove = (e) => {
      if (!dragging.current) return;
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      activeMove(x);
      if (e.cancelable) e.preventDefault();
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('touchmove', onMove, { passive: false });
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchend', onUp);
    };
  }, [fullscreen, moveInline, moveFullscreen]);

  // ESC closes fullscreen
  useEffect(() => {
    if (!fullscreen) return;
    const k = (e) => { if (e.key === 'Escape') setFullscreen(false); };
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, [fullscreen]);

  // Lock body scroll when fullscreen
  useEffect(() => {
    document.body.style.overflow = fullscreen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [fullscreen]);

  const onDown = (ref) => (e) => {
    dragging.current = true;
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    makeMove(ref)(x);
  };

  const SliderFrame = ({ ref: fRef, className = '' }) => (
    <div
      className={`ba-frame ${className}`}
      ref={fRef}
      style={{ '--pos': `${pos}%` }}
      onMouseDown={onDown(fRef)}
      onTouchStart={onDown(fRef)}
    >
      <img src={project.before} alt={`${project.label} — before`} draggable="false" />
      <img src={project.after}  alt={`${project.label} — after`}  className="ba-after" draggable="false" />
      <div className="ba-label before">Before</div>
      <div className="ba-label after">After</div>
      <div className="ba-handle" />
      <div className="ba-knob" />
    </div>
  );

  return (
    <section className="ba" id="work">
      <div className="container">
        <Reveal className="ba-head">
          <Eyebrow>Transformations</Eyebrow>
          <h2>See the before.<br/><em style={{fontStyle:'italic', fontWeight:500, color:'var(--bronze-light)'}}>Feel the after.</em></h2>
          <p>Drag the handle. Every project on this page is ours — start to finish, permits to paint. Full home renovations in Vancouver, Burnaby, Coquitlam, Richmond and across the Lower Mainland.</p>
        </Reveal>

        <Reveal>
          {/* Inline frame wrapper — relative so expand btn can sit inside */}
          <div className="ba-frame-wrap">
            <div
              className="ba-frame"
              ref={frameRef}
              style={{ '--pos': `${pos}%` }}
              onMouseDown={onDown(frameRef)}
              onTouchStart={onDown(frameRef)}
            >
              <img src={project.before} alt={`${project.label} — before`} draggable="false" />
              <img src={project.after}  alt={`${project.label} — after`}  className="ba-after" draggable="false" />
              <div className="ba-label before">Before</div>
              <div className="ba-label after">After</div>
              <div className="ba-handle" />
              <div className="ba-knob" />
            </div>

            {/* Expand button — clearly separate from slider interaction */}
            <button
              className="ba-expand-btn"
              onClick={() => setFullscreen(true)}
              aria-label="View fullscreen"
              title="Fullscreen"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M8 3H5a2 2 0 0 0-2 2v3M21 8V5a2 2 0 0 0-2-2h-3M3 16v3a2 2 0 0 0 2 2h3M16 21h3a2 2 0 0 0 2-2v-3"/>
              </svg>
              <span>Expand</span>
            </button>
          </div>

          <div className="ba-pager">
            {window.BEFORE_AFTER.map((p, i) => (
              <button key={i} className={`ba-dot ${i === idx ? 'active' : ''}`} onClick={() => { setIdx(i); setPos(50); }}>
                {p.label}
              </button>
            ))}
          </div>
          <div className="ba-footer">
            <p className="ba-hint">← Drag to reveal →</p>
            <a href="projects.html" className="btn btn-outline">
              View All Projects <Icon name="arrow" size={13} />
            </a>
          </div>
        </Reveal>
      </div>

      {/* ── Fullscreen overlay ── */}
      {fullscreen && (
        <div className="ba-fullscreen-overlay" onClick={(e) => { if (e.target.classList.contains('ba-fullscreen-overlay')) setFullscreen(false); }}>
          <div className="ba-fullscreen-inner">
            {/* Close button */}
            <button className="ba-fs-close" onClick={() => setFullscreen(false)} aria-label="Close fullscreen">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                <path d="M18 6 6 18M6 6l12 12"/>
              </svg>
            </button>

            {/* Label */}
            <div className="ba-fs-label">{project.label}</div>

            {/* Fullscreen slider */}
            <div
              className="ba-frame ba-frame-fs"
              ref={fsFrameRef}
              style={{ '--pos': `${pos}%` }}
              onMouseDown={onDown(fsFrameRef)}
              onTouchStart={onDown(fsFrameRef)}
            >
              <img src={project.before} alt={`${project.label} — before`} draggable="false" />
              <img src={project.after}  alt={`${project.label} — after`}  className="ba-after" draggable="false" />
              <div className="ba-label before">Before</div>
              <div className="ba-label after">After</div>
              <div className="ba-handle" />
              <div className="ba-knob" />
            </div>

            <p className="ba-fs-hint">← Drag to reveal · ESC to close</p>
          </div>
        </div>
      )}
    </section>
  );
}
window.BeforeAfter = BeforeAfter;
