// Tutoriais animados do Vértice OS. Mesma técnica do vídeo de apresentação (Pitch 30s): um palco determinístico
// em que cada quadro é função do tempo t (segundos), com interface encenada, cursor, textos cinéticos e legendas.
// Aqui o palco roda dentro do app (960x540, escalado), com capítulos clicáveis para rever cada etapa.
// O palco é uma peça de vídeo: tem paleta fixa (azul petróleo da marca), igual nos temas claro e escuro.
const tuC = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const tuP = (t, a, b) => tuC((t - a) / (b - a));
const tuE = x => 1 - Math.pow(1 - x, 3);
const tuIO = x => x < .5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
const tuL = (a, b, x) => a + (b - a) * x;
const tuIn = (t, at, dur = .5, dy = 14) => { const p = tuE(tuP(t, at, at + dur)); return { opacity: p, transform: 'translateY(' + ((1 - p) * dy) + 'px)' }; };
const tuPop = (t, at, dur = .4) => { const p = tuE(tuP(t, at, at + dur)); return { opacity: p, transform: 'scale(' + tuL(.82, 1, p) + ')' }; };
const tuType = (s, t, at, cps = 15) => s.slice(0, Math.max(0, Math.floor((t - at) * cps)));
const tuNum = (t, at, dur, to) => Math.round(to * tuE(tuP(t, at, at + dur)));
const TC = { bg: '#071722', petrol: '#0D283A', deep: '#114B5F', accent: '#1E7A8C', light: '#5FA3AE', win: '#0a1b29', side: '#081622', card: '#102536', card2: '#16303f', line: 'rgba(255,255,255,.08)', text: '#e8eef2', mute: '#8da2b1', dim: '#5d7484', sky: '#6cc5d3', blue: '#2563eb', green: '#34d399', amber: '#fbbf24', red: '#f87171' };
const TU_MONO = { fontFamily: 'var(--font-mono)' };
const tuAbs = (x, y, w, h, extra) => ({ position: 'absolute', left: x, top: y, width: w, height: h, ...extra });

// Cena: só existe entre a e b, com entrada e saída suaves.
function TuScene({ t, a, b, children }) {
  if (t < a - .01 || t > b + .01) return null;
  const o = Math.min(tuP(t, a, a + .45), 1 - tuP(t, b - .4, b));
  return <div style={{ position: 'absolute', inset: 0, opacity: o }}>{children}</div>;
}
// Texto cinético: palavras entram uma a uma (camada "textos" do vídeo).
function TuTitle({ t, at, kicker, text, y = 190, size = 44, w = 780, sub }) {
  const words = text.split(' ');
  return <div style={{ position: 'absolute', left: (960 - w) / 2, top: y, width: w, textAlign: 'center' }}>
    {kicker && <div style={{ ...TU_MONO, fontSize: 13, letterSpacing: '.22em', textTransform: 'uppercase', color: TC.sky, marginBottom: 14, ...tuIn(t, at, .5, 8) }}>{kicker}</div>}
    <div style={{ fontSize: size, fontWeight: 600, letterSpacing: '-.03em', lineHeight: 1.12, color: '#fff' }}>
      {words.map((w2, i) => { const p = tuE(tuP(t, at + .15 + i * .08, at + .6 + i * .08)); return <span key={i} style={{ display: 'inline-block', marginRight: '.26em', opacity: p, transform: 'translateY(' + ((1 - p) * 18) + 'px)', filter: 'blur(' + ((1 - p) * 6) + 'px)' }}>{w2}</span>; })}
    </div>
    {sub && <div style={{ fontSize: 19, color: TC.mute, marginTop: 16, lineHeight: 1.4, ...tuIn(t, at + .5 + words.length * .08, .6, 10) }}>{sub}</div>}
  </div>;
}
// Legenda narrativa (camada "legendas").
function TuCaption({ t, lines }) {
  const cur = lines.find(l => t >= l[0] && t < l[1]);
  if (!cur) return null;
  const o = Math.min(tuP(t, cur[0], cur[0] + .3), 1 - tuP(t, cur[1] - .3, cur[1]));
  return <div style={{ position: 'absolute', left: 0, right: 0, bottom: 22, display: 'flex', justifyContent: 'center', opacity: o }}>
    <span style={{ maxWidth: 800, padding: '10px 20px', borderRadius: 12, background: 'rgba(4,14,21,.82)', border: '1px solid ' + TC.line, fontSize: 17, lineHeight: 1.35, color: TC.text, textAlign: 'center' }}>{cur[2]}</span>
  </div>;
}
// Cursor rastreado: path = [[t, x, y, clica?]].
function TuCursor({ t, path }) {
  if (!path.length || t < path[0][0]) return null;
  let i = 0; while (i < path.length - 1 && t >= path[i + 1][0]) i++;
  const a = path[i], b = path[i + 1] || a, p = b === a ? 1 : tuIO(tuP(t, Math.max(a[0], b[0] - .9), b[0]));
  const x = tuL(a[1], b[1], p), y = tuL(a[2], b[2], p);
  const click = path.find(k => k[3] && t >= k[0] && t < k[0] + .45), cp = click ? tuP(t, click[0], click[0] + .45) : 0;
  return <div style={{ position: 'absolute', left: x, top: y, pointerEvents: 'none', opacity: tuP(t, path[0][0], path[0][0] + .3) }}>
    {click && <span style={{ position: 'absolute', left: -18, top: -18, width: 36, height: 36, borderRadius: '50%', border: '2px solid ' + TC.sky, opacity: 1 - cp, transform: 'scale(' + tuL(.4, 1.5, cp) + ')' }} />}
    <svg width="22" height="26" viewBox="0 0 22 26" style={{ display: 'block', filter: 'drop-shadow(0 3px 6px rgba(0,0,0,.5))', transform: 'scale(' + (click ? tuL(.86, 1, cp) : 1) + ')', transformOrigin: '0 0' }}><path d="M2 2l0 19 5.2-4.6 3.4 7.4 3-1.4-3.4-7.3 7-.6z" fill="#fff" stroke="#06131c" strokeWidth="1.4" strokeLinejoin="round" /></svg>
  </div>;
}
// Janela do app encenada: barra lateral com o logo real e a tela ativa.
const TU_NAV = ['Primeiros passos', 'Recomendações', 'Perfil do licitante', 'Oportunidades', 'Go / No-Go', 'Central de Ajuda'];
function TuWin({ t, at = 0, active, eyebrow, title, children }) {
  const p = tuE(tuP(t, at, at + .7));
  return <div style={{ ...tuAbs(50, 26, 860, 418), borderRadius: 16, background: TC.win, border: '1px solid ' + TC.line, boxShadow: '0 30px 80px rgba(0,0,0,.45)', overflow: 'hidden', opacity: p, transform: 'translateY(' + ((1 - p) * 24) + 'px) scale(' + tuL(.97, 1, p) + ')' }}>
    <div style={{ ...tuAbs(0, 0, 168, 418), background: TC.side, borderRight: '1px solid ' + TC.line }}>
      <img src="assets/vertice-logo.svg" alt="" style={{ position: 'absolute', left: 16, top: 16, width: 104 }} />
      {TU_NAV.map((n, i) => <div key={n} style={{ ...tuAbs(8, 70 + i * 34, 152, 28), borderRadius: 7, display: 'flex', alignItems: 'center', paddingLeft: 10, boxSizing: 'border-box', fontSize: 11.5, fontWeight: n === active ? 600 : 400, color: n === active ? '#fff' : TC.mute, background: n === active ? 'rgba(30,122,140,.32)' : 'transparent' }}>{n}</div>)}
    </div>
    <div style={{ ...tuAbs(168, 0, 692, 418) }}>
      {eyebrow && <div style={{ ...tuAbs(28, 22), ...TU_MONO, fontSize: 9.5, letterSpacing: '.18em', textTransform: 'uppercase', color: TC.dim }}>{eyebrow}</div>}
      {title && <div style={{ ...tuAbs(28, 38), fontSize: 23, fontWeight: 600, letterSpacing: '-.02em', color: '#fff' }}>{title}</div>}
      {children}
    </div>
  </div>;
}
function TuField({ x, y, w, label, value, focus, placeholder }) {
  return <div style={tuAbs(x, y, w)}>
    <div style={{ fontSize: 10.5, color: TC.mute, marginBottom: 5 }}>{label}</div>
    <div style={{ height: 32, borderRadius: 8, background: '#07141e', border: '1px solid ' + (focus ? TC.sky : TC.line), boxShadow: focus ? '0 0 0 3px rgba(108,197,211,.16)' : 'none', display: 'flex', alignItems: 'center', padding: '0 10px', fontSize: 12.5, color: value ? TC.text : TC.dim, whiteSpace: 'nowrap', overflow: 'hidden' }}>
      {value || placeholder || ''}{focus && <span style={{ width: 1.5, height: 15, background: TC.sky, marginLeft: 1 }} />}
    </div>
  </div>;
}
function TuChip({ children, on, tone, style }) {
  const c = tone === 'red' ? TC.red : tone === 'green' ? TC.green : TC.sky;
  return <span style={{ display: 'inline-flex', alignItems: 'center', height: 24, padding: '0 10px', borderRadius: 999, fontSize: 11.5, fontWeight: 500, color: on ? '#fff' : TC.mute, background: on ? (tone === 'red' ? 'rgba(248,113,113,.16)' : tone === 'green' ? 'rgba(52,211,153,.16)' : 'rgba(30,122,140,.4)') : 'rgba(255,255,255,.04)', border: '1px solid ' + (on ? c : TC.line), textDecoration: tone === 'red' && on ? 'line-through' : 'none', ...style }}>{children}</span>;
}
function TuBtn({ x, y, w = 150, children, primary = true, press = 0, style }) {
  return <div style={{ ...tuAbs(x, y, w, 32), borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12.5, fontWeight: 600, color: '#fff', background: primary ? TC.blue : 'rgba(255,255,255,.07)', border: '1px solid ' + (primary ? 'transparent' : TC.line), transform: 'scale(' + (1 - .05 * press) + ')', ...style }}>{children}</div>;
}
function TuToast({ t, at, children }) {
  const p = tuE(tuP(t, at, at + .4)) * (1 - tuP(t, at + 3.4, at + 3.8));
  return <div style={{ position: 'absolute', left: 0, right: 0, top: 380, display: 'flex', justifyContent: 'center', opacity: p, transform: 'translateY(' + ((1 - p) * 12) + 'px)' }}>
    <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center', padding: '10px 16px', borderRadius: 10, background: '#0e2a22', border: '1px solid rgba(52,211,153,.45)', color: '#d5f7e8', fontSize: 13, fontWeight: 500 }}><span style={{ color: TC.green }}>✓</span>{children}</span>
  </div>;
}
// Arco do score (0–100).
function TuGauge({ x, y, value, size = 170, color = TC.green }) {
  const r = size / 2 - 12, len = Math.PI * r;
  return <div style={tuAbs(x, y, size, size / 2 + 26)}>
    <svg width={size} height={size / 2 + 4} viewBox={'0 0 ' + size + ' ' + (size / 2 + 4)}>
      <path d={'M12 ' + size / 2 + ' A' + r + ' ' + r + ' 0 0 1 ' + (size - 12) + ' ' + size / 2} fill="none" stroke="rgba(255,255,255,.08)" strokeWidth="12" strokeLinecap="round" />
      <path d={'M12 ' + size / 2 + ' A' + r + ' ' + r + ' 0 0 1 ' + (size - 12) + ' ' + size / 2} fill="none" stroke={color} strokeWidth="12" strokeLinecap="round" strokeDasharray={len} strokeDashoffset={len * (1 - value / 100)} />
    </svg>
    <div style={{ position: 'absolute', left: 0, right: 0, top: size / 2 - 40, textAlign: 'center', ...TU_MONO, fontSize: 40, fontWeight: 600, color: '#fff' }}>{Math.round(value)}</div>
  </div>;
}
function TuStepNo({ t, at, n }) {
  return <div style={{ ...tuAbs(64, 56), ...TU_MONO, fontSize: 96, fontWeight: 600, letterSpacing: '-.04em', color: 'transparent', WebkitTextStroke: '1.5px rgba(108,197,211,.55)', ...tuIn(t, at, .6, 20) }}>{n}</div>;
}
// Cartão de recomendação encenado.
function TuRec({ x, y, w = 636, t, at, title, meta, score, badge, tone = 'green', dim = 0, children, h = 74 }) {
  return <div style={{ ...tuAbs(x, y, w, h), borderRadius: 12, background: TC.card, border: '1px solid ' + TC.line, boxSizing: 'border-box', padding: '12px 14px', ...tuIn(t, at, .5, 16), opacity: tuE(tuP(t, at, at + .5)) * (1 - .78 * dim) }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: TC.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
        <div style={{ fontSize: 11, color: TC.mute, marginTop: 5 }}>{meta}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 'none', height: 24 }}>
        <TuChip on tone={tone === 'green' ? 'green' : undefined}>{badge}</TuChip>
        <span style={{ ...TU_MONO, fontSize: 19, fontWeight: 600, color: '#fff', width: 28, textAlign: 'right' }}>{tuNum(t, at + .3, .9, score)}</span>
      </div>
    </div>
    {children}
  </div>;
}

// ---------------------------------------------------------------- 1. Boas-vindas
function tuWelcome(t) {
  const rows = [['ph-map-pin', 'Onde você atende', 'Cidade-base, raio em km e estados'], ['ph-package', 'O que você fornece', 'Palavras-chave do seu negócio'], ['ph-scales', 'Como você disputa', 'Faixa de valor e modalidades']];
  const recs = [['Serviços de limpeza e conservação predial', 94, 'Alta aderência', 'green'], ['Manutenção de áreas verdes e jardinagem', 78, 'Boa aderência', 'sky'], ['Limpeza de unidades escolares', 71, 'Boa aderência', 'sky']];
  const g = tuE(tuP(t, 24, 26.2)) * 78;
  return <>
    <TuScene t={t} a={0} b={6.6}>
      <img src="assets/vertice-logo.svg" alt="" style={{ position: 'absolute', left: 380, top: 96, width: 200, ...tuPop(t, .2, .9) }} />
      <TuTitle t={t} at={1.1} y={214} size={48} text="Bem-vindo ao Vértice OS" sub="As licitações certas para a sua empresa, em três passos." />
    </TuScene>
    <TuScene t={t} a={6.6} b={14}>
      <TuStepNo t={t} at={6.8} n="01" />
      <div style={{ ...tuAbs(64, 176, 360), ...tuIn(t, 7.1) }}><div style={{ fontSize: 34, fontWeight: 600, letterSpacing: '-.03em', color: '#fff', lineHeight: 1.12 }}>Conte quem é a sua empresa</div><div style={{ fontSize: 17, color: TC.mute, marginTop: 14, lineHeight: 1.4 }}>O Perfil do licitante leva uns 3 minutos e é a base de tudo.</div></div>
      <div style={{ ...tuAbs(486, 92, 410, 300), borderRadius: 18, background: TC.card, border: '1px solid ' + TC.line, boxSizing: 'border-box', padding: 22, ...tuIn(t, 7.5, .6, 22) }}>
        <div style={{ ...TU_MONO, fontSize: 10, letterSpacing: '.18em', color: TC.sky, textTransform: 'uppercase' }}>Perfil do licitante</div>
        {rows.map((r, i) => <div key={r[1]} style={{ display: 'flex', gap: 14, alignItems: 'center', marginTop: 20, ...tuIn(t, 8.3 + i * .9, .5, 12) }}>
          <span style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(30,122,140,.3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}><i className={'ph ' + r[0]} style={{ fontSize: 22, color: TC.sky }} /></span>
          <span><div style={{ fontSize: 16, fontWeight: 600, color: '#fff' }}>{r[1]}</div><div style={{ fontSize: 13, color: TC.mute, marginTop: 3 }}>{r[2]}</div></span>
          <span style={{ marginLeft: 'auto', color: TC.green, fontSize: 18, ...tuPop(t, 8.9 + i * .9) }}>✓</span>
        </div>)}
      </div>
    </TuScene>
    <TuScene t={t} a={14} b={22.4}>
      <TuStepNo t={t} at={14.2} n="02" />
      <div style={{ ...tuAbs(64, 176, 330), ...tuIn(t, 14.5) }}><div style={{ fontSize: 34, fontWeight: 600, letterSpacing: '-.03em', color: '#fff', lineHeight: 1.12 }}>Receba recomendações</div><div style={{ fontSize: 17, color: TC.mute, marginTop: 14, lineHeight: 1.4 }}>O Vértice cruza seu perfil com as licitações abertas do PNCP e explica cada escolha.</div></div>
      {Array.from({ length: 16 }).map((_, i) => { const p = ((t - 14.6) * .22 + i / 16) % 1, on = t > 14.6; return <span key={i} style={{ ...tuAbs(tuL(410, 520, p), 110 + (i * 53) % 270, 34 + (i * 17) % 40, 6), borderRadius: 3, background: TC.light, opacity: on ? .5 * Math.sin(p * Math.PI) : 0 }} />; })}
      {recs.map((r, i) => <TuRec key={r[0]} x={540} y={104 + i * 96} w={360} h={82} t={t} at={16.2 + i * 1.1} title={r[0]} meta="Motivo de cada ponto na tela" score={r[1]} badge={r[2]} tone={r[3]} />)}
    </TuScene>
    <TuScene t={t} a={22.4} b={31}>
      <TuStepNo t={t} at={22.6} n="03" />
      <div style={{ ...tuAbs(64, 176, 360), ...tuIn(t, 22.9) }}><div style={{ fontSize: 34, fontWeight: 600, letterSpacing: '-.03em', color: '#fff', lineHeight: 1.12 }}>Decida com segurança</div><div style={{ fontSize: 17, color: TC.mute, marginTop: 14, lineHeight: 1.4 }}>O Go/No-Go mostra se vale a pena participar antes de você investir tempo na proposta.</div></div>
      <div style={{ ...tuAbs(500, 96, 380, 290), borderRadius: 18, background: TC.card, border: '1px solid ' + TC.line, ...tuIn(t, 23.3, .6, 22) }}>
        <TuGauge x={95} y={30} size={190} value={g} />
        <div style={{ position: 'absolute', left: 0, right: 0, top: 168, textAlign: 'center', fontSize: 13, color: TC.mute }}>Score Go/No-Go</div>
        <div style={{ position: 'absolute', left: 24, right: 24, top: 214, display: 'flex', gap: 10, justifyContent: 'center' }}>
          {['Participar', 'Avaliar', 'Não participar'].map((b, i) => <span key={b} style={{ padding: '9px 14px', borderRadius: 9, fontSize: 13, fontWeight: 600, color: '#fff', background: i === 0 && t > 27 ? '#15803d' : 'rgba(255,255,255,.07)', border: '1px solid ' + (i === 0 && t > 27 ? TC.green : TC.line), ...tuIn(t, 25.6 + i * .2, .4, 8) }}>{b}</span>)}
        </div>
      </div>
    </TuScene>
    <TuScene t={t} a={31} b={36}>
      <TuTitle t={t} at={31.2} y={186} kicker="Vamos começar" text="Primeiro, o seu perfil." sub="A seguir, um tutorial curto mostra como preencher cada parte." />
    </TuScene>
  </>;
}

// ---------------------------------------------------------------- 2. Perfil do licitante
const TU_DOTS = (() => { let s = 7; const r = () => (s = (s * 16807) % 2147483647) / 2147483647; return Array.from({ length: 64 }).map(() => [r() * 250 + 10, r() * 190 + 12]); })();
function tuPerfil(t) {
  const kw = 'limpeza, conservação, jardinagem', typedKw = tuType(kw, t, 20.6, 13), chips = typedKw.split(',').map(s => s.trim()).filter((s, i, a) => s && (i < a.length - 1 || typedKw.length === kw.length));
  const raio = tuNum(t, 12.2, 2, 150), rp = raio / 150 * 82;
  const lo = tuL(8, 22, tuE(tuP(t, 31.5, 33))), hi = tuL(92, 70, tuE(tuP(t, 33.2, 34.8)));
  const objs = [['Contratação de serviços de limpeza e conservação predial', 'limpeza'], ['Aquisição de material hospitalar descartável', 'hospitalar'], ['Manutenção de jardinagem em praças e canteiros', 'jardinagem'], ['Locação de veículos com motorista', '']];
  return <>
    <TuScene t={t} a={0} b={7}>
      <TuWin t={t} at={.2} active={t > 3.6 ? 'Perfil do licitante' : 'Primeiros passos'} eyebrow={t > 3.6 ? 'Inteligência · sua empresa' : 'Bem-vindo'} title={t > 3.6 ? 'Perfil do licitante' : 'Primeiros passos'}>
        <div style={{ ...tuAbs(28, 84, 600), fontSize: 13, lineHeight: 1.5, color: TC.mute, ...tuIn(t, 3.9) }}>Conte onde sua empresa atua, o que fornece e em que faixa de valor disputa.</div>
        {['Onde você atende', 'O que você fornece', 'Como você disputa'].map((s, i) => <div key={s} style={{ ...tuAbs(28 + i * 216, 136, 204, 120), borderRadius: 12, background: TC.card, border: '1px solid ' + TC.line, boxSizing: 'border-box', padding: 14, ...tuIn(t, 4.3 + i * .25) }}><div style={{ ...TU_MONO, fontSize: 22, color: TC.sky }}>{i + 1}</div><div style={{ fontSize: 14, fontWeight: 600, color: '#fff', marginTop: 10 }}>{s}</div></div>)}
      </TuWin>
      <TuCursor t={t} path={[[1.4, 520, 300], [3.4, 130, 177, 1], [5.5, 300, 250]]} />
    </TuScene>
    <TuScene t={t} a={7} b={19.6}>
      <TuWin t={t} at={0} active="Perfil do licitante" eyebrow="Passo 1 de 3" title="Onde você atende">
        <TuField x={28} y={86} w={110} label="UF da cidade-base" value={t > 8.4 ? 'SP' : ''} focus={t > 7.9 && t < 9.2} placeholder="Escolha" />
        <TuField x={150} y={86} w={190} label="Cidade-base" value={tuType('Campinas', t, 9.6)} focus={t > 9.3 && t < 11.4} placeholder="Escolha a cidade" />
        <TuField x={28} y={150} w={312} label="Raio de atendimento (km)" value={t > 12.1 ? String(raio) : ''} focus={t > 11.6 && t < 14.6} placeholder="Ex.: 150" />
        <div style={{ ...tuAbs(28, 216, 312), fontSize: 10.5, color: TC.mute }}>UFs inteiras em que você também atende</div>
        <div style={{ ...tuAbs(28, 236, 320), display: 'flex', gap: 6, flexWrap: 'wrap' }}>{['MG', 'PR', 'RJ', 'SC', 'SP', 'RS', 'GO'].map(u => <TuChip key={u} on={(u === 'SP' && t > 16) || (u === 'MG' && t > 17.1)}>{u}</TuChip>)}</div>
        <div style={{ ...tuAbs(28, 304, 320), fontSize: 11.5, color: TC.sky, ...tuIn(t, 14.6) }}>Até {raio} km de Campinas/SP{t > 16 ? ' · UFs inteiras: SP' + (t > 17.1 ? ', MG' : '') : ''}</div>
        <div style={{ ...tuAbs(376, 84, 288, 232), borderRadius: 14, background: '#07141e', border: '1px solid ' + TC.line, overflow: 'hidden' }}>
          {TU_DOTS.map((d, i) => { const inside = Math.hypot(d[0] - 138, d[1] - 112) < rp; return <span key={i} style={{ ...tuAbs(d[0], d[1], 5, 5), borderRadius: '50%', background: inside ? TC.green : TC.dim, opacity: inside ? 1 : .5, transform: 'scale(' + (inside ? 1.3 : 1) + ')' }} />; })}
          <span style={{ ...tuAbs(138 - rp, 112 - rp, rp * 2, rp * 2), borderRadius: '50%', border: '1.5px solid ' + TC.sky, background: 'rgba(108,197,211,.1)', boxSizing: 'border-box', opacity: tuP(t, 12.1, 12.5) }} />
          <span style={{ ...tuAbs(132, 106, 12, 12), borderRadius: '50%', background: '#fff', boxShadow: '0 0 0 5px rgba(255,255,255,.18)', ...tuPop(t, 10.3) }} />
          <span style={{ ...tuAbs(150, 100), fontSize: 11, fontWeight: 600, color: '#fff', ...tuIn(t, 10.5, .4, 4) }}>Campinas</span>
        </div>
        <div style={{ ...tuAbs(376, 326, 288), fontSize: 11, color: TC.mute, ...tuIn(t, 13) }}>Cada ponto é um município. <span style={{ color: TC.green }}>{TU_DOTS.filter(d => Math.hypot(d[0] - 138, d[1] - 112) < rp).length} no seu raio</span></div>
      </TuWin>
      <TuCursor t={t} path={[[7.3, 400, 320], [8, 300, 150, 1], [9.4, 420, 150, 1], [11.6, 340, 214, 1], [15, 480, 260], [15.9, 372, 300, 1], [17, 264, 300, 1], [18.4, 520, 360]]} />
    </TuScene>
    <TuScene t={t} a={19.6} b={30.6}>
      <TuWin t={t} at={0} active="Perfil do licitante" eyebrow="Passo 2 de 3" title="O que você fornece">
        <TuField x={28} y={86} w={312} label="Palavras-chave (separe por vírgula)" value={typedKw} focus={t > 20.2 && t < 23.6} placeholder="limpeza, conservação, jardinagem" />
        <div style={{ ...tuAbs(28, 146, 320), display: 'flex', gap: 6, flexWrap: 'wrap' }}>{chips.map(c => <TuChip key={c} on>{c}</TuChip>)}</div>
        <TuField x={28} y={190} w={312} label="Palavras a evitar" value={tuType('hospitalar', t, 25)} focus={t > 24.6 && t < 26.4} placeholder="hospitalar, veículo" />
        <div style={{ ...tuAbs(28, 250, 320), ...tuPop(t, 26.2) }}><TuChip on tone="red">hospitalar</TuChip></div>
        <div style={{ ...tuAbs(376, 84, 288), ...TU_MONO, fontSize: 9.5, letterSpacing: '.16em', color: TC.dim, textTransform: 'uppercase' }}>Objetos de licitações abertas</div>
        {objs.map((o, i) => { const hit = o[1] && o[1] !== 'hospitalar' && typedKw.includes(o[1]), bad = o[1] === 'hospitalar' && t > 26.2; return <div key={o[0]} style={{ ...tuAbs(376, 106 + i * 58, 288, 48), borderRadius: 10, boxSizing: 'border-box', padding: '8px 12px', fontSize: 11.5, lineHeight: 1.35, background: hit ? 'rgba(52,211,153,.1)' : TC.card, border: '1px solid ' + (hit ? 'rgba(52,211,153,.5)' : bad ? 'rgba(248,113,113,.4)' : TC.line), color: bad ? TC.dim : TC.text, textDecoration: bad ? 'line-through' : 'none', opacity: bad ? .6 : 1, ...tuIn(t, 19.9 + i * .12) }}>{o[0]}</div>; })}
      </TuWin>
      <TuCursor t={t} path={[[19.8, 560, 330], [20.4, 330, 150, 1], [24.7, 330, 254, 1], [27.5, 600, 180]]} />
    </TuScene>
    <TuScene t={t} a={30.6} b={39.4}>
      <TuWin t={t} at={0} active="Perfil do licitante" eyebrow="Passo 3 de 3" title="Como você disputa">
        <div style={{ ...tuAbs(28, 86, 636), fontSize: 10.5, color: TC.mute }}>Faixa de valor estimado das licitações</div>
        <div style={{ ...tuAbs(28, 124, 636, 6), borderRadius: 3, background: 'rgba(255,255,255,.08)' }}><span style={{ position: 'absolute', left: lo + '%', width: (hi - lo) + '%', top: 0, bottom: 0, borderRadius: 3, background: TC.sky }} />{[lo, hi].map((v, i) => <span key={i} style={{ position: 'absolute', left: 'calc(' + v + '% - 8px)', top: -5, width: 16, height: 16, borderRadius: '50%', background: '#fff', boxShadow: '0 2px 6px rgba(0,0,0,.4)' }} />)}</div>
        <div style={{ ...tuAbs(28, 146, 636), display: 'flex', justifyContent: 'space-between', ...TU_MONO, fontSize: 13, color: '#fff' }}><span>mín. R$ {tuNum(t, 31.5, 1.5, 50)} mil</span><span>máx. R$ {(tuL(5, 2, tuE(tuP(t, 33.2, 34.8)))).toFixed(1).replace('.', ',')} mi</span></div>
        <div style={{ ...tuAbs(28, 190, 636), fontSize: 10.5, color: TC.mute }}>Modalidades</div>
        {['Pregão - Eletrônico', 'Concorrência - Eletrônica', 'Dispensa de Licitação', 'Credenciamento'].map((m, i) => { const on = (i === 0 && t > 35.8) || (i === 2 && t > 36.8); return <div key={m} style={{ ...tuAbs(28 + (i % 2) * 320, 214 + Math.floor(i / 2) * 36, 300), display: 'flex', alignItems: 'center', gap: 9, fontSize: 12.5, color: TC.text }}><span style={{ width: 16, height: 16, borderRadius: 4, border: '1.5px solid ' + (on ? TC.blue : TC.dim), background: on ? TC.blue : 'transparent', color: '#fff', fontSize: 11, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{on ? '✓' : ''}</span>{m}</div>; })}
        <div style={{ ...tuAbs(28, 300, 636), fontSize: 11.5, color: TC.mute, ...tuIn(t, 37.2) }}>Nenhuma marcada? Todas as modalidades entram. Até 20% fora da faixa de valor ainda aparece, com aviso.</div>
      </TuWin>
      <TuCursor t={t} path={[[30.9, 600, 340], [31.5, 262, 160], [33, 354, 160], [33.3, 836, 160], [34.8, 690, 160], [35.8, 256, 250, 1], [36.8, 256, 286, 1], [38.2, 560, 380]]} />
    </TuScene>
    <TuScene t={t} a={39.4} b={47}>
      <TuWin t={t} at={0} active="Perfil do licitante" eyebrow="Inteligência · sua empresa" title="Perfil do licitante">
        {[['Onde você atende', 'Até 150 km de Campinas/SP · SP, MG'], ['O que você fornece', 'limpeza, conservação, jardinagem'], ['Como você disputa', 'R$ 50 mil a R$ 2 mi · 2 modalidades']].map((s, i) => <div key={s[0]} style={{ ...tuAbs(28, 86 + i * 62, 636, 52), borderRadius: 10, background: TC.card, border: '1px solid ' + TC.line, boxSizing: 'border-box', padding: '9px 14px', ...tuIn(t, 39.6 + i * .15) }}><div style={{ fontSize: 10.5, color: TC.mute }}>{s[0]}</div><div style={{ fontSize: 13, fontWeight: 600, color: '#fff', marginTop: 4 }}>{s[1]}</div><span style={{ position: 'absolute', right: 14, top: 16, color: TC.green }}>✓</span></div>)}
        <TuBtn x={28} y={284} w={130} press={t > 41.5 && t < 41.8 ? 1 : 0}>Criar perfil</TuBtn>
      </TuWin>
      <TuCursor t={t} path={[[39.8, 620, 300], [41.5, 300, 330, 1], [43, 460, 350]]} />
      <TuToast t={t} at={42}>Perfil salvo. As recomendações já usam estes dados.</TuToast>
    </TuScene>
    <TuScene t={t} a={47} b={52}>
      <TuTitle t={t} at={47.2} y={186} kicker="Pronto" text="Agora é a sua vez." sub="Você pode ajustar o perfil quando quiser. As recomendações se atualizam junto." />
    </TuScene>
  </>;
}

// ---------------------------------------------------------------- 3. Recomendações
function tuRecs(t) {
  const motivos = [['Objeto: “limpeza” e “conservação” no texto', 40, 40], ['A 42 km de Campinas/SP (seu raio: 150 km)', 27, 30], ['Valor dentro da sua faixa', 15, 15], ['Prazo de proposta em aberto', 7, 10], ['Modalidade: Pregão - Eletrônico', 5, 5]];
  const filt = t > 21.2 ? 1 : 0;
  return <>
    <TuScene t={t} a={0} b={8.4}>
      <TuWin t={t} at={.2} active="Recomendações" eyebrow="Inteligência · para sua empresa" title="Recomendações">
        <TuRec x={28} y={92} t={t} at={1.6} title="Serviços de limpeza e conservação predial" meta="Prefeitura · a 42 km · Pregão - Eletrônico · R$ 480.000" score={94} badge="Alta aderência" />
        <TuRec x={28} y={176} t={t} at={2.3} title="Manutenção de áreas verdes e jardinagem" meta="Autarquia · a 96 km · Pregão - Eletrônico · R$ 210.000" score={78} badge="Boa aderência" tone="sky" />
        <TuRec x={28} y={260} t={t} at={3} title="Limpeza de unidades escolares" meta="Secretaria · a 138 km · Concorrência - Eletrônica · R$ 1.900.000" score={61} badge="Exploratória" tone="sky" />
      </TuWin>
    </TuScene>
    <TuScene t={t} a={8.4} b={18.6}>
      <TuWin t={t} at={0} active="Recomendações" eyebrow="Por que foi recomendada" title="Cada ponto tem um motivo">
        <TuRec x={28} y={88} h={270} t={t} at={8.5} title="Serviços de limpeza e conservação predial" meta="Prefeitura · a 42 km · Pregão - Eletrônico · R$ 480.000" score={94} badge="Alta aderência">
          {motivos.map((m, i) => { const p = tuE(tuP(t, 9.8 + i * 1.3, 10.8 + i * 1.3)); return <div key={m[0]} style={{ marginTop: i ? 12 : 18, ...tuIn(t, 9.6 + i * 1.3, .4, 8) }}>
            <div style={{ height: 6, borderRadius: 3, background: 'rgba(255,255,255,.08)' }}><div style={{ height: 6, borderRadius: 3, width: (p * 100 * m[1] / m[2]) + '%', background: TC.sky }} /></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: TC.text, marginTop: 5 }}><span>{m[0]}</span><span style={{ ...TU_MONO, color: TC.mute }}>{Math.round(p * m[1])}/{m[2]}</span></div>
          </div>; })}
        </TuRec>
      </TuWin>
    </TuScene>
    <TuScene t={t} a={18.6} b={25.6}>
      <TuWin t={t} at={0} active="Recomendações" eyebrow="Inteligência · para sua empresa" title="Recomendações">
        <div style={{ ...tuAbs(28, 84, 636), display: 'flex', gap: 8 }}>{['Todas · 3', 'Alta aderência · 1', 'Boa aderência · 1', 'Exploratória · 1'].map((c, i) => <TuChip key={c} on={filt ? i === 1 : i === 0} tone={i === 1 ? 'green' : undefined}>{c}</TuChip>)}</div>
        <TuRec x={28} y={124} t={t} at={18.6} title="Serviços de limpeza e conservação predial" meta="Prefeitura · a 42 km · Pregão - Eletrônico · R$ 480.000" score={94} badge="Alta aderência" />
        <TuRec x={28} y={208} t={t} at={18.6} dim={tuP(t, 21.2, 21.7)} title="Manutenção de áreas verdes e jardinagem" meta="Autarquia · a 96 km · Pregão - Eletrônico · R$ 210.000" score={78} badge="Boa aderência" tone="sky" />
        <TuRec x={28} y={292} t={t} at={18.6} dim={tuP(t, 21.2, 21.7)} title="Limpeza de unidades escolares" meta="Secretaria · a 138 km · Concorrência - Eletrônica · R$ 1.900.000" score={61} badge="Exploratória" tone="sky" />
      </TuWin>
      <TuCursor t={t} path={[[19.2, 560, 330], [21.1, 360, 122, 1], [23.5, 520, 240]]} />
    </TuScene>
    <TuScene t={t} a={25.6} b={35}>
      <TuWin t={t} at={0} active={t > 31.6 ? 'Go / No-Go' : 'Recomendações'} eyebrow="Inteligência · para sua empresa" title="Recomendações">
        <TuRec x={28} y={92} h={118} t={t} at={25.6} title="Serviços de limpeza e conservação predial" meta="Prefeitura · a 42 km · Pregão - Eletrônico · R$ 480.000" score={94} badge="Alta aderência">
          <div style={{ position: 'relative', height: 44 }}><TuBtn x={0} y={14} w={190} press={t > 28.6 && t < 28.9 ? 1 : 0}>{t > 28.9 && t < 30 ? 'Levando…' : 'Levar para Oportunidades'}</TuBtn></div>
        </TuRec>
        <div style={{ ...tuAbs(28, 228, 636), fontSize: 12, lineHeight: 1.5, color: TC.mute, ...tuIn(t, 26.4) }}>Recomendação não é garantia de viabilidade: confirme no edital e decida no Go/No-Go.</div>
      </TuWin>
      <TuCursor t={t} path={[[26, 620, 320], [28.6, 330, 205, 1], [31, 520, 300]]} />
      <TuToast t={t} at={29.6}>Levada para Oportunidades. Abrindo o Go/No-Go…</TuToast>
    </TuScene>
  </>;
}

// ---------------------------------------------------------------- 4. Go/No-Go
function tuDecisao(t) {
  const crit = [['Valor', 15, 15], ['Distância', 10, 10], ['Margem', 14, 20], ['Mão de obra', 14, 15], ['Documentos', 13, 15], ['Equipamentos', 10, 10], ['Experiência', 15, 15]];
  const total = crit.reduce((s, c, i) => s + c[1] * tuE(tuP(t, 8.4 + i * 1.15, 9.3 + i * 1.15)), 0);
  const modal = tuE(tuP(t, 29, 29.4)) * (1 - tuP(t, 31.6, 32));
  return <>
    <TuScene t={t} a={0} b={7}>
      <TuTitle t={t} at={.4} y={170} size={50} kicker="Score Go/No-Go" text="Vale a pena participar?" sub="Sete critérios da sua empresa, uma resposta clara antes de investir tempo na proposta." />
    </TuScene>
    <TuScene t={t} a={7} b={26.4}>
      <TuWin t={t} at={0} active="Go / No-Go" eyebrow="Score Go/No-Go" title="Vale a pena participar?">
        {crit.map((c, i) => { const p = tuE(tuP(t, 8.4 + i * 1.15, 9.3 + i * 1.15)); return <div key={c[0]} style={{ ...tuAbs(28, 90 + i * 40, 380), ...tuIn(t, 7.4 + i * .12, .4, 8) }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: TC.text }}><span>{c[0]}</span><span style={{ ...TU_MONO, color: TC.mute }}>{Math.round(p * c[1])}/{c[2]}</span></div>
          <div style={{ height: 6, borderRadius: 3, background: 'rgba(255,255,255,.08)', marginTop: 6 }}><div style={{ height: 6, borderRadius: 3, width: (p * 100 * c[1] / c[2]) + '%', background: c[1] / c[2] < .75 ? TC.amber : TC.green }} /></div>
        </div>; })}
        <div style={{ ...tuAbs(440, 86, 224, 280), borderRadius: 14, background: TC.card, border: '1px solid ' + (t > 18 ? 'rgba(52,211,153,.4)' : TC.line) }}>
          <TuGauge x={22} y={26} size={180} value={total} color={total >= 70 ? TC.green : total >= 45 ? TC.amber : TC.red} />
          <div style={{ position: 'absolute', left: 0, right: 0, top: 150, display: 'flex', justifyContent: 'center', ...tuPop(t, 18) }}><TuChip on tone="green">Verde · Participar</TuChip></div>
          <div style={{ position: 'absolute', left: 18, right: 18, top: 190, fontSize: 11.5, lineHeight: 1.45, color: TC.mute, textAlign: 'center', ...tuIn(t, 18.6) }}>Critérios favoráveis. Ponto mais fraco: Margem.</div>
          <div style={{ position: 'absolute', left: 18, right: 18, top: 240, textAlign: 'center', ...TU_MONO, fontSize: 10.5, color: TC.dim, ...tuIn(t, 19.4) }}>70+ participar · 45+ avaliar</div>
        </div>
      </TuWin>
      <TuCursor t={t} path={[[7.6, 600, 380], [9, 330, 146], [12.4, 300, 226], [16, 340, 346], [18.4, 660, 250], [24, 600, 330]]} />
    </TuScene>
    <TuScene t={t} a={26.4} b={36}>
      <TuWin t={t} at={0} active="Go / No-Go" eyebrow="Score Go/No-Go" title="Registre a decisão">
        <TuBtn x={28} y={96} w={150} press={t > 28.6 && t < 28.9 ? 1 : 0} style={{ background: '#15803d' }}>Participar</TuBtn>
        <TuBtn x={190} y={96} w={150} primary={false}>Avaliar</TuBtn>
        <TuBtn x={352} y={96} w={150} primary={false}>Não participar</TuBtn>
        {[['Participar', 'Vira uma oportunidade e segue para Disputas.'], ['Avaliar', 'Fica em Oportunidades para discutir com a equipe.'], ['Não participar', 'Fica no histórico, com o motivo registrado.']].map((r, i) => <div key={r[0]} style={{ ...tuAbs(28, 156 + i * 52, 636, 44), borderRadius: 10, background: TC.card, border: '1px solid ' + TC.line, boxSizing: 'border-box', padding: '12px 14px', fontSize: 12.5, color: TC.mute, ...tuIn(t, 26.8 + i * .25) }}><b style={{ color: '#fff', fontWeight: 600 }}>{r[0]}:</b> {r[1]}</div>)}
        <div style={{ ...tuAbs(146, 110, 400, 170), borderRadius: 14, background: '#0c2130', border: '1px solid rgba(108,197,211,.35)', boxShadow: '0 30px 70px rgba(0,0,0,.6)', boxSizing: 'border-box', padding: 20, opacity: modal, transform: 'scale(' + tuL(.94, 1, modal) + ')' }}>
          <div style={{ ...TU_MONO, fontSize: 9.5, letterSpacing: '.18em', color: TC.dim, textTransform: 'uppercase' }}>Go/No-Go</div>
          <div style={{ fontSize: 17, fontWeight: 600, color: '#fff', marginTop: 8 }}>Registrar esta decisão?</div>
          <div style={{ fontSize: 12, color: TC.mute, marginTop: 8, lineHeight: 1.45 }}>Você revisa os sete critérios de uma vez antes de confirmar.</div>
          <TuBtn x={250} y={120} w={130} press={t > 31.1 && t < 31.4 ? 1 : 0}>Confirmar</TuBtn>
        </div>
      </TuWin>
      <TuCursor t={t} path={[[27, 620, 340], [28.6, 290, 142, 1], [31.1, 690, 268, 1], [33, 560, 340]]} />
      <TuToast t={t} at={31.8}>Decisão registrada. A oportunidade está em Oportunidades.</TuToast>
    </TuScene>
  </>;
}

// ---------------------------------------------------------------- Catálogo
const VX_TUTORIALS = [
  { id: 'boas-vindas', title: 'Bem-vindo ao Vértice OS', summary: 'Como o Vértice encontra as licitações certas para a sua empresa, em três passos.', icon: 'ph-hand-waving', duration: 36, poster: 18.5, render: tuWelcome,
    cta: { label: 'Ver como preencher o perfil', tutorial: 'perfil' },
    chapters: [{ at: 0, title: 'Boas-vindas', text: 'O Vértice OS trabalha em três passos: perfil, recomendações e decisão.' }, { at: 6.6, title: 'Conte quem é a sua empresa', text: 'O Perfil do licitante diz onde você atende, o que fornece e como disputa.' }, { at: 14, title: 'Receba recomendações', text: 'O sistema cruza o perfil com as licitações abertas do PNCP e explica cada escolha.' }, { at: 22.4, title: 'Decida com segurança', text: 'O Go/No-Go mostra se vale a pena participar antes de montar a proposta.' }, { at: 31, title: 'Por onde começar', text: 'O primeiro passo é preencher o perfil.' }],
    captions: [[2.6, 6.4, 'Você acabou de entrar. Em poucos minutos o sistema começa a trabalhar por você.'], [8.4, 13.8, 'Tudo começa com três informações sobre a sua empresa.'], [15.6, 22.2, 'Cada recomendação vem com uma nota e o motivo de estar ali.'], [24, 30.8, 'E você decide com critérios claros, não no palpite.']] },
  { id: 'perfil', title: 'Como preencher o Perfil do licitante', summary: 'Passo a passo da configuração inicial: onde você atende, o que fornece e como disputa.', icon: 'ph-identification-card', duration: 52, poster: 15, render: tuPerfil,
    cta: { label: 'Preencher meu perfil agora', page: 'capacidades' },
    chapters: [{ at: 0, title: 'Abra o Perfil do licitante', text: 'No menu, em Inteligência, clique em Perfil do licitante.' }, { at: 7, title: 'Onde você atende', text: 'Escolha a UF e a cidade-base e informe o raio em km. Se atende estados inteiros, marque as UFs. Sem nada marcado, vale o Brasil inteiro.' }, { at: 19.6, title: 'O que você fornece', text: 'Digite as palavras que aparecem no objeto das licitações que interessam, separadas por vírgula. Em “Palavras a evitar”, ponha o que não quer receber.' }, { at: 30.6, title: 'Como você disputa', text: 'Informe o valor mínimo e o máximo e marque as modalidades. Sem modalidade marcada, todas entram.' }, { at: 39.4, title: 'Salve o perfil', text: 'Clique em Criar perfil. As recomendações passam a usar esses dados na hora.' }, { at: 47, title: 'Sua vez', text: 'Você pode ajustar o perfil quando quiser.' }],
    captions: [[1, 6.8, 'O Perfil do licitante é o que o Vértice usa para procurar licitações para você.'], [7.6, 14.4, 'Primeiro, a cidade-base e o raio de atendimento em quilômetros.'], [14.6, 19.4, 'Se você atende estados inteiros, marque as UFs também.'], [20, 24.4, 'Depois, as palavras que descrevem o que a sua empresa fornece.'], [24.6, 30.4, 'E as palavras que você quer evitar. Licitações com elas não são recomendadas.'], [31, 35.6, 'Defina a faixa de valor em que vale a pena disputar.'], [35.8, 39.2, 'Marque as modalidades em que você participa.'], [39.8, 46.8, 'Salve. O perfil já está valendo.']] },
  { id: 'recomendacoes', title: 'Como ler suas recomendações', summary: 'A nota de aderência, o motivo de cada ponto e como levar uma licitação para Oportunidades.', icon: 'ph-sparkle', duration: 35, poster: 14, render: tuRecs,
    cta: { label: 'Abrir minhas recomendações', page: 'recomendacoes' },
    chapters: [{ at: 0, title: 'Sua lista de recomendações', text: 'Licitações abertas do PNCP que combinam com o seu perfil, da maior para a menor aderência.' }, { at: 8.4, title: 'Por que foi recomendada', text: 'A nota vai até 100: objeto (40), localização (30), valor (15), prazo (10) e modalidade (5). Cada critério mostra o motivo.' }, { at: 18.6, title: 'Filtre por aderência', text: 'Use os filtros Alta aderência, Boa aderência e Exploratória para focar no que importa.' }, { at: 25.6, title: 'Leve para Oportunidades', text: 'Clique em Levar para Oportunidades. A licitação entra no seu funil e abre o Go/No-Go.' }],
    captions: [[1.2, 8.2, 'Estas são as licitações abertas que combinam com o seu perfil.'], [8.8, 18.4, 'Cada ponto da nota tem um motivo. Nada de caixa-preta.'], [19, 25.4, 'Filtre pela aderência para começar pelas melhores.'], [26, 34.6, 'Gostou? Leve para Oportunidades com um clique.']] },
  { id: 'decisao', title: 'Como decidir com o Go/No-Go', summary: 'Os sete critérios, o score e o que acontece com cada decisão.', icon: 'ph-gauge', duration: 36, poster: 20, render: tuDecisao,
    cta: { label: 'Abrir Oportunidades', page: 'oportunidades' },
    chapters: [{ at: 0, title: 'A pergunta', text: 'Antes de investir tempo na proposta: vale a pena participar?' }, { at: 7, title: 'Os sete critérios e o score', text: 'Valor, distância, margem, mão de obra, documentos, equipamentos e experiência. A partir de 70 pontos a indicação é participar; de 45 a 69, avaliar.' }, { at: 26.4, title: 'Registre a decisão', text: 'Participar e Avaliar criam uma oportunidade. Não participar fica no histórico. Antes de confirmar, você revisa os sete critérios.' }],
    captions: [[7.6, 17.8, 'Informe os sete critérios da sua empresa para esta licitação.'], [18, 26.2, 'O score soma os pontos e mostra o ponto mais fraco.'], [26.8, 35.6, 'Registre a decisão. Ela fica guardada com o edital.']] },
];
const vxTutorial = id => VX_TUTORIALS.find(x => x.id === id) || null;
// Narração (voz Vinícius Barroso, a mesma do Pitch 30s): trilha mp3 por tutorial, gerada por scripts/narracao/montar.mjs.
// A trilha tem a mesma duração do tutorial, então basta manter audio.currentTime == t. As legendas são o texto falado.
const vxNarr = id => (window.VxNarration && window.VxNarration[id]) || null;
const tuPref = (k, d) => { try { const v = localStorage.getItem('vx_tut_' + k); return v === null ? d : v === '1'; } catch (e) { return d; } };
const tuSetPref = (k, v) => { try { localStorage.setItem('vx_tut_' + k, v ? '1' : '0'); } catch (e) {} };
// A trilha inteira é baixada para a memória antes de tocar (blob). Tocar direto do endereço fazia o navegador buscar o mp3 aos
// pedaços; enquanto ele carregava, o relógio da animação seguia e corrigia a posição do áudio a cada instante, e a voz picotava
// até o arquivo entrar no cache. Com o blob, tocar e arrastar a barra são instantâneos e a animação espera o áudio ficar pronto.
const vxNarrBlobs = {};
function vxNarrBlob(id) {
  const n = vxNarr(id); if (!n) return Promise.resolve(null);
  if (!vxNarrBlobs[id]) vxNarrBlobs[id] = fetch(n.src).then(r => { if (!r.ok) throw new Error('http ' + r.status); return r.blob(); }).then(b => URL.createObjectURL(b)).catch(() => { delete vxNarrBlobs[id]; return null; });
  return vxNarrBlobs[id];
}
const tuClock = s => Math.floor(s / 60) + ':' + String(Math.floor(s % 60)).padStart(2, '0');

// Palco escalado: 960x540 lógicos, do tamanho do contêiner.
function TutorialStage({ tutorial, t, style, cc = true }) {
  const ref = React.useRef(null), [scale, setScale] = React.useState(0);
  React.useLayoutEffect(() => {
    const el = ref.current; if (!el) return;
    const fit = () => setScale(el.clientWidth / 960);
    fit();
    const ro = window.ResizeObserver ? new ResizeObserver(fit) : null;
    if (ro) ro.observe(el); else window.addEventListener('resize', fit);
    return () => { if (ro) ro.disconnect(); else window.removeEventListener('resize', fit); };
  }, []);
  return <div ref={ref} aria-hidden="true" style={{ position: 'relative', width: '100%', aspectRatio: '16 / 9', overflow: 'hidden', background: TC.bg, color: TC.text, fontFamily: 'var(--font-sans)', userSelect: 'none', ...style }}>
    {scale > 0 && <div style={{ position: 'absolute', left: 0, top: 0, width: 960, height: 540, transform: 'scale(' + scale + ')', transformOrigin: '0 0' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(90% 75% at 50% 42%, ' + TC.deep + ' 0%, ' + TC.petrol + ' 46%, ' + TC.bg + ' 100%)' }} />
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(rgba(95,163,174,.08) 1px,transparent 1px),linear-gradient(90deg,rgba(95,163,174,.08) 1px,transparent 1px)', backgroundSize: '48px 48px', WebkitMaskImage: 'radial-gradient(ellipse at center,#000 20%,transparent 72%)', maskImage: 'radial-gradient(ellipse at center,#000 20%,transparent 72%)' }} />
      {tutorial.render(t)}
      {cc && <TuCaption t={t} lines={(vxNarr(tutorial.id) || {}).lines || tutorial.captions || []} />}
    </div>}
  </div>;
}

// Player: palco + controles + capítulos clicáveis (o passo a passo em texto, para rever sem assistir tudo de novo).
function TutorialPlayer({ tutorial, autoPlay, onCta, onEnded, compact }) {
  const reduce = React.useMemo(() => { try { return matchMedia('(prefers-reduced-motion: reduce)').matches; } catch (e) { return false; } }, []);
  const [t, setT] = React.useState(0), [playing, setPlaying] = React.useState(!!autoPlay && !reduce), [ended, setEnded] = React.useState(false), [speed, setSpeed] = React.useState(1);
  const narr = vxNarr(tutorial.id), [sound, setSound] = React.useState(() => tuPref('sound', true)), [cc, setCc] = React.useState(() => tuPref('cc', true)), [blocked, setBlocked] = React.useState(false), [ready, setReady] = React.useState(!vxNarr(tutorial.id)), readyRef = React.useRef(ready);
  readyRef.current = ready;
  const audioRef = React.useRef(null), soundRef = React.useRef(sound);
  soundRef.current = sound;
  const tRef = React.useRef(0), speedRef = React.useRef(1), wrap = React.useRef(null), endedCb = React.useRef(onEnded);
  endedCb.current = onEnded; speedRef.current = speed;
  React.useEffect(() => { tRef.current = 0; setT(0); setEnded(false); setPlaying(!!autoPlay && !reduce); }, [tutorial.id]);
  React.useEffect(() => {
    setBlocked(false);
    if (!narr) { audioRef.current = null; readyRef.current = true; setReady(true); return; }
    readyRef.current = false; setReady(false);
    let alive = true, a = null;
    const timer = setTimeout(() => { if (alive && !readyRef.current) { readyRef.current = true; setReady(true); } }, 8000); // rede lenta: segue sem voz
    vxNarrBlob(tutorial.id).then(url => {
      if (!alive) return;
      setTimeout(() => VX_TUTORIALS.forEach(x => vxNarrBlob(x.id)), 1500); // adianta as outras trilhas (pequenas) para a próxima aula começar na hora
      a = new Audio(); a.preload = 'auto'; a.src = url || narr.src; audioRef.current = a;
      const go = () => { if (alive && !readyRef.current) { readyRef.current = true; setReady(true); } };
      if (a.readyState >= 3) go(); else { a.addEventListener('canplaythrough', go, { once: true }); a.addEventListener('error', go, { once: true }); a.load(); }
    });
    return () => { alive = false; clearTimeout(timer); if (a) { a.pause(); a.removeAttribute('src'); a.load(); if (audioRef.current === a) audioRef.current = null; } };
  }, [tutorial.id]);
  // Mantém a voz em sincronia com play, pausa, arrastar a barra e velocidade.
  React.useEffect(() => {
    const a = audioRef.current; if (!a) return;
    a.playbackRate = speed;
    if (playing && sound) {
      if (Math.abs(a.currentTime - tRef.current) > .25) a.currentTime = tRef.current;
      const pr = a.play(); if (pr && pr.catch) pr.then(() => setBlocked(false)).catch(() => setBlocked(true));
    } else a.pause();
  }, [playing, sound, speed, tutorial.id, ready]);
  React.useEffect(() => {
    if (!playing) return;
    let raf, last = performance.now();
    const tick = now => {
      const dt = Math.min(.1, (now - last) / 1000); last = now;
      if (!readyRef.current && soundRef.current) { raf = requestAnimationFrame(tick); return; } // espera a voz carregar; palco e áudio saem juntos
      // Com a voz tocando, o áudio é o relógio: a animação segue a posição dele e o áudio nunca é reposicionado durante a reprodução
      // (reposicionar a cada diferença de relógio era o que picotava a voz, principalmente em 1,5x e 2x).
      const au = audioRef.current, follow = au && soundRef.current && !au.paused && !au.ended && au.readyState >= 2;
      const next = follow ? Math.max(tRef.current, au.currentTime) : tRef.current + dt * speedRef.current;
      if (next >= tutorial.duration) { tRef.current = tutorial.duration; setT(tutorial.duration); setPlaying(false); setEnded(true); window.VxOnboarding.markWatched(tutorial.id); if (endedCb.current) endedCb.current(); return; }
      tRef.current = next; setT(next); raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing, tutorial.id]);
  const seek = (s, play) => { const v = tuC(s, 0, tutorial.duration); tRef.current = v; setT(v); setEnded(false); if (audioRef.current) audioRef.current.currentTime = v; if (play !== undefined) setPlaying(play); };
  const toggle = () => { if (ended || t >= tutorial.duration) seek(0, true); else setPlaying(p => !p); };
  const scrub = e => { const r = e.currentTarget.getBoundingClientRect(); seek((e.clientX - r.left) / r.width * tutorial.duration); };
  const chapterIdx = tutorial.chapters.reduce((a, c, i) => t >= c.at - .01 ? i : a, 0);
  const full = () => { const el = wrap.current; if (!el) return; if (document.fullscreenElement) document.exitFullscreen(); else if (el.requestFullscreen) el.requestFullscreen().catch(() => {}); };
  const key = e => { if (e.key === ' ' || e.key === 'k') { e.preventDefault(); toggle(); } else if (e.key === 'ArrowRight') seek(tRef.current + 5); else if (e.key === 'ArrowLeft') seek(tRef.current - 5); };
  const ctl = { all: 'unset', cursor: 'pointer', width: 34, height: 34, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 18, flex: 'none' };
  return <div style={{ display: 'flex', flexWrap: 'wrap', gap: 20, alignItems: 'flex-start' }}>
    <div ref={wrap} tabIndex={0} onKeyDown={key} role="group" aria-label={'Tutorial: ' + tutorial.title} style={{ flex: '999 1 480px', minWidth: 0, borderRadius: 16, overflow: 'hidden', border: '1px solid var(--border-default)', background: TC.bg, outline: 'none', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
      <div style={{ position: 'relative', cursor: 'pointer' }} onClick={toggle}>
        <TutorialStage tutorial={tutorial} t={t} cc={cc} />
        {playing && narr && sound && !ready && <div style={{ position: 'absolute', top: 12, right: 12, padding: '6px 12px', borderRadius: 10, background: 'rgba(4,14,21,.88)', border: '1px solid rgba(255,255,255,.2)', color: '#fff', fontSize: 12.5 }}>Carregando a narração…</div>}
        {playing && narr && sound && blocked && <button type="button" onClick={e => { e.stopPropagation(); const a = audioRef.current; if (a) { a.currentTime = tRef.current; a.play().then(() => setBlocked(false)).catch(() => {}); } }} style={{ all: 'unset', cursor: 'pointer', position: 'absolute', top: 12, right: 12, display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 10, background: 'rgba(4,14,21,.88)', border: '1px solid rgba(255,255,255,.3)', color: '#fff', fontSize: 13, fontWeight: 600 }}><i className="ph ph-speaker-high" /> Toque para ouvir a narração</button>}
        {!playing && !ended && <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: t === 0 ? 'rgba(4,14,21,.45)' : 'rgba(4,14,21,.25)' }}>
          <span style={{ width: 72, height: 72, borderRadius: '50%', background: 'rgba(255,255,255,.14)', border: '1px solid rgba(255,255,255,.4)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 30 }}><i className="ph ph-play" /></span>
        </div>}
        {ended && <div onClick={e => e.stopPropagation()} style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'center', justifyContent: 'center', background: 'rgba(4,14,21,.8)', cursor: 'default', animation: 'vx-enter .3s ease backwards' }}>
          {tutorial.cta && onCta && <button type="button" onClick={() => onCta(tutorial.cta)} style={{ all: 'unset', cursor: 'pointer', padding: '13px 22px', borderRadius: 10, background: TC.blue, color: '#fff', fontSize: 15, fontWeight: 600 }}>{tutorial.cta.label} →</button>}
          <button type="button" onClick={() => seek(0, true)} style={{ all: 'unset', cursor: 'pointer', padding: '9px 16px', borderRadius: 10, color: '#fff', fontSize: 13, border: '1px solid rgba(255,255,255,.25)' }}><i className="ph ph-arrow-counter-clockwise" /> Rever do início</button>
        </div>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 10px', background: '#06121a', borderTop: '1px solid ' + TC.line }}>
        <button type="button" style={ctl} onClick={toggle} aria-label={playing ? 'Pausar' : 'Reproduzir'}><i className={'ph ' + (playing ? 'ph-pause' : 'ph-play')} /></button>
        <span style={{ ...TU_MONO, fontSize: 12, color: TC.mute, flex: 'none' }}>{tuClock(t)} / {tuClock(tutorial.duration)}</span>
        <div onClick={scrub} role="slider" aria-label="Posição do tutorial" aria-valuemin={0} aria-valuemax={Math.round(tutorial.duration)} aria-valuenow={Math.round(t)} style={{ flex: 1, height: 26, display: 'flex', alignItems: 'center', cursor: 'pointer', margin: '0 8px', minWidth: 60 }}>
          <div style={{ position: 'relative', width: '100%', height: 5, borderRadius: 3, background: 'rgba(255,255,255,.14)' }}>
            <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: (t / tutorial.duration * 100) + '%', borderRadius: 3, background: TC.sky }} />
            {tutorial.chapters.slice(1).map(c => <span key={c.at} style={{ position: 'absolute', left: (c.at / tutorial.duration * 100) + '%', top: -2, width: 2, height: 9, background: '#06121a' }} />)}
          </div>
        </div>
        <button type="button" style={{ ...ctl, width: 'auto', padding: '0 8px', ...TU_MONO, fontSize: 12 }} onClick={() => setSpeed(s => s === 1 ? 1.5 : s === 1.5 ? 2 : 1)} aria-label="Velocidade">{String(speed).replace('.', ',')}x</button>
        {narr && <button type="button" style={{ ...ctl, opacity: sound ? 1 : .55 }} onClick={() => setSound(v => { tuSetPref('sound', !v); return !v; })} aria-pressed={sound} aria-label={sound ? 'Desligar narração' : 'Ligar narração'} title={sound ? 'Desligar narração' : 'Ligar narração'}><i className={'ph ' + (sound ? 'ph-speaker-high' : 'ph-speaker-slash')} /></button>}
        <button type="button" style={{ ...ctl, opacity: cc ? 1 : .55, boxShadow: cc ? 'inset 0 -2px 0 ' + TC.sky : 'none' }} onClick={() => setCc(v => { tuSetPref('cc', !v); return !v; })} aria-pressed={cc} aria-label={cc ? 'Ocultar legendas' : 'Mostrar legendas'} title={cc ? 'Ocultar legendas' : 'Mostrar legendas'}><i className="ph ph-closed-captioning" /></button>
        <button type="button" style={ctl} onClick={full} aria-label="Tela cheia"><i className="ph ph-corners-out" /></button>
      </div>
    </div>
    {!compact && <ol style={{ flex: '1 1 260px', minWidth: 0, margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6 }}>
      <li style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-subtle)', fontWeight: 600, padding: '2px 12px 6px' }}>Passo a passo</li>
      {tutorial.chapters.map((c, i) => { const on = i === chapterIdx; return <li key={c.at}>
        <button type="button" onClick={() => seek(c.at, true)} aria-current={on ? 'step' : undefined} style={{ all: 'unset', boxSizing: 'border-box', width: '100%', cursor: 'pointer', display: 'flex', gap: 12, padding: '10px 12px', borderRadius: 12, background: on ? 'var(--action-selected-bg)' : 'transparent', border: '1px solid ' + (on ? 'var(--border-default)' : 'transparent') }}>
          <span style={{ width: 24, height: 24, borderRadius: '50%', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-mono)', background: i < chapterIdx ? 'var(--status-success)' : on ? 'var(--action-primary)' : 'var(--overlay-06)', color: i <= chapterIdx ? '#fff' : 'var(--text-muted)' }}>{i < chapterIdx ? '✓' : i + 1}</span>
          <span style={{ minWidth: 0 }}>
            <span style={{ display: 'block', fontSize: 14, fontWeight: 600, color: 'var(--text-primary)' }}>{c.title} <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 400, color: 'var(--text-subtle)' }}>{tuClock(c.at)}</span></span>
            <span style={{ display: 'block', fontSize: 13, lineHeight: 1.45, color: 'var(--text-muted)', marginTop: 3 }}>{c.text}</span>
          </span>
        </button>
      </li>; })}
    </ol>}
  </div>;
}

// Cartão de tutorial com um quadro real do próprio tutorial como capa.
function TutorialCard({ tutorial, onOpen }) {
  const watched = window.VxOnboarding.watched(tutorial.id);
  return <button type="button" onClick={() => onOpen(tutorial.id)} className="vx-tutcard" style={{ all: 'unset', boxSizing: 'border-box', cursor: 'pointer', display: 'flex', flexDirection: 'column', borderRadius: 16, overflow: 'hidden', background: 'var(--surface-flat)', border: '1px solid var(--border-default)', minWidth: 0 }}>
    <span style={{ position: 'relative', display: 'block' }}>
      <TutorialStage tutorial={tutorial} t={tutorial.poster} />
      <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(4,14,21,.3)' }}><span style={{ width: 52, height: 52, borderRadius: '50%', background: 'rgba(255,255,255,.16)', border: '1px solid rgba(255,255,255,.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 22 }}><i className="ph ph-play" /></span></span>
      <span style={{ position: 'absolute', right: 10, bottom: 10, padding: '3px 8px', borderRadius: 6, background: 'rgba(4,14,21,.85)', color: '#fff', fontFamily: 'var(--font-mono)', fontSize: 11 }}>{tuClock(tutorial.duration)}</span>
    </span>
    <span style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: '14px 16px 16px' }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 15, fontWeight: 600, color: 'var(--text-primary)' }}>{tutorial.title}</span>
      <span style={{ fontSize: 13, lineHeight: 1.45, color: 'var(--text-muted)' }}>{tutorial.summary}</span>
      <span style={{ fontSize: 12, color: watched ? 'var(--status-success)' : 'var(--text-subtle)', marginTop: 2 }}>{watched ? '✓ Assistido · rever' : tutorial.chapters.length + ' etapas'}</span>
    </span>
  </button>;
}

// Janela do tutorial, aberta de qualquer tela: window.VxTutorials.open('perfil').
// Com `sequence`, toca os tutoriais em ordem (boas-vindas do primeiro acesso: animação, depois a configuração).
function TutorialHost({ go }) {
  const [st, setSt] = React.useState(null); // { ids, i, welcome }
  React.useEffect(() => {
    const h = e => { const d = e.detail || {}; const ids = (d.sequence || [d.id]).filter(vxTutorial); if (ids.length) setSt({ ids, i: 0, welcome: !!d.welcome }); };
    window.addEventListener('vx-tutorial-open', h);
    return () => window.removeEventListener('vx-tutorial-open', h);
  }, []);
  React.useEffect(() => { if (!st) return; const k = e => { if (e.key === 'Escape') setSt(null); }; window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k); }, [!!st]);
  if (!st) return null;
  const tut = vxTutorial(st.ids[st.i]), last = st.i === st.ids.length - 1;
  const close = () => setSt(null);
  const cta = c => { if (c.tutorial && vxTutorial(c.tutorial)) { const at = st.ids.indexOf(c.tutorial); setSt(at >= 0 ? { ...st, i: at } : { ids: [c.tutorial], i: 0 }); return; } close(); if (c.page) go(c.page); };
  return <div role="dialog" aria-modal="true" aria-label={tut.title} style={{ position: 'fixed', inset: 0, zIndex: 400, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, boxSizing: 'border-box' }}>
    <div onClick={close} style={{ position: 'absolute', inset: 0, background: 'var(--bg-overlay)', backdropFilter: 'blur(4px)' }} />
    <div style={{ position: 'relative', width: 'min(1180px, 100%)', maxHeight: '100%', overflowY: 'auto', borderRadius: 20, background: 'var(--surface-dialog)', border: '1px solid var(--border-default)', boxShadow: '0 40px 120px rgba(0,0,0,.5)', padding: 24, boxSizing: 'border-box', display: 'flex', flexDirection: 'column', gap: 18, animation: 'vx-enter .3s ease backwards' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-subtle)', fontWeight: 600 }}>{st.welcome ? 'Boas-vindas' : 'Tutorial'}{st.ids.length > 1 ? ' · ' + (st.i + 1) + ' de ' + st.ids.length : ''}</div>
          <h2 style={{ margin: '6px 0 0', fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{tut.title}</h2>
        </div>
        <button type="button" onClick={close} style={{ all: 'unset', cursor: 'pointer', padding: '8px 12px', borderRadius: 8, fontSize: 13, color: 'var(--text-muted)', border: '1px solid var(--border-default)', flex: 'none' }}>{st.welcome ? 'Pular por agora' : 'Fechar'}</button>
      </div>
      <TutorialPlayer key={tut.id} tutorial={tut} autoPlay onCta={cta} onEnded={() => { if (!last) setTimeout(() => setSt(s => s && s.ids[s.i] === tut.id ? { ...s, i: s.i + 1 } : s), 1400); }} />
      {st.welcome && <span style={{ fontSize: 12, color: 'var(--text-subtle)' }}>Você pode rever estes tutoriais quando quiser na Central de Ajuda.</span>}
    </div>
  </div>;
}

window.VxTutorials = { list: VX_TUTORIALS, byId: vxTutorial, open: (id, opts) => window.dispatchEvent(new CustomEvent('vx-tutorial-open', { detail: { id, ...(opts || {}) } })), openSequence: (ids, opts) => window.dispatchEvent(new CustomEvent('vx-tutorial-open', { detail: { sequence: ids, ...(opts || {}) } })) };
Object.assign(window, { TutorialStage, TutorialPlayer, TutorialCard, TutorialHost });
