/* ==========================================================================
   BeforeAfter.jsx | 07 Before & after
   Comparison slider with pointer dragging (mouse, pen, touch) and full
   keyboard support on the handle (role="slider"). Uses real job photos from
   MC_ASSETS when supplied; otherwise labelled placeholders, never fake results.
   ========================================================================== */

const MC_BA_PAIRS = [
  { id: 'kitchen', label: 'Kitchen', before: 'baKitchenBefore', after: 'baKitchenAfter' },
  { id: 'bathroom', label: 'Bathroom', before: 'baBathroomBefore', after: 'baBathroomAfter' },
  { id: 'living', label: 'Living area', before: 'baLivingBefore', after: 'baLivingAfter' },
];

/* Rooms with both photos are shown; until any pair has photos, all three
   rooms show their labelled placeholders. */
function mcBaVisiblePairs() {
  const withPhotos = MC_BA_PAIRS.filter((p) => MC_ASSETS.photos[p.before] && MC_ASSETS.photos[p.after]);
  return withPhotos.length ? withPhotos : MC_BA_PAIRS;
}

function MCBeforeAfter() {
  const baPairs = mcBaVisiblePairs();
  const [baPairId, setBaPairId] = React.useState(baPairs[0].id);
  const [baPos, setBaPos] = React.useState(50);
  const [baDragging, setBaDragging] = React.useState(false);
  const baFrameRef = React.useRef(null);
  const baPointerRef = React.useRef(null);

  const pair = baPairs.find((p) => p.id === baPairId) || baPairs[0];
  const realPhotos = Boolean(MC_ASSETS.photos[pair.before] && MC_ASSETS.photos[pair.after]);
  const illustrative = realPhotos && MC_CONFIG.beforeAfterIllustrative;
  const altPrefix = illustrative ? 'Illustrative image: ' : '';

  const clampPos = (value) => Math.min(100, Math.max(0, value));

  const setFromClientX = (clientX) => {
    const frame = baFrameRef.current;
    if (!frame) return;
    const rect = frame.getBoundingClientRect();
    if (!rect.width) return;
    setBaPos(clampPos(((clientX - rect.left) / rect.width) * 100));
  };

  const handlePointerDown = (event) => {
    if (event.button !== undefined && event.button !== 0) return;
    baPointerRef.current = event.pointerId;
    if (baFrameRef.current && baFrameRef.current.setPointerCapture) {
      try {
        baFrameRef.current.setPointerCapture(event.pointerId);
      } catch (err) {
        /* capture is optional */
      }
    }
    setFromClientX(event.clientX);
  };

  const handlePointerMove = (event) => {
    if (baPointerRef.current !== event.pointerId) return;
    if (!baDragging) setBaDragging(true);
    setFromClientX(event.clientX);
  };

  const endPointer = (event) => {
    if (baPointerRef.current !== event.pointerId) return;
    baPointerRef.current = null;
    setBaDragging(false);
  };

  const handleKeyDown = (event) => {
    const step = event.shiftKey ? 10 : 2;
    let next = null;
    switch (event.key) {
      case 'ArrowLeft':
      case 'ArrowDown':
        next = baPos - step;
        break;
      case 'ArrowRight':
      case 'ArrowUp':
        next = baPos + step;
        break;
      case 'PageDown':
        next = baPos - 10;
        break;
      case 'PageUp':
        next = baPos + 10;
        break;
      case 'Home':
        next = 0;
        break;
      case 'End':
        next = 100;
        break;
      default:
        break;
    }
    if (next !== null) {
      event.preventDefault();
      setBaPos(clampPos(next));
    }
  };

  const choosePair = (id) => {
    setBaPairId(id);
    setBaPos(50);
  };

  const rounded = Math.round(baPos);

  return (
    <section className="mc-section mc-ba" id="before-after" aria-labelledby="mc-ba-title">
      <div className="mc-wrap">
        <header className="mc-head" data-reveal>
          <MCEyebrow>See the difference</MCEyebrow>
          <h2 className="mc-h2" id="mc-ba-title">
            <span className="mc-phrase">A little before.</span> <span className="mc-phrase">A lot less dust.</span>
          </h2>
        </header>

        <div data-reveal>
          <div className="mc-ba__bar">
            <div className="mc-ba__pairs" role="group" aria-label="Choose a room">
              {baPairs.map((p) => (
                <button
                  key={p.id}
                  type="button"
                  className="mc-ba__pairbtn"
                  aria-pressed={p.id === baPairId}
                  onClick={() => choosePair(p.id)}
                >
                  {p.label}
                </button>
              ))}
            </div>
            <p className="mc-ba__hint" id="mc-ba-hint">
              Drag the handle, or focus it and use the arrow keys.
            </p>
          </div>

          <div
            ref={baFrameRef}
            className={`mc-ba__frame${baDragging ? ' is-dragging' : ''}`}
            style={{ '--pos': `${baPos}%` }}
            onPointerDown={handlePointerDown}
            onPointerMove={handlePointerMove}
            onPointerUp={endPointer}
            onPointerCancel={endPointer}
            onLostPointerCapture={endPointer}
            onDragStart={(event) => event.preventDefault()}
          >
            <div className="mc-ba__layer mc-ba__after">
              <MCImageSlot photoKey={pair.after} variant="after" align="end" sizes="(max-width: 760px) 100vw, 1240px" altPrefix={altPrefix} />
            </div>
            <div className="mc-ba__layer mc-ba__before">
              <MCImageSlot photoKey={pair.before} variant="before" align="top" sizes="(max-width: 760px) 100vw, 1240px" altPrefix={altPrefix} />
            </div>

            <span className="mc-ba__tag mc-ba__tag--before" style={{ opacity: baPos < 12 ? 0 : 1 }} aria-hidden="true">
              Before
            </span>
            <span className="mc-ba__tag mc-ba__tag--after" style={{ opacity: baPos > 88 ? 0 : 1 }} aria-hidden="true">
              After
            </span>

            {illustrative ? (
              <span className="mc-ba__badge" aria-hidden="true">
                Illustrative example
              </span>
            ) : null}

            <span className="mc-ba__divider" aria-hidden="true" />
            <div
              className="mc-ba__handle"
              role="slider"
              tabIndex={0}
              aria-label={`${pair.label}: before and after comparison`}
              aria-describedby="mc-ba-hint"
              aria-valuemin={0}
              aria-valuemax={100}
              aria-valuenow={rounded}
              aria-valuetext={`Showing ${rounded}% before, ${100 - rounded}% after`}
              aria-orientation="horizontal"
              onKeyDown={handleKeyDown}
            >
              <MCIcon name="arrows" />
            </div>
          </div>

          {realPhotos ? null : (
            <p className="mc-ba__note">
              <MCPh>Placeholder images: swap in real before-and-after photos from Dusty Cleaning jobs, taken from the same spot in similar light</MCPh>
            </p>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { MCBeforeAfter, mcBaVisiblePairs });
