// Act 2 — Match board & review (0:15 – 0:30)

const CANDIDATES = [
  { initials: 'RE', name: 'Ragna E.', pct: 94 },
  { initials: 'SÓ', name: 'Snorri Ó.', pct: 88 },
  { initials: 'VJ', name: 'Vera J.', pct: 84 },
  { initials: 'ÞB', name: 'Þorbjörg B.', pct: 82 },
  { initials: 'HG', name: 'Hrafn G.', pct: 78 },
  { initials: 'KS', name: 'Kári S.', pct: 76 },
  { initials: 'ÁL', name: 'Álfur L.', pct: 74 },
];

function Column({ title, fg, bg, children, highlight = false, count }) {
  return (
    <div style={{
      background: '#fff',
      border: highlight ? `2px dashed ${WP.brand}` : '1px solid rgba(0,0,0,0.06)',
      borderRadius: 12,
      padding: 14,
      display: 'flex', flexDirection: 'column', gap: 10,
      minHeight: 0,
    }}>
      <div style={{
        background: bg, color: fg,
        padding: '8px 14px', borderRadius: 8,
        fontSize: 13, fontWeight: 700, letterSpacing: '1px', textTransform: 'uppercase',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <span>{title}</span>
        {count != null && <span style={{ fontFamily: 'ui-monospace, monospace' }}>{count}</span>}
      </div>
      {children}
    </div>
  );
}

function CandidateCard({ c, tilted = false, highlighted = false, style }) {
  return (
    <div style={{
      background: '#fff',
      border: highlighted ? `2px solid ${WP.brand}` : '1px solid rgba(0,0,0,0.08)',
      borderRadius: 10,
      padding: '12px 14px',
      display: 'flex', alignItems: 'center', gap: 12,
      boxShadow: highlighted ? '0 8px 24px -8px rgba(82,49,255,0.35)' : '0 1px 2px rgba(0,0,0,0.04)',
      transform: tilted ? 'rotate(-3deg) scale(1.02)' : 'none',
      ...style,
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: '50%',
        background: WP.brandLighter, color: WP.brand,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontWeight: 700, fontSize: 13, flexShrink: 0,
      }}>{c.initials}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: WP.ink }}>{c.name}</div>
        <div style={{ fontSize: 11, color: WP.textDim, letterSpacing: '0.5px' }}>SENIOR EMBEDDED</div>
      </div>
      <div style={{
        fontSize: 16, fontWeight: 700, color: WP.brand,
        fontVariantNumeric: 'tabular-nums',
      }}>{c.pct}%</div>
    </div>
  );
}

// ── Scene 04: Match board populates (15-20s) ────────────────────────────
function Scene04() {
  const { localTime } = useSprite();
  const topCardRef = React.useRef(null);
  const bodyRef = React.useRef(null);
  const [target, setTarget] = React.useState({ x: 220, y: 140 });

  React.useLayoutEffect(() => {
    if (topCardRef.current && bodyRef.current) {
      const p = offsetWithin(topCardRef.current, bodyRef.current);
      setTarget({ x: p.x + p.w * 0.5, y: p.y + p.h * 0.5 });
    }
  }, [localTime > 0.3]);

  // Cards arrive staggered. 7 cards total, first appears at 0.2s then every 0.25s.
  const shown = Math.min(CANDIDATES.length, Math.max(0, Math.floor((localTime - 0.2) / 0.25) + 1));
  // Counter matches the number of cards actually rendered so they stay in sync.
  const counter = shown;

  // Cursor flies in and lands on the top card well before the scene transitions,
  // so the click motivates the cut to the profile view.
  const cursorX = interpolate([0, 2.0, 3.2, 4.9], [1300, 1300, target.x, target.x], Easing.easeInOutCubic)(localTime);
  const cursorY = interpolate([0, 2.0, 3.2, 4.9], [700, 700, target.y, target.y], Easing.easeInOutCubic)(localTime);
  const pressed = localTime > 3.3 && localTime < 3.55;
  const rippleT = clamp((localTime - 3.3) / 0.5, 0, 1);

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#ebe7dc' }}>
      <AppWindow active="Matches" width={1760} height={900} x={80} y={40}
        title="Match board"
        right={
          <div style={{
            background: WP.brandLighter, color: WP.brand,
            padding: '8px 16px', borderRadius: 999,
            fontSize: 14, fontWeight: 700, letterSpacing: '0.5px',
            fontVariantNumeric: 'tabular-nums',
          }}>
            <span style={{ fontSize: 20, fontWeight: 800 }}>{counter}</span> new matches
          </div>
        }>
        <div ref={bodyRef} style={{
          padding: '16px 28px 28px',
          height: '100%', boxSizing: 'border-box',
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14,
        }}>
          <Column title="Reviewing" fg={WP.colReviewFg} bg={WP.colReview} count={Math.min(shown, 7)}>
            {CANDIDATES.slice(0, shown).map((c, i) => (
              <div key={c.initials} ref={i === 0 ? topCardRef : null} style={{
                animation: 'cardDrop 400ms cubic-bezier(0.34, 1.56, 0.64, 1) both',
              }}>
                <CandidateCard c={c} highlighted={i === 0 && localTime > 3.3} />
              </div>
            ))}
          </Column>
          <Column title="Interviewing" fg={WP.colInterviewFg} bg={WP.colInterview} count={0}>
            <EmptyGhost />
          </Column>
          <Column title="Hiring" fg={WP.colHiringFg} bg={WP.colHiring} count={0}>
            <EmptyGhost />
          </Column>
          <Column title="Other" fg={WP.colOtherFg} bg={WP.colOther} count={0}>
            <EmptyGhost />
          </Column>
          <ClickRipple x={cursorX + 4} y={cursorY + 4} t={rippleT} />
          <Cursor x={cursorX} y={cursorY} rotate={-8} pressed={pressed} />
        </div>
      </AppWindow>
    </div>
  );
}

function EmptyGhost() {
  return <div style={{
    border: '1px dashed rgba(0,0,0,0.15)',
    borderRadius: 10,
    padding: 22, textAlign: 'center',
    color: WP.textDim, fontSize: 12, letterSpacing: '0.5px',
  }}>—</div>;
}

// ── Scene 05: Opening a profile (20-25s) ────────────────────────────────
function Scene05() {
  const { localTime } = useSprite();
  // Right panel slides in 0..0.5s
  const slideT = Easing.easeOutCubic(clamp(localTime / 0.5, 0, 1));
  // Center CV fades in alongside the panel — no delay so it reads as the main content
  const cvT = Easing.easeOutCubic(clamp(localTime / 0.25, 0, 1));

  // 3 reason rows highlight sequentially: 0.8, 1.4, 2.0
  const reasonT = [0.8, 1.4, 2.0].map(t => clamp((localTime - t) / 0.4, 0, 1));

  // Pill pulse once around 2.4s
  const pulseT = clamp((localTime - 2.4) / 0.6, 0, 1);
  const pulseScale = 1 + Math.sin(pulseT * Math.PI) * 0.08;

  const experience = [
    { yrs: '2022 — now', role: 'Senior Embedded Engineer', org: 'Marel · Reykjavík', bullets: ['Led firmware for sonar DSP board (Rust + C)', 'Cut field recalibration time from 12h → 40min'] },
    { yrs: '2018 — 2022', role: 'Embedded Engineer',        org: 'CCP Games · Reykjavík',  bullets: ['Custom telemetry board for latency capture', 'Owned CI for 6 hardware variants'] },
    { yrs: '2015 — 2018', role: 'Systems Engineer',          org: 'Össur · Reykjavík',       bullets: ['Sensor fusion pipeline for prosthetics'] },
  ];
  const skills = [
    { name: 'Rust',       level: 5 },
    { name: 'Embedded C', level: 5 },
    { name: 'Sonar DSP',  level: 4 },
    { name: 'RTOS',       level: 4 },
    { name: 'Hardware CI',level: 3 },
  ];

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#ebe7dc' }}>
      <AppWindow active="Matches" width={1760} height={900} x={80} y={40}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '220px 1fr 420px',
          height: '100%',
          background: '#fafaf5',
        }}>
          {/* Left: overview board (shortlist at a glance) */}
          <div style={{
            borderRight: '1px solid rgba(0,0,0,0.06)',
            padding: '20px 14px',
            background: '#fff',
            display: 'flex', flexDirection: 'column', gap: 8, minHeight: 0,
          }}>
            <div style={{
              fontSize: 11, fontWeight: 700, letterSpacing: '1.5px',
              color: WP.textDim, textTransform: 'uppercase', padding: '0 6px', marginBottom: 6,
            }}>Reviewing · 7</div>
            {CANDIDATES.map((c, i) => (
              <div key={c.initials} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 8px', borderRadius: 8,
                background: i === 0 ? WP.brandLighter : 'transparent',
                border: i === 0 ? `1px solid ${WP.brand}` : '1px solid transparent',
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: '50%',
                  background: i === 0 ? WP.brand : WP.brandLighter,
                  color: i === 0 ? '#fff' : WP.brand,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 700, fontSize: 10, flexShrink: 0,
                }}>{c.initials}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: WP.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                </div>
                <div style={{
                  fontSize: 11, fontWeight: 700, color: i === 0 ? WP.brand : WP.textDim,
                  fontVariantNumeric: 'tabular-nums',
                }}>{c.pct}%</div>
              </div>
            ))}
          </div>

          {/* Center: CV */}
          <div style={{
            padding: '28px 44px 40px', overflow: 'hidden',
            opacity: cvT, transform: `translateY(${(1 - cvT) * 12}px)`,
          }}>
            <div style={{
              background: '#fff',
              border: '1px solid rgba(0,0,0,0.06)',
              borderRadius: 14,
              padding: '28px 36px',
              boxShadow: '0 1px 2px rgba(0,0,0,0.04), 0 12px 32px -20px rgba(0,0,0,0.18)',
            }}>
              {/* CV header */}
              <div style={{ display: 'flex', gap: 20, alignItems: 'center', marginBottom: 22 }}>
                <div style={{
                  width: 68, height: 68, borderRadius: '50%',
                  background: WP.brandLighter, color: WP.brand,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 20, fontWeight: 700, flexShrink: 0,
                }}>RE</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 26, fontWeight: 700, color: WP.ink, letterSpacing: '-0.01em', lineHeight: 1.1 }}>
                    Ragna Eiríksdóttir
                  </div>
                  <div style={{ fontSize: 13, color: WP.textDim, marginTop: 4, letterSpacing: '0.3px' }}>
                    Senior Embedded Engineer · 8 yrs · Reykjavík
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '1.5px', color: WP.textDim, textTransform: 'uppercase' }}>CV · verified</div>
                  <div style={{ fontSize: 12, color: WP.green, fontWeight: 600 }}>● Opus Futura</div>
                </div>
              </div>

              {/* Summary line */}
              <div style={{
                fontSize: 14, lineHeight: 1.55, color: WP.text,
                padding: '0 0 18px', borderBottom: '1px solid rgba(0,0,0,0.06)', marginBottom: 20,
              }}>
                Firmware &amp; systems engineer focused on sonar DSP and low-latency telemetry.
                Likes shipping hardware that people actually touch. Open to hybrid roles in Reykjavík.
              </div>

              {/* Experience */}
              <div style={{
                fontSize: 11, fontWeight: 700, letterSpacing: '1.5px',
                color: WP.textDim, textTransform: 'uppercase', marginBottom: 12,
              }}>Experience</div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 22 }}>
                {experience.map((x, i) => (
                  <div key={i} style={{ display: 'flex', gap: 18 }}>
                    <div style={{
                      width: 110, flexShrink: 0, fontSize: 12, color: WP.textDim,
                      fontWeight: 600, letterSpacing: '0.3px',
                      fontVariantNumeric: 'tabular-nums', paddingTop: 2,
                    }}>{x.yrs}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 15, fontWeight: 700, color: WP.ink }}>{x.role}</div>
                      <div style={{ fontSize: 12, color: WP.textDim, marginBottom: 6 }}>{x.org}</div>
                      {x.bullets.map((b, j) => (
                        <div key={j} style={{
                          fontSize: 13, color: WP.text, lineHeight: 1.45,
                          paddingLeft: 14, position: 'relative',
                        }}>
                          <span style={{
                            position: 'absolute', left: 0, top: 8,
                            width: 4, height: 4, borderRadius: '50%', background: WP.brand,
                          }} />
                          {b}
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>

              {/* Skills */}
              <div style={{
                fontSize: 11, fontWeight: 700, letterSpacing: '1.5px',
                color: WP.textDim, textTransform: 'uppercase', marginBottom: 10,
              }}>Skills</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {skills.map((s) => (
                  <div key={s.name} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                    padding: '7px 12px',
                    background: WP.brandLighter, color: WP.brand,
                    borderRadius: 999, fontSize: 13, fontWeight: 600,
                  }}>
                    <span>{s.name}</span>
                    <span style={{ display: 'inline-flex', gap: 2 }}>
                      {Array.from({ length: 5 }).map((_, i) => (
                        <span key={i} style={{
                          width: 5, height: 5, borderRadius: '50%',
                          background: i < s.level ? WP.brand : 'rgba(82,49,255,0.2)',
                        }} />
                      ))}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Right: match reasons panel */}
          <div style={{
            background: '#fff',
            borderLeft: '1px solid rgba(0,0,0,0.08)',
            padding: '28px 28px',
            transform: `translateX(${(1 - slideT) * 420}px)`,
            opacity: slideT,
            boxShadow: '-20px 0 60px -20px rgba(0,0,0,0.15)',
            display: 'flex', flexDirection: 'column', minHeight: 0,
          }}>
            <div style={{
              fontSize: 11, fontWeight: 700, letterSpacing: '1.5px',
              color: WP.textDim, textTransform: 'uppercase', marginBottom: 18,
            }}>Why this is a match</div>

            <div style={{ transform: `scale(${pulseScale})`, transformOrigin: 'left', marginBottom: 20 }}>
              <div style={{
                display: 'inline-flex', alignItems: 'baseline', gap: 8,
                background: WP.brand, color: '#fff',
                borderRadius: 999, padding: '10px 18px',
                fontWeight: 800, letterSpacing: '0.5px',
              }}>
                <span style={{ fontSize: 24, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>94</span>
                <span style={{ fontSize: 12 }}>% MATCH</span>
              </div>
            </div>

            {[
              { label: '5 of 6 skills at expert level', kind: 'green', tag: 'STRONG' },
              { label: 'Salary expectation within range', kind: 'green', tag: 'STRONG' },
              { label: 'Ships on deadline — 4 refs confirm', kind: 'blue', tag: 'GOOD' },
            ].map((r, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                background: '#fff',
                border: `1px solid ${reasonT[i] > 0 ? 'rgba(82,49,255,0.4)' : 'rgba(0,0,0,0.08)'}`,
                borderRadius: 10, padding: '12px 14px',
                marginBottom: 10,
                position: 'relative', overflow: 'hidden',
              }}>
                <div style={{
                  position: 'absolute', inset: 0,
                  background: `linear-gradient(90deg, ${WP.brandLighter} 0%, transparent 100%)`,
                  width: `${reasonT[i] * 100}%`, opacity: 0.7,
                }} />
                <div style={{ position: 'relative', flex: 1, fontSize: 13, color: WP.ink, fontWeight: 500, lineHeight: 1.35 }}>
                  {r.label}
                </div>
                <Pill kind={r.kind} size="sm" style={{ position: 'relative' }}>{r.tag}</Pill>
              </div>
            ))}

            <div style={{
              marginTop: 'auto', paddingTop: 18,
              borderTop: '1px solid rgba(0,0,0,0.06)',
              display: 'flex', gap: 10,
            }}>
              <div style={{
                flex: 1, textAlign: 'center',
                padding: '12px 10px', borderRadius: 8,
                border: '1px solid rgba(0,0,0,0.1)', fontSize: 13, fontWeight: 600, color: WP.text,
              }}>Pass</div>
              <div style={{
                flex: 1, textAlign: 'center',
                padding: '12px 10px', borderRadius: 8,
                background: WP.brand, color: '#fff',
                fontSize: 13, fontWeight: 700, letterSpacing: '0.5px',
              }}>Move to interview →</div>
            </div>
          </div>
        </div>
      </AppWindow>
    </div>
  );
}

// ── Scene 06: Drag to Interviewing (25-30s) ─────────────────────────────
function Scene06() {
  const { localTime } = useSprite();

  // Timing:
  //  0–0.9s   — cursor flies in from off-frame and lands on Ragna's card
  //  0.9–1.0s  — brief click (cursor presses, card lifts with small pop)
  //  1.0–3.2s  — drag card from col0 to col1 (eased)
  //  3.2–3.6s  — land: tilt & scale settle into the Interviewing slot
  //  3.6s+      — dropped, card lives in column
  const approach  = localTime <= 1.0;                      // cursor approaching + clicking
  const lifted    = localTime > 1.0;                        // card is off the column
  const settling  = localTime > 3.2 && localTime <= 3.6;
  const dropped   = localTime > 3.6;
  const dragging  = lifted && !dropped;                    // drag + settle window

  // Card start/end positions anchored to the real column slots (body coords).
  // Body padding is 16/28; columns have 14px padding and a 30px header row.
  // Ragna's visible card sits at ~(42, 70) in the Reviewing column.
  const startX = 42,  startY = 70;
  const endX   = 410, endY   = 70;

  // Drag path 1.0 → 3.2s
  const dragT = clamp((localTime - 1.0) / 2.2, 0, 1);
  const eased = Easing.easeInOutCubic(dragT);
  const cardX = interpolate([0, 1], [startX, endX])(eased);
  const cardY = interpolate([0, 1], [startY, endY])(eased);

  // Lift pop: tiny scale kick when the click lands (1.0s)
  const liftT  = clamp((localTime - 0.95) / 0.18, 0, 1);
  const liftPop = 1 + Math.sin(liftT * Math.PI) * 0.06;

  // Settle animation: tilt relax + gentle bounce
  const settleT = clamp((localTime - 3.2) / 0.4, 0, 1);
  const tiltDeg = dragging ? (1 - settleT) * -3 : 0;       // 3° → 0° during settle
  const scale   = dragging ? liftPop * (1.02 + Math.sin(settleT * Math.PI) * 0.04 - settleT * 0.02) : 1;

  // ── Cursor path ──
  // Approach: off-frame top-right → onto Ragna's card in Reviewing (~(370, 430))
  // During drag: follows the card (offset to the top-left of the card)
  // After drop: hidden
  const cursorOffsetX = 180, cursorOffsetY = 28;
  const approachX = interpolate([0, 0.9], [1600, startX + cursorOffsetX], Easing.easeInOutCubic)(localTime);
  const approachY = interpolate([0, 0.9], [900,  startY + cursorOffsetY], Easing.easeInOutCubic)(localTime);
  const cursorX = approach ? approachX : cardX + cursorOffsetX;
  const cursorY = approach ? approachY : cardY + cursorOffsetY;
  // Click press happens briefly around the lift moment
  const pressed = localTime > 0.85 && localTime < 1.05;
  const clickRippleT = clamp((localTime - 0.88) / 0.5, 0, 1);

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#ebe7dc' }}>
      <AppWindow active="Matches" width={1760} height={900} x={80} y={40}
        title="Match board">
        <div style={{
          padding: '16px 28px 28px',
          height: '100%', boxSizing: 'border-box',
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14,
          position: 'relative',
        }}>
          <Column title="Reviewing" fg={WP.colReviewFg} bg={WP.colReview} count={lifted ? 6 : 7}>
            {/* Ragna sits here until the drag lifts her; remaining cards shift up as the slot collapses */}
            {!lifted && <CandidateCard c={CANDIDATES[0]} />}
            {lifted && (() => {
              const collapse = Easing.easeInOutCubic(clamp((localTime - 1.0) / 0.35, 0, 1));
              const h = 64 * (1 - collapse);
              const mb = -10 * collapse; // cancel the 10px flex gap as we collapse
              if (h < 0.5) return null;
              return <div style={{ height: h, marginBottom: mb, opacity: 1 - collapse }} />;
            })()}
            {CANDIDATES.slice(1, 5).map(c => <CandidateCard key={c.initials} c={c} />)}
          </Column>
          <Column title="Interviewing" fg={WP.colInterviewFg} bg={WP.colInterview} count={dropped ? 1 : 0} highlight={dragging && dragT > 0.4}>
            {dropped ? (
              <CandidateCard c={CANDIDATES[0]} highlighted />
            ) : (
              <EmptyGhost />
            )}
          </Column>
          <Column title="Hiring" fg={WP.colHiringFg} bg={WP.colHiring} count={0}>
            <EmptyGhost />
          </Column>
          <Column title="Other" fg={WP.colOtherFg} bg={WP.colOther} count={0}>
            <EmptyGhost />
          </Column>

          {/* Dragged card overlay — visible only once lifted; disappears at drop */}
          {dragging && (
            <div style={{
              position: 'absolute', left: cardX, top: cardY,
              width: 320, pointerEvents: 'none', zIndex: 20,
              transform: `rotate(${tiltDeg}deg) scale(${scale})`,
              transformOrigin: 'center center',
              transition: 'none',
            }}>
              <CandidateCard c={CANDIDATES[0]} highlighted />
            </div>
          )}

        </div>
      </AppWindow>
    </div>
  );
}

Object.assign(window, { Scene04, Scene05, Scene06, CANDIDATES });
