// before-after.jsx — interactive workflow diagram with drag slider
const { useState: useStateBA, useRef: useRefBA, useEffect: useEffectBA } = React;

function BeforeAfter() {
  const isMobile = useIsMobile(640);
  const isMobileHeader = useIsMobile(640);
  const [pct, setPct] = useStateBA(50);
  const ref = useRefBA(null);
  const draggingRef = useRefBA(false);
  // Auto-animation state. The slider gently sweeps left/right on its
  // own (10s sweep window) so the comparison reads at a glance for
  // passive viewers. Any user interaction (mousedown/touchstart) sets
  // userActiveRef and pauses the animation; after 10s of no activity
  // we resume the auto-sweep where it left off.
  const userActiveRef = useRefBA(false);
  const lastInteractRef = useRefBA(0);
  const animStartRef = useRefBA(null);
  const rafRef = useRefBA(null);
  const visibleRef = useRefBA(false);
  const containerRef = useRefBA(null);

  const onPointer = (clientX) => {
    const r = ref.current.getBoundingClientRect();
    const x = Math.max(0, Math.min(r.width, clientX - r.left));
    setPct((x / r.width) * 100);
  };

  const markInteract = () => {
    userActiveRef.current = true;
    lastInteractRef.current = performance.now();
    animStartRef.current = null; // force re-sync when auto resumes
  };

  useEffectBA(() => {
    const onMove = (e) => {
      if (!draggingRef.current) return;
      onPointer(e.clientX ?? e.touches?.[0]?.clientX);
    };
    const onUp = () => { draggingRef.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('touchmove', onMove);
    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);
    };
  }, []);

  // Visibility tracking: only animate when the slider is actually on
  // screen, so we don't burn cycles when the user is elsewhere on the
  // page. Resets the animation phase when re-entering view so the
  // sweep always starts from a clean state.
  useEffectBA(() => {
    if (!containerRef.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        visibleRef.current = e.isIntersecting;
        if (e.isIntersecting) animStartRef.current = null;
      });
    }, { threshold: 0.2 });
    io.observe(containerRef.current);
    return () => io.disconnect();
  }, []);

  // Auto-sweep loop. Sine wave between ~15% and ~85% with a 10s
  // period, gated on (a) user not interacting, (b) 10s elapsed since
  // last interaction, (c) slider is in view.
  useEffectBA(() => {
    const IDLE_MS = 10000;
    const PERIOD_MS = 10000;
    const tick = (now) => {
      const idle = !userActiveRef.current ||
                   (now - lastInteractRef.current) > IDLE_MS;
      if (idle && visibleRef.current && !draggingRef.current) {
        if (userActiveRef.current) userActiveRef.current = false;
        if (animStartRef.current == null) {
          // Sync sine phase to current pct so resume is seamless: solve
          // pct = 50 + 35*sin(theta) for theta, then back-derive start.
          const target = (pct - 50) / 35;
          const theta = Math.asin(Math.max(-1, Math.min(1, target)));
          animStartRef.current = now - (theta / (2 * Math.PI)) * PERIOD_MS;
        }
        const phase = ((now - animStartRef.current) / PERIOD_MS) * 2 * Math.PI;
        const next = 50 + Math.sin(phase) * 35;
        setPct(next);
      }
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <section className="section">
      <div style={{ display: 'grid', gridTemplateColumns: isMobileHeader ? '1fr' : '1fr 1fr', gap: isMobileHeader ? 16 : 80, marginBottom: isMobileHeader ? 32 : 56, alignItems: 'end' }}>
        <Reveal>
          <div>
            <div className="mono" style={{ color: 'var(--accent)', marginBottom: 18 }}>// THE DELTA</div>
            <h2 style={{
              fontSize: 'clamp(32px, 4.5vw, 56px)', fontWeight: 500,
              letterSpacing: '-0.03em', lineHeight: 1.02, margin: 0, textWrap: 'balance',
            }}>
              Drag to compare a day before<br/>and after timegain.
            </h2>
          </div>
        </Reveal>
        <Reveal delay={120}>
          <p style={{ color: 'var(--ink-dim)', fontSize: 17, lineHeight: 1.5, margin: 0, maxWidth: 460 }}>
            Same team. Same volume. The admin tax disappears and those hours come back.
            Industry studies estimate <span style={{ color: 'var(--ink)' }}>skilled workers lose roughly 30% of their week</span> to non-billable administrative tasks.
          </p>
        </Reveal>
      </div>

      <Reveal delay={200}>
        {isMobile ? (
          <div style={{ display: 'grid', gap: 16, width: '100%' }}>
            <div>
              <div style={{
                display: 'inline-block', marginBottom: 10,
                padding: '6px 12px', borderRadius: 999, fontFamily: 'var(--font-mono)',
                fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
                background: 'rgba(255,255,255,0.06)', border: '1px solid var(--bg-line)',
              }}>BEFORE</div>
              <div style={{
                borderRadius: 16, overflow: 'hidden',
                border: '1px solid var(--bg-line)', background: 'var(--bg-elev)',
              }}>
                <WorkflowPane variant="before" mobile={true}/>
              </div>
            </div>
            <div>
              <div style={{
                display: 'inline-block', marginBottom: 10,
                padding: '6px 12px', borderRadius: 999, fontFamily: 'var(--font-mono)',
                fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
                background: 'rgba(139,233,253,0.12)', border: '1px solid rgba(139,233,253,0.3)',
                color: 'var(--accent)',
              }}>AFTER · TIMEGAIN</div>
              <div style={{
                borderRadius: 16, overflow: 'hidden',
                border: '1px solid var(--bg-line)', background: 'var(--bg-elev)',
              }}>
                <WorkflowPane variant="after" mobile={true}/>
              </div>
            </div>
          </div>
        ) : (
        <div
          ref={(node) => { ref.current = node; containerRef.current = node; }}
          onMouseDown={(e) => { markInteract(); draggingRef.current = true; onPointer(e.clientX); }}
          onTouchStart={(e) => { markInteract(); draggingRef.current = true; onPointer(e.touches[0].clientX); }}
          style={{
            position: 'relative', height: 540, borderRadius: 16, overflow: 'hidden',
            border: '1px solid var(--bg-line)', cursor: 'ew-resize',
            userSelect: 'none', touchAction: 'none',
            background: 'var(--bg-elev)',
          }}>
          {/* After (full) */}
          <WorkflowPane variant="after" />
          {/* Before (clipped). No CSS transition on clip-path: the
              handle position is updated every animation frame already,
              so a transition just creates a 100ms lag between handle
              and clip and competes with the rAF loop, which the
              browser also throttles when nothing else on the page is
              repainting. Driving clip directly off pct keeps panel and
              handle locked together. */}
          <div style={{
            position: 'absolute', inset: 0,
            clipPath: `inset(0 ${100 - pct}% 0 0)`,
          }}>
            <WorkflowPane variant="before" />
          </div>

          {/* Drag handle */}
          <div style={{
            position: 'absolute', top: 0, bottom: 0,
            left: `${pct}%`, width: 2,
            background: 'var(--accent)', transform: 'translateX(-1px)',
            boxShadow: '0 0 24px rgba(139,233,253,0.6)', pointerEvents: 'none',
          }}>
            <div style={{
              position: 'absolute', top: '50%', left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 44, height: 44, borderRadius: 22,
              background: 'var(--accent)', color: 'var(--bg)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 8px 24px rgba(139,233,253,0.4)',
            }}>
              <svg width="20" height="20" viewBox="0 0 20 20">
                <path d="M7 6 L3 10 L7 14 M13 6 L17 10 L13 14" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
          </div>

          {/* Labels */}
          <div style={{
            position: 'absolute', top: 20, left: 24,
            padding: '6px 12px', borderRadius: 999, fontFamily: 'var(--font-mono)',
            fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
            background: 'rgba(255,255,255,0.06)', border: '1px solid var(--bg-line)',
            backdropFilter: 'blur(8px)',
          }}>BEFORE</div>
          <div style={{
            position: 'absolute', top: 20, right: 24,
            padding: '6px 12px', borderRadius: 999, fontFamily: 'var(--font-mono)',
            fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
            background: 'rgba(139,233,253,0.12)', border: '1px solid rgba(139,233,253,0.3)',
            color: 'var(--accent)', backdropFilter: 'blur(8px)',
          }}>AFTER · TIMEGAIN</div>
        </div>
        )}
      </Reveal>
    </section>
  );
}

function WorkflowPane({ variant, mobile }) {
  const isBefore = variant === 'before';
  const rows = isBefore ? [
    { label: 'Intake form',       time: '18m', color: 'muted' },
    { label: 'Copy to CRM',       time: '12m', color: 'muted' },
    { label: 'Research context',  time: '26m', color: 'muted' },
    { label: 'Manual categorize', time: '14m', color: 'muted' },
    { label: 'Draft response',    time: '22m', color: 'muted' },
    { label: 'Internal handoff',  time: '08m', color: 'muted' },
    { label: 'Follow-up chase',   time: '16m', color: 'muted' },
  ] : [
    { label: 'Intake → enrich',   time: '0.4s', color: 'accent' },
    { label: 'Auto-categorize',   time: '0.2s', color: 'accent' },
    { label: 'Context retrieval', time: '0.9s', color: 'accent' },
    { label: 'Draft + review',    time: '1.1s', color: 'accent' },
    { label: 'Human approval',    time: '45s',  color: 'ink' },
    { label: 'Auto-dispatch',     time: '0.1s', color: 'accent' },
  ];

  if (mobile) {
    return (
      <div style={{
        padding: '24px 20px',
        background: isBefore
          ? 'radial-gradient(ellipse at 30% 20%, rgba(255,180,120,0.08), transparent 60%), var(--bg-elev)'
          : 'radial-gradient(ellipse at 70% 20%, rgba(139,233,253,0.10), transparent 60%), var(--bg-elev)',
        display: 'flex', flexDirection: 'column', gap: 20,
      }}>
        {/* Summary row */}
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <div className="mono" style={{ fontSize: 10, marginBottom: 8, color: isBefore ? 'var(--warn)' : 'var(--accent)' }}>
              Cycle time · ticket
            </div>
            <div style={{
              fontSize: 64, fontWeight: 500, letterSpacing: '-0.04em',
              lineHeight: 1, fontFeatureSettings: '"tnum"',
            }}>
              {isBefore ? '116m' : <><span style={{ color: 'var(--accent)' }}>48</span>s</>}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 16, paddingBottom: 6, flexWrap: 'wrap' }}>
            {(isBefore ? [
              ['Tasks', '7'], ['Tools', '5'], ['Handoffs', '3'],
            ] : [
              ['Tasks', '6'], ['Tools', '1'], ['Handoffs', '0'],
            ]).map(([k, v]) => (
              <div key={k}>
                <div className="mono" style={{ fontSize: 10, marginBottom: 4 }}>{k}</div>
                <div style={{ fontSize: 20, fontWeight: 500 }}>{v}</div>
              </div>
            ))}
          </div>
        </div>
        {/* Step list */}
        <div style={{ display: 'grid', gap: 6 }}>
          {rows.map((r, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '9px 12px', borderRadius: 8,
              border: '1px solid var(--bg-line)',
              background: r.color === 'accent' ? 'rgba(139,233,253,0.04)' : 'rgba(255,255,255,0.015)',
            }}>
              <div style={{
                width: 18, height: 18, borderRadius: 4, flexShrink: 0,
                border: '1px solid var(--bg-line)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--ink-faint)',
              }}>{i+1}</div>
              <div style={{ flex: 1, fontSize: 13 }}>{r.label}</div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 12, flexShrink: 0,
                color: r.color === 'accent' ? 'var(--accent)' :
                       r.color === 'ink' ? 'var(--ink)' : 'var(--ink-dim)',
              }}>{r.time}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="workflow-pane" style={{
      position: 'absolute', inset: 0, padding: '72px 48px 48px',
      background: isBefore
        ? 'radial-gradient(ellipse at 30% 40%, rgba(255,180,120,0.08), transparent 60%), var(--bg-elev)'
        : 'radial-gradient(ellipse at 70% 40%, rgba(139,233,253,0.10), transparent 60%), var(--bg-elev)',
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, alignContent: 'center',
    }}>
      {/* Left: clock / summary */}
      <div style={{ paddingLeft: 24 }}>
        <div className="mono" style={{ marginBottom: 12, color: isBefore ? 'var(--warn)' : 'var(--accent)' }}>
          {isBefore ? 'Cycle time · ticket' : 'Cycle time · ticket'}
        </div>
        <div style={{
          fontSize: 96, fontWeight: 500, letterSpacing: '-0.04em',
          lineHeight: 1, fontFeatureSettings: '"tnum"',
        }}>
          {isBefore ? '116m' : <><span style={{ color: 'var(--accent)' }}>48</span>s</>}
        </div>
        <div style={{ marginTop: 20, display: 'flex', gap: 24 }}>
          {(isBefore ? [
            ['Tasks', '7'], ['Tools', '5'], ['Handoffs', '3'],
          ] : [
            ['Tasks', '6'], ['Tools', '1'], ['Handoffs', '0'],
          ]).map(([k, v]) => (
            <div key={k}>
              <div className="mono" style={{ fontSize: 10, marginBottom: 4 }}>{k}</div>
              <div style={{ fontSize: 22, fontWeight: 500 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Right: step list */}
      <div style={{ display: 'grid', gap: 8, alignContent: 'center', paddingRight: 24 }}>
        {rows.map((r, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '10px 14px', borderRadius: 8,
            border: '1px solid var(--bg-line)',
            background: r.color === 'accent' ? 'rgba(139,233,253,0.04)' : 'rgba(255,255,255,0.015)',
          }}>
            <div style={{
              width: 20, height: 20, borderRadius: 4,
              border: '1px solid var(--bg-line)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-faint)',
            }}>{i+1}</div>
            <div style={{ flex: 1, fontSize: 13 }}>{r.label}</div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 12,
              color: r.color === 'accent' ? 'var(--accent)' :
                     r.color === 'ink' ? 'var(--ink)' : 'var(--ink-dim)',
            }}>{r.time}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.BeforeAfter = BeforeAfter;
