/* global React, useInViewProgress, clamp, lerp, easeOut */
const { useRef: _prRef, useMemo: _prMemo } = React;

// Chaos -> Order: scattered nodes that align into a grid as user scrolls.
function Problem() {
  const ref = _prRef(null);
  const p = useInViewProgress(ref, { enterAt: 0.85, exitAt: 0.1 });

  // Generate nodes once
  const nodes = _prMemo(() => {
    const arr = [];
    const rows = 5, cols = 12;
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        arr.push({
          id: `${r}-${c}`,
          // chaos positions: random-ish scatter (deterministic)
          chaosX: 10 + (Math.sin(r*7.3 + c*2.1) * 0.5 + 0.5) * 80,
          chaosY: 10 + (Math.cos(r*3.7 + c*4.3) * 0.5 + 0.5) * 80,
          // order positions: grid
          orderX: 4 + (c / (cols - 1)) * 92,
          orderY: 14 + (r / (rows - 1)) * 72,
          filled: (r + c) % 4 !== 0 && (r*3 + c*2) % 5 !== 1,
        });
      }
    }
    return arr;
  }, []);

  const t = easeOut(clamp(p * 1.1, 0, 1));

  return (
    <section className="sec page" id="problem" ref={ref}>
      <div className="phase-num" style={{ top: '5%', left: '-2%', transform: `translateY(${p*60}px)` }}>02</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 48 }}>
        <div className="section-label">
          <span className="dot"></span>
          <span className="mono">Phase / 02 · From chaos</span>
        </div>
        <div className="mono mono-sm" style={{ color: 'var(--olive)' }}>ALIGNMENT · {Math.round(t*100)}%</div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'start', marginBottom: 32 }}>
        <h2 className="display" style={{ fontSize: 'clamp(36px, 4.5vw, 64px)', margin: 0, lineHeight: 1.02 }}>
          A semester<br/>doesn't fit<br/>on a <span className="serif-it" style={{ color: 'var(--olive)' }}>to-do list</span>.
        </h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, justifySelf: 'end', minWidth: 280 }}>
          <div className="mini-stat"><span className="mono mono-sm">Tasks</span><span className="mini-v">{Math.round(lerp(180, 48, t))}</span></div>
          <div className="mini-stat"><span className="mono mono-sm">Scattered across</span><span className="mini-v">{Math.round(lerp(12, 3, t))} <span className="u">apps</span></span></div>
          <div className="mini-stat"><span className="mono mono-sm">Clarity</span><span className="mini-v" style={{ color: t > 0.6 ? 'var(--olive)' : 'var(--warn)' }}>{Math.round(lerp(14, 92, t))}%</span></div>
        </div>
      </div>

      <div style={{ position: 'relative', height: 360, border: '1px solid var(--line)', background: 'var(--bg)', overflow: 'hidden' }}>
        {nodes.map((n) => {
          const x = lerp(n.chaosX, n.orderX, t);
          const y = lerp(n.chaosY, n.orderY, t);
          const size = lerp(6, 14, t);
          const fill = n.filled && t > 0.5 ? 'var(--accent)' : 'transparent';
          const border = t > 0.3 ? 'var(--line-strong)' : 'rgba(14,15,16,0.15)';
          return (
            <div key={n.id} style={{
              position: 'absolute',
              left: `${x}%`, top: `${y}%`,
              width: size, height: size,
              transform: 'translate(-50%, -50%)',
              border: `1px solid ${border}`,
              background: fill,
              borderRadius: lerp(999, 1, t),
              transition: 'border-radius 0ms, background 300ms',
              opacity: lerp(0.5, 1, t),
            }}/>
          );
        })}
        {/* Caption overlay */}
        <div style={{ position: 'absolute', left: 20, top: 16, fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
          {t < 0.3 ? 'Before' : t < 0.7 ? 'Aligning' : 'After'} · {60} commitments
        </div>
        <div style={{ position: 'absolute', right: 20, bottom: 16, fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--olive)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
          {t > 0.7 ? '15 weeks · grid locked' : 'drift'}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', marginTop: 32, borderTop: '1px solid var(--line)' }}>
        {[
          ['Task apps', 'Built for today.'],
          ['Calendars', 'Built for two weeks.'],
          ['Habit apps', 'Count. Forgive nothing.'],
        ].map(([k, v], i) => (
          <div key={i} style={{ padding: '20px 24px 0', borderRight: i < 2 ? '1px solid var(--line)' : 'none' }}>
            <div className="mono mono-sm" style={{ marginBottom: 8 }}>{k}</div>
            <div style={{ fontFamily: 'Inter Tight', fontWeight: 600, fontSize: 22, letterSpacing: '-0.02em' }}>{v}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { Problem });
