// koryo-scenes-b.jsx — Scenes 5-10 (employee + results + CTA)

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 5: MESSAGING APP — DM arrives (39-48s = 9s)
// ═══════════════════════════════════════════════════════════════════════════
function SceneMessagingDM() {
  const { localTime, duration } = useSprite();
  // Show messaging app, then DM card slides in, mouse hovers over Answer button.

  const cardIn = Easing.easeOutCubic(clamp((localTime - 1.4) / 0.6, 0, 1));
  const cursorPath = [
    { t: 0.10, x: 500, y: 500 },
    { t: 0.55, x: 740, y: 510 }, // moves toward Answer survey button
    { t: 0.82, x: 740, y: 510 },
  ];
  // Camera: starts wide, slowly zooms to DM area
  const camScale = 1 + Math.max(0, (localTime - 2.0) / 6) * 0.12;
  const camY = -Math.max(0, (localTime - 2.0) / 6) * 30;

  return (
    <SceneFade>
      <MessagingChrome unread={localTime > 1.4} threadFocus={localTime > 1.4}>
        <MessageThread>
          <div style={{ transform: `scale(${camScale}) translateY(${camY}px)`, transformOrigin: '40% 60%', willChange: 'transform' }}>
            {/* Earlier history (dimmed) */}
            <div style={{ display: 'flex', gap: 12, opacity: 0.4, marginBottom: 18 }}>
              <div style={{ width: 36, height: 36, background: '#0e0e1a', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <KoryoMark size={22} color="oklch(78% 0.16 280)"/>
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                  <span style={{ fontWeight: 800, fontSize: 14, color: '#1d1c1d' }}>Koryo</span>
                  <span style={{ fontSize: 10, color: '#616061', fontWeight: 700, padding: '1px 5px', background: 'rgba(0,0,0,0.06)', borderRadius: 3 }}>APP</span>
                  <span style={{ fontSize: 12, color: '#868686' }}>Tue 9:02 AM</span>
                </div>
                <div style={{ fontSize: 13.5, color: '#616061', marginTop: 2 }}>Thank you for your feedback! 🎉 Your answers have been recorded.</div>
              </div>
            </div>

            {/* Day divider */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12, margin: '6px 0 18px',
            }}>
              <div style={{ flex: 1, height: 1, background: 'rgba(15,18,40,0.08)' }}/>
              <div style={{ fontSize: 11.5, color: '#1d1c1d', fontWeight: 700, padding: '3px 12px', background: '#fff', border: '1px solid rgba(15,18,40,0.08)', borderRadius: 999, whiteSpace: 'nowrap' }}>Monday, October 6th</div>
              <div style={{ flex: 1, height: 1, background: 'rgba(15,18,40,0.08)' }}/>
            </div>

            {/* "New" divider */}
            <div style={{ opacity: cardIn }}>
              <ThreadDivider label="New"/>
            </div>

            {/* The new DM */}
            <div style={{
              opacity: cardIn,
              transform: `translateY(${(1 - cardIn) * 16}px)`,
              padding: '8px 0',
            }}>
              <KoryoDM
                title="Q3 Pulse — Engagement & Wellbeing"
                body="Your opinion matters. It takes about 90 seconds — and your answers are anonymous. Tap the button below to start."
                time="9:00 AM"
                showButton={true}
              />
            </div>
          </div>
        </MessageThread>

        {/* Notification toast top-right (Mac-style) */}
        {localTime > 0.4 && localTime < 3.6 && (
          <div style={{
            position: 'absolute', top: 48, right: 24,
            width: 320,
            background: '#fff',
            border: '1px solid rgba(15,18,40,0.10)',
            borderRadius: 12,
            padding: '12px 14px',
            display: 'flex', gap: 10,
            boxShadow: '0 14px 36px rgba(15,18,40,0.18)',
            opacity: clamp((localTime - 0.4) / 0.4, 0, 1) * (1 - clamp((localTime - 3.2) / 0.4, 0, 1)),
            transform: `translateX(${(1 - clamp((localTime - 0.4) / 0.5, 0, 1)) * 40}px)`,
          }}>
            <div style={{ width: 32, height: 32, background: '#0e0e1a', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <KoryoMark size={19} color="oklch(78% 0.16 280)"/>
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <div style={{ fontWeight: 700, fontSize: 13, color: '#1d1c1d' }}>Koryo</div>
                <div style={{ fontSize: 11, color: '#868686' }}>now</div>
              </div>
              <div style={{ fontSize: 12.5, color: '#1d1c1d', marginTop: 2, lineHeight: 1.35 }}>You have a new survey waiting — Q3 Pulse</div>
            </div>
          </div>
        )}

        <Cursor path={cursorPath} color="#0e0e1a"/>
      </MessagingChrome>
      <Caption kicker="05 · DELIVERY" line="A friendly DM lands where your team already works."/>
    </SceneFade>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 6: ANSWER MODAL (48-58s = 10s)
// ═══════════════════════════════════════════════════════════════════════════
function SceneAnswerModal() {
  const { localTime } = useSprite();

  // Three quick question states + submit
  // 0-0.4s: modal appears
  // 0.4-2.8s: Q1 — scale, user clicks 8
  // 2.8-5.2s: Q2 — scale, user clicks 7
  // 5.2-8.5s: Q3 — text answer being typed
  // 8.5-9.5s: Submit clicks, success state

  let stage;
  if (localTime < 2.8) stage = 1;
  else if (localTime < 5.2) stage = 2;
  else if (localTime < 8.2) stage = 3;
  else stage = 4;

  const q1Selected = localTime > 1.6 ? 8 : null;
  const q2Selected = localTime > 4.0 ? 7 : null;
  const q3Text = "More clarity on quarterly goals would really help our team plan ahead.";
  const q3N = Math.floor(clamp((localTime - 5.6) / 2.0, 0, 1) * q3Text.length);

  const showSuccess = localTime > 9.0;

  const cursorPaths = {
    1: [{ t: 0.0, x: 800, y: 500 }, { t: 0.6, x: 920, y: 470 }, { t: 0.95, x: 920, y: 470 }],
    2: [{ t: 0.0, x: 920, y: 470 }, { t: 0.5, x: 870, y: 470 }, { t: 0.95, x: 870, y: 470 }],
    3: [{ t: 0.0, x: 870, y: 470 }, { t: 0.3, x: 720, y: 500 }, { t: 0.95, x: 720, y: 500 }],
    4: [{ t: 0.0, x: 720, y: 500 }, { t: 0.7, x: 1030, y: 640 }, { t: 1.0, x: 1030, y: 640 }],
  };

  return (
    <SceneFade>
      <MessagingChrome unread={false} threadFocus={true}>
        <MessageThread>
          <div style={{ opacity: 0.4 }}>
            <KoryoDM
              title="Q3 Pulse — Engagement & Wellbeing"
              body="Your opinion matters. It takes about 90 seconds — and your answers are anonymous."
              showButton={false}
              time="9:00 AM"
            />
          </div>
        </MessageThread>

        {!showSuccess && (
          <SurveyModal
            title="Q3 Pulse — Engagement & Wellbeing"
            questionNum={stage === 1 ? 1 : stage === 2 ? 2 : 3}
            totalQuestions={9}
            step={1} totalSteps={2}
            questionLabel={
              stage === 1 ? "I would recommend Northwind as a great place to work" :
              stage === 2 ? "I have the resources I need to do my job effectively" :
              "Anything you'd like leadership to know? (optional)"
            }
            options={stage <= 2 ? ['1','2','3','4','5','6','7','8','9','10'] : []}
            selected={stage === 1 ? q1Selected : stage === 2 ? q2Selected : null}
            optionsType={stage === 3 ? 'text' : 'scale'}
            textValue={stage === 3 ? q3Text.slice(0, q3N) : ''}
            showSubmit={stage === 4 || (stage === 3 && q3N === q3Text.length)}
          />
        )}

        {showSuccess && (
          <div style={{
            position: 'absolute', inset: 0,
            background: 'rgba(20,18,30,0.45)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: 30,
          }}>
            <div style={{
              width: 460,
              background: '#fff',
              borderRadius: 12,
              padding: '32px 28px',
              textAlign: 'center',
              boxShadow: '0 24px 60px rgba(0,0,0,0.25), 0 0 0 1px rgba(15,18,40,0.06)',
              opacity: clamp((localTime - 9.0) / 0.4, 0, 1),
              transform: `scale(${0.94 + clamp((localTime - 9.0) / 0.4, 0, 1) * 0.06})`,
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: '#007a5a', color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                margin: '0 auto 14px',
                fontSize: 26, fontWeight: 800,
              }}>✓</div>
              <div style={{ fontWeight: 800, fontSize: 18, color: '#1d1c1d', marginBottom: 6 }}>Thank you for your feedback! 🎉</div>
              <div style={{ fontSize: 14, color: '#616061' }}>Your answers have been recorded — and they're anonymous.</div>
            </div>
          </div>
        )}

        {!showSuccess && <Cursor path={cursorPaths[stage]} color="#0e0e1a"/>}
        {!showSuccess && stage === 1 && <ClickPulse x={920} y={470} at={1.5} color="#007a5a"/>}
        {!showSuccess && stage === 2 && <ClickPulse x={870} y={470} at={3.9} color="#007a5a"/>}
        {!showSuccess && stage === 4 && <ClickPulse x={1030} y={640} at={8.6} color="#007a5a"/>}
      </MessagingChrome>
      <Caption kicker="06 · ANSWER" line="One tap, three questions, anonymous — done in under 90 seconds."/>
    </SceneFade>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 7: RESULTS DASHBOARD — line trends up (58-70s = 12s)
// ═══════════════════════════════════════════════════════════════════════════
function SceneResults() {
  const { localTime } = useSprite();

  // Data: 4 surveys over time, scores trending UP
  const surveys = [
    { name: 'Q1 Pulse',         date: 'Jan',  score: 6.2 },
    { name: 'Q1 Wellbeing',     date: 'Feb',  score: 6.6 },
    { name: 'Q2 Pulse',         date: 'Apr',  score: 7.1 },
    { name: 'Q2 Manager check', date: 'May',  score: 7.4 },
    { name: 'Q3 Pulse',         date: 'Aug',  score: 8.1 },
  ];

  const W = 940, H = 320, PAD = 50;
  const innerW = W - PAD * 2;
  const innerH = H - PAD * 2;
  const xAt = (i) => PAD + (i / (surveys.length - 1)) * innerW;
  const yAt = (s) => PAD + (1 - s / 10) * innerH;

  // Animated draw: line draws across with progress 0..1
  const drawStart = 1.6, drawDur = 3.6;
  const drawP = clamp((localTime - drawStart) / drawDur, 0, 1);
  const drawEased = Easing.easeInOutCubic(drawP);

  // Build path
  const pts = surveys.map((s, i) => ({ x: xAt(i), y: yAt(s.score), s }));
  // Smooth path using cubic bezier
  const buildPath = (fract) => {
    const lastIdx = (surveys.length - 1) * fract;
    let d = `M ${pts[0].x} ${pts[0].y}`;
    for (let i = 1; i < surveys.length; i++) {
      const localFrac = clamp(lastIdx - (i - 1), 0, 1);
      if (localFrac <= 0) break;
      const x0 = pts[i - 1].x, y0 = pts[i - 1].y;
      const x1 = pts[i].x, y1 = pts[i].y;
      const cx1 = x0 + (x1 - x0) * 0.5;
      const cx2 = x0 + (x1 - x0) * 0.5;
      const x = x0 + (x1 - x0) * localFrac;
      const y = y0 + (y1 - y0) * localFrac;
      // simple smoothed curve segment
      d += ` Q ${cx1} ${y0}, ${x} ${y}`;
    }
    return d;
  };

  const linePath = buildPath(drawEased);
  // Filled area path
  const areaPath = `${linePath} L ${xAt(Math.min(surveys.length - 1, Math.floor((surveys.length - 1) * drawEased + 0.999)))} ${H - PAD} L ${pts[0].x} ${H - PAD} Z`;

  // Dot visible when its x is reached
  const dotVis = (i) => {
    const lastIdx = (surveys.length - 1) * drawEased;
    return clamp((lastIdx - i + 0.6) / 0.5, 0, 1);
  };

  // Trend chip animates from neutral to positive
  const trendShown = drawP > 0.8;

  // Card scores (KPIs) — count up
  const counter = (target, startT = 3.2, dur = 1.4) => {
    const p = clamp((localTime - startT) / dur, 0, 1);
    return (Easing.easeOutCubic(p) * target).toFixed(1);
  };

  return (
    <SceneFade>
      <KoryoApp active="results">
        <div style={{ position: 'absolute', inset: 0, padding: '32px 48px' }}>
          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
            <div style={{ width: 38, height: 38, borderRadius: 9, background: KORYO.indigoSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <NavIcon kind="results" size={20} color={KORYO.indigo}/>
            </div>
            <div>
              <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: '-0.02em' }}>Results</div>
              <div style={{ fontSize: 12.5, color: KORYO.inkSoft, marginTop: 2 }}>Score evolution across 5 surveys</div>
            </div>
          </div>

          {/* AI trend predictions banner */}
          <div style={{
            background: '#fff',
            borderRadius: 12, padding: '14px 18px',
            display: 'flex', alignItems: 'center', gap: 14,
            boxShadow: '0 1px 0 rgba(15,18,40,0.04)',
            marginBottom: 16,
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: 8,
              background: `linear-gradient(135deg, ${KORYO.indigo}, oklch(60% 0.21 320))`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontSize: 16, fontWeight: 800,
            }}>✦</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 15, color: KORYO.ink }}>Trend predictions</div>
              <div style={{ fontSize: 12.5, color: KORYO.inkSoft }}>AI-detected changes between your last two surveys</div>
            </div>
            <div style={{
              padding: '8px 14px', borderRadius: 7,
              background: KORYO.indigo, color: '#fff',
              fontSize: 13, fontWeight: 700,
            }}>✦ Detect trends</div>
          </div>

          {/* Chart panel */}
          <div style={{
            background: '#fff', borderRadius: 14, padding: '20px 24px',
            boxShadow: '0 1px 0 rgba(15,18,40,0.04), 0 8px 28px -14px rgba(15,18,40,0.18)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
              <div>
                <div style={{ fontWeight: 800, fontSize: 17 }}>Score over time</div>
                <div style={{ fontSize: 12.5, color: KORYO.inkSoft, marginTop: 2 }}>5 surveys · Engagement</div>
              </div>
              <div style={{ flex: 1 }}/>
              <div style={{ display: 'flex', gap: 6, marginRight: 10 }}>
                <div style={{ padding: '6px 12px', background: '#fff', border: `1px solid ${KORYO.indigo}`, borderRadius: 6, fontSize: 12, fontWeight: 700, color: KORYO.indigoText }}>Global</div>
                <div style={{ padding: '6px 12px', borderRadius: 6, fontSize: 12, fontWeight: 600, color: KORYO.inkSoft }}>By category</div>
                <div style={{ padding: '6px 12px', borderRadius: 6, fontSize: 12, fontWeight: 600, color: KORYO.inkSoft }}>eNPS</div>
              </div>
              <div style={{
                padding: '6px 12px', borderRadius: 999,
                background: trendShown ? KORYO.greenBg : '#f1f1f6',
                color: trendShown ? KORYO.green : KORYO.inkSoft,
                fontSize: 12.5, fontWeight: 700,
                transition: 'background 0.3s, color 0.3s',
              }}>{trendShown ? '↑ 1.9 pts' : '— —'}</div>
            </div>

            {/* SVG chart */}
            <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', width: '100%', height: 'auto' }}>
              <defs>
                <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={KORYO.indigo} stopOpacity="0.28"/>
                  <stop offset="100%" stopColor={KORYO.indigo} stopOpacity="0"/>
                </linearGradient>
              </defs>
              {/* Gridlines */}
              {[0, 2, 4, 6, 8, 10].map((v) => (
                <g key={v}>
                  <line x1={PAD} y1={yAt(v)} x2={W - PAD} y2={yAt(v)} stroke={KORYO.borderSoft} strokeWidth="1"/>
                  <text x={PAD - 8} y={yAt(v) + 4} fontSize="11" fill={KORYO.inkMute} textAnchor="end">{v}</text>
                </g>
              ))}
              {/* x-axis labels */}
              {surveys.map((s, i) => (
                <text key={i} x={xAt(i)} y={H - PAD + 22} fontSize="11" fill={KORYO.inkSoft} textAnchor="middle" fontWeight="600">{s.name}</text>
              ))}
              {/* area */}
              <path d={areaPath} fill="url(#areaGrad)" opacity={drawP > 0.05 ? 1 : 0}/>
              {/* line */}
              <path d={linePath} fill="none" stroke={KORYO.indigo} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/>
              {/* dots */}
              {pts.map((p, i) => (
                <g key={i} opacity={dotVis(i)}>
                  <circle cx={p.x} cy={p.y} r="7" fill="#fff" stroke={KORYO.indigo} strokeWidth="3"/>
                  <text x={p.x} y={p.y - 16} fontSize="13" fill={KORYO.indigoText} textAnchor="middle" fontWeight="800">{p.s.score.toFixed(1)}</text>
                </g>
              ))}
            </svg>
          </div>

          {/* 3-stat row beneath */}
          <div style={{
            marginTop: 16,
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14,
            opacity: clamp((localTime - 3.0) / 0.5, 0, 1),
          }}>
            {[
              { l: 'Engagement', v: counter(8.1), delta: '+1.0', color: KORYO.green },
              { l: 'Wellbeing',  v: counter(7.6), delta: '+0.6', color: KORYO.green },
              { l: 'Response rate', v: '94%',     delta: '+12%', color: KORYO.green, raw: true },
            ].map((it, i) => (
              <div key={i} style={{
                background: '#fff', borderRadius: 10, padding: '14px 18px',
                boxShadow: '0 1px 0 rgba(15,18,40,0.04)',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div>
                  <div style={{ fontSize: 11, color: KORYO.inkMute, fontWeight: 700, letterSpacing: '0.12em' }}>{it.l.toUpperCase()}</div>
                  <div style={{ fontSize: 26, fontWeight: 800, color: KORYO.ink, marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>
                    {it.raw ? it.v : it.v}
                  </div>
                </div>
                <div style={{ flex: 1 }}/>
                <div style={{ padding: '4px 10px', borderRadius: 999, background: KORYO.greenBg, color: it.color, fontSize: 12, fontWeight: 800 }}>
                  ↑ {it.delta}
                </div>
              </div>
            ))}
          </div>
        </div>
      </KoryoApp>
      <Caption kicker="07 · RESULTS" line="Watch engagement trend over time — every survey, every team."/>
    </SceneFade>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 8: RADAR CHART (70-80s = 10s)
// ═══════════════════════════════════════════════════════════════════════════
function SceneRadar() {
  const { localTime } = useSprite();

  const categories = [
    { name: 'Engagement',           score: 8.2 },
    { name: 'Diversity & Inclusion', score: 7.4 },
    { name: 'Health & Wellbeing',   score: 7.6 },
    { name: 'Manager Support',      score: 8.5 },
    { name: 'Growth',               score: 6.9 },
    { name: 'Recognition',          score: 7.1 },
  ];

  const cx = 380, cy = 320, R = 220;
  const n = categories.length;
  const angle = (i) => -Math.PI / 2 + (i / n) * Math.PI * 2;
  const point = (i, s) => {
    const r = (s / 10) * R;
    return { x: cx + Math.cos(angle(i)) * r, y: cy + Math.sin(angle(i)) * r };
  };

  // Animated radar: each axis grows from center over its window
  const axisStart = 1.5;
  const axisDur = 2.5;
  const axisP = clamp((localTime - axisStart) / axisDur, 0, 1);
  const axisEased = Easing.easeInOutCubic(axisP);

  const animPts = categories.map((c, i) => {
    const pt = point(i, c.score * axisEased);
    return pt;
  });
  const polyPoints = animPts.map(p => `${p.x},${p.y}`).join(' ');

  // Right-side: category list, each highlighting in turn
  const highlightIdx = Math.floor(clamp((localTime - 5.2) / 0.7, 0, n - 0.01));

  return (
    <SceneFade>
      <KoryoApp active="results">
        <div style={{ position: 'absolute', inset: 0, padding: '32px 48px' }}>
          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <div style={{ width: 38, height: 38, borderRadius: 9, background: KORYO.indigoSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <NavIcon kind="results" size={20} color={KORYO.indigo}/>
            </div>
            <div>
              <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: '-0.02em' }}>Q3 Pulse — Engagement & Wellbeing</div>
              <div style={{ fontSize: 12.5, color: KORYO.inkSoft, marginTop: 2 }}>119 of 124 responded · response rate 96%</div>
            </div>
            <div style={{ flex: 1 }}/>
            <div style={{ padding: '6px 14px', borderRadius: 999, background: KORYO.greenBg, color: KORYO.green, fontSize: 13, fontWeight: 800 }}>8.1 ↑</div>
          </div>

          {/* Tabs */}
          <div style={{ display: 'flex', gap: 0, marginTop: 8, marginBottom: 18, border: `1px solid ${KORYO.border}`, borderRadius: 8, overflow: 'hidden', background: '#fff', maxWidth: 480 }}>
            <div style={{ flex: 1, padding: '9px 18px', textAlign: 'center', fontSize: 13, color: KORYO.inkSoft, fontWeight: 600 }}>Categories</div>
            <div style={{ flex: 1, padding: '9px 18px', textAlign: 'center', fontSize: 13, color: KORYO.indigoText, fontWeight: 800, border: `2px solid ${KORYO.indigo}`, borderRadius: 7, margin: -1 }}>Radar chart</div>
          </div>

          {/* Chart panel */}
          <div style={{
            background: '#fff', borderRadius: 14, padding: 24,
            boxShadow: '0 1px 0 rgba(15,18,40,0.04), 0 8px 28px -14px rgba(15,18,40,0.18)',
            display: 'flex', gap: 32,
            alignItems: 'center',
          }}>
            <svg width="760" height="640" viewBox="0 0 760 640" style={{ flexShrink: 0 }}>
              {/* Grid polygons */}
              {[0.25, 0.5, 0.75, 1].map((scale, gi) => {
                const ps = categories.map((_, i) => {
                  const pt = point(i, 10 * scale);
                  return `${pt.x},${pt.y}`;
                }).join(' ');
                return <polygon key={gi} points={ps} fill="none" stroke={KORYO.borderSoft} strokeWidth="1"/>;
              })}
              {/* Axis lines */}
              {categories.map((_, i) => {
                const pt = point(i, 10);
                return <line key={i} x1={cx} y1={cy} x2={pt.x} y2={pt.y} stroke={KORYO.borderSoft} strokeWidth="1"/>;
              })}
              {/* Scale labels */}
              {[2, 4, 6, 8, 10].map((v, i) => (
                <text key={v} x={cx + 6} y={cy - (v / 10) * R + 4} fontSize="10" fill={KORYO.inkMute}>{v}</text>
              ))}
              {/* Data polygon */}
              <polygon points={polyPoints} fill={KORYO.indigo} fillOpacity="0.22" stroke={KORYO.indigo} strokeWidth="2.5"/>
              {/* Data points */}
              {animPts.map((p, i) => (
                <g key={i}>
                  <circle cx={p.x} cy={p.y} r={highlightIdx === i ? 7 : 5} fill="#fff" stroke={KORYO.indigo} strokeWidth="3"/>
                </g>
              ))}
              {/* Category labels */}
              {categories.map((c, i) => {
                const lbl = point(i, 12.4);
                return (
                  <g key={i}>
                    <text x={lbl.x} y={lbl.y}
                      fontSize="13" fontWeight={highlightIdx === i ? 800 : 600}
                      fill={highlightIdx === i ? KORYO.indigoText : KORYO.ink}
                      textAnchor="middle" alignmentBaseline="middle"
                    >{c.name}</text>
                  </g>
                );
              })}
            </svg>

            {/* Categories list */}
            <div style={{ flex: 1, minWidth: 280 }}>
              <div style={{ fontSize: 11, color: KORYO.inkMute, fontWeight: 700, letterSpacing: '0.12em', marginBottom: 10 }}>CATEGORIES · HIGHEST FIRST</div>
              {categories.slice().sort((a, b) => b.score - a.score).map((c, i) => {
                const isHigh = c.score >= 7.5;
                return (
                  <div key={i} style={{
                    padding: '11px 14px',
                    borderRadius: 8,
                    background: isHigh ? KORYO.greenBg : KORYO.amberBg,
                    marginBottom: 6,
                    display: 'flex', alignItems: 'center',
                    border: highlightIdx === categories.indexOf(c) ? `2px solid ${KORYO.indigo}` : '2px solid transparent',
                    transition: 'border-color 0.2s',
                  }}>
                    <div style={{ fontWeight: 700, fontSize: 14, color: KORYO.ink }}>{c.name}</div>
                    <div style={{ flex: 1 }}/>
                    <div style={{
                      width: 130, height: 5, borderRadius: 3,
                      background: 'rgba(0,0,0,0.06)', marginRight: 12,
                      position: 'relative', overflow: 'hidden',
                    }}>
                      <div style={{
                        position: 'absolute', left: 0, top: 0, bottom: 0,
                        width: `${(c.score / 10) * 100 * axisEased}%`,
                        background: isHigh ? KORYO.green : KORYO.amber,
                      }}/>
                    </div>
                    <div style={{ fontWeight: 800, fontSize: 14, color: isHigh ? KORYO.green : KORYO.amber, width: 36, textAlign: 'right' }}>
                      {c.score.toFixed(1)} ↑
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </KoryoApp>
      <Caption kicker="08 · CATEGORIES" line="See your team's strengths and gaps across every dimension."/>
    </SceneFade>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 9: AI ANALYSIS + COMMENTS (80-87s = 7s)
// ═══════════════════════════════════════════════════════════════════════════
function SceneComments() {
  const { localTime } = useSprite();

  const aiText = "Engagement and Manager Support drove this quarter's lift (+1.0). Three repeated themes in open comments: clearer quarterly goals, more cross-team rituals, and continued flexibility on hours. Recommended focus: goal-setting in October planning.";
  const aiN = Math.floor(clamp((localTime - 1.4) / 3.0, 0, 1) * aiText.length);
  const aiShown = aiText.slice(0, aiN);

  const comments = [
    { who: 'Anonymous · Product', text: 'Loving the new flexible hours policy — it actually changed my mornings.', sentiment: 'pos' },
    { who: 'Anonymous · Design',  text: 'More clarity on quarterly goals would really help our team plan ahead.', sentiment: 'neu' },
    { who: 'Anonymous · Eng',     text: "Cross-team comms could be tighter; the new app forum helps but isn't enough.", sentiment: 'neu' },
    { who: 'Anonymous · Ops',     text: 'Manager 1:1s are the highlight of my week. Please keep them protected.', sentiment: 'pos' },
  ];
  const commentIn = (i) => clamp((localTime - 4.2 - i * 0.18) / 0.4, 0, 1);

  return (
    <SceneFade>
      <KoryoApp active="results">
        <div style={{ position: 'absolute', inset: 0, padding: '32px 48px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
            <div style={{ width: 38, height: 38, borderRadius: 9, background: KORYO.indigoSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <NavIcon kind="results" size={20} color={KORYO.indigo}/>
            </div>
            <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.02em' }}>Q3 Pulse — Insights</div>
          </div>

          {/* AI analysis card */}
          <div style={{
            background: 'linear-gradient(135deg, #0e0e1a, #1c1933)',
            color: '#fff',
            borderRadius: 14, padding: '22px 26px',
            boxShadow: '0 12px 32px -16px rgba(15,18,40,0.4)',
            marginBottom: 18,
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', right: -40, top: -40,
              width: 200, height: 200,
              borderRadius: '50%',
              background: 'radial-gradient(circle, oklch(72% 0.20 280 / 0.4), transparent 70%)',
            }}/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, position: 'relative' }}>
              <div style={{ width: 34, height: 34, borderRadius: 8, background: 'oklch(72% 0.20 280)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800 }}>✦</div>
              <div style={{ fontWeight: 800, fontSize: 16 }}>AI analysis</div>
              <div style={{ fontSize: 11, color: 'oklch(80% 0.05 280)', padding: '2px 8px', borderRadius: 4, background: 'rgba(255,255,255,0.06)' }}>Generated just now</div>
            </div>
            <div style={{
              fontSize: 15, color: '#dbd9ef', lineHeight: 1.55,
              position: 'relative',
              minHeight: 84,
            }}>
              {aiShown}
              {aiN > 0 && aiN < aiText.length && <span style={{ borderLeft: '2px solid oklch(78% 0.16 280)', marginLeft: 1 }}/>}
            </div>
          </div>

          {/* Comments */}
          <div style={{
            background: '#fff', borderRadius: 14, padding: '18px 22px',
            boxShadow: '0 1px 0 rgba(15,18,40,0.04), 0 8px 28px -14px rgba(15,18,40,0.18)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
              <div style={{ fontWeight: 800, fontSize: 16 }}>Open comments</div>
              <span style={{ marginLeft: 8, padding: '2px 8px', background: '#f1f1f6', borderRadius: 4, fontSize: 12, color: KORYO.inkSoft, fontWeight: 700 }}>52</span>
              <div style={{ flex: 1 }}/>
              <div style={{ display: 'flex', gap: 8 }}>
                <Btn variant="outline">Export CSV</Btn>
                <Btn variant="outline">Export PDF</Btn>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {comments.map((c, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 12,
                  padding: '14px 16px',
                  background: '#fafaff',
                  border: `1px solid ${KORYO.borderSoft}`,
                  borderRadius: 10,
                  opacity: commentIn(i),
                  transform: `translateY(${(1 - commentIn(i)) * 10}px)`,
                }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 6,
                    background: c.sentiment === 'pos' ? KORYO.greenBg : '#f1f1f6',
                    color: c.sentiment === 'pos' ? KORYO.green : KORYO.inkSoft,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0, fontSize: 14,
                  }}>{c.sentiment === 'pos' ? '☺' : '◌'}</div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 12, color: KORYO.inkMute, fontWeight: 700, marginBottom: 3 }}>{c.who}</div>
                    <div style={{ fontSize: 14, color: KORYO.ink, lineHeight: 1.45 }}>"{c.text}"</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </KoryoApp>
      <Caption kicker="09 · INSIGHTS" line="AI surfaces themes — and every anonymous comment is one click away."/>
    </SceneFade>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SCENE 10: CTA — "Try Koryo on Slack" (87-95s = 8s)
// ═══════════════════════════════════════════════════════════════════════════
function SceneCTA() {
  const { localTime, duration } = useSprite();
  const logoIn = Easing.easeOutCubic(clamp(localTime / 0.7, 0, 1));
  const titleIn = Easing.easeOutCubic(clamp((localTime - 0.6) / 0.6, 0, 1));
  const subIn = Easing.easeOutCubic(clamp((localTime - 1.0) / 0.6, 0, 1));
  const btnIn = Easing.easeOutBack(clamp((localTime - 1.5) / 0.7, 0, 1));
  const urlIn = Easing.easeOutCubic(clamp((localTime - 2.8) / 0.7, 0, 1));
  // gentle parallax
  const drift = Math.sin(localTime * 0.6) * 6;

  return (
    <SceneFade>
      <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
        <CrossBG/>
        {/* Soft radial accent */}
        <div style={{
          position: 'absolute',
          left: '50%', top: '50%',
          transform: 'translate(-50%, -50%)',
          width: 900, height: 900,
          borderRadius: '50%',
          background: `radial-gradient(circle, ${KORYO.indigo}22, transparent 60%)`,
          pointerEvents: 'none',
        }}/>

        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          gap: 20,
          fontFamily: KORYO.font,
        }}>
          <div style={{
            opacity: logoIn,
            transform: `translateY(${(1 - logoIn) * 20 + drift * 0.3}px) scale(${0.92 + logoIn * 0.08})`,
          }}>
            <KoryoAppIcon size={104}/>
          </div>
          <div style={{
            fontSize: 72, fontWeight: 800,
            letterSpacing: '-0.035em',
            color: KORYO.ink,
            opacity: titleIn,
            transform: `translateY(${(1 - titleIn) * 14}px)`,
            lineHeight: 1,
          }}>Koryo</div>
          <div style={{
            fontSize: 22, color: KORYO.inkSoft,
            opacity: subIn,
            transform: `translateY(${(1 - subIn) * 10}px)`,
            textAlign: 'center',
            maxWidth: 720,
            lineHeight: 1.35,
          }}>
            Engagement surveys, where your team already works.
          </div>
          <div style={{
            marginTop: 18,
            display: 'flex', gap: 14,
            opacity: btnIn,
            transform: `scale(${0.96 + btnIn * 0.04}) translateY(${(1 - btnIn) * 10}px)`,
          }}>
            <div style={{
              padding: '16px 32px',
              background: KORYO.ink, color: '#fff',
              borderRadius: 10,
              fontSize: 17, fontWeight: 700,
              display: 'inline-flex', alignItems: 'center', gap: 10,
              boxShadow: '0 8px 24px -10px rgba(15,18,40,0.4)',
            }}>
              <SlackGlyph size={20}/>
              Try Koryo on Slack
            </div>
            <div style={{
              padding: '16px 28px',
              background: '#fff', color: KORYO.ink,
              border: `1px solid ${KORYO.border}`,
              borderRadius: 10,
              fontSize: 17, fontWeight: 600,
            }}>
              koryo.work
            </div>
          </div>

          {/* AXON APPS website highlight */}
          <div style={{
            marginTop: 38,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
            opacity: urlIn,
            transform: `translateY(${(1 - urlIn) * 14}px)`,
          }}>
            <div style={{
              fontSize: 11, color: KORYO.inkMute,
              letterSpacing: '0.32em', fontWeight: 600,
            }}>
              AN AXON APPS PRODUCT
            </div>
            <div style={{
              fontSize: 38, fontWeight: 700,
              fontFamily: KORYO.fontMono,
              letterSpacing: '-0.01em',
              color: KORYO.ink,
              padding: '10px 28px',
              background: '#fff',
              border: `1.5px solid ${KORYO.indigo}33`,
              borderRadius: 12,
              boxShadow: `0 8px 24px -12px ${KORYO.indigo}44`,
              whiteSpace: 'nowrap',
              wordBreak: 'keep-all',
            }}>
              www.axon-apps.com
            </div>
          </div>
        </div>
      </div>
    </SceneFade>
  );
}

Object.assign(window, {
  SceneMessagingDM, SceneAnswerModal, SceneResults, SceneRadar, SceneComments, SceneCTA,
});
