// ═══════════════════════════════════════════════════════════════════
// Screen: Simulador de comissão — aba dedicada
// Monta um lead hipotético com as escolhas do vendedor e roda no motor
// real (calcularComissoes) — mostra exatamente o que ele receberia.
//
// Mobile (≤768px): carrossel horizontal de 5 passos com scroll-snap +
// resultado sticky no topo. Desktop: coluna dupla (inputs | resultado).
// ═══════════════════════════════════════════════════════════════════

function SimuladorScreen({ state, vendedorId, setState }) {
  const { leads: leadsTodos, regras, vendedores, trimestre } = state;
  const { isMobile } = useMobile();
  const origens = window.origemLabels || {};

  // Filtra leads pelo trimestre exibido (mesmo padrão do dashboard/extrato).
  // Hiago 2026-06-18: sem isso, o simulador somava leads de 2T/2026 no total
  // do 1T/2026, dando "meu atual" inflado.
  const leads = useMemo(() => (leadsTodos || []).filter(l => {
    const tl = (l && l.trimestre) || '1T/2026';
    return tl === trimestre;
  }), [leadsTodos, trimestre]);

  const vendedor = vendedores.find(v => v.id === vendedorId);
  const meu = useMemo(() => {
    const todos = calcularComissoes(leads, regras, vendedores);
    return todos[vendedorId] || { variavel: 0, fixaSetor: 0, evento: 0, total: 0, linhas: [] };
  }, [leads, regras, vendedores, vendedorId]);

  const ativos = vendedores.filter(v => v.ativo && v.papel !== 'Diretora' && v.papel !== 'Diretor');

  const [simValor, setSimValor] = useState(200000);
  const [simOrigem, setSimOrigem] = useState('ativa');
  const [simMarkup, setSimMarkup] = useState(30);
  const [simQuals, setSimQuals] = useState([vendedorId]);
  const [simFinals, setSimFinals] = useState([vendedorId]);
  const [simVersao, setSimVersao] = useState('2026_projetos');
  const [simGatilhos, setSimGatilhos] = useState(() => new Set(['reuniao', 'proposta']));
  const [simNpsNota, setSimNpsNota] = useState('4.5');
  const [simPassouQual, setSimPassouQual] = useState('sim');
  const [simEditalModo, setSimEditalModo] = useState('A');
  const [simSetorProj, setSimSetorProj] = useState('pd');

  const toggleQual  = (id) => setSimQuals(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  const toggleFinal = (id) => setSimFinals(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);

  const simTiposDisponiveis = useMemo(() => {
    const regrasSim = window.simularRegras ? window.simularRegras(simVersao, regras) : regras;
    return window.gatilhosPorOrigem ? window.gatilhosPorOrigem(simOrigem, regrasSim) : [];
  }, [simOrigem, simVersao, regras]);

  // Mantém só gatilhos válidos pra esse cenário; default = proposta/edital/todos.
  useEffect(() => {
    setSimGatilhos(prev => {
      const novo = new Set();
      simTiposDisponiveis.forEach(t => { if (prev.has(t)) novo.add(t); });
      if (novo.size === 0) {
        if (simTiposDisponiveis.includes('proposta')) novo.add('proposta');
        else if (simTiposDisponiveis.includes('edital')) novo.add('edital');
        else simTiposDisponiveis.forEach(t => novo.add(t));
      }
      return novo;
    });
  }, [simTiposDisponiveis.join('|')]);

  const toggleSimGatilho = (tipo) => setSimGatilhos(prev => {
    const novo = new Set(prev);
    if (novo.has(tipo)) novo.delete(tipo); else novo.add(tipo);
    return novo;
  });

  // Auto-prefill participantes: usa o mesmo helper do motor (autoComissionados)
  // pra pré-marcar quem normalmente participa naquele cenário. O vendedor só
  // destira quem não estava no caso dele.
  useEffect(() => {
    if (!window.autoComissionados) return;
    const regrasSim = window.simularRegras ? window.simularRegras(simVersao, regras) : regras;
    const leadHipotetico = {
      versaoRegras: simVersao,
      origem: simOrigem,
      tipo: simOrigem === 'editais' ? 'edital' : 'projeto',
      setorProjeto: simSetorProj,
      passouQualificacao: simPassouQual,
      editalFixaModo: simEditalModo,
      origemSubmissao: 'ativa',
    };
    const idsQualif = new Set();
    Array.from(simGatilhos).forEach(tipo => {
      if (tipo === 'proposta' || tipo === 'proposta_fidel' || tipo === 'proposta_bonus') return;
      (window.autoComissionados(tipo, leadHipotetico, regrasSim) || []).forEach(id => idsQualif.add(id));
    });
    if (vendedorId) idsQualif.add(vendedorId);

    const idsFinal = new Set();
    const hasProposta = simGatilhos.has('proposta') || simGatilhos.has('proposta_fidel') || simGatilhos.has('proposta_bonus');
    if (hasProposta) {
      const tDe = (n) => (window.timeDe ? window.timeDe(n, regrasSim) : []);
      if (simOrigem === 'fidelizacao') {
        const time  = simSetorProj === 'nne' ? tDe('time_nne') : tDe('time_pd');
        const lider = simSetorProj === 'nne' ? tDe('pos_nne')  : tDe('pos_pd');
        [...time, ...lider].forEach(id => idsFinal.add(id));
      } else {
        vendedores
          .filter(v => v.ativo && !v.isTeam && (v.papel === 'Comercial' || v.papel === 'Fidelização'))
          .forEach(v => idsFinal.add(v.id));
      }
    }
    if (vendedorId) idsFinal.add(vendedorId);

    setSimQuals(prev => {
      const a = Array.from(idsQualif).sort();
      const b = [...prev].sort();
      if (a.length === b.length && a.every((x, i) => x === b[i])) return prev;
      return Array.from(idsQualif);
    });
    setSimFinals(prev => {
      const a = Array.from(idsFinal).sort();
      const b = [...prev].sort();
      if (a.length === b.length && a.every((x, i) => x === b[i])) return prev;
      return Array.from(idsFinal);
    });
  }, [simVersao, simOrigem, simGatilhos, simSetorProj, simPassouQual, simEditalModo, vendedorId, regras]);

  const simulado = useMemo(() => {
    const regrasSim = window.simularRegras ? window.simularRegras(simVersao, regras) : regras;
    const participantes = Array.from(new Set([...simQuals, ...simFinals]));
    const participacoes = [
      ...simQuals.map(id => ({ v: id, papel: 'Qualificador' })),
      ...simFinals.map(id => ({ v: id, papel: 'Finalizador' })),
    ];
    if (participacoes.length === 0 || simGatilhos.size === 0) {
      return { total: 0, delta: 0, divisao: [], variavelMeu: 0, fixaMeu: 0, totalMeu: 0, linhasMeu: [], fixaTotal: 0, pctFixa: 0 };
    }
    const dataHoje = new Date().toISOString().slice(0, 10);
    const gatilhos = Array.from(simGatilhos).map(tipo => {
      const comissionados = tipo === 'nps' || tipo === 'edital' ? [] : participantes;
      const extra = tipo === 'nps' ? String(simNpsNota).replace(',', '.') : '';
      return { tipo, ok: true, data: dataHoje, comissionados, extra };
    });

    const fakeLead = {
      id: 'SIM', lead: 'Projeto hipotético', cliente: 'Simulação', origem: simOrigem,
      vendido: true, valor: simValor, markup: simMarkup,
      versaoRegras: simVersao,
      tipo: simOrigem === 'editais' ? 'edital' : 'projeto',
      setorProjeto: simSetorProj,
      passouQualificacao: simPassouQual,
      editalFixaModo: simEditalModo,
      origemSubmissao: 'ativa',
      participacoes, gatilhos,
      comissiona: true, status: 'fechado', data: dataHoje,
      comissaoFixa: 0,
    };

    if (simOrigem !== 'editais') {
      const m = +simMarkup || 0;
      let pctRaw = 0;
      if (m <= 25)      pctRaw = regrasSim.fixa?.markup_baixo?.valor || 0;
      else if (m <= 35) pctRaw = regrasSim.fixa?.markup_medio?.valor || 0;
      else              pctRaw = regrasSim.fixa?.markup_alto?.valor  || 0;
      fakeLead.comissaoFixa = (+simValor || 0) * (pctRaw / 100);
    } else {
      const m = +simMarkup || 0;
      let pctRaw = 0;
      if (m <= 25)      pctRaw = regrasSim.fixa?.edital_baixo?.valor || 0;
      else if (m <= 35) pctRaw = regrasSim.fixa?.edital_medio?.valor || 0;
      else              pctRaw = regrasSim.fixa?.edital_alto?.valor  || 0;
      fakeLead.comissaoFixa = (+simValor || 0) * (pctRaw / 100);
    }

    const simIsolado = calcularComissoes([fakeLead], regrasSim, vendedores);
    const simTotal   = calcularComissoes([...leads, fakeLead], regrasSim, vendedores);
    const novo = simTotal[vendedorId] || { total: 0, variavel: 0, fixaSetor: 0, evento: 0 };
    const meuIsolado = simIsolado[vendedorId] || { total: 0, variavel: 0, fixaSetor: 0, linhas: [] };

    return {
      total: novo.total,
      delta: novo.total - meu.total,
      variavelMeu: meuIsolado.variavel || 0,
      fixaMeu:    (meuIsolado.fixaSetor || 0) + (meuIsolado.fixaAdicional || 0),
      totalMeu:    meuIsolado.total || 0,
      linhasMeu:   meuIsolado.linhas || [],
      pctFixa:    +simValor > 0 ? (fakeLead.comissaoFixa / +simValor) * 100 : 0,
      fixaTotal:  fakeLead.comissaoFixa,
      divisao: vendedores
        .filter(v => simIsolado[v.id]?.total > 0.01)
        .map(v => ({
          id: v.id, nome: v.nome,
          total:    simIsolado[v.id].total,
          variavel: simIsolado[v.id].variavel,
          fixa:    (simIsolado[v.id].fixaSetor || 0) + (simIsolado[v.id].fixaAdicional || 0),
          papeis:   [...(simQuals.includes(v.id) ? ['Qualificador'] : []), ...(simFinals.includes(v.id) ? ['Finalizador'] : [])],
        }))
        .sort((a, b) => b.total - a.total),
    };
  }, [leads, regras, vendedores, vendedorId, simValor, simOrigem, simMarkup, simQuals, simFinals,
      simVersao, simGatilhos, simNpsNota, simPassouQual, simEditalModo, simSetorProj, meu]);

  if (!vendedor) return <div>Vendedor não encontrado.</div>;

  // ───────────────────────────────────────────────────────────────
  // Conteúdo de cada passo — usado tanto no carrossel mobile quanto
  // empilhado no desktop. Mantém a fonte única de verdade pra UI.
  // ───────────────────────────────────────────────────────────────

  const StepLabel = ({ idx, children }) => (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 10.5, fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--escalab-mute)' }}>
      <span style={{ color: 'var(--escalab-brand)', fontVariantNumeric: 'tabular-nums' }}>{idx}</span>
      <span style={{ width: 1, height: 9, background: 'var(--escalab-line)' }} />
      <span>{children}</span>
    </div>
  );

  const versaoOpts = [
    { v: '2025',           label: '2025' },
    { v: '2026_projetos',  label: '2026 · Projetos' },
    { v: '2026_editais',   label: '2026 · Editais' },
  ];

  const pillBtn = (on) => ({
    border: `1px solid ${on ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
    background: on ? 'var(--escalab-brand-tint)' : '#fff',
    color: on ? 'var(--escalab-brand-deep)' : 'var(--escalab-slate)',
    fontWeight: 600, padding: '9px 14px', borderRadius: 10, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
    minHeight: 40, flexShrink: 0,
    transition: 'all .2s var(--ease-out)',
  });

  const renderVersao = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0 }}>
      <StepLabel idx="1">Versão das regras</StepLabel>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {versaoOpts.map(opt => (
          <button key={opt.v} onClick={() => {
            setSimVersao(opt.v);
            if (opt.v === '2026_editais') setSimOrigem('editais');
            else if (simOrigem === 'editais') setSimOrigem('ativa');
          }} style={pillBtn(simVersao === opt.v)}>{opt.label}</button>
        ))}
      </div>
      <p style={{ fontSize: 12.5, color: 'var(--escalab-mute)', margin: '4px 0 0', lineHeight: 1.4 }}>
        O conjunto de regras que vai rodar — gatilhos, NPS limiar, fixa por markup mudam entre versões.
      </p>
    </div>
  );

  const renderOrigem = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
      <StepLabel idx="2">Origem do lead</StepLabel>
      <Select value={simOrigem} onChange={v => {
        setSimOrigem(v);
        if (v === 'editais') setSimVersao('2026_editais');
        else if (simVersao === '2026_editais') setSimVersao('2026_projetos');
      }}
        options={Object.entries(origens).map(([v, l]) => ({ value: v, label: l }))} />

      {simOrigem === 'ativa' && simVersao === '2026_projetos' && (
        <Field label="O lead passou pela qualificação?">
          <div style={{ display: 'flex', gap: 8 }}>
            {[{v:'sim', l:'Sim'}, {v:'nao', l:'Não (venda direta)'}].map(o => (
              <button key={o.v} onClick={() => setSimPassouQual(o.v)} style={{ ...pillBtn(simPassouQual === o.v), flex: 1 }}>{o.l}</button>
            ))}
          </div>
        </Field>
      )}
      {simOrigem === 'fidelizacao' && (
        <Field label="Setor do projeto fidelizado">
          <div style={{ display: 'flex', gap: 8 }}>
            {[{v:'pd', l:'P&D'}, {v:'nne', l:'NNE'}].map(o => (
              <button key={o.v} onClick={() => setSimSetorProj(o.v)} style={{ ...pillBtn(simSetorProj === o.v), flex: 1 }}>{o.l}</button>
            ))}
          </div>
        </Field>
      )}
      {simOrigem === 'editais' && (
        <Field label="Modo da fixa do edital">
          <div style={{ display: 'flex', gap: 8 }}>
            {[{v:'A', l:'Modo A'}, {v:'B', l:'Modo B'}].map(o => (
              <button key={o.v} onClick={() => setSimEditalModo(o.v)} style={{ ...pillBtn(simEditalModo === o.v), flex: 1 }}>{o.l}</button>
            ))}
          </div>
        </Field>
      )}
    </div>
  );

  const renderValor = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
      <StepLabel idx="3">Tamanho do projeto</StepLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 11.5, color: 'var(--escalab-slate)' }}>Valor do contrato</span>
          <strong style={{ color: 'var(--escalab-brand-deep)', fontSize: 17, fontVariantNumeric: 'tabular-nums', letterSpacing: '-.01em' }}>{brl(simValor)}</strong>
        </div>
        <input type="range" min="10000" max="2000000" step="5000" value={simValor} onChange={e => setSimValor(+e.target.value)} style={{ width: '100%', accentColor: 'var(--escalab-brand)' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--escalab-mute)', fontVariantNumeric: 'tabular-nums' }}>
          <span>R$ 10k</span><span>R$ 2M</span>
        </div>
      </div>
      <Field label="Markup">
        <Input value={simMarkup} onChange={v => setSimMarkup(+v || 0)} type="number" suffix="%" inputMode="numeric" />
      </Field>
    </div>
  );

  const renderGatilhos = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
      <StepLabel idx="4">Gatilhos atingidos</StepLabel>
      {simTiposDisponiveis.length === 0 ? (
        <div style={{ fontSize: 13, color: 'var(--escalab-mute)', padding: '12px 14px', background: 'var(--escalab-paper)', border: '1px dashed var(--escalab-line)', borderRadius: 10 }}>
          Sem gatilhos variáveis nessa origem.
        </div>
      ) : (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {simTiposDisponiveis.map(tipo => {
            const labels = { reuniao: 'Reunião', proposta: 'Proposta', proposta_bonus: 'Bônus margem', proposta_fidel: 'Proposta fidelização', nps: 'NPS', publicacao: 'Publicação', edital: 'Edital submetido' };
            const on = simGatilhos.has(tipo);
            return (
              <button key={tipo} onClick={() => toggleSimGatilho(tipo)} style={{
                border: `1px solid ${on ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
                background: on ? 'var(--escalab-brand-tint)' : '#fff',
                color: on ? 'var(--escalab-brand-deep)' : 'var(--escalab-slate)',
                fontWeight: 600, padding: '8px 12px', borderRadius: 999, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 7, minHeight: 36,
                transition: 'all .18s var(--ease-out)',
              }}>
                <span style={{ display: 'inline-block', width: 11, height: 11, borderRadius: 3, border: `1.5px solid ${on ? 'var(--escalab-brand)' : 'var(--escalab-mute)'}`, background: on ? 'var(--escalab-brand)' : 'transparent', transition: 'all .18s var(--ease-out)' }} />
                {labels[tipo] || tipo}
              </button>
            );
          })}
        </div>
      )}
      {simGatilhos.has('nps') && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: 'var(--escalab-brand-tint)', borderRadius: 10, border: '1px solid var(--escalab-brand-soft)' }}>
          <span style={{ fontSize: 12, color: 'var(--escalab-brand-deep)', fontWeight: 600 }}>Nota NPS recebida:</span>
          <div style={{ width: 84 }}>
            <Input value={simNpsNota} onChange={v => setSimNpsNota(v)} type="number" inputMode="decimal" />
          </div>
        </div>
      )}
    </div>
  );

  const renderParticipantes = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0 }}>
      <StepLabel idx="5">Quem participou</StepLabel>
      <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', flexWrap: 'wrap', gap: 12 }}>
        {[
          { label: 'Qualificou', checked: simQuals, toggle: toggleQual, accent: 'var(--escalab-brand)' },
          { label: 'Finalizou',  checked: simFinals, toggle: toggleFinal, accent: 'var(--escalab-brand-deep)' },
        ].map(grupo => (
          <div key={grupo.label} style={{ flex: '1 1 200px', minWidth: 0, background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: 10 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: grupo.accent, marginBottom: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>{grupo.label} <span style={{ color: 'var(--escalab-mute)', fontWeight: 600 }}>· {ativos.length} pessoas</span></span>
              <span style={{ fontVariantNumeric: 'tabular-nums', background: '#fff', border: '1px solid var(--escalab-line)', padding: '2px 7px', borderRadius: 999, fontSize: 10.5, color: 'var(--escalab-slate)' }}>{grupo.checked.length} selecionado{grupo.checked.length !== 1 ? 's' : ''}</span>
            </div>
            {/* Maria 2026-06-26: feedback do time — em notebook/touchpad o
                scrollbar nem sempre aparece e a lista parecia travada.
                Mudanças:
                 - `overflow-y: scroll` (não `auto`) força a barra a SEMPRE
                   aparecer, em qualquer browser/SO.
                 - maxHeight desktop subiu pra 280 (era 170) — cabem 7+
                   pessoas sem precisar rolar.
                 - paddingRight reserva espaço pro scrollbar, evita texto
                   debaixo dele.
                 - position: relative + gradiente fade no fundo dão dica
                   visual de "tem mais abaixo" mesmo sem barra visível. */}
            <div style={{ position: 'relative', minWidth: 0 }}>
              <div style={{
                display: 'flex', flexDirection: 'column', gap: 2,
                maxHeight: isMobile ? 320 : 280,
                overflowY: 'scroll',
                paddingRight: 6,
                scrollbarWidth: 'thin',
                scrollbarColor: 'var(--escalab-brand-soft) transparent',
                background: '#fff',
                border: '1px solid var(--escalab-line)',
                borderRadius: 8,
                padding: 4,
              }}>
                {ativos.map(v => {
                  const on = grupo.checked.includes(v.id);
                  return (
                    <label key={v.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 8px', borderRadius: 8, cursor: 'pointer', background: on ? 'var(--escalab-brand-tint)' : 'transparent', border: on ? `1px solid ${grupo.accent}` : '1px solid transparent', transition: 'all .15s var(--ease-out)' }}>
                      <input type="checkbox" checked={on} onChange={() => grupo.toggle(v.id)} style={{ accentColor: grupo.accent, width: 16, height: 16, flexShrink: 0 }} />
                      <Avatar v={v} size={22} />
                      <span style={{ fontSize: 12.5, fontWeight: on ? 600 : 500, color: on ? 'var(--escalab-ink)' : 'var(--escalab-slate)', lineHeight: 1.2, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {v.isTeam ? v.nome : v.nome.split(' ')[0]}
                        <span style={{ fontSize: 10, color: 'var(--escalab-mute)', display: 'block', fontWeight: 500 }}>{v.papel}</span>
                      </span>
                    </label>
                  );
                })}
              </div>
              {/* Fade-out na borda inferior — dica visual de "rola pra ver mais" */}
              <div aria-hidden="true" style={{
                position: 'absolute', left: 1, right: 13, bottom: 1, height: 24,
                background: 'linear-gradient(180deg, transparent 0%, #fff 100%)',
                pointerEvents: 'none',
                borderBottomLeftRadius: 8, borderBottomRightRadius: 8,
              }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  // ───────────────────────────────────────────────────────────────
  // Resultado — duas variações (compacto sticky vs. completo)
  // ───────────────────────────────────────────────────────────────

  const renderResultado = ({ compact }) => (
    <div style={{
      background: 'linear-gradient(135deg, #00382E 0%, #005E4D 100%)',
      color: '#fff',
      borderRadius: compact ? 10 : 14,
      padding: compact ? '8px 12px' : '18px 20px',
      position: 'relative',
      overflow: 'hidden',
      minWidth: 0,
      boxShadow: compact ? '0 6px 16px rgba(0,56,46,.20)' : 'none',
    }}>
      <div style={{ position: 'absolute', top: -60, right: -60, width: 140, height: 140, borderRadius: '50%', background: 'radial-gradient(circle, rgba(94,233,196,.22), transparent 70%)', pointerEvents: 'none' }} />
      <div style={{ position: 'relative', minWidth: 0, width: '100%' }}>
        {compact ? (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
            <div style={{ minWidth: 0, flex: '1 1 auto' }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--escalab-brand-accent)', lineHeight: 1 }}>Você receberia</div>
              <div key={Math.round(simulado.totalMeu)} className="value-shift" style={{
                fontSize: 'clamp(20px, 6vw, 26px)',
                fontWeight: 700, letterSpacing: '-.02em', lineHeight: 1.1,
                margin: '2px 0 0', color: '#fff',
                overflowWrap: 'anywhere', wordBreak: 'break-word',
                fontVariantNumeric: 'tabular-nums',
              }}>{brl(simulado.totalMeu || 0)}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2, flexShrink: 0 }}>
              <span style={{ fontSize: 9.5, color: 'rgba(255,255,255,.65)', fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase' }}>variável</span>
              <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--escalab-brand-accent)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{brlCents(simulado.variavelMeu || 0)}</span>
              <span style={{ fontSize: 9.5, color: 'rgba(255,255,255,.65)', fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', marginTop: 2 }}>fixa</span>
              <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--escalab-brand-accent)', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{brlCents(simulado.fixaMeu || 0)}</span>
            </div>
          </div>
        ) : (
          <>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--escalab-brand-accent)' }}>Você receberia</div>
            <div key={Math.round(simulado.totalMeu)} className="value-shift" style={{
              fontSize: 'clamp(20px, 3.8vw, 30px)',
              fontWeight: 700, letterSpacing: '-.025em', lineHeight: 1.05,
              margin: '4px 0 6px', color: '#fff',
              overflowWrap: 'anywhere', wordBreak: 'break-word',
              maxWidth: '100%', fontVariantNumeric: 'tabular-nums',
            }}>{brl(simulado.totalMeu || 0)}</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, padding: '4px 9px', borderRadius: 999, background: 'rgba(94,233,196,.14)', border: '1px solid rgba(94,233,196,.32)', color: 'rgba(255,255,255,.92)' }}>
                variável <strong style={{ color: 'var(--escalab-brand-accent)', fontVariantNumeric: 'tabular-nums' }}>{brlCents(simulado.variavelMeu || 0)}</strong>
              </span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, padding: '4px 9px', borderRadius: 999, background: 'rgba(94,233,196,.14)', border: '1px solid rgba(94,233,196,.32)', color: 'rgba(255,255,255,.92)' }}>
                fixa <strong style={{ color: 'var(--escalab-brand-accent)', fontVariantNumeric: 'tabular-nums' }}>{brlCents(simulado.fixaMeu || 0)}</strong>
              </span>
            </div>
            {(simulado.linhasMeu || []).filter(l => l.lead === 'Projeto hipotético').length > 0 && (
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid rgba(255,255,255,.18)', display: 'flex', flexDirection: 'column', gap: 3 }}>
                {(simulado.linhasMeu || []).filter(l => l.lead === 'Projeto hipotético').map((l, i) => (
                  <div key={i} style={{ display: 'flex', flexWrap: 'wrap', gap: 6, fontSize: 11, color: 'rgba(255,255,255,.82)' }}>
                    <span style={{ flex: '1 1 140px', minWidth: 0 }}>↳ {l.gatilho}</span>
                    <span style={{ fontVariantNumeric: 'tabular-nums', color: 'var(--escalab-brand-accent)', fontWeight: 600 }}>{brlCents(l.valor)}</span>
                  </div>
                ))}
              </div>
            )}
            {simulado.delta > 0.01 && (
              <div style={{ marginTop: 8, fontSize: 11, color: 'rgba(255,255,255,.7)' }}>
                Acumulado no trimestre subiria pra <strong style={{ color: '#fff' }}>{brl(simulado.total)}</strong>.
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );

  const renderDivisao = () => (
    <div style={{ background: '#fff', border: '1px solid var(--escalab-brand-soft)', padding: 14, borderRadius: 12, minWidth: 0 }}>
      <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-brand-deep)', marginBottom: 6 }}>Divisão entre todos</div>
      <div style={{ fontSize: 11.5, color: 'var(--escalab-slate)', marginBottom: 10, lineHeight: 1.5 }}>
        {brl(simValor)} · {simMarkup}% markup · fixa {brl(simulado.fixaTotal || 0)} ({(simulado.pctFixa || 0).toFixed(1).replace('.', ',')}%)
      </div>
      {simulado.divisao.length === 0 ? (
        <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', padding: '12px 0' }}>Selecione participantes e gatilhos pra ver a divisão.</div>
      ) : simulado.divisao.map((p, pi) => {
        const eVoce = p.id === vendedorId;
        const vend = vendedores.find(v => v.id === p.id);
        return (
          <div key={p.id} style={{ padding: '8px 0', borderBottom: pi < simulado.divisao.length - 1 ? '1px solid var(--escalab-line)' : 'none' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <Avatar v={vend} size={28} />
              <div style={{ flex: '1 1 100px', minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: eVoce ? 700 : 600, color: 'var(--escalab-ink)', display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                  <span>{(vend?.isTeam ? vend.nome : (p.nome || '').split(' ')[0])}</span>
                  {eVoce && <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '.08em', color: 'var(--escalab-brand)', background: 'var(--escalab-brand-tint)', padding: '1px 6px', borderRadius: 4 }}>VOCÊ</span>}
                </div>
                {p.papeis.length > 0 && <div style={{ fontSize: 10.5, color: 'var(--escalab-brand)', fontWeight: 500, marginTop: 1 }}>{p.papeis.join(' + ')}</div>}
              </div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--escalab-brand-deep)', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{brl(p.total)}</div>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, paddingLeft: 38, marginTop: 2, fontSize: 11, color: 'var(--escalab-slate)' }}>
              {p.variavel > 0.01 && <span>↳ variável <span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 600, color: 'var(--escalab-brand-deep)' }}>{brlCents(p.variavel)}</span></span>}
              {p.fixa > 0.01 && <span>↳ fixa <span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 600, color: 'var(--escalab-brand-deep)' }}>{brlCents(p.fixa)}</span></span>}
            </div>
          </div>
        );
      })}
    </div>
  );

  const header = (
    <div>
      <Eyebrow idx="↳">Simulador</Eyebrow>
      <h1 style={{ fontSize: isMobile ? 26 : 38, margin: 0, letterSpacing: '-.02em', lineHeight: 1.05, maxWidth: 740 }}>
        Quanto eu receberia <em style={{ fontStyle: 'normal', color: 'var(--escalab-brand)' }}>nesse cenário</em>?
      </h1>
      <p style={{ marginTop: 10, color: 'var(--escalab-slate)', fontSize: isMobile ? 13 : 15, maxWidth: 640, lineHeight: 1.5 }}>
        {isMobile
          ? 'Deslize entre os passos pra montar o cenário. O resultado fica no topo, sempre visível.'
          : 'Monte um lead hipotético — escolha origem, valor, gatilhos e quem participou. A simulação roda no mesmo motor que calcula a sua comissão real.'}
      </p>
    </div>
  );

  // ───────────────────────────────────────────────────────────────
  // MOBILE: carrossel horizontal de passos + resultado sticky
  // ───────────────────────────────────────────────────────────────

  if (isMobile) {
    return <MobileSimulador
      header={header}
      steps={[
        { id: 'versao',    label: 'Regras',   render: renderVersao },
        { id: 'origem',    label: 'Origem',   render: renderOrigem },
        { id: 'valor',     label: 'Valor',    render: renderValor },
        { id: 'gatilhos',  label: 'Gatilhos', render: renderGatilhos },
        { id: 'time',      label: 'Time',     render: renderParticipantes },
      ]}
      renderResultadoCompacto={() => renderResultado({ compact: true })}
      renderDivisao={renderDivisao}
    />;
  }

  // ───────────────────────────────────────────────────────────────
  // DESKTOP: coluna dupla (inputs em etapas | resultado sticky)
  // O painel esquerdo agora mostra UM passo por vez (como no mobile)
  // com stepper visual, chips numerados e navegação anterior/próximo.
  // Pedido colaborador 2026-06-17 (Hiago): mesma UX do mobile no desktop.
  // ───────────────────────────────────────────────────────────────

  const desktopSteps = [
    { id: 'versao',    label: 'Regras',   render: renderVersao },
    { id: 'origem',    label: 'Origem',   render: renderOrigem },
    { id: 'valor',     label: 'Valor',    render: renderValor },
    { id: 'gatilhos',  label: 'Gatilhos', render: renderGatilhos },
    { id: 'time',      label: 'Time',     render: renderParticipantes },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {header}

      <Card pad={0}>
        <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'stretch' }}>

          {/* COLUNA INPUTS — em etapas */}
          <div data-tut="sim-passos" style={{ flex: '1.05 1 0', minWidth: 0, padding: '22px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <DesktopStepper steps={desktopSteps} />
          </div>

          {/* COLUNA RESULTADO — sticky no topo, divisão rola embaixo. */}
          <div data-tut="sim-resultado" style={{
            flex: '.95 1 0',
            minWidth: 0,
            padding: '22px 24px',
            display: 'flex', flexDirection: 'column', gap: 12,
            background: 'linear-gradient(180deg, var(--escalab-paper) 0%, #fff 100%)',
            borderLeft: '1px solid var(--escalab-line)',
            alignSelf: 'flex-start',
          }}>
            <div style={{ position: 'sticky', top: 16, zIndex: 2 }}>
              {renderResultado({ compact: false })}
            </div>
            {renderDivisao()}
          </div>

        </div>
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// DesktopStepper — versão desktop do MobileSimulador (sem carrossel
// horizontal, sem sticky no topo). Mostra UM passo por vez, com:
// • Barras de progresso animadas (mesma estética do mobile)
// • Chips numerados clicáveis (1·Regras → 2·Origem → ...)
// • Botões Anterior / Próximo no rodapé
// Cada passo só renderiza quando ativo — altura adapta naturalmente.
// ═══════════════════════════════════════════════════════════════════

function DesktopStepper({ steps }) {
  const [step, setStep] = useState(0);
  const goTo = (idx) => setStep(Math.max(0, Math.min(steps.length - 1, idx)));
  const current = steps[step];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minWidth: 0 }}>
      {/* Dots de progresso */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 2px' }}>
        <div style={{ display: 'flex', gap: 5, flex: 1, minWidth: 0 }}>
          {steps.map((s, i) => {
            const active = i === step;
            const done = i < step;
            return (
              <button key={s.id} onClick={() => goTo(i)} aria-label={`Passo ${i + 1}: ${s.label}`}
                style={{
                  flex: active ? 2.4 : 1, height: 5, borderRadius: 999,
                  background: active
                    ? 'linear-gradient(90deg, var(--escalab-brand-deep), var(--escalab-brand))'
                    : (done ? 'var(--escalab-brand-soft)' : 'var(--escalab-line)'),
                  border: 0, padding: 0, cursor: 'pointer',
                  transition: 'flex .42s var(--ease-out), background .3s var(--ease-out)',
                }} />
            );
          })}
        </div>
        <div style={{ fontSize: 11, color: 'var(--escalab-mute)', fontWeight: 600, letterSpacing: '.06em', whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>
          {step + 1} / {steps.length}
        </div>
      </div>

      {/* Chips de atalho */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {steps.map((s, i) => {
          const active = i === step;
          return (
            <button key={s.id} onClick={() => goTo(i)}
              style={{
                padding: '7px 13px', borderRadius: 999,
                border: `1px solid ${active ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
                background: active ? 'var(--escalab-brand)' : '#fff',
                color: active ? '#fff' : 'var(--escalab-slate)',
                fontSize: 12, fontWeight: 600, letterSpacing: '.02em',
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 6,
                transition: 'all .2s var(--ease-out)',
              }}>
              <span style={{ fontVariantNumeric: 'tabular-nums', opacity: active ? .85 : .55 }}>{i + 1}</span>
              <span>{s.label}</span>
            </button>
          );
        })}
      </div>

      {/* Conteúdo do passo ativo */}
      <div key={current.id} className="fade-up" style={{
        background: '#fff', border: '1px solid var(--escalab-line)',
        borderRadius: 14, padding: '20px 18px',
        boxShadow: 'var(--shadow-md)', minWidth: 0,
      }}>
        {current.render()}
      </div>

      {/* Nav anterior / próximo */}
      <div style={{ display: 'flex', gap: 10 }}>
        <button onClick={() => goTo(step - 1)} disabled={step === 0}
          style={{
            flex: 1, minHeight: 44, padding: '0 14px',
            borderRadius: 10, border: '1px solid var(--escalab-line)',
            background: '#fff', color: step === 0 ? 'var(--escalab-mute)' : 'var(--escalab-ink)',
            fontWeight: 600, fontSize: 13.5, cursor: step === 0 ? 'not-allowed' : 'pointer',
            fontFamily: 'inherit', opacity: step === 0 ? .55 : 1,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            transition: 'all .18s var(--ease-out)',
          }}>
          <span aria-hidden="true">←</span> Anterior
        </button>
        <button onClick={() => goTo(step + 1)} disabled={step === steps.length - 1}
          style={{
            flex: 1.4, minHeight: 44, padding: '0 14px',
            borderRadius: 10, border: 0,
            background: step === steps.length - 1 ? 'var(--escalab-slate)' : 'var(--escalab-brand)',
            color: '#fff',
            fontWeight: 700, fontSize: 13.5, cursor: step === steps.length - 1 ? 'not-allowed' : 'pointer',
            fontFamily: 'inherit', opacity: step === steps.length - 1 ? .55 : 1,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            boxShadow: step === steps.length - 1 ? 'none' : '0 6px 16px rgba(0,150,123,.28)',
            transition: 'all .18s var(--ease-out)',
          }}>
          {step === steps.length - 1 ? 'Concluído' : <>Próximo <span aria-hidden="true">→</span></>}
        </button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// MobileSimulador — wrapper com:
// • Resultado sticky no topo (compacto, sempre visível)
// • Carrossel horizontal de passos com scroll-snap nativo
// • Dots de progresso clicáveis + indicador "X de Y"
// • Botões Anterior/Próximo como fallback de navegação
// • Divisão entre todos rolando logo abaixo
// ═══════════════════════════════════════════════════════════════════

function MobileSimulador({ header, steps, renderResultadoCompacto, renderDivisao }) {
  const [step, setStep] = useState(0);
  const carouselRef = useRef(null);
  // Refs dos cards de cada passo, pra medir a altura intrínseca de cada um.
  const slideRefs = useRef([]);
  // Altura do passo ATIVO — o container do carrossel adota essa altura,
  // animando entre os passos. Sem isso, scroll-snap + display:flex impõem
  // align-items: stretch e todos os passos ficam com a altura do passo 5
  // (lista de qualificadores/finalizadores), criando muito espaço em branco
  // nos passos 1-4. Hiago 2026-06-17 pedido do colaborador.
  const [alturaAtiva, setAlturaAtiva] = useState('auto');

  const medirAtiva = () => {
    const el = slideRefs.current[step];
    if (!el) return;
    // scrollHeight pega a altura intrínseca mesmo se o pai impôs uma altura menor.
    const h = el.scrollHeight;
    setAlturaAtiva(prev => (prev === h ? prev : h));
  };

  // Mede sempre que o passo muda, no próximo frame (pra deixar o DOM
  // renderizar o conteúdo do novo passo antes da medição).
  React.useLayoutEffect(() => {
    const raf = requestAnimationFrame(medirAtiva);
    return () => cancelAnimationFrame(raf);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [step]);

  // Remede ao redimensionar a viewport ou quando o conteúdo do passo ativo
  // mudar (ex: marcar gatilho NPS abre input extra, lista de finalizadores
  // muda ao trocar origem). Usa ResizeObserver no slide ativo.
  React.useEffect(() => {
    if (typeof ResizeObserver === 'undefined') return;
    const el = slideRefs.current[step];
    if (!el) return;
    const ro = new ResizeObserver(() => medirAtiva());
    ro.observe(el);
    const onResize = () => medirAtiva();
    window.addEventListener('resize', onResize);
    return () => { ro.disconnect(); window.removeEventListener('resize', onResize); };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [step]);

  // Sincroniza step com o scroll horizontal (swipe nativo).
  // Throttle simples via rAF — evita setState a cada pixel.
  const tickingRef = useRef(false);
  const onScroll = () => {
    if (tickingRef.current) return;
    tickingRef.current = true;
    requestAnimationFrame(() => {
      const el = carouselRef.current;
      if (el) {
        const idx = Math.round(el.scrollLeft / el.clientWidth);
        const clamped = Math.max(0, Math.min(steps.length - 1, idx));
        setStep(prev => prev === clamped ? prev : clamped);
      }
      tickingRef.current = false;
    });
  };

  const goTo = (idx) => {
    const clamped = Math.max(0, Math.min(steps.length - 1, idx));
    setStep(clamped);
    const el = carouselRef.current;
    if (el) el.scrollTo({ left: clamped * el.clientWidth, behavior: 'smooth' });
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, minWidth: 0 }}>
      {header}

      {/* Resultado sticky compacto — sempre visível durante o uso. O wrapper
          tem um pequeno fade pra evitar "colisão" visual quando o conteúdo
          desliza por baixo (gap entre wrapper e card cria respiro). */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 10,
        marginInline: -12, paddingInline: 12, paddingTop: 4, paddingBottom: 6,
        background: 'linear-gradient(180deg, var(--escalab-paper) 0%, var(--escalab-paper) 80%, rgba(247,248,249,0) 100%)',
      }}>
        {renderResultadoCompacto()}
      </div>

      {/* Dots de progresso */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 2px' }}>
        <div style={{ display: 'flex', gap: 5, flex: 1, minWidth: 0 }}>
          {steps.map((s, i) => {
            const active = i === step;
            const done = i < step;
            return (
              <button
                key={s.id}
                onClick={() => goTo(i)}
                aria-label={`Passo ${i + 1}: ${s.label}`}
                style={{
                  flex: active ? 2.4 : 1,
                  height: 5,
                  borderRadius: 999,
                  background: active
                    ? 'linear-gradient(90deg, var(--escalab-brand-deep), var(--escalab-brand))'
                    : (done ? 'var(--escalab-brand-soft)' : 'var(--escalab-line)'),
                  border: 0, padding: 0, cursor: 'pointer',
                  transition: 'flex .42s var(--ease-out), background .3s var(--ease-out)',
                }}
              />
            );
          })}
        </div>
        <div style={{ fontSize: 10.5, color: 'var(--escalab-mute)', fontWeight: 600, letterSpacing: '.06em', whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>
          {step + 1} / {steps.length}
        </div>
      </div>

      {/* Chips de atalho — sempre mostra qual o passo atual */}
      <div className="no-scrollbar" style={{ display: 'flex', gap: 6, overflowX: 'auto', marginInline: -16, paddingInline: 16, paddingBottom: 2 }}>
        {steps.map((s, i) => {
          const active = i === step;
          return (
            <button
              key={s.id}
              onClick={() => goTo(i)}
              style={{
                flexShrink: 0,
                padding: '6px 12px',
                borderRadius: 999,
                border: `1px solid ${active ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
                background: active ? 'var(--escalab-brand)' : '#fff',
                color: active ? '#fff' : 'var(--escalab-slate)',
                fontSize: 11.5, fontWeight: 600, letterSpacing: '.02em',
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 6,
                transition: 'all .2s var(--ease-out)',
              }}
            >
              <span style={{ fontVariantNumeric: 'tabular-nums', opacity: active ? .85 : .55 }}>{i + 1}</span>
              <span>{s.label}</span>
            </button>
          );
        })}
      </div>

      {/* Carrossel — altura adapta ao passo ativo (height animada).
          alignItems: flex-start impede que slides curtos cresçam até a altura
          do mais alto (passo 5). overflow-y: hidden esconde sobras de slides
          curtos enquanto o container animado encolhe. */}
      <div
        ref={carouselRef}
        onScroll={onScroll}
        className="snap-x"
        style={{
          marginInline: -16,
          paddingInline: 16,
          paddingBottom: 4,
          gap: 12,
          alignItems: 'flex-start',
          height: typeof alturaAtiva === 'number' ? alturaAtiva + 'px' : alturaAtiva,
          transition: 'height .32s var(--ease-out)',
        }}
      >
        {steps.map((s, i) => (
          <div
            key={s.id}
            ref={el => { slideRefs.current[i] = el; }}
            style={{
              flex: '0 0 100%',
              minWidth: 0,
              alignSelf: 'flex-start',
              background: '#fff',
              border: '1px solid var(--escalab-line)',
              borderRadius: 14,
              padding: '18px 16px',
              boxShadow: i === step ? 'var(--shadow-md)' : 'var(--shadow-sm)',
              transition: 'box-shadow .3s var(--ease-out), transform .3s var(--ease-out)',
              transform: i === step ? 'scale(1)' : 'scale(.98)',
              opacity: i === step ? 1 : .82,
            }}
          >
            {i === step ? <div className="fade-up">{s.render()}</div> : s.render()}
          </div>
        ))}
      </div>

      {/* Nav anterior / próximo */}
      <div style={{ display: 'flex', gap: 10 }}>
        <button
          onClick={() => goTo(step - 1)}
          disabled={step === 0}
          style={{
            flex: 1, minHeight: 46, padding: '0 14px',
            borderRadius: 12, border: '1px solid var(--escalab-line)',
            background: '#fff', color: step === 0 ? 'var(--escalab-mute)' : 'var(--escalab-ink)',
            fontWeight: 600, fontSize: 13.5, cursor: step === 0 ? 'not-allowed' : 'pointer',
            fontFamily: 'inherit', opacity: step === 0 ? .55 : 1,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            transition: 'all .18s var(--ease-out)',
          }}
        >
          <span aria-hidden="true">←</span> Anterior
        </button>
        <button
          onClick={() => goTo(step + 1)}
          disabled={step === steps.length - 1}
          style={{
            flex: 1.4, minHeight: 46, padding: '0 14px',
            borderRadius: 12, border: 0,
            background: step === steps.length - 1 ? 'var(--escalab-slate)' : 'var(--escalab-brand)',
            color: '#fff',
            fontWeight: 700, fontSize: 13.5, cursor: step === steps.length - 1 ? 'not-allowed' : 'pointer',
            fontFamily: 'inherit', opacity: step === steps.length - 1 ? .55 : 1,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            boxShadow: step === steps.length - 1 ? 'none' : '0 6px 16px rgba(0,150,123,.28)',
            transition: 'all .18s var(--ease-out)',
          }}
        >
          {step === steps.length - 1 ? 'Concluído' : <>Próximo <span aria-hidden="true">→</span></>}
        </button>
      </div>

      {/* Divisão entre todos */}
      <div className="fade-up">
        {renderDivisao()}
      </div>
    </div>
  );
}

Object.assign(window, { SimuladorScreen, MobileSimulador, DesktopStepper });
