// Act 1 — Create the job (0:00 – 0:15)

// ── Scene 01: Empty dashboard (0-5s) ───────────────────────────────────
function Scene01() {
  const { localTime, progress } = useSprite();
  const btnRef = React.useRef(null);
  const bodyRef = React.useRef(null);
  const [target, setTarget] = React.useState({ x: 780, y: 500 });

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

  // gentle breathe on empty-state
  const breathe = 1 + Math.sin(localTime * 1.4) * 0.01;
  // global fade-in (first 0.5s)
  const intro = clamp(localTime / 0.5, 0, 1);

  // Cursor: fades in from bottom-right, parks near button by 3.5s, presses at 4.2s
  const cursorX = interpolate([0, 3.5, 4.5], [1300, target.x, target.x], Easing.easeInOutCubic)(localTime);
  const cursorY = interpolate([0, 3.5, 4.5], [700, target.y, target.y], Easing.easeInOutCubic)(localTime);
  const cursorOpacity = clamp((localTime - 1.6) / 0.5, 0, 1);
  const pressed = localTime > 4.2 && localTime < 4.5;
  const rippleT = clamp((localTime - 4.2) / 0.55, 0, 1);

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#ebe7dc', opacity: intro }}>
      <AppWindow active="Dashboard" width={1760} height={900} x={80} y={40}>
        <div ref={bodyRef} style={{ padding: '40px 48px', height: '100%', boxSizing: 'border-box', position: 'relative' }}>
          <div style={{ fontSize: 32, fontWeight: 600, color: WP.ink, marginBottom: 6 }}>
            Good morning, Freyja
          </div>
          <div style={{ fontSize: 15, color: WP.textDim, marginBottom: 40 }}>
            Your Workplace, at a glance.
          </div>

          {/* Empty state */}
          <div style={{
            background: '#fff', borderRadius: 14,
            border: '1px dashed rgba(82,49,255,0.25)',
            padding: '80px 40px',
            textAlign: 'center',
            transform: `scale(${breathe})`,
            transformOrigin: 'center',
          }}>
            <div style={{
              width: 96, height: 96, margin: '0 auto 20px',
              borderRadius: '50%',
              background: WP.brandLighter, color: WP.brand,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 52, fontWeight: 300, lineHeight: 1,
            }}>+</div>
            <div style={{ fontSize: 22, fontWeight: 600, color: WP.ink, marginBottom: 8 }}>
              No jobs yet.
            </div>
            <div style={{ fontSize: 15, color: WP.textDim, marginBottom: 24 }}>
              Post your first role to see matches stream in.
            </div>
            <div ref={btnRef} style={{
              display: 'inline-block',
              background: WP.brand, color: '#fff',
              padding: '14px 28px', borderRadius: 8,
              fontSize: 15, fontWeight: 600, letterSpacing: '0.2px',
              transform: pressed ? 'translateY(2px)' : 'translateY(0)',
              boxShadow: pressed ? '0 2px 6px -2px rgba(82,49,255,0.4)' : '0 6px 16px -4px rgba(82,49,255,0.4)',
              transition: 'all 80ms',
            }}>+ New job</div>
          </div>

          {/* KPI row — all zero */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16, marginTop: 24 }}>
            {[['Active jobs', '0'], ['Matches', '0'], ['Time to hire', '—']].map(([k,v]) => (
              <Card key={k} pad={20} style={{ background: '#fff' }}>
                <div style={{ fontSize: 12, color: WP.textDim, letterSpacing: '1.5px', textTransform: 'uppercase', fontWeight: 600 }}>{k}</div>
                <div style={{ fontSize: 36, fontWeight: 700, color: WP.ink, marginTop: 6, letterSpacing: '-0.02em' }}>{v}</div>
              </Card>
            ))}
          </div>

          <ClickRipple x={cursorX + 4} y={cursorY + 4} t={rippleT} />
          <Cursor x={cursorX} y={cursorY} rotate={-8} pressed={pressed} style={{ opacity: cursorOpacity }} />
        </div>
      </AppWindow>
    </div>
  );
}

// ── Scene 02: Drafting the role (5-10s, localTime 0..5) ────────────────
function Scene02() {
  const { localTime } = useSprite();
  const publishRef = React.useRef(null);
  const bodyRef = React.useRef(null);
  const [targetPos, setTargetPos] = React.useState({ x: 1300, y: 560 });
  const upperRef = React.useRef(null);
  const lowerRef = React.useRef(null);
  const [upperPos, setUpperPos] = React.useState({ x: 900, y: 360 });
  const [lowerPos, setLowerPos] = React.useState({ x: 430, y: 360 });

  React.useLayoutEffect(() => {
    if (publishRef.current && bodyRef.current) {
      const p = offsetWithin(publishRef.current, bodyRef.current);
      setTargetPos({ x: p.x + p.w * 0.35, y: p.y + p.h * 0.5 });
    }
    if (upperRef.current && bodyRef.current) {
      const p = offsetWithin(upperRef.current, bodyRef.current);
      setUpperPos({ x: p.x + p.w * 0.5, y: p.y + p.h * 0.5 });
    }
    if (lowerRef.current && bodyRef.current) {
      const p = offsetWithin(lowerRef.current, bodyRef.current);
      setLowerPos({ x: p.x + p.w * 0.5, y: p.y + p.h * 0.5 });
    }
  }, [localTime > 4.4]);

  // Typing: 0..1.5s for the title (22 chars)
  const title = 'Ocean Systems Engineer';
  const typeT = clamp(localTime / 1.5, 0, 1);
  const typed = title.slice(0, Math.floor(typeT * title.length));
  const cursorOn = Math.floor(localTime * 2) % 2 === 0;

  // Description fills in during 1.6 → 4.2s, backgrounded behind pills/salary
  const description = 'Firmware for our next-gen sonar DSP boards. Rust + embedded C. Small, senior team — Reykjavík, hybrid 2/3. Ships hardware you can touch.';
  const descT = clamp((localTime - 1.6) / 2.6, 0, 1);
  const descTyped = description.slice(0, Math.floor(descT * description.length));
  const descActive = descT > 0 && descT < 1;

  // Pills appear at 2.0, 2.4, 2.8s
  const pills = [
    { label: 'Rust', t: 2.0 },
    { label: 'Embedded C', t: 2.4 },
    { label: 'Sonar DSP', t: 2.8 },
    { label: 'Reykjavík', t: 3.2 },
  ];

  // Salary slider: upper handle animates 3.4 → 4.0s, lower handle 4.0 → 4.4s
  const highT = clamp((localTime - 3.4) / 0.6, 0, 1);
  const lowT  = clamp((localTime - 4.0) / 0.5, 0, 1);
  const low  = Math.round(interpolate([0, 1], [0, 6500], Easing.easeOutCubic)(lowT));
  const high = Math.round(interpolate([0, 1], [0, 8500], Easing.easeOutCubic)(highT));

  // Cursor: absent during form fill, fades in as it approaches PUBLISH, presses at 4.7s
  const cursorX = interpolate([0, 4.2, 4.7], [targetPos.x + 140, targetPos.x + 40, targetPos.x], Easing.easeOutCubic)(localTime);
  const cursorY = interpolate([0, 4.2, 4.7], [targetPos.y + 90,  targetPos.y + 30, targetPos.y], Easing.easeOutCubic)(localTime);
  const cursorOpacity = clamp((localTime - 4.0) / 0.35, 0, 1);

  // Publish button "press" at 4.7
  const pressed = localTime > 4.7 && localTime < 5.0;
  const rippleT = clamp((localTime - 4.7) / 0.55, 0, 1);

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#ebe7dc' }}>
      <AppWindow active="Jobs" width={1760} height={900} x={80} y={40}
        title="New job"
        right={<Pill kind="gray" size="md">Step 1 of 3</Pill>}>
        <div ref={bodyRef} style={{ padding: '24px 48px 40px', height: '100%', boxSizing: 'border-box', position: 'relative' }}>

          {/* Title field */}
          <Label>Job title</Label>
          <div style={{
            background: '#fff',
            border: `2px solid ${WP.brand}`,
            borderRadius: 10,
            padding: '16px 20px',
            fontSize: 22, fontWeight: 600, color: WP.ink,
            boxShadow: `0 0 0 4px ${WP.brandLighter}`,
            marginBottom: 22,
          }}>
            {typed}
            <span style={{ opacity: cursorOn && typeT < 1 ? 1 : 0, color: WP.brand }}>|</span>
          </div>

          {/* Description */}
          <Label>Description</Label>
          <div style={{
            background: '#fff',
            border: `1px solid ${descActive ? WP.brand : 'rgba(0,0,0,0.08)'}`,
            borderRadius: 10,
            padding: '14px 18px',
            fontSize: 15, fontWeight: 500, color: descTyped ? WP.ink : WP.textDim,
            lineHeight: 1.45, minHeight: 64,
            boxShadow: descActive ? `0 0 0 3px ${WP.brandLighter}` : 'none',
            marginBottom: 22,
            transition: 'border-color 140ms, box-shadow 140ms',
          }}>
            {descTyped || 'Tell Talents what the role is really about…'}
            {descActive && (
              <span style={{
                display: 'inline-block',
                width: 2, height: 18, verticalAlign: -3, marginLeft: 2,
                background: WP.brand,
                opacity: cursorOn ? 1 : 0,
              }} />
            )}
          </div>

          {/* Skills */}
          <Label>Skills & location</Label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 28, minHeight: 44 }}>
            {pills.map(p => (
              <SkillPill key={p.label} label={p.label} show={localTime > p.t} />
            ))}
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '9px 16px',
              background: '#fff',
              border: '1px dashed rgba(82,49,255,0.35)',
              borderRadius: 999, fontSize: 14, fontWeight: 600,
              color: WP.brand, lineHeight: 1,
            }}>
              <span style={{ fontSize: 16, fontWeight: 400, lineHeight: 1 }}>+</span>
              <span>add</span>
            </div>
          </div>

          {/* Salary */}
          <Label>Salary range (EUR / mo)</Label>
          <div style={{
            background: '#fff', border: '1px solid rgba(0,0,0,0.08)', borderRadius: 10,
            padding: '22px 24px',
            display: 'flex', alignItems: 'center', gap: 24,
          }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: WP.ink, minWidth: 280, fontVariantNumeric: 'tabular-nums' }}>
              €{low.toLocaleString('en-IE')} <span style={{ color: WP.textDim, fontWeight: 400 }}>—</span> €{high.toLocaleString('en-IE')}
            </div>
            <div style={{ flex: 1, height: 6, background: '#ece8df', borderRadius: 3, position: 'relative' }}>
              <div style={{
                position: 'absolute', left: `${lowT * 20}%`,
                width: `${Math.max(0, highT * 65 - lowT * 20)}%`,
                height: 6, background: WP.brand, borderRadius: 3,
              }} />
              {/* Lower handle */}
              <div ref={lowerRef} style={{
                position: 'absolute', left: `${lowT * 20}%`, top: '50%',
                width: 20, height: 20, borderRadius: '50%', background: WP.brand,
                border: '3px solid #fff', boxShadow: '0 2px 6px rgba(0,0,0,0.2)',
                transform: 'translate(-50%, -50%)',
              }} />
              {/* Upper handle */}
              <div ref={upperRef} style={{
                position: 'absolute', left: `${highT * 65}%`, top: '50%',
                width: 20, height: 20, borderRadius: '50%', background: WP.brand,
                border: '3px solid #fff', boxShadow: '0 2px 6px rgba(0,0,0,0.2)',
                transform: 'translate(-50%, -50%)',
              }} />
            </div>
          </div>

          {/* Publish button */}
          <div style={{ marginTop: 32, display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
            <div style={{
              padding: '14px 22px', fontSize: 14, fontWeight: 600,
              color: WP.text, background: '#fff',
              border: '1px solid rgba(0,0,0,0.12)', borderRadius: 8,
            }}>Save draft</div>
            <div ref={publishRef} style={{
              padding: '14px 32px', fontSize: 15, fontWeight: 700, letterSpacing: '0.5px',
              color: '#fff', background: WP.brand, borderRadius: 8,
              transform: pressed ? 'translateY(2px) scale(0.98)' : 'translateY(0)',
              boxShadow: pressed ? '0 2px 6px -2px rgba(82,49,255,0.5)' : '0 8px 20px -4px rgba(82,49,255,0.45)',
              transition: 'all 80ms',
            }}>PUBLISH ROLE →</div>
          </div>

          <ClickRipple x={cursorX + 4} y={cursorY + 4} t={rippleT} />
          <Cursor x={cursorX} y={cursorY} rotate={-8} pressed={pressed} style={{ opacity: cursorOpacity }} />
        </div>
      </AppWindow>
    </div>
  );
}

function Label({ children }) {
  return <div style={{
    fontSize: 12, fontWeight: 700, letterSpacing: '1.5px',
    textTransform: 'uppercase', color: WP.textDim, marginBottom: 10,
  }}>{children}</div>;
}

function SkillPill({ label, show }) {
  if (!show) return <div style={{ padding: '10px 18px', visibility: 'hidden' }}>{label}</div>;
  return (
    <div style={{
      padding: '10px 18px',
      background: WP.brandLighter, color: WP.brand,
      fontWeight: 600, fontSize: 14, borderRadius: 999,
      animation: 'pillIn 300ms cubic-bezier(0.34, 1.56, 0.64, 1) both',
    }}>{label}</div>
  );
}

// ── Scene 03: Draft → Active (10-15s) ──────────────────────────────────
function Scene03() {
  const { localTime } = useSprite();
  // Tick scales in 0..0.6
  const tickT = clamp(localTime / 0.6, 0, 1);
  const tickScale = Easing.easeOutBack(tickT);
  // Badge morph: DRAFT (grey) until 0.4, ACTIVE (green) after
  const isActive = localTime > 0.4;

  // Confetti at 0.6s
  const confetti = localTime > 0.6 ? localTime - 0.6 : 0;

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#ebe7dc' }}>
      <AppWindow active="Jobs" width={1760} height={900} x={80} y={40}
        title="Ocean Systems Engineer"
        right={
          isActive
            ? <Pill kind="green" size="lg">● ACTIVE</Pill>
            : <Pill kind="gray" size="lg">● DRAFT</Pill>
        }
      >
        <div style={{
          height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexDirection: 'column', gap: 24, position: 'relative', overflow: 'hidden',
        }}>
          {/* Confetti */}
          {confetti > 0 && Array.from({ length: 18 }).map((_, i) => {
            const seed = i * 13.37;
            const x = (seed * 9301 + 49297) % 233280 / 233280;
            const delay = (i % 6) * 0.06;
            const t = Math.max(0, confetti - delay);
            const fallY = t * 600;
            const spinDeg = t * 360;
            const colors = [WP.brand, WP.purple, WP.yellow, WP.green];
            return (
              <div key={i} style={{
                position: 'absolute',
                left: `${x * 100}%`,
                top: -20,
                width: 8, height: 14,
                background: colors[i % colors.length],
                transform: `translateY(${fallY}px) rotate(${spinDeg}deg)`,
                opacity: Math.max(0, 1 - t / 3),
              }} />
            );
          })}

          <div style={{
            width: 140, height: 140, borderRadius: '50%',
            background: isActive ? WP.green : WP.textDim,
            transition: 'background 400ms',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transform: `scale(${tickScale})`,
            boxShadow: isActive ? '0 0 0 16px rgba(82,185,99,0.15)' : 'none',
          }}>
            <svg width="72" height="72" viewBox="0 0 24 24" fill="none">
              <path d="M5 12.5l4.5 4.5L19 7.5" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <div style={{ fontSize: 32, fontWeight: 600, color: WP.ink, letterSpacing: '-0.01em', opacity: tickT }}>
            Your job is live.
          </div>
          <div style={{ fontSize: 16, color: WP.textDim, opacity: tickT }}>
            Finding matches<TypingDots t={localTime} />
          </div>
        </div>
      </AppWindow>
    </div>
  );
}

function TypingDots({ t }) {
  const step = Math.floor(t * 2) % 4;
  return <span style={{ fontVariantNumeric: 'tabular-nums' }}>{'.'.repeat(step)}</span>;
}

Object.assign(window, { Scene01, Scene02, Scene03 });
