// ════════════════════════════════════════════════════════════════
// Agentic Forge · Manager Day · v2 · 180s
// Surface: forge.ledgerline.com — intelligence surface, dashboard mode.
// All AF content renders natively as dashboard cards / drill-down panels
// / admin views. No popups, no toasts. Burned-in subtitles throughout.
// ════════════════════════════════════════════════════════════════

const T = window.TOKENS;

const MD = {
  carbon: '#080c14',
  charcoal: '#1c1e24',
  charcoalLine: '#2a2d35',
  charcoalAlt: '#161820',
  bgDim: '#0f1218',
  textWhite: '#ffffff',
  textGray: '#a0a4ab',
  textDim: '#6e7178',
  textMute: '#5a5d64',
  green: '#00da41',
  blue: '#3b82f6',
  red: '#ff6b6b',
  amber: '#f4b400',
};

const ease = t => { if (t<=0) return 0; if (t>=1) return 1; return 1 - Math.pow(1-t, 3); };
const fade = (time, start, dur=0.2) => Math.max(0, Math.min(1, ease((time-start)/dur)));
const slideUp = (time, start, dur=0.2, dist=4) => (1 - fade(time, start, dur)) * dist;
// Gradient — display-size emphasized green text. Reference as the "gradient" style.
const gradientStyle = {
  background: 'linear-gradient(135deg, #00E87B 0%, #00da41 50%, #00B35A 100%)',
  WebkitBackgroundClip: 'text',
  WebkitTextFillColor: 'transparent',
  backgroundClip: 'text',
  textShadow: 'none',
};

// ─── Chip ──────────────────────────────────────────────────────
function AFChip({ skill, start = 0 }) {
  const time = useTime();
  const o = fade(time, start, 0.18);
  return (
    <div style={{
      display:'inline-flex', alignItems:'center', gap:8,
      background: MD.charcoal,
      borderLeft:`2px solid ${MD.green}`,
      borderRadius:4, padding:'4px 10px',
      fontFamily:T.sans, fontSize:11, fontWeight:500, color:MD.textGray,
      letterSpacing:'0.01em',
      opacity:o, transform:`translateY(${slideUp(time,start)}px)`,
    }}>
      <span style={{ width:6, height:6, borderRadius:3, background:MD.green, flexShrink:0 }} />
      <span>Agentic Forge · {skill}</span>
    </div>
  );
}

// ─── Card ──────────────────────────────────────────────────────
function MDCard({ children, accent, start = 0, style, padding = 16 }) {
  const time = useTime();
  const o = fade(time, start, 0.22);
  return (
    <div style={{
      position:'relative',
      background: MD.charcoal,
      border:`1px solid ${MD.charcoalLine}`,
      borderRadius:12, padding,
      fontFamily:T.sans, color:MD.textWhite,
      opacity:o, transform:`translateY(${slideUp(time,start)}px)`,
      overflow:'hidden',
      ...style,
    }}>
      {accent && <div style={{ position:'absolute', left:0, top:0, bottom:0, width:4, background:accent }} />}
      {children}
    </div>
  );
}
function CardDivider() { return <div style={{ height:1, background:MD.charcoalLine, margin:'12px 0' }} />; }
function SectionLabel({ children }) { return <div style={{ fontSize:13, color:MD.textGray, fontWeight:500, marginBottom:8 }}>{children}</div>; }

// ─── Browser chrome + intelligence surface shell ───────────────
function BrowserShell({ url, children }) {
  return (
    <div style={{ position:'absolute', inset:0, background:'#0a0d12', display:'flex', flexDirection:'column' }}>
      <div style={{ height:42, background:'#14171d', borderBottom:'1px solid #1e2128', display:'flex', alignItems:'center', padding:'0 14px', gap:14, flexShrink:0 }}>
        <div style={{ display:'flex', gap:8 }}>
          <div style={{ width:12, height:12, borderRadius:6, background:'#ff5f57' }} />
          <div style={{ width:12, height:12, borderRadius:6, background:'#febc2e' }} />
          <div style={{ width:12, height:12, borderRadius:6, background:'#28c840' }} />
        </div>
        <div style={{ flex:1, display:'flex', justifyContent:'center' }}>
          <div style={{ background:'#0a0d12', border:'1px solid #1e2128', borderRadius:6, padding:'5px 14px', fontSize:12, color:MD.textGray, fontFamily:T.mono, minWidth:420, textAlign:'center' }}>
            <span style={{ color:MD.textDim }}>🔒 </span>{url}
          </div>
        </div>
        <div style={{ width:60 }} />
      </div>
      {children}
    </div>
  );
}

function ForgeChrome({ url, activeNav, children }) {
  return (
    <BrowserShell url={url}>
      <div style={{ flex:1, display:'flex', minHeight:0, background:MD.carbon }}>
        <Sidebar activeNav={activeNav} />
        <div style={{ flex:1, display:'flex', flexDirection:'column', minWidth:0 }}>
          <TopBar />
          <div style={{ flex:1, overflow:'hidden', position:'relative' }}>
            {children}
          </div>
        </div>
      </div>
    </BrowserShell>
  );
}

function TopBar() {
  return (
    <div style={{ height:54, background:MD.bgDim, borderBottom:`1px solid ${MD.charcoalLine}`, display:'flex', alignItems:'center', padding:'0 28px', gap:24, flexShrink:0 }}>
      <div style={{ display:'flex', alignItems:'center', gap:8 }}>
        <span style={{ width:9, height:9, borderRadius:5, background:MD.green }} />
        <span style={{ fontFamily:T.sans, fontWeight:500, fontSize:15, color:MD.textWhite, letterSpacing:'-0.01em' }}>Agentic Forge</span>
      </div>
      <div style={{ display:'flex', gap:4, marginLeft:14 }}>
        <ProjectTab name="platform" active />
        <ProjectTab name="compliance-suite" />
      </div>
      <div style={{ marginLeft:'auto', display:'flex', alignItems:'center', gap:14 }}>
        <span style={{ fontSize:12, color:MD.textGray, fontFamily:T.mono }}>Mon · Apr 14</span>
        <div style={{ width:30, height:30, borderRadius:15, background:'#3b4a6b', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:13, fontWeight:500 }}>P</div>
      </div>
    </div>
  );
}
function ProjectTab({ name, active }) {
  return (
    <div style={{
      padding:'5px 12px', borderRadius:6, fontSize:13,
      background: active ? MD.charcoal : 'transparent',
      color: active ? MD.textWhite : MD.textGray,
      border: active ? `1px solid ${MD.charcoalLine}` : '1px solid transparent',
      fontWeight: active ? 500 : 400,
    }}>{name}</div>
  );
}

function Sidebar({ activeNav }) {
  const items = [
    ['Dashboard', 'dashboard'],
    ['Calibration', 'calibration'],
    ['Governance', 'governance'],
    ['Skills', 'skills'],
    ['Admin', 'admin'],
    ['Integrations', 'integrations'],
  ];
  return (
    <div style={{ width:240, background:MD.bgDim, borderRight:`1px solid ${MD.charcoalLine}`, flexShrink:0, padding:'18px 0', display:'flex', flexDirection:'column', gap:2 }}>
      <div style={{ padding:'4px 22px', fontSize:11, color:MD.textDim, letterSpacing:'0.06em', fontWeight:500, marginBottom:8 }}>WORKSPACE</div>
      {items.map(([label, key]) => {
        const active = key === activeNav;
        return (
          <div key={key} style={{
            padding:'8px 22px', fontSize:14,
            background: active ? MD.charcoal : 'transparent',
            color: active ? MD.textWhite : MD.textGray,
            borderLeft: active ? `2px solid ${MD.green}` : '2px solid transparent',
            fontWeight: active ? 500 : 400,
            display:'flex', alignItems:'center', gap:10,
          }}>
            <NavIcon name={key} active={active} />
            <span>{label}</span>
          </div>
        );
      })}
      <div style={{ marginTop:'auto', padding:'14px 22px', fontSize:11, color:MD.textDim, fontFamily:T.sans, lineHeight:1.5 }}>
        All data queryable via API · exportable to standard analytics tools
      </div>
    </div>
  );
}
function NavIcon({ name, active }) {
  const c = active ? MD.textWhite : MD.textDim;
  const sw = 1.5, s = 16;
  switch (name) {
    case 'dashboard': return <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><rect x="2" y="2" width="5" height="5" stroke={c} strokeWidth={sw}/><rect x="9" y="2" width="5" height="5" stroke={c} strokeWidth={sw}/><rect x="2" y="9" width="5" height="5" stroke={c} strokeWidth={sw}/><rect x="9" y="9" width="5" height="5" stroke={c} strokeWidth={sw}/></svg>;
    case 'calibration': return <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><path d="M2 13L6 9L9 11L14 4" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"/></svg>;
    case 'governance': return <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><path d="M8 2L2 4v4c0 3.5 2.5 6 6 6s6-2.5 6-6V4L8 2z" stroke={c} strokeWidth={sw} strokeLinejoin="round"/></svg>;
    case 'skills': return <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><circle cx="8" cy="6" r="2" stroke={c} strokeWidth={sw}/><path d="M3 14c0-2.5 2.2-4 5-4s5 1.5 5 4" stroke={c} strokeWidth={sw}/></svg>;
    case 'admin': return <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="2" stroke={c} strokeWidth={sw}/><path d="M8 1.5v2M8 12.5v2M14.5 8h-2M3.5 8h-2M12.6 3.4l-1.4 1.4M4.8 11.2l-1.4 1.4M12.6 12.6l-1.4-1.4M4.8 4.8L3.4 3.4" stroke={c} strokeWidth={sw} strokeLinecap="round"/></svg>;
    case 'integrations': return <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><circle cx="4" cy="8" r="2" stroke={c} strokeWidth={sw}/><circle cx="12" cy="4" r="2" stroke={c} strokeWidth={sw}/><circle cx="12" cy="12" r="2" stroke={c} strokeWidth={sw}/><path d="M6 8l4-4M6 8l4 4" stroke={c} strokeWidth={sw}/></svg>;
  }
}

function PageHeader({ breadcrumb }) {
  return (
    <div style={{ padding:'24px 36px 18px', borderBottom:`1px solid ${MD.charcoalLine}`, display:'flex', alignItems:'baseline', gap:8 }}>
      {breadcrumb.map((part, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span style={{ color:MD.textDim, fontSize:14 }}>›</span>}
          <span style={{ fontSize: i === breadcrumb.length - 1 ? 22 : 14, fontWeight: i === breadcrumb.length - 1 ? 500 : 400, color: i === breadcrumb.length - 1 ? MD.textWhite : MD.textGray, letterSpacing:'-0.01em' }}>{part}</span>
        </React.Fragment>
      ))}
    </div>
  );
}

// ─── Subtitles ────────────────────────────────────────────────
const SUBS = [
  { t: 0.5,   end: 9.0,   text: "Priya leads platform engineering at Ledgerline." },
  { t: 9.2,   end: 14.5,  text: "She doesn't run standups for status recovery anymore." },
  { t: 25.0,  end: 30.5,  text: "Three things need her this morning." },
  { t: 30.7,  end: 36.5,  text: "Each one names what the framework saw and why she should care." },
  { t: 38.5,  end: 43.5,  text: "Auth-flow estimates are getting worse." },
  { t: 43.7,  end: 48.0,  text: "Not because the engineers are sloppy." },
  { t: 48.2,  end: 52.0,  text: "Because they don't have context." },
  { t: 78.0,  end: 82.5,  text: "A skill regression." },
  { t: 82.7,  end: 88.5,  text: "Engineers have been overriding it more than usual." },
  { t: 88.7,  end: 94.5,  text: "Priya rolls it back without filing a ticket." },
  { t: 133.0, end: 138.0, text: "Weekly governance health." },
  { t: 138.2, end: 145.0, text: "One bypass attempt last week, caught and remediated within eighteen hours." },
  { t: 145.2, end: 151.0, text: "The next standup won't need to discuss it." },
  { t: 168.5, end: 175.5, text: "Coordination becomes the byproduct of doing the work." },
  { t: 175.7, end: 179.0, text: "Not the work itself." },
];

function Subtitles() {
  const time = useTime();
  const active = SUBS.find(s => time >= s.t && time <= s.end);
  if (!active) return null;
  const words = active.text.split(' ');
  const lines = [];
  let cur = '';
  for (const w of words) {
    const next = cur ? cur + ' ' + w : w;
    if (next.length > 42) { lines.push(cur); cur = w; } else cur = next;
  }
  if (cur) lines.push(cur);
  return (
    <div style={{ position:'absolute', left:0, right:0, bottom:80, display:'flex', justifyContent:'center', pointerEvents:'none', zIndex:50 }}>
      <div style={{ background:'rgba(28, 30, 36, 0.78)', borderRadius:4, padding:'8px 14px', maxWidth:'70%' }}>
        {lines.map((l, i) => (
          <div key={i} style={{ fontFamily:T.sans, fontWeight:500, fontSize:22, color:'#fff', textAlign:'center', lineHeight:1.35 }}>{l}</div>
        ))}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// SCENE 1 — Monday dashboard (0-38s)
// ════════════════════════════════════════════════════════════════
function Scene1() {
  const time = useTime();
  // Beats: 0-5 establish, 5-15 signal cards stream in, 15-28 attention items, 28-38 hold
  const c1 = 5.5, c2 = 5.7, c3 = 5.9, c4 = 6.1;  // signal cards
  const a1 = 15.5, a2 = 17.5, a3 = 19.5;          // attention items
  // Cursor moving to calibration card at 34
  const cursorMove = time > 34 ? Math.min(1, (time - 34) / 2.5) : 0;
  // From "Calibration health" card to sidebar Calibration item then Auth-flow click
  return (
    <ForgeChrome url="forge.ledgerline.com/dashboard" activeNav="dashboard">
      <PageHeader breadcrumb={['Dashboard', 'platform']} />
      <div style={{ padding:'24px 36px 32px', overflow:'auto', height:'calc(100% - 76px)' }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:20 }}>
          {/* LEFT — Today's signal */}
          <div>
            <div style={{ fontSize:13, color:MD.textDim, fontWeight:500, marginBottom:10, letterSpacing:'0.04em' }}>TODAY'S SIGNAL</div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
              <SignalCard start={c1} title="Stories in flight" value="12" valueColor={MD.textWhite} sub="+2 vs last Monday" />
              <SignalCard start={c2} title="Blocked decisions" value="2" valueColor={MD.amber} subLines={['DECISION-019: 21d', 'DECISION-024: 4d']} />
              <SignalCard start={c3} title="This week's velocity" value="8" valueColor={MD.green} sub="stories completed · ratio 1.12×" />
              <SignalCard start={c4} title="Calibration health" valueRow={<><span style={{ color:MD.red, fontSize:14 }}>⚠</span> <span style={{ color:MD.textWhite, fontSize:24, fontWeight:500 }}>1 alert</span></>} sub="auth-flow trending worse (1.45×)" actionable />
            </div>
          </div>

          {/* RIGHT — Attention */}
          <div>
            <div style={{ fontSize:13, color:MD.textDim, fontWeight:500, marginBottom:10, letterSpacing:'0.04em' }}>NEEDS YOU</div>
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <AttentionCard
                start={a1}
                title="1 governance waiver expires today"
                lines={[
                  ['WAIVER-001', '· STORY-041 coverage gap'],
                  ['Granted by you 5 days ago.', null],
                ]}
                action="confirm remediation or extend."
              />
              <AttentionCard
                start={a2}
                title="1 skill regression detected"
                lines={[
                  ['criteria-verification v3', null],
                  ['Override rate up from 4% (v2) to 11% (v3)', null],
                  ['over 7 days.', null],
                ]}
                action="review and consider rollback."
                actionLabel="Recommendation"
              />
              <AttentionCard
                start={a3}
                title="1 misuse pattern flagged"
                lines={[
                  ['Jessica · 7 vague Slack demand captures', null],
                  ['→ all required clarifying round-trips.', null],
                ]}
                action="suggest demand-capture conventions training."
                actionLabel="Suggestion"
              />
            </div>
          </div>
        </div>
      </div>
      {/* Cursor moving toward calibration health card around 34s */}
      {cursorMove > 0 && <Cursor x={310 + (1-cursorMove)*40} y={510 - (1-cursorMove)*30} />}
    </ForgeChrome>
  );
}

function SignalCard({ start, title, value, valueColor, valueRow, sub, subLines, actionable }) {
  return (
    <MDCard start={start} accent={actionable ? MD.green : null} padding={18}>
      <div style={{ fontSize:13, color:MD.textGray, fontWeight:500, marginBottom:14 }}>{title}</div>
      {valueRow ? (
        <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8 }}>{valueRow}</div>
      ) : (
        <div style={{ fontSize:36, fontWeight:500, color:valueColor || MD.textWhite, lineHeight:1, marginBottom:10, letterSpacing:'-0.02em' }}>{value}</div>
      )}
      {sub && <div style={{ fontSize:12, color:MD.textGray }}>{sub}</div>}
      {subLines && subLines.map((l, i) => (
        <div key={i} style={{ fontSize:12, color:MD.textGray, fontFamily:T.mono, lineHeight:1.6 }}>{l}</div>
      ))}
    </MDCard>
  );
}

function AttentionCard({ start, title, lines, action, actionLabel = 'Action' }) {
  return (
    <MDCard start={start} accent={MD.green} padding={16}>
      <div style={{ fontSize:14, color:MD.textWhite, fontWeight:500, marginBottom:10 }}>{title}</div>
      <div style={{ height:1, background:MD.charcoalLine, margin:'0 0 10px' }} />
      <div style={{ display:'flex', flexDirection:'column', gap:3, marginBottom:12 }}>
        {lines.map(([txt, sub], i) => (
          <div key={i} style={{ fontSize:13, color:MD.textWhite, lineHeight:1.5 }}>{txt}{sub && <span style={{ color:MD.textGray }}> {sub}</span>}</div>
        ))}
      </div>
      <div style={{ fontSize:13 }}>
        <span style={{ color:MD.textGray }}>{actionLabel}: </span>
        <span style={{ color:MD.textWhite }}>{action}</span>
      </div>
    </MDCard>
  );
}

function Cursor({ x, y }) {
  return (
    <svg width="20" height="22" viewBox="0 0 20 22" style={{ position:'absolute', left:x, top:y, pointerEvents:'none', zIndex:60, filter:'drop-shadow(0 1px 2px rgba(0,0,0,0.6))' }}>
      <path d="M2 1 L2 16 L6 13 L9 19 L11.5 18 L8.5 12 L14 11 Z" fill="#fff" stroke="#000" strokeWidth="1" />
    </svg>
  );
}

// ════════════════════════════════════════════════════════════════
// SCENE 2 — Calibration drill-down (38-78s)
// ════════════════════════════════════════════════════════════════
function Scene2({ sceneStart = 38 }) {
  const time = useTime();
  const t = time - sceneStart;
  const heroT = sceneStart + 4;
  const causeT = sceneStart + 17;
  return (
    <ForgeChrome url="forge.ledgerline.com/calibration/auth-flow" activeNav="calibration">
      <PageHeader breadcrumb={['Calibration', 'auth-flow']} />
      <div style={{ padding:'24px 36px 32px', overflow:'auto', height:'calc(100% - 76px)' }}>
        <AFChip skill="estimation-calibration" start={sceneStart + 1.5} />
        <div style={{ height:14 }} />
        <div style={{ fontSize:24, fontWeight:500, color:MD.textWhite, marginBottom:18, letterSpacing:'-0.01em', opacity:fade(time, sceneStart + 2.0, 0.3) }}>
          Auth-flow story estimates trending worse
        </div>

        <MDCard start={heroT} padding={22} style={{ marginBottom:18 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14, gap:24 }}>
            <div>
              <div style={{ fontSize:13, color:MD.textGray, marginBottom:4 }}>Category</div>
              <div style={{ fontSize:16, color:MD.textWhite, fontWeight:500 }}>auth-flow</div>
            </div>
            <div>
              <div style={{ fontSize:13, color:MD.textGray, marginBottom:4 }}>Project</div>
              <div style={{ fontSize:16, color:MD.textWhite, fontWeight:500, fontFamily:T.mono }}>PROJECT-platform</div>
            </div>
          </div>
          <div style={{ height:1, background:MD.charcoalLine, margin:'4px 0 18px' }} />
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:24 }}>
            <div>
              <StatRow label="Correction factor" value={<span><span style={{ color:MD.red, fontWeight:500 }}>1.45×</span> <span style={{ color:MD.textGray, fontSize:13 }}>(was 1.0× · 8w ago)</span></span>} />
              <StatRow label="Sample size" value="N = 11" />
              <StatRow label="Confidence" value="high" />
              <StatRow label="Trend" value={<span style={{ color:MD.red }}>degrading</span>} />
            </div>
            <div>
              <div style={{ fontSize:13, color:MD.textGray, marginBottom:10 }}>Last 4 weeks</div>
              <Sparkline values={[0.95, 1.02, 1.18, 1.32, 1.45]} />
            </div>
          </div>
        </MDCard>

        <MDCard start={causeT} accent={MD.blue} padding={20}>
          <div style={{ fontSize:14, color:MD.textWhite, fontWeight:500, marginBottom:10 }}>Probable cause</div>
          <div style={{ height:1, background:MD.charcoalLine, marginBottom:14 }} />
          <div style={{ fontSize:14, color:MD.textWhite, lineHeight:1.6, marginBottom:14 }}>
            Auth-flow stories estimated by engineers unfamiliar with{' '}
            <span style={{ fontFamily:T.mono, fontSize:13, color:MD.textGray, background:MD.bgDim, padding:'1px 6px', borderRadius:3 }}>DECISION-004</span> (JWT) and{' '}
            <span style={{ fontFamily:T.mono, fontSize:13, color:MD.textGray, background:MD.bgDim, padding:'1px 6px', borderRadius:3 }}>DECISION-007</span> (session strategy).
          </div>
          <div style={{ fontSize:14, color:MD.textWhite, lineHeight:1.6, marginBottom:18 }}>
            7 of last 11 auth stories: assigned to engineers with <span style={{ color:MD.textWhite, fontWeight:500 }}>&lt;90 days</span> exposure to those decisions.
          </div>
          <SectionLabel>Suggested action</SectionLabel>
          <ul style={{ margin:0, paddingLeft:18, fontSize:14, color:MD.textWhite, lineHeight:1.7 }}>
            <li>Route auth-flow stories to engineers with deeper context, or</li>
            <li>Add DECISION-004 + DECISION-007 to onboarding materials</li>
          </ul>
        </MDCard>
      </div>
    </ForgeChrome>
  );
}

function StatRow({ label, value }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', padding:'8px 0', borderBottom:`1px solid ${MD.charcoalLine}` }}>
      <span style={{ fontSize:13, color:MD.textGray }}>{label}</span>
      <span style={{ fontSize:14, color:MD.textWhite, fontWeight:400 }}>{value}</span>
    </div>
  );
}

function Sparkline({ values }) {
  const max = Math.max(...values);
  return (
    <div>
      <div style={{ display:'flex', alignItems:'flex-end', gap:6, height:60, marginBottom:8 }}>
        {values.map((v, i) => (
          <div key={i} style={{
            width:36, height: `${(v/max) * 100}%`,
            background: i === values.length - 1 ? MD.red : MD.green,
            opacity: 0.3 + 0.7 * (i / (values.length - 1)),
            borderRadius:2,
          }} />
        ))}
      </div>
      <div style={{ display:'flex', gap:6, fontFamily:T.mono, fontSize:11, color:MD.textGray }}>
        {values.map((v, i) => <span key={i} style={{ width:36, textAlign:'center' }}>{v.toFixed(2)}</span>)}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// SCENE 3 — Skill rollback (78-133s)
// ════════════════════════════════════════════════════════════════
function Scene3({ sceneStart = 78 }) {
  const time = useTime();
  const t = time - sceneStart;
  const headerT = sceneStart + 4;
  const timelineT = sceneStart + 8;
  const recoT = sceneStart + 18;
  const clickT = sceneStart + 35;
  const successT = sceneStart + 38;
  const showSuccess = time > successT - 0.1;

  return (
    <ForgeChrome url="forge.ledgerline.com/admin/skills" activeNav="skills">
      <PageHeader breadcrumb={['Skills', 'criteria-verification']} />
      <div style={{ padding:'24px 36px 32px', overflow:'auto', height:'calc(100% - 76px)' }}>
        <AFChip skill="criteria-verification" start={sceneStart + 1.5} />
        <div style={{ height:14 }} />

        <MDCard start={headerT} padding={20} style={{ marginBottom:18 }}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:24 }}>
            <div>
              <div style={{ fontSize:13, color:MD.textGray, marginBottom:4 }}>Skill</div>
              <div style={{ fontSize:16, color:MD.textWhite, fontWeight:500, fontFamily:T.mono }}>criteria-verification</div>
            </div>
            <div>
              <div style={{ fontSize:13, color:MD.textGray, marginBottom:4 }}>Agent</div>
              <div style={{ fontSize:16, color:MD.textWhite, fontWeight:500 }}>Code Reviewer · Quality</div>
            </div>
            <div>
              <div style={{ fontSize:13, color:MD.textGray, marginBottom:4 }}>Active version</div>
              <div style={{ fontSize:16, color:MD.textWhite, fontWeight:500 }}>v3</div>
            </div>
          </div>
        </MDCard>

        {/* Version timeline */}
        <div style={{ marginBottom:18, opacity:fade(time, timelineT, 0.3), transform:`translateY(${slideUp(time, timelineT, 0.3, 6)}px)` }}>
          <SectionLabel>Version timeline</SectionLabel>
          <div style={{ display:'flex', alignItems:'center', gap:14 }}>
            <VersionPill version="v1" duration="active 8 weeks" rate="3%" rateColor={MD.textWhite} />
            <Chevron />
            <VersionPill version="v2" duration="active 4 weeks" rate="4%" rateColor={MD.textWhite} />
            <Chevron />
            <VersionPill version="v3 (active)" duration="active 7 days" rate="11%" rateColor={MD.red} flagged />
          </div>
        </div>

        {!showSuccess && (
          <MDCard start={recoT} accent={MD.blue} padding={20}>
            <div style={{ fontSize:14, color:MD.textWhite, fontWeight:500, marginBottom:10 }}>Recommendation: rollback to v2</div>
            <div style={{ height:1, background:MD.charcoalLine, marginBottom:14 }} />
            <div style={{ fontSize:14, color:MD.textWhite, lineHeight:1.65, marginBottom:14 }}>
              The Calibration Engineer flagged this regression on Friday. v3's change history shows it added stricter
              visual-criteria evaluation that engineers are overriding for design-heavy stories — legitimate variance,
              not engineer error.
            </div>
            <SectionLabel>Override rate by story type (last 7 days)</SectionLabel>
            <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:18 }}>
              <OverrideRow label="Design-heavy stories" pct={32} color={MD.red} />
              <OverrideRow label="Standard stories" pct={4} color={MD.green} />
            </div>
            <div style={{ fontSize:13, color:MD.textGray, lineHeight:1.6, marginBottom:18 }}>
              One-click rollback creates v4 with v2's content. v3 archived for review. No redeployment needed.
              Effective immediately.
            </div>
            <div style={{ display:'flex', justifyContent:'flex-end', gap:10 }}>
              <button style={{ background:'transparent', border:`1px solid ${MD.charcoalLine}`, color:MD.textWhite, fontFamily:T.sans, fontSize:13, padding:'8px 14px', borderRadius:5 }}>Cancel</button>
              <button style={{
                background: time > clickT && time < successT ? '#00b835' : MD.green,
                border:'none', color:'#001106', fontFamily:T.sans, fontWeight:500, fontSize:13, padding:'8px 18px', borderRadius:5,
                boxShadow: time > clickT && time < successT ? `0 0 0 3px ${MD.green}40` : 'none',
              }}>
                {time > clickT && time < successT ? <Spinner /> : 'Rollback to v2 →'}
              </button>
            </div>
          </MDCard>
        )}

        {showSuccess && (
          <MDCard start={successT} accent={MD.green} padding={20}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}>
              <CheckGlyph />
              <span style={{ fontSize:14, color:MD.textWhite, fontWeight:500 }}>criteria-verification rolled back</span>
            </div>
            <div style={{ height:1, background:MD.charcoalLine, marginBottom:14 }} />
            <div style={{ fontSize:14, color:MD.textWhite, lineHeight:1.65, marginBottom:10 }}>
              v4 now active (v2 content). Effective for next agent invocation.
            </div>
            <div style={{ fontSize:14, color:MD.textWhite, lineHeight:1.65, marginBottom:14 }}>
              v3 archived with note: <span style={{ color:MD.textGray }}>"override regression — needs review of visual criteria handling."</span>
            </div>
            <div style={{ fontSize:13, color:MD.textGray, lineHeight:1.6 }}>
              Calibration Engineer will re-evaluate after N=10 invocations of v4.
            </div>
          </MDCard>
        )}
      </div>
    </ForgeChrome>
  );
}

function VersionPill({ version, duration, rate, rateColor, flagged }) {
  return (
    <div style={{
      flex:1, background:MD.charcoal,
      border: flagged ? `1px solid ${MD.red}` : `1px solid ${MD.charcoalLine}`,
      borderRadius:8, padding:'12px 16px',
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:14, color:MD.textWhite, fontWeight:500, marginBottom:4 }}>
        {version}
        {flagged && <span style={{ color:MD.red, fontSize:13 }}>⚠</span>}
      </div>
      <div style={{ fontSize:12, color:MD.textGray, marginBottom:6 }}>{duration}</div>
      <div style={{ fontSize:12, color:MD.textGray }}>override rate: <span style={{ color:rateColor, fontWeight:500 }}>{rate}</span></div>
    </div>
  );
}
function Chevron() {
  return <span style={{ color:MD.textDim, fontSize:18 }}>›</span>;
}
function OverrideRow({ label, pct, color }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:14 }}>
      <span style={{ fontSize:13, color:MD.textWhite, minWidth:200 }}>{label}</span>
      <div style={{ flex:1, height:6, background:MD.bgDim, borderRadius:3, overflow:'hidden' }}>
        <div style={{ width:`${pct*2}%`, height:'100%', background:color, borderRadius:3 }} />
      </div>
      <span style={{ fontSize:13, fontFamily:T.mono, color, fontWeight:500, minWidth:48, textAlign:'right' }}>{pct}%</span>
    </div>
  );
}
function Spinner() {
  const time = useTime();
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:8 }}>
      <svg width="14" height="14" viewBox="0 0 14 14" style={{ transform:`rotate(${(time*360)%360}deg)` }}>
        <circle cx="7" cy="7" r="5.5" stroke="rgba(0,17,6,0.3)" strokeWidth="1.6" fill="none" />
        <path d="M7 1.5 A5.5 5.5 0 0 1 12.5 7" stroke="#001106" strokeWidth="1.6" fill="none" strokeLinecap="round" />
      </svg>
      Applying…
    </span>
  );
}
function CheckGlyph() {
  return (
    <svg width="16" height="16" viewBox="0 0 14 14">
      <path d="M3 7.2 L6 10 L11.2 4.4" stroke={MD.green} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ════════════════════════════════════════════════════════════════
// SCENE 4 — Governance health (133-168s)
// ════════════════════════════════════════════════════════════════
function Scene4({ sceneStart = 133 }) {
  const time = useTime();
  const heroT = sceneStart + 4;
  const ruleT = sceneStart + 11;
  return (
    <ForgeChrome url="forge.ledgerline.com/governance/health" activeNav="governance">
      <PageHeader breadcrumb={['Governance', 'Weekly health · week of Apr 7']} />
      <div style={{ padding:'24px 36px 32px', overflow:'auto', height:'calc(100% - 76px)' }}>
        <AFChip skill="governance-health-analysis" start={sceneStart + 1.5} />
        <div style={{ height:14 }} />

        <MDCard start={heroT} padding={22} style={{ marginBottom:18 }}>
          <div style={{ fontSize:14, color:MD.textWhite, fontWeight:500, marginBottom:4 }}>Compliance-suite project · weekly health</div>
          <div style={{ fontSize:13, color:MD.textGray, marginBottom:14 }}>Apr 7 – Apr 13</div>
          <div style={{ height:1, background:MD.charcoalLine, marginBottom:18 }} />

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:24, marginBottom:20 }}>
            <BigStat label="Rules fired" value="47" color={MD.textWhite} />
            <BigStat label="Violations" value="3" color={MD.amber} />
            <BigStat label="Waivers" value="1" color={MD.textWhite} />
          </div>

          <div style={{ background:MD.bgDim, border:`1px solid ${MD.charcoalLine}`, borderRadius:8, padding:16 }}>
            <div style={{ fontSize:13, color:MD.textGray, marginBottom:10 }}>Bypass attempts: <span style={{ color:MD.textWhite, fontWeight:500 }}>1</span></div>
            <div style={{ fontSize:14, color:MD.textWhite, lineHeight:1.65 }}>
              <div style={{ marginBottom:4 }}>· David · STORY-082 · week 4</div>
              <div style={{ marginLeft:12, color:MD.textGray, fontSize:13 }}>Status: <span style={{ color:MD.green }}>detected, remediated within 18h</span></div>
              <div style={{ marginLeft:12, color:MD.textGray, fontSize:13 }}>Net consequence: governance gap closed, added <span style={{ fontFamily:T.mono, color:MD.textWhite }}>RULE-readonly_evidence_collectors</span></div>
            </div>
          </div>

          <div style={{ marginTop:16, fontSize:13, color:MD.textGray, lineHeight:1.6 }}>
            <span style={{ color:MD.textWhite, fontWeight:500 }}>Trending:</span> rule density appropriate, no over- or under-enforcement signals this week.
          </div>
        </MDCard>

        <MDCard start={ruleT} padding={18}>
          <div style={{ fontSize:14, color:MD.textWhite, fontWeight:500, marginBottom:12 }}>Top rules by activity (last 7 days)</div>
          <div style={{ height:1, background:MD.charcoalLine, marginBottom:14 }} />
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <RuleRow rule="test_coverage" fires={24} viols={2} />
            <RuleRow rule="acceptance_criteria" fires={18} viols={1} />
            <RuleRow rule="pii_logging" fires={12} viols={0} />
            <RuleRow rule="no_hardcoded_secrets" fires={11} viols={0} />
            <RuleRow rule="jwt_validation" fires={6} viols={0} />
            <RuleRow rule="readonly_evidence_collectors" fires={4} viols={0} />
          </div>
        </MDCard>
      </div>
    </ForgeChrome>
  );
}

function BigStat({ label, value, color }) {
  return (
    <div>
      <div style={{ fontSize:36, fontWeight:500, color, lineHeight:1, letterSpacing:'-0.02em', marginBottom:6 }}>{value}</div>
      <div style={{ fontSize:13, color:MD.textGray }}>{label}</div>
    </div>
  );
}
function RuleRow({ rule, fires, viols }) {
  return (
    <div style={{ display:'flex', alignItems:'baseline', gap:14, fontFamily:T.sans }}>
      <span style={{ fontSize:13, color:MD.textWhite, minWidth:240 }}>{rule}</span>
      <span style={{ fontSize:13, color:MD.textWhite, fontFamily:T.mono, fontWeight:500, minWidth:60 }}>{fires} fires</span>
      <span style={{ color:MD.textDim }}>·</span>
      <span style={{ fontSize:13, color: viols > 0 ? MD.red : MD.textDim, fontFamily:T.mono, fontWeight:500 }}>{viols} viol</span>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// SCENE 5 — Closing card (168-180s)
// ════════════════════════════════════════════════════════════════
function Scene5({ sceneStart = 168 }) {
  const time = useTime();
  const a = fade(time, sceneStart + 0.3, 0.7);
  const b = fade(time, sceneStart + 1.8, 0.7);
  const c = fade(time, sceneStart + 3.0, 0.7);
  const bgO = fade(time, sceneStart, 0.6);
  return (
    <div style={{ position:'absolute', inset:0, background:MD.carbon, color:MD.textWhite, fontFamily:T.sans, display:'flex', alignItems:'center', justifyContent:'center', textAlign:'center' }}>
      <div style={{ position:'absolute', inset:0, background:'url(/assets/images/bg_hero.jpg) center/cover no-repeat', opacity:bgO }} />
      <div style={{ position:'relative', display:'flex', flexDirection:'column', alignItems:'center', gap:54, textShadow:'0 2px 12px rgba(0,0,0,0.7)' }}>
        <div style={{ fontSize:36, fontWeight:300, color:MD.textWhite, lineHeight:1.4, opacity:a, transform:`translateY(${(1-a)*8}px)` }}>
          Priya didn't run a standup.<br/>
          She didn't ask for a status update.
        </div>
        <div style={{ fontSize:32, fontWeight:300, color:MD.textWhite, lineHeight:1.45, opacity:b, transform:`translateY(${(1-b)*8}px)` }}>
          <span style={gradientStyle}>Coordination becomes the byproduct</span><br/>
          of doing the work, not the work itself.
        </div>
      </div>
      <div style={{ position:'absolute', bottom:80, left:0, right:0, display:'flex', flexDirection:'column', alignItems:'center', gap:24, opacity:c }}>
        <span style={{ fontSize:19, fontWeight:500, ...gradientStyle }}>Agentic Forge</span>
        <img src="/assets/logo.svg" alt="Quantivex" style={{ height:28, display:'block' }} />
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// APP — 180s timeline
// ════════════════════════════════════════════════════════════════
function App() {
  return (
    <DemoStage duration={180} captions={[]}>
      <Sprite start={0}    end={38} ><Scene1 /></Sprite>
      <Sprite start={38}   end={78} ><Scene2 sceneStart={38} /></Sprite>
      <Sprite start={78}   end={133}><Scene3 sceneStart={78} /></Sprite>
      <Sprite start={133}  end={168}><Scene4 sceneStart={133} /></Sprite>
      <Sprite start={168}  end={180}><Scene5 sceneStart={168} /></Sprite>
      {/* <Subtitles /> — disabled: no voiceover. Re-enable when audio lands. */}
    </DemoStage>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
