// ═══════════════════════════════════════════════════════════════
// SCREEN · Treinamentos · Monitoramento
// ═══════════════════════════════════════════════════════════════

const TREINAMENTOS_KEY = 'escalab_treinamentos_v2';
const TREINAMENTOS_KEY_LEGACY = 'escalab_treinamentos';

const TREINAMENTOS_INICIAL = [
  {
    id: 'TR001', ano: 2025, data: '2025-01-31', titulo: "Organização e gestão de tempo (+4 subtemas)",
    responsavel: "Maria", local: "UFMG", tipo: 'tecnico', happyhour: false,
    status: 'concluido',
    freq_fixos: 68, freq_assoc: null, nps: 97,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "Rotina dos setores + Dinâmica · Intervalo · Ferramentas de Inteligência Artificial (Acadêmica) · Excel",
    detratores: 1, neutros: 2, promotores: 97,
  },
  {
    id: 'TR002', ano: 2025, data: '2025-03-07', titulo: "Curso de Segurança P&D",
    responsavel: "Júlia Braga", local: "CIT", tipo: 'tecnico', happyhour: true,
    status: 'concluido',
    freq_fixos: 52, freq_assoc: null, nps: 88,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: 4, neutros: 8, promotores: 88,
  },
  {
    id: 'TR003', ano: 2025, data: '2025-04-11', titulo: "Unidades de negócio (+2 subtemas)",
    responsavel: "Maria", local: "UFMG", tipo: 'comercial', happyhour: false,
    status: 'concluido',
    freq_fixos: 66, freq_assoc: null, nps: 99,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "Adiado por: A Maria teve imprevistos e não pôde estar em BH na data em que seria o Escalab Day, adiamos uma semana",
    detratores: 0, neutros: 1, promotores: 99,
  },
  {
    id: 'TR004', ano: 2025, data: '2025-04-25', titulo: "Inteligência de mercado (+1 subtemas)",
    responsavel: "Rafa", local: "CIT", tipo: 'comercial', happyhour: false,
    status: 'concluido',
    freq_fixos: 55, freq_assoc: null, nps: 97,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "Mapeamento de Informações",
    detratores: 1, neutros: 2, promotores: 97,
  },
  {
    id: 'TR005', ano: 2025, data: '2025-05-16', titulo: "Mercados - Mineração e Siderurgia",
    responsavel: "Amanda/Vanessa", local: "UFMG", tipo: 'comercial', happyhour: true,
    status: 'concluido',
    freq_fixos: 66, freq_assoc: null, nps: 92,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "Adiado: Vanessa e Amanda iriam ter compromisso na data que tinha sido marcada anteriormente",
    detratores: 2, neutros: 6, promotores: 92,
  },
  {
    id: 'TR006', ano: 2025, data: '2025-06-27', titulo: "Mercados- Química e Alimentícia + EscalabDay",
    responsavel: "Vanessa", local: "CIT", tipo: 'comercial', happyhour: true,
    status: 'concluido',
    freq_fixos: 69, freq_assoc: null, nps: null,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: null, neutros: null, promotores: null,
  },
  {
    id: 'TR007', ano: 2025, data: '2025-08-08', titulo: "Visão",
    responsavel: "Maria/ Carol", local: "", tipo: 'escalabday', happyhour: true,
    status: 'concluido',
    freq_fixos: 59, freq_assoc: null, nps: 100,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: 0, neutros: 0, promotores: 100,
  },
  {
    id: 'TR008', ano: 2025, data: '2025-08-22', titulo: "Trilha",
    responsavel: "", local: "", tipo: 'tecnico', happyhour: false,
    status: 'cancelado',
    freq_fixos: null, freq_assoc: null, nps: null,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "Não realizado por baixa adesão",
    detratores: null, neutros: null, promotores: null,
  },
  {
    id: 'TR009', ano: 2025, data: '2025-09-25', titulo: "Cultura (+1 subtemas)",
    responsavel: "Maria, Ana Campos, Rochel e Fabiano", local: "", tipo: 'comportamental', happyhour: true,
    status: 'concluido',
    freq_fixos: 68, freq_assoc: null, nps: 100,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "Empreendedorismo",
    detratores: 0, neutros: 0, promotores: 100,
  },
  {
    id: 'TR010', ano: 2025, data: '2025-10-24', titulo: "Planejamento de carreira (imbutido empreendedorismo)",
    responsavel: "", local: "UFMG", tipo: 'escalabday', happyhour: false,
    status: 'cancelado',
    freq_fixos: null, freq_assoc: null, nps: null,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: null, neutros: null, promotores: null,
  },
  {
    id: 'TR011', ano: 2025, data: '2025-11-28', titulo: "Visita Guiada (Alguma mineradora próxima)",
    responsavel: "Maria Clara", local: "", tipo: 'tecnico', happyhour: true,
    status: 'cancelado',
    freq_fixos: null, freq_assoc: null, nps: null,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: null, neutros: null, promotores: null,
  },
  {
    id: 'TR012', ano: 2025, data: '2025-12-19', titulo: "Festa de Final de Ano (+23 subtemas)",
    responsavel: "Maria Clara/Ana Campos", local: "", tipo: 'tecnico', happyhour: false,
    status: 'concluido',
    freq_fixos: null, freq_assoc: null, nps: null,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "SUGESTÕES · Dinâmica de levantamento de problemas e priorização · Investimento: Como comprar uma casa, carro, viagem · Diversidade e inclusão · Acho que seria legal ter um Escalabday sobre empreendedorismo, no sentido de falar sobre como acontece o empreendedorismo mesmo, mas principalmente explicando sobre jargões, pq tem muitos momentos em reuniões que eu não sei do que tá falando pq eu não sei o significado da palavra mesmo. Coisas como \"B2b\", etc. Acho necessário pra estar todo mundo alinhado durante as reuniões e também ter uma compreensão mais abrangente do processo de alguns setores · Seria muito interessante temas sobre o empreendedorismo no campo científico, assim como a criação do escalab. · Planejamento de carreira · Seria legal um Escalabday sobre feedbacks · Um dia prático com um profissional dando aula de primeiros socorros · como foi trazido hoje, acho que apresentar a missão do Escalab, visto que temos muitos novos colaboradores seria uma boa ideia · Noções básicas de empreendedorismo na química e como isso foi aplicado ao escalab · Gestão de resíduos (convidado externo) · Boas práticas ESG pessoais · Feedback + Investimento Cultura · Gostaria de aprender sobre pesquisa de artigos, de como descobrir se uma revista cientifica é relevante, qual fator de impacto, número de citações, se é confiável e quais sites posso pesquisar. · Pauta da defesa pessoal com moça da ufmg (entrar\nem contato) · Explorar o branding do Escalab/Escale-se · Gestão de tempo · Cultura · Defesa Pessoal · Relação pessoal e trabalho - empulsionamento e equilíbrio · Massagem?? · Análise de dados do Escalab/ Ferramentas de Gestão de Projetos",
    detratores: null, neutros: null, promotores: null,
  },
  {
    id: 'TR013', ano: 2026, data: '2026-03-13', titulo: "EscalabDay · Carreira",
    responsavel: "", local: "", tipo: 'escalabday', happyhour: false,
    status: 'concluido',
    freq_fixos: null, freq_assoc: null, nps: 98,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: 1, neutros: 1, promotores: 98,
  },
  {
    id: 'TR014', ano: 2026, data: '2026-03-27', titulo: "EscalabDay · Produtos Escalab",
    responsavel: "", local: "", tipo: 'escalabday', happyhour: false,
    status: 'concluido',
    freq_fixos: null, freq_assoc: null, nps: 93,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: 2, neutros: 5, promotores: 93,
  },
  {
    id: 'TR015', ano: 2026, data: '2026-04-24', titulo: "EscalabDay · Noções do Negócio",
    responsavel: "", local: "", tipo: 'escalabday', happyhour: false,
    status: 'concluido',
    freq_fixos: null, freq_assoc: null, nps: 88,
    presentes_fixos: null, total_fixos: null, presentes_assoc: null, total_assoc: null,
    descricao: "",
    detratores: 4, neutros: 8, promotores: 88,
  },
];


// PDF Site AVD (2): adicionar 'Comercial'. 'EscalabDay' já existia.
const TIPOS_TREINO = [
  { id: 'todos',        label: 'Todos os tipos' },
  { id: 'onboarding',   label: 'Onboarding'   },
  { id: 'tecnico',      label: 'Técnico'       },
  { id: 'comportamental', label: 'Comportamental' },
  { id: 'lideranca',    label: 'Liderança'     },
  { id: 'comercial',    label: 'Comercial'     },
  { id: 'escalabday',   label: 'EscalabDay'    },
];

const STATUS_TREINO = {
  concluido: { label: 'Concluído', cor: '#00836B', bg: '#E6F5F1', tone: 'success' },
  em_breve:  { label: 'Em 5 dias', cor: '#1F4A8A', bg: '#EEF3FA', tone: 'info'    },
  agendado:  { label: 'Agendado',  cor: '#B56500', bg: '#FFF7EB', tone: 'warn'    },
};

function getTreinamentos() {
  try {
    const raw = localStorage.getItem(TREINAMENTOS_KEY);
    if (raw) return JSON.parse(raw);
    // Limpa chave legacy v1 (tinha treinos ficticios) e carrega os reais
    if (localStorage.getItem(TREINAMENTOS_KEY_LEGACY)) {
      localStorage.removeItem(TREINAMENTOS_KEY_LEGACY);
    }
    localStorage.setItem(TREINAMENTOS_KEY, JSON.stringify(TREINAMENTOS_INICIAL));
    return TREINAMENTOS_INICIAL;
  } catch { return TREINAMENTOS_INICIAL; }
}

function salvarTreinamentos(lista) {
  try { localStorage.setItem(TREINAMENTOS_KEY, JSON.stringify(lista)); } catch {}
}

function gerarIdTR() { return 'TR' + Date.now().toString(36).toUpperCase(); }

// ── Configuração do formulário de NPS (editável pelo GC) ──────────────────────
const NPS_CONFIG_KEY = 'escalab_nps_config';
const NPS_CONFIG_PADRAO = {
  npsLabel: 'Em uma escala de 0 a 10, como você avalia este treinamento?',
  npsSublabel: '0 = péssimo · 10 = excelente',
  comentarioLabel: 'O que você achou? Tem sugestões de melhoria?',
  comentarioObrigatorio: false,
  extras: [],
};
function getNpsConfig() {
  try { const r = JSON.parse(localStorage.getItem(NPS_CONFIG_KEY) || 'null'); return r ? { ...NPS_CONFIG_PADRAO, ...r } : { ...NPS_CONFIG_PADRAO }; } catch { return { ...NPS_CONFIG_PADRAO }; }
}
function salvarNpsConfig(cfg) { try { localStorage.setItem(NPS_CONFIG_KEY, JSON.stringify(cfg)); } catch {} }
function getNpsRespostas(treinoId) {
  try { return JSON.parse(localStorage.getItem('escalab_nps_respostas') || '[]').filter(r => !treinoId || r.treinoId === treinoId); } catch { return []; }
}

// ── NPS in-app: o formulario fica disponivel pro colaborador dentro do
// proprio sistema (alternativa ao QR code). Os dados sao gravados no
// mesmo escalab_nps_respostas que o QR usa, entao o calculo agregado
// (% promotores/detratores/neutros) ja funciona automaticamente.
function ativarNpsInApp(treinoId, ativo) {
  try {
    const lista = getTreinamentos();
    const idx = lista.findIndex(t => t.id === treinoId);
    if (idx < 0) return false;
    lista[idx] = { ...lista[idx], npsInAppAtivo: !!ativo, npsInAppAtivadoEm: ativo ? new Date().toISOString() : null };
    salvarTreinamentos(lista);
    return true;
  } catch { return false; }
}
function jaRespondeuNpsInApp(treinoId, colaboradorId) {
  return getNpsRespostas(treinoId).some(r => r.colaboradorId === colaboradorId);
}
function salvarRespostaNpsInApp({ treinoId, colaboradorId, nota, comentario, extras }) {
  try {
    const arr = JSON.parse(localStorage.getItem('escalab_nps_respostas') || '[]');
    // Substitui resposta anterior do mesmo colab no mesmo treino (so 1 voto por pessoa)
    const limpa = arr.filter(r => !(r.treinoId === treinoId && r.colaboradorId === colaboradorId));
    limpa.push({
      treinoId, colaboradorId,
      nota: Number(nota),
      comentario: comentario || '',
      extras: extras || {},
      fonte: 'in-app',
      enviadaEm: new Date().toISOString(),
    });
    localStorage.setItem('escalab_nps_respostas', JSON.stringify(limpa));
    return true;
  } catch { return false; }
}

// ── Modal NPS in-app (colaborador) ───────────────────────────────────────
const ModalRespostaNpsColab = ({ treino, user, onClose, onEnviado }) => {
  const cfg = getNpsConfig();
  const [nota, setNota] = useState(null);
  const [comentario, setComentario] = useState('');
  const [extras, setExtras] = useState({});

  function enviar() {
    if (nota == null) { alert('Escolha uma nota de 0 a 10.'); return; }
    if (cfg.comentarioObrigatorio && !comentario.trim()) { alert('O campo de comentário é obrigatório.'); return; }
    const ok = salvarRespostaNpsInApp({ treinoId: treino.id, colaboradorId: user.id, nota, comentario, extras });
    if (!ok) { alert('Erro ao salvar resposta. Tente novamente.'); return; }
    onEnviado?.();
    onClose();
  }

  // Cor da nota: 0-6 vermelho, 7-8 amarelo, 9-10 verde (escala NPS)
  function corNota(n) {
    if (n <= 6) return '#B3261E';
    if (n <= 8) return '#E89B3B';
    return '#00836B';
  }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,15,18,.55)', backdropFilter:'blur(4px)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:16, width:'100%', maxWidth:520, maxHeight:'92vh', overflow:'auto', animation:'popIn .22s var(--ease-out)' }}>
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--escalab-line)', display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
          <div>
            <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'.12em', textTransform:'uppercase', color:'var(--escalab-brand)', marginBottom:3 }}>Escalab School · NPS</div>
            <h3 style={{ margin:0, fontSize:17, fontWeight:800, color:'var(--escalab-ink)' }}>Avaliar treinamento</h3>
            <div style={{ fontSize:12.5, color:'var(--escalab-slate)', marginTop:4 }}>{treino.titulo}</div>
          </div>
          <button onClick={onClose} style={{ border:0, background:'transparent', cursor:'pointer', color:'var(--escalab-slate)' }}><Icon name="close" size={18}/></button>
        </div>

        <div style={{ padding:'20px 24px', display:'flex', flexDirection:'column', gap:18 }}>
          {/* Nota 0-10 */}
          <div>
            <div style={{ fontSize:13.5, fontWeight:600, color:'var(--escalab-ink)', marginBottom:8, lineHeight:1.5 }}>
              {cfg.npsLabel} <span style={{ color:'#B3261E' }}>*</span>
            </div>
            <div style={{ display:'flex', gap:5, flexWrap:'wrap' }}>
              {Array.from({ length: 11 }, (_, n) => n).map(n => {
                const sel = nota === n;
                const cor = corNota(n);
                return (
                  <button key={n} type="button" onClick={() => setNota(n)} style={{
                    flex:'1 1 36px', minHeight:44, maxWidth:56,
                    border:`2px solid ${sel ? cor : '#9CA5B0'}`,
                    background: sel ? cor : '#fff',
                    color: sel ? '#fff' : 'var(--escalab-ink)',
                    borderRadius:8, fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:'var(--font-sans)',
                  }}>{n}</button>
                );
              })}
            </div>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:11, color:'var(--escalab-slate)', marginTop:6, fontWeight:600 }}>
              <span>{cfg.npsSublabel?.split('·')[0]?.trim() || '0 = péssimo'}</span>
              <span>{cfg.npsSublabel?.split('·')[1]?.trim() || '10 = excelente'}</span>
            </div>
          </div>

          {/* Comentario */}
          <div>
            <div style={{ fontSize:13.5, fontWeight:600, color:'var(--escalab-ink)', marginBottom:8, lineHeight:1.5 }}>
              {cfg.comentarioLabel} {cfg.comentarioObrigatorio && <span style={{ color:'#B3261E' }}>*</span>}
            </div>
            <textarea value={comentario} onChange={e => setComentario(e.target.value)} rows={3}
              placeholder="Sua resposta…"
              style={{ width:'100%', border:'1.5px solid #9CA5B0', borderRadius:8, padding:'10px 13px', fontSize:14, fontFamily:'var(--font-sans)', outline:0, resize:'vertical', boxSizing:'border-box', color:'var(--escalab-ink)', lineHeight:1.5 }}/>
          </div>

          {/* Perguntas extras configuradas pelo GC */}
          {(cfg.extras || []).map(ex => (
            <div key={ex.id || ex.label}>
              <div style={{ fontSize:13.5, fontWeight:600, color:'var(--escalab-ink)', marginBottom:8, lineHeight:1.5 }}>
                {ex.label}
              </div>
              <textarea value={extras[ex.id || ex.label] || ''} onChange={e => setExtras(s => ({ ...s, [ex.id || ex.label]: e.target.value }))} rows={2}
                style={{ width:'100%', border:'1.5px solid #9CA5B0', borderRadius:8, padding:'9px 12px', fontSize:13.5, fontFamily:'var(--font-sans)', outline:0, resize:'vertical', boxSizing:'border-box', color:'var(--escalab-ink)' }}/>
            </div>
          ))}

          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:4 }}>
            <Button variant="outline" onClick={onClose}>Cancelar</Button>
            <Button variant="primary" onClick={enviar}>Enviar avaliação</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Modal Novo Treinamento ─────────────────────────────────────────────────

// ── Modal: Concluir Treinamento (NPS obrigatório) ─────────────────────────────

const ModalConcluirTreinamento = ({ treino, onClose, onConcluir }) => {
  const totalFixos = COLABORADORES.filter(c => getCategoriaColaborador(c.id).categoria === 'fixo').length;
  const totalAssoc = COLABORADORES.filter(c => getCategoriaColaborador(c.id).categoria !== 'fixo').length;

  const [form, setForm] = useState({
    presentes_fixos: treino.total_fixos || totalFixos,
    presentes_assoc: treino.total_assoc || totalAssoc,
    nps: '',
    detratores: '', neutros: '', promotores: '',
    observacao: '',
  });
  const [showChamada, setShowChamada] = useState(false);
  const [showRespostas, setShowRespostas] = useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const podeSubmeter = form.nps !== '' && form.presentes_fixos !== '' && form.presentes_assoc !== '';

  function handleSalvar() {
    const pFixos = Number(form.presentes_fixos) || 0;
    const pAssoc = Number(form.presentes_assoc) || 0;
    const tFixos = treino.total_fixos || totalFixos;
    const tAssoc = treino.total_assoc || totalAssoc;
    onConcluir({
      status: 'concluido',
      presentes_fixos: pFixos, presentes_assoc: pAssoc,
      total_fixos: tFixos, total_assoc: tAssoc,
      freq_fixos: tFixos > 0 ? Math.round(pFixos / tFixos * 100) : 0,
      freq_assoc: tAssoc > 0 ? Math.round(pAssoc / tAssoc * 100) : 0,
      nps: Number(form.nps),
      detratores: Number(form.detratores) || 0,
      neutros:    Number(form.neutros)    || 0,
      promotores: Number(form.promotores) || 0,
      observacao: form.observacao,
    });
    onClose();
  }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,15,18,.55)', backdropFilter:'blur(4px)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:16, width:'100%', maxWidth:480, animation:'popIn .22s var(--ease-out)', maxHeight:'92vh', overflow:'auto' }}>
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--escalab-line)', display:'flex', justifyContent:'space-between', alignItems:'center', position:'sticky', top:0, background:'#fff', zIndex:1 }}>
          <div>
            <h3 style={{ margin:0, fontSize:17, fontWeight:700 }}>Concluir Treinamento</h3>
            <div style={{ fontSize:12.5, color:'var(--escalab-mute)', marginTop:2 }}>{treino.titulo}</div>
          </div>
          <button onClick={onClose} style={{ border:0, background:'transparent', cursor:'pointer', color:'var(--escalab-mute)' }}><Icon name="close" size={18} /></button>
        </div>
        <div style={{ padding:'20px 24px', display:'flex', flexDirection:'column', gap:16 }}>
          {/* Presença */}
          <div style={{ background:'var(--escalab-paper)', borderRadius:12, padding:'14px 16px' }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
              <div style={{ fontSize:12, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase', color:'var(--escalab-mute)' }}>Presença</div>
              <button onClick={() => setShowChamada(true)} style={{ display:'flex', gap:5, alignItems:'center', border:'1px solid var(--escalab-brand-soft)', background:'var(--escalab-brand-tint)', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12, color:'var(--escalab-brand-deep)', fontFamily:'var(--font-sans)', fontWeight:600, marginLeft:'auto' }}>
                <Icon name="users" size={12} /> Fazer chamada
              </button>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
              <Field label={`Fixos presentes (de ${treino.total_fixos || totalFixos})`}>
                <Input value={form.presentes_fixos} onChange={v => set('presentes_fixos', v)} type="number" placeholder="0" />
              </Field>
              <Field label={`Associados presentes (de ${treino.total_assoc || totalAssoc})`}>
                <Input value={form.presentes_assoc} onChange={v => set('presentes_assoc', v)} type="number" placeholder="0" />
              </Field>
            </div>
          </div>

          {/* NPS obrigatório */}
          <div style={{ background:'#EEF3FA', borderRadius:12, padding:'14px 16px', border:'2px solid #1F4A8A30' }}>
            <div style={{ display:'flex', gap:8, alignItems:'center', marginBottom:12, flexWrap:'wrap' }}>
              <div style={{ fontSize:12, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase', color:'#1F4A8A' }}>NPS · Obrigatório</div>
              <span style={{ fontSize:10.5, background:'#B3261E', color:'#fff', borderRadius:4, padding:'1px 7px', fontWeight:700 }}>Obrigatório</span>
              <button onClick={() => {
                try {
                  const respostas = JSON.parse(localStorage.getItem('escalab_nps_respostas') || '[]')
                    .filter(r => r.treinoId === treino.id);
                  if (respostas.length === 0) { alert('Nenhuma resposta recebida ainda (QR code ou formulário in-app).'); return; }
                  const notas = respostas.map(r => Number(r.nota));
                  const det  = Math.round(notas.filter(n => n <= 6).length / notas.length * 100);
                  const neut = Math.round(notas.filter(n => n >= 7 && n <= 8).length / notas.length * 100);
                  const prom = 100 - det - neut;
                  const nps  = prom - det;
                  set('nps', String(nps)); set('detratores', String(det)); set('neutros', String(neut)); set('promotores', String(prom));
                  alert(`${respostas.length} respostas carregadas. NPS: ${nps}`);
                } catch { alert('Erro ao carregar respostas.'); }
              }} style={{ display:'flex', gap:5, alignItems:'center', border:'1px solid #C9D7EC', background:'#fff', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12, color:'#1F4A8A', fontFamily:'var(--font-sans)', fontWeight:600, marginLeft:'auto' }}>
                <Icon name="download" size={12} /> Carregar respostas
              </button>
              <button onClick={() => setShowRespostas(true)} style={{ display:'flex', gap:5, alignItems:'center', border:'1px solid #C9D7EC', background:'#fff', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12, color:'#1F4A8A', fontFamily:'var(--font-sans)', fontWeight:600 }}>
                <Icon name="message" size={12} /> Ver respostas
              </button>
            </div>
            <div style={{ fontSize:11.5, color:'var(--escalab-mute)', marginBottom:12, lineHeight:1.5 }}>
              "Carregar respostas" agrega tudo que chegou pelo QR Code <strong>e</strong> pelo formulário in-app — calcula o NPS automaticamente.
            </div>
            {/* Formulario NPS in-app · alternativa ao QR Code, fica disponivel na plataforma pra cada colab */}
            {(() => {
              const ativo = !!treino.npsInAppAtivo;
              const nResp = getNpsRespostas(treino.id).length;
              return (
                <div style={{ background:'#fff', border:`1.5px solid ${ativo ? '#00836B' : '#C9D7EC'}`, borderRadius:10, padding:'12px 14px', marginBottom:14 }}>
                  <div style={{ display:'flex', gap:10, alignItems:'flex-start', flexWrap:'wrap' }}>
                    <div style={{ flex:1, minWidth:200 }}>
                      <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
                        <Icon name="send" size={13} />
                        <div style={{ fontSize:12.5, fontWeight:700, color:'var(--escalab-ink)' }}>Formulário NPS dentro do sistema</div>
                        {ativo && <span style={{ fontSize:10.5, background:'#00836B', color:'#fff', borderRadius:4, padding:'1px 7px', fontWeight:700 }}>Disponível</span>}
                      </div>
                      <div style={{ fontSize:12, color:'var(--escalab-slate)', lineHeight:1.5 }}>
                        {ativo
                          ? <>Os colaboradores podem responder direto na guia Treinamentos · <strong>{nResp}</strong> resposta{nResp !== 1 ? 's' : ''} recebida{nResp !== 1 ? 's' : ''} até agora.</>
                          : <>Disponibiliza o formulário de NPS in-app — alternativa ao QR Code. Cada colab vê um botão "Avaliar treinamento" na tela de Treinamentos.</>}
                      </div>
                    </div>
                    <button onClick={() => {
                      if (ativo) {
                        if (!confirm('Desativar o formulário in-app? As respostas que já vieram continuam salvas, mas ninguém novo vai conseguir responder.')) return;
                      }
                      const ok = ativarNpsInApp(treino.id, !ativo);
                      if (ok) {
                        treino.npsInAppAtivo = !ativo;
                        set('__nps_in_app_toggle', String(Date.now())); // forca re-render
                      }
                    }}
                      style={{ border:`1px solid ${ativo ? '#F4C7C3' : '#B5E3D7'}`, background:ativo ? '#FDECEC' : '#E6F5F1', color: ativo ? '#B3261E' : '#00836B', borderRadius:7, padding:'7px 13px', cursor:'pointer', fontSize:12.5, fontFamily:'var(--font-sans)', fontWeight:700, whiteSpace:'nowrap', display:'inline-flex', alignItems:'center', gap:5 }}>
                      <Icon name={ativo ? 'lock' : 'send'} size={12}/> {ativo ? 'Desativar formulário' : 'Enviar formulário NPS aos colaboradores'}
                    </button>
                  </div>
                </div>
              );
            })()}
            {/* QR Code real */}
            {(() => {
              const npsUrl = `${window.location.origin}${window.location.pathname.replace('index.html','').replace(/\/[^/]*$/, '/')}nps.html?treino=${treino.id}`;
              const qrUrl  = `https://api.qrserver.com/v1/create-qr-code/?size=140x140&data=${encodeURIComponent(npsUrl)}&bgcolor=ffffff&color=0A0F12&margin=6`;
              return (
                <div style={{ display:'flex', gap:14, alignItems:'flex-start', marginBottom:14 }}>
                  <div style={{ flexShrink:0, borderRadius:10, border:'1px solid var(--escalab-line)', overflow:'hidden', width:84, height:84 }}>
                    <img src={qrUrl} width={84} height={84} alt="QR NPS" style={{ display:'block' }}/>
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:12.5, fontWeight:600, color:'var(--escalab-ink)', marginBottom:6 }}>QR Code NPS gerado para este treinamento</div>
                    <div style={{ fontSize:12, color:'var(--escalab-mute)', marginBottom:8 }}>Projete na tela ou imprima para os participantes avaliarem.</div>
                    <a href={npsUrl} target="_blank" rel="noopener noreferrer" style={{ fontSize:12, color:'#1F4A8A', display:'inline-flex', alignItems:'center', gap:5, textDecoration:'none' }}>
                      <Icon name="eye" size={12} /> Abrir página de NPS ↗
                    </a>
                  </div>
                </div>
              );
            })()}
            <Field label="Nota NPS geral (0 a 100)">
              <Input value={form.nps} onChange={v => set('nps', v)} type="number" placeholder="Ex: 78 · ou clique 'Carregar do Google Forms'" />
            </Field>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10, marginTop:10 }}>
              <Field label="% Detratores"><Input value={form.detratores} onChange={v => set('detratores', v)} type="number" placeholder="0" /></Field>
              <Field label="% Neutros">  <Input value={form.neutros}    onChange={v => set('neutros', v)}    type="number" placeholder="0" /></Field>
              <Field label="% Promotores"><Input value={form.promotores} onChange={v => set('promotores', v)} type="number" placeholder="0" /></Field>
            </div>
          </div>

          <Field label="Observações (opcional)">
            <textarea value={form.observacao} onChange={e => set('observacao', e.target.value)} rows={2}
              placeholder="Anotações sobre o treinamento…"
              style={{ width:'100%', border:'1px solid var(--escalab-line)', borderRadius:8, padding:'9px 12px', fontSize:14, fontFamily:'var(--font-sans)', outline:0, resize:'vertical', boxSizing:'border-box' }} />
          </Field>

          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:4 }}>
            <Button variant="outline" onClick={onClose}>Cancelar</Button>
            <Button variant="primary" onClick={handleSalvar} disabled={!podeSubmeter}>Concluir treinamento</Button>
          </div>
        </div>
        {showChamada && <ModalChamada treino={treino} onClose={() => setShowChamada(false)}
          onSalvar={upd => { set('presentes_fixos', String(upd.presentes_fixos)); set('presentes_assoc', String(upd.presentes_assoc)); setShowChamada(false); }} />}
        {showRespostas && <ModalRespostasNps treino={treino} onClose={() => setShowRespostas(false)} />}
      </div>
    </div>
  );
};

// ── Modal: Novo Treinamento ───────────────────────────────────────────────────

const ModalNovoTreinamento = ({ onClose, onSalvar }) => {
  const totalFixos = COLABORADORES.filter(c => getCategoriaColaborador(c.id).categoria === 'fixo').length;
  const totalAssoc = COLABORADORES.filter(c => getCategoriaColaborador(c.id).categoria !== 'fixo').length;

  const [form, setForm] = useState({
    titulo: '', responsavel: '', local: '', data: '', tipo: 'tecnico',
    happyhour: false, descricao: '', total_fixos: String(totalFixos), total_assoc: String(totalAssoc),
    emailDestino: '', horario: '', esperadosIds: [],
    duracaoHoras: '',
    custo: '', // PDF Site AVD (2): R$ investido neste treinamento
  });
  const [buscaEsp, setBuscaEsp] = useState('');
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleEsp = (id) => setForm(f => ({ ...f, esperadosIds: f.esperadosIds.includes(id) ? f.esperadosIds.filter(x => x !== id) : [...f.esperadosIds, id] }));

  function handleSalvar() {
    if (!form.titulo || !form.data) return;
    const esperados = form.esperadosIds;
    // Se selecionou pessoas, deriva totais automaticamente
    let tf = Number(form.total_fixos) || 0;
    let ta = Number(form.total_assoc) || 0;
    if (esperados.length > 0) {
      tf = COLABORADORES.filter(c => esperados.includes(c.id) && getCategoriaColaborador(c.id).categoria === 'fixo').length;
      ta = COLABORADORES.filter(c => esperados.includes(c.id) && getCategoriaColaborador(c.id).categoria !== 'fixo').length;
    }
    const novo = {
      id: gerarIdTR(), ano: new Date(form.data).getFullYear(),
      ...form,
      total_fixos: tf,
      total_assoc: ta,
      status: 'agendado',
      freq_fixos: null, freq_assoc: null, nps: null,
      presentes_fixos: null, presentes_assoc: null,
      detratores: null, neutros: null, promotores: null,
    };
    onSalvar(novo);
    // Salva nas datas importantes da intranet
    try {
      const key = 'escalab_datas_importantes';
      const datas = JSON.parse(localStorage.getItem(key) || '[]');
      datas.push({ data: form.data, tipo: 'treinamento', titulo: form.titulo, local: form.local || '', id: novo.id });
      localStorage.setItem(key, JSON.stringify(datas));
    } catch {}
    onClose();
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,15,18,.55)', backdropFilter: 'blur(4px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 520, animation: 'popIn .22s var(--ease-out)', maxHeight: '92vh', overflow: 'auto' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'sticky', top: 0, background: '#fff', zIndex: 1 }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700 }}>Novo Treinamento</h3>
            <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginTop: 2 }}>Adicione um treinamento ao calendário</div>
          </div>
          <button onClick={onClose} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-mute)' }}><Icon name="close" size={18} /></button>
        </div>
        <div style={{ padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Field label="Título do treinamento">
            <Input value={form.titulo} onChange={v => set('titulo', v)} placeholder="Ex: Onboarding · turma jun/2025" />
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Data">
              <input type="date" value={form.data} onChange={e => set('data', e.target.value)}
                style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', outline: 0 }} />
            </Field>
            <Field label="Tipo">
              <select value={form.tipo} onChange={e => set('tipo', e.target.value)}
                style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', outline: 0, background: '#fff' }}>
                {TIPOS_TREINO.filter(t => t.id !== 'todos').map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
              </select>
            </Field>
          </div>
          <Field label="Responsável">
            <select value={form.responsavel} onChange={e => set('responsavel', e.target.value)}
              style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', outline: 0, background: '#fff' }}>
              <option value="">Selecione…</option>
              {COLABORADORES.filter(c => c.nivel !== 'liderado').map(c => <option key={c.id}>{c.nome}</option>)}
            </select>
          </Field>
          <Field label="Local">
            <Input value={form.local} onChange={v => set('local', v)} placeholder="Ex: Sala A, Online (Meet)…" />
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Horário">
              <Input value={form.horario} onChange={v => set('horario', v)} placeholder="Ex: 09:00 – 17:00" />
            </Field>
            <Field label="Duração (horas)" hint="Usado no dashboard de Treinamento & Desenvolvimento">
              <Input value={form.duracaoHoras} onChange={v => set('duracaoHoras', v)} type="number" placeholder="Ex: 8" />
            </Field>
          </div>
          <Field label="Custo do treinamento (R$)" hint="Investimento total · soma no painel de Treinamentos">
            <Input value={form.custo} onChange={v => set('custo', v)} type="number" placeholder="Ex: 1500" prefix="R$" />
          </Field>
          {form.esperadosIds.length === 0 ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label={`Fixos esperados (total: ${totalFixos})`}>
                <Input value={form.total_fixos} onChange={v => set('total_fixos', v)} placeholder={String(totalFixos)} />
              </Field>
              <Field label={`Associados esperados (total: ${totalAssoc})`}>
                <Input value={form.total_assoc} onChange={v => set('total_assoc', v)} placeholder={String(totalAssoc)} />
              </Field>
            </div>
          ) : (
            <div style={{ background: 'var(--escalab-brand-tint)', borderRadius: 8, padding: '10px 14px', fontSize: 12.5, color: 'var(--escalab-brand-deep)' }}>
              <Icon name="check" size={13} /> {form.esperadosIds.length} pessoa{form.esperadosIds.length > 1 ? 's' : ''} esperada{form.esperadosIds.length > 1 ? 's' : ''} (totais calculados automaticamente abaixo)
            </div>
          )}

          <Field label="Pessoas esperadas (opcional)" hint="Selecione quem foi convidado. Se vazio, considera todos os colaboradores.">
            <div style={{ border: '1px solid var(--escalab-line)', borderRadius: 8, background: '#fff', overflow: 'hidden' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '7px 12px', borderBottom: '1px solid var(--escalab-line)', background: 'var(--escalab-paper)' }}>
                <Icon name="search" size={13} />
                <input value={buscaEsp} onChange={e => setBuscaEsp(e.target.value)} placeholder="Buscar colaborador…"
                  style={{ border: 0, outline: 0, background: 'transparent', fontSize: 13, fontFamily: 'var(--font-sans)', flex: 1 }} />
                {form.esperadosIds.length > 0 && (
                  <button type="button" onClick={() => set('esperadosIds', [])} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-mute)', fontSize: 11.5, fontFamily: 'var(--font-sans)', textDecoration: 'underline' }}>
                    Limpar ({form.esperadosIds.length})
                  </button>
                )}
              </div>
              <div style={{ maxHeight: 180, overflowY: 'auto' }}>
                {COLABORADORES.filter(c => !buscaEsp || c.nome.toLowerCase().includes(buscaEsp.toLowerCase()) || c.setor.toLowerCase().includes(buscaEsp.toLowerCase())).map(c => {
                  const checked = form.esperadosIds.includes(c.id);
                  return (
                    <label key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px', cursor: 'pointer', background: checked ? 'var(--escalab-brand-tint)' : '#fff', borderBottom: '1px solid var(--escalab-line)' }}>
                      <input type="checkbox" checked={checked} onChange={() => toggleEsp(c.id)} />
                      <span style={{ fontSize: 13, fontWeight: checked ? 600 : 400, color: checked ? 'var(--escalab-brand-deep)' : 'var(--escalab-ink)' }}>{c.nome.split(' ').slice(0, 3).join(' ')}</span>
                      <span style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginLeft: 'auto' }}>{c.setor}</span>
                    </label>
                  );
                })}
              </div>
            </div>
          </Field>
          <Field label="Enviar convite para (e-mail ou grupo)">
            <Input value={form.emailDestino} onChange={v => set('emailDestino', v)} placeholder="fixosescalab@googlegroups.com ou e-mails separados por vírgula" />
          </Field>
          <label style={{ display: 'flex', gap: 10, alignItems: 'center', cursor: 'pointer' }}>
            <input type="checkbox" checked={form.happyhour} onChange={e => set('happyhour', e.target.checked)}
              style={{ width: 16, height: 16 }} />
            <span style={{ fontSize: 13.5, color: 'var(--escalab-slate)' }}>Terá happy hour após o treinamento</span>
          </label>
          <Field label="Descrição (opcional)">
            <textarea value={form.descricao} onChange={e => set('descricao', e.target.value)} rows={2}
              placeholder="Objetivo e conteúdo do treinamento…"
              style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }} />
          </Field>
          <div style={{ background: 'var(--escalab-brand-tint)', borderRadius: 8, padding: '10px 14px', fontSize: 12.5, color: 'var(--escalab-brand-deep)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
            <Icon name="info" size={14} />
            <div>
              <div>Treinamento adicionado automaticamente às <strong>Datas Importantes</strong> da Intranet.</div>
              <div style={{ marginTop:4 }}>QR code NPS gerado ao concluir o treinamento.</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 4 }}>
            <Button variant="outline" onClick={onClose}>Cancelar</Button>
            <Button variant="primary" onClick={handleSalvar} disabled={!form.titulo || !form.data}>Adicionar treinamento</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Modal Chamada de Presença ─────────────────────────────────────────────────

const CHAMADA_KEY = 'escalab_chamadas';

function getChamada(treinoId) {
  try { const m = JSON.parse(localStorage.getItem(CHAMADA_KEY) || '{}'); return m[treinoId] || {}; } catch { return {}; }
}
function salvarChamada(treinoId, mapa) {
  try { const m = JSON.parse(localStorage.getItem(CHAMADA_KEY) || '{}'); m[treinoId] = mapa; localStorage.setItem(CHAMADA_KEY, JSON.stringify(m)); } catch {}
}

const ModalChamada = ({ treino, onClose, onSalvar }) => {
  const [presenca, setPresenca] = useState(() => getChamada(treino.id));
  const [busca, setBusca] = useState('');
  const [verNaoEsperados, setVerNaoEsperados] = useState(false);

  const esperadosIds = Array.isArray(treino.esperadosIds) ? treino.esperadosIds : [];
  const temListaEsperados = esperadosIds.length > 0;
  const esperados = temListaEsperados ? COLABORADORES.filter(c => esperadosIds.includes(c.id)) : COLABORADORES;
  // Quem está sendo exibido na lista (filtragem por busca e modo)
  const baseLista = temListaEsperados ? (verNaoEsperados ? COLABORADORES.filter(c => !esperadosIds.includes(c.id)) : esperados) : COLABORADORES;
  const colabs = baseLista.filter(c => !busca || c.nome.toLowerCase().includes(busca.toLowerCase()));

  // Métricas baseadas APENAS nos esperados (presentes "não esperados" não contam para o pct)
  const nPresentesEsperados = esperados.filter(c => presenca[c.id] === true).length;
  const nAusentesEsperados  = esperados.filter(c => presenca[c.id] === false).length;
  const nMarcadosEsperados  = nPresentesEsperados + nAusentesEsperados;
  const denominador = esperados.length || 1;
  const pct = Math.round(nPresentesEsperados / denominador * 100);
  const nNaoEsperados = COLABORADORES.filter(c => !esperadosIds.includes(c.id) && presenca[c.id] === true).length;

  const toggle = (id, val) => setPresenca(p => ({ ...p, [id]: p[id] === val ? undefined : val }));

  function salvar() {
    salvarChamada(treino.id, presenca);
    onSalvar({ presentes_fixos: COLABORADORES.filter(c => presenca[c.id] === true && getCategoriaColaborador(c.id).categoria === 'fixo').length, presentes_assoc: COLABORADORES.filter(c => presenca[c.id] === true && getCategoriaColaborador(c.id).categoria !== 'fixo').length, pct_presenca: pct });
    onClose();
  }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,15,18,.55)', backdropFilter:'blur(4px)', zIndex:1010, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:'#fff', borderRadius:18, width:'100%', maxWidth:600, maxHeight:'90vh', display:'flex', flexDirection:'column', boxShadow:'0 12px 48px rgba(0,0,0,.2)', animation:'popIn .22s var(--ease-out)' }}>
        {/* Header */}
        <div style={{ padding:'18px 22px', borderBottom:'1px solid var(--escalab-line)', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:16, fontWeight:700 }}>Chamada de Presença</div>
            <div style={{ fontSize:12.5, color:'var(--escalab-mute)', marginTop:2 }}>{treino.titulo}</div>
          </div>
          <button onClick={onClose} style={{ border:0, background:'transparent', cursor:'pointer', color:'var(--escalab-mute)' }}><Icon name="close" size={18}/></button>
        </div>

        {/* Resumo */}
        <div style={{ padding:'14px 22px', borderBottom:'1px solid var(--escalab-line)', display:'flex', gap:20, alignItems:'center', flexShrink:0, background:'var(--escalab-paper)', flexWrap:'wrap' }}>
          {[
            { label:'Presentes', val:nPresentesEsperados, cor:'#00836B', bg:'#E6F5F1' },
            { label:'Ausentes',  val:nAusentesEsperados,  cor:'#B3261E', bg:'#FDECEC' },
            { label:'Não marcado', val:esperados.length-nMarcadosEsperados, cor:'var(--escalab-mute)', bg:'#fff' },
          ].map(k=>(
            <div key={k.label} style={{ background:k.bg, borderRadius:9, padding:'8px 16px', textAlign:'center' }}>
              <div style={{ fontSize:22, fontWeight:800, color:k.cor }}>{k.val}</div>
              <div style={{ fontSize:11, color:'var(--escalab-mute)' }}>{k.label}</div>
            </div>
          ))}
          {nNaoEsperados > 0 && (
            <div style={{ background:'#FFF7EB', borderRadius:9, padding:'8px 16px', textAlign:'center', border:'1px solid #F2D9A0' }}>
              <div style={{ fontSize:22, fontWeight:800, color:'#B56500' }}>+{nNaoEsperados}</div>
              <div style={{ fontSize:11, color:'#B56500' }}>não esperados</div>
            </div>
          )}
          <div style={{ flex:1, textAlign:'right' }}>
            <div style={{ fontSize:28, fontWeight:900, color:pct>=80?'#00836B':pct>=60?'#B56500':'#B3261E' }}>{pct}%</div>
            <div style={{ fontSize:11, color:'var(--escalab-mute)' }}>presença {temListaEsperados ? `dos esperados (${esperados.length})` : 'geral'}</div>
          </div>
        </div>

        {/* Tabs esperados / não esperados */}
        {temListaEsperados && (
          <div style={{ display:'flex', gap:0, padding:'0 22px', borderBottom:'1px solid var(--escalab-line)', flexShrink:0, background:'#fff' }}>
            <button onClick={() => setVerNaoEsperados(false)} style={{ border:0, background:'transparent', cursor:'pointer', padding:'10px 14px', fontSize:13, fontWeight:!verNaoEsperados?700:500, color:!verNaoEsperados?'var(--escalab-brand)':'var(--escalab-mute)', borderBottom:`2px solid ${!verNaoEsperados?'var(--escalab-brand)':'transparent'}`, fontFamily:'var(--font-sans)' }}>
              Esperados ({esperados.length})
            </button>
            <button onClick={() => setVerNaoEsperados(true)} style={{ border:0, background:'transparent', cursor:'pointer', padding:'10px 14px', fontSize:13, fontWeight:verNaoEsperados?700:500, color:verNaoEsperados?'#B56500':'var(--escalab-mute)', borderBottom:`2px solid ${verNaoEsperados?'#B56500':'transparent'}`, fontFamily:'var(--font-sans)' }}>
              Não esperados ({COLABORADORES.length - esperados.length}) <span style={{ fontSize:10.5, opacity:.7 }}>· não contam no pct</span>
            </button>
          </div>
        )}

        {/* Busca */}
        <div style={{ padding:'10px 22px', borderBottom:'1px solid var(--escalab-line)', flexShrink:0 }}>
          <div style={{ display:'flex', gap:7, alignItems:'center', background:'var(--escalab-paper)', borderRadius:8, padding:'7px 12px' }}>
            <Icon name="search" size={14}/>
            <input value={busca} onChange={e=>setBusca(e.target.value)} placeholder="Buscar colaborador..." style={{ border:0, outline:0, background:'transparent', fontSize:14, fontFamily:'var(--font-sans)', flex:1 }}/>
          </div>
        </div>

        {/* Lista */}
        <div style={{ flex:1, overflowY:'auto', padding:'8px 14px' }}>
          {colabs.map(c => {
            const st = presenca[c.id];
            return (
              <div key={c.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 8px', borderRadius:9, marginBottom:2 }}>
                <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={30}/>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13, fontWeight:500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{c.nome}</div>
                  <div style={{ fontSize:11, color:'var(--escalab-mute)' }}>{c.setor}</div>
                </div>
                <div style={{ display:'flex', gap:6 }}>
                  <button onClick={()=>toggle(c.id, true)} style={{ padding:'5px 14px', border:`2px solid ${st===true?'#00836B':'var(--escalab-line)'}`, borderRadius:7, background:st===true?'#E6F5F1':'#fff', color:st===true?'#00836B':'var(--escalab-mute)', cursor:'pointer', fontSize:13, fontWeight:st===true?700:400, fontFamily:'var(--font-sans)' }}>✓</button>
                  <button onClick={()=>toggle(c.id, false)} style={{ padding:'5px 14px', border:`2px solid ${st===false?'#B3261E':'var(--escalab-line)'}`, borderRadius:7, background:st===false?'#FDECEC':'#fff', color:st===false?'#B3261E':'var(--escalab-mute)', cursor:'pointer', fontSize:13, fontWeight:st===false?700:400, fontFamily:'var(--font-sans)' }}>✗</button>
                </div>
              </div>
            );
          })}
        </div>

        {/* Footer */}
        <div style={{ padding:'14px 22px', borderTop:'1px solid var(--escalab-line)', display:'flex', gap:10, justifyContent:'flex-end', flexShrink:0 }}>
          <Button variant="outline" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" onClick={salvar}>Salvar chamada</Button>
        </div>
      </div>
    </div>
  );
};

// ── Modal detalhe do treinamento ───────────────────────────────────────────

// ── Materiais do treinamento (uploads) ───────────────────────────────────────
const TREINO_MATERIAIS_KEY = 'escalab_treino_materiais';
function getMateriais(treinoId) {
  try { return (JSON.parse(localStorage.getItem(TREINO_MATERIAIS_KEY) || '{}'))[treinoId] || []; } catch { return []; }
}
function addMaterial(treinoId, material) {
  try {
    const all = JSON.parse(localStorage.getItem(TREINO_MATERIAIS_KEY) || '{}');
    all[treinoId] = [...(all[treinoId] || []), material];
    localStorage.setItem(TREINO_MATERIAIS_KEY, JSON.stringify(all));
  } catch {}
}
function removeMaterial(treinoId, materialId) {
  try {
    const all = JSON.parse(localStorage.getItem(TREINO_MATERIAIS_KEY) || '{}');
    all[treinoId] = (all[treinoId] || []).filter(m => m.id !== materialId);
    localStorage.setItem(TREINO_MATERIAIS_KEY, JSON.stringify(all));
  } catch {}
}

function buildGoogleAgendaUrl(treino) {
  const fmt = d => d.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
  let start, end;
  if (treino.data) {
    if (treino.horario && /\d{1,2}[:h]\d{2}/.test(treino.horario)) {
      const [hIni, hFim] = treino.horario.split(/[\s–-]+/);
      const [h1, m1] = hIni.split(/[:h]/);
      start = new Date(`${treino.data}T${String(h1).padStart(2,'0')}:${(m1||'00').padStart(2,'0')}:00`);
      if (hFim) {
        const [h2, m2] = hFim.split(/[:h]/);
        end = new Date(`${treino.data}T${String(h2).padStart(2,'0')}:${(m2||'00').padStart(2,'0')}:00`);
      } else {
        end = new Date(start.getTime() + 60 * 60 * 1000);
      }
    } else {
      start = new Date(`${treino.data}T09:00:00`);
      end = new Date(`${treino.data}T17:00:00`);
    }
  } else {
    start = new Date();
    end = new Date(Date.now() + 60 * 60 * 1000);
  }
  // Convidados: e-mails dos esperados (obrigatórios) + e-mail extra fornecido
  const esperadosIds = Array.isArray(treino.esperadosIds) ? treino.esperadosIds : [];
  const emails = [];
  esperadosIds.forEach(id => {
    const c = COLABORADORES.find(x => x.id === id);
    if (c && c.email) emails.push(c.email);
  });
  if (treino.emailDestino) {
    treino.emailDestino.split(',').map(s => s.trim()).filter(Boolean).forEach(e => emails.push(e));
  }
  const params = new URLSearchParams();
  params.set('action', 'TEMPLATE');
  params.set('text', treino.titulo || 'Treinamento Escalab');
  params.set('dates', `${fmt(start)}/${fmt(end)}`);
  if (treino.local) params.set('location', treino.local);
  if (treino.descricao) params.set('details', treino.descricao);
  if (emails.length) params.set('add', emails.join(','));
  return `https://calendar.google.com/calendar/render?${params.toString()}`;
}

const ModalDetalheTreino = ({ treino, onClose, onChamada, user }) => {
  const st = STATUS_TREINO[treino.status] || STATUS_TREINO.agendado;
  const dataBR = treino.data ? treino.data.split('-').reverse().join('/') : '·';
  const chamada = getChamada(treino.id);
  const nPresentes = Object.values(chamada).filter(v => v === true).length;
  const pctChamada = COLABORADORES.length > 0 ? Math.round(nPresentes / COLABORADORES.length * 100) : 0;
  const npsUrl = `${window.location.origin}${window.location.pathname.replace(/[^/]*$/,'')}nps.html?treino=${treino.id}`;
  const agendaUrl = buildGoogleAgendaUrl(treino);
  const [showResp, setShowResp] = useState(false);
  const [materiais, setMateriais] = useState(() => getMateriais(treino.id));
  const nRespNps = getNpsRespostas(treino.id).length;
  const isAdmin = user?.perfil === 'admin';
  const isResp = treino.responsavel && user?.nome && treino.responsavel.toLowerCase().includes(user.nome.split(' ')[0].toLowerCase());
  const podeSubirMaterial = isAdmin || isResp;

  function handleUploadMaterial(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => {
      const novo = {
        id: 'M' + Date.now(),
        nome: file.name,
        tipo: file.type || 'arquivo',
        tamanho: file.size,
        dataUrl: ev.target.result,
        em: new Date().toISOString(),
        por: user?.nome || 'Desconhecido',
      };
      addMaterial(treino.id, novo);
      setMateriais(getMateriais(treino.id));
    };
    reader.readAsDataURL(file);
    e.target.value = '';
  }
  function handleRemoverMaterial(id) {
    if (!window.confirm('Remover este material?')) return;
    removeMaterial(treino.id, id);
    setMateriais(getMateriais(treino.id));
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,15,18,.55)', backdropFilter: 'blur(4px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 540, animation: 'popIn .22s var(--ease-out)', maxHeight: '90vh', overflow: 'auto' }}>
        {/* Header */}
        <div style={{ background: 'var(--escalab-brand)', padding: '22px 24px 50px', position: 'relative' }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 14, right: 14, border: 0, background: 'rgba(255,255,255,.2)', borderRadius: 8, cursor: 'pointer', padding: '4px 8px', color: '#fff' }}>
            <Icon name="close" size={16} />
          </button>
          <div style={{ color: 'rgba(255,255,255,.85)', fontSize: 12, marginBottom: 6, fontWeight: 500 }}>{dataBR}</div>
          <div style={{ color: '#fff', fontSize: 18, fontWeight: 700, marginBottom: 4 }}>{treino.titulo}</div>
          <div style={{ color: 'rgba(255,255,255,.8)', fontSize: 13 }}>
            {treino.responsavel?.split(' ').slice(0, 2).join(' ')} · {treino.local}
            {treino.happyhour && <span style={{ marginLeft: 8, background: 'rgba(255,255,255,.2)', borderRadius: 4, padding: '1px 6px', fontSize: 11 }}>happy hour</span>}
          </div>
        </div>

        <div style={{ padding: '16px 24px 24px' }}>
          {/* Status + ações */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap:'wrap' }}>
            <span style={{ fontSize: 12.5, fontWeight: 600, padding: '4px 12px', borderRadius: 6, background: st.bg, color: st.cor }}>{st.label}</span>
            <button onClick={onChamada} style={{ display:'flex', gap:6, alignItems:'center', border:'1px solid var(--escalab-brand-soft)', background:'var(--escalab-brand-tint)', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12.5, fontFamily:'var(--font-sans)', color:'var(--escalab-brand-deep)', fontWeight:600 }}>
              <Icon name="users" size={13}/> {nPresentes > 0 ? `Chamada (${pctChamada}%)` : 'Fazer chamada'}
            </button>
            <a href={npsUrl} target="_blank" rel="noopener noreferrer" style={{ display:'flex', gap:6, alignItems:'center', border:'1px solid #C9D7EC', background:'#EEF3FA', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12.5, fontFamily:'var(--font-sans)', color:'#1F4A8A', fontWeight:600, textDecoration:'none' }}>
              <Icon name="grid" size={13}/> QR NPS
            </a>
            <button onClick={() => setShowResp(true)} style={{ display:'flex', gap:6, alignItems:'center', border:'1px solid #C9D7EC', background:'#EEF3FA', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12.5, fontFamily:'var(--font-sans)', color:'#1F4A8A', fontWeight:600 }}>
              <Icon name="message" size={13}/> Respostas NPS{nRespNps > 0 ? ` (${nRespNps})` : ''}
            </button>
            <a href={agendaUrl} target="_blank" rel="noopener noreferrer" style={{ display:'flex', gap:6, alignItems:'center', border:'1px solid #F2D9A0', background:'#FFF7EB', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12.5, fontFamily:'var(--font-sans)', color:'#B56500', fontWeight:600, textDecoration:'none' }} title="Convida automaticamente os e-mails marcados como obrigatórios">
              <Icon name="calendar" size={13}/> Google Agenda
            </a>
          </div>
          {showResp && <ModalRespostasNps treino={treino} onClose={() => setShowResp(false)} />}

          {/* Materiais do treinamento */}
          <div style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '14px 16px', marginBottom: 16 }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}>
              <Icon name="file" size={13} />
              <div style={{ fontSize:12.5, fontWeight:700, color:'var(--escalab-ink)' }}>Materiais do treinamento</div>
              <span style={{ fontSize:11, color:'var(--escalab-mute)', marginLeft:4 }}>{materiais.length}</span>
              {podeSubirMaterial && (
                <label style={{ marginLeft:'auto', display:'inline-flex', gap:5, alignItems:'center', border:'1px solid var(--escalab-brand-soft)', background:'var(--escalab-brand-tint)', color:'var(--escalab-brand-deep)', borderRadius:7, padding:'4px 11px', cursor:'pointer', fontSize:12, fontWeight:600 }}>
                  <Icon name="upload" size={12} /> Subir material
                  <input type="file" onChange={handleUploadMaterial} style={{ display:'none' }} />
                </label>
              )}
            </div>
            {materiais.length === 0 ? (
              <div style={{ fontSize:12.5, color:'var(--escalab-mute)' }}>
                {podeSubirMaterial ? 'Nenhum material ainda. O responsável pode subir slides, PDFs ou links aqui · fica salvo para revisitar depois.' : 'O responsável ainda não disponibilizou material.'}
              </div>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {materiais.map(m => (
                  <div key={m.id} style={{ display:'flex', alignItems:'center', gap:9, padding:'7px 10px', background:'#fff', borderRadius:8, border:'1px solid var(--escalab-line)' }}>
                    <Icon name="file" size={13} />
                    <a href={m.dataUrl} download={m.nome} style={{ flex:1, fontSize:12.5, fontWeight:600, color:'var(--escalab-brand-deep)', textDecoration:'none', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                      {m.nome}
                    </a>
                    <span style={{ fontSize:11, color:'var(--escalab-mute)' }}>{m.por}</span>
                    {podeSubirMaterial && (
                      <button onClick={() => handleRemoverMaterial(m.id)} style={{ border:0, background:'transparent', cursor:'pointer', color:'#B3261E', padding:2 }} title="Remover">
                        <Icon name="close" size={12} />
                      </button>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Métricas se concluído */}
          {treino.status === 'concluido' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 20 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                {[
                  { label: 'Freq. Fixos',   val: treino.freq_fixos + '%', sub: `${treino.presentes_fixos}/${treino.total_fixos}`, cor: '#00967B' },
                  { label: 'Freq. Assoc.',  val: treino.freq_assoc + '%', sub: `${treino.presentes_assoc}/${treino.total_assoc}`,  cor: '#E89B3B' },
                  { label: 'NPS',           val: treino.nps,              sub: treino.nps >= 75 ? 'Excelência' : treino.nps >= 50 ? 'Bom' : 'Atenção', cor: treino.nps >= 75 ? '#00967B' : '#E89B3B' },
                ].map(k => (
                  <div key={k.label} style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '14px', textAlign: 'center' }}>
                    <div style={{ fontSize: 11, color: 'var(--escalab-mute)', marginBottom: 4 }}>{k.label}</div>
                    <div style={{ fontSize: 22, fontWeight: 800, color: k.cor }}>{k.val}</div>
                    <div style={{ fontSize: 11, color: 'var(--escalab-mute)', marginTop: 2 }}>{k.sub}</div>
                  </div>
                ))}
              </div>

              {/* NPS distribuição */}
              {treino.detratores != null && (
                <div style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '14px 16px' }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--escalab-slate)', marginBottom: 10 }}>Distribuição NPS</div>
                  <div style={{ display: 'flex', borderRadius: 6, overflow: 'hidden', height: 14, marginBottom: 10 }}>
                    <div style={{ width: treino.detratores + '%', background: '#E05050' }} />
                    <div style={{ width: treino.neutros + '%', background: '#E89B3B' }} />
                    <div style={{ width: treino.promotores + '%', background: '#00967B' }} />
                  </div>
                  <div style={{ display: 'flex', gap: 14, fontSize: 12 }}>
                    {[
                      { label: 'Detratores', val: treino.detratores, cor: '#E05050' },
                      { label: 'Neutros',    val: treino.neutros,    cor: '#E89B3B' },
                      { label: 'Promotores', val: treino.promotores, cor: '#00967B' },
                    ].map(d => (
                      <div key={d.label} style={{ display: 'flex', gap: 5, alignItems: 'center', color: 'var(--escalab-mute)' }}>
                        <div style={{ width: 8, height: 8, borderRadius: '50%', background: d.cor }} />
                        {d.label}: <strong style={{ color: d.cor }}>{d.val}%</strong>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {treino.descricao && (
            <div style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '14px 16px', marginBottom: 16, fontSize: 13.5, color: 'var(--escalab-slate)', lineHeight: 1.6 }}>
              {treino.descricao}
            </div>
          )}

          {/* Capacidade */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[
              { label: 'Fixos esperados', val: treino.total_fixos, cor: '#1F4A8A' },
              { label: 'Associados esperados', val: treino.total_assoc, cor: '#6B3FA0' },
            ].map(k => (
              <div key={k.label} style={{ background: 'var(--escalab-paper)', borderRadius: 9, padding: '12px 14px', display: 'flex', gap: 10, alignItems: 'center' }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: k.cor, flexShrink: 0 }} />
                <div>
                  <div style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>{k.label}</div>
                  <div style={{ fontSize: 16, fontWeight: 700, color: k.cor }}>{k.val || '·'}</div>
                </div>
              </div>
            ))}
          </div>

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 20 }}>
            <Button variant="outline" onClick={onClose}>Fechar</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Modal: Respostas do NPS (votações + comentários) ──────────────────────────

const ModalRespostasNps = ({ treino, onClose }) => {
  const cfg = getNpsConfig();
  const respostas = getNpsRespostas(treino.id).slice().reverse();
  const notas = respostas.map(r => Number(r.nota)).filter(n => !isNaN(n));
  const det  = notas.filter(n => n <= 6).length;
  const neut = notas.filter(n => n >= 7 && n <= 8).length;
  const prom = notas.filter(n => n >= 9).length;
  const nps  = notas.length ? Math.round((prom - det) / notas.length * 100) : null;
  const corNota = n => n >= 9 ? '#00836B' : n >= 7 ? '#1F4A8A' : n >= 5 ? '#B56500' : '#B3261E';

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,15,18,.55)', backdropFilter:'blur(4px)', zIndex:1015, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:18, width:'100%', maxWidth:600, maxHeight:'90vh', display:'flex', flexDirection:'column', animation:'popIn .22s var(--ease-out)' }}>
        <div style={{ padding:'18px 22px', borderBottom:'1px solid var(--escalab-line)', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:16, fontWeight:700 }}>Respostas do NPS</div>
            <div style={{ fontSize:12.5, color:'var(--escalab-mute)', marginTop:2 }}>{treino.titulo}</div>
          </div>
          <button onClick={onClose} style={{ border:0, background:'transparent', cursor:'pointer', color:'var(--escalab-mute)' }}><Icon name="close" size={18}/></button>
        </div>

        <div style={{ padding:'14px 22px', borderBottom:'1px solid var(--escalab-line)', display:'flex', gap:18, alignItems:'center', flexWrap:'wrap', background:'var(--escalab-paper)', flexShrink:0 }}>
          <div style={{ textAlign:'center' }}>
            <div style={{ fontSize:26, fontWeight:900, color:'#1F4A8A' }}>{respostas.length}</div>
            <div style={{ fontSize:11, color:'var(--escalab-mute)' }}>respostas</div>
          </div>
          <div style={{ textAlign:'center' }}>
            <div style={{ fontSize:26, fontWeight:900, color: nps != null && nps >= 0 ? '#00836B' : '#B3261E' }}>{nps != null ? nps : '·'}</div>
            <div style={{ fontSize:11, color:'var(--escalab-mute)' }}>NPS</div>
          </div>
          <div style={{ display:'flex', gap:12, fontSize:12, marginLeft:'auto' }}>
            {[['Promotores',prom,'#00967B'],['Neutros',neut,'#E89B3B'],['Detratores',det,'#E05050']].map(([l,v,c]) => (
              <div key={l} style={{ display:'flex', gap:5, alignItems:'center', color:'var(--escalab-mute)' }}>
                <div style={{ width:8, height:8, borderRadius:'50%', background:c }} /> {l}: <strong style={{ color:c }}>{v}</strong>
              </div>
            ))}
          </div>
        </div>

        <div style={{ flex:1, overflowY:'auto', padding:'14px 22px' }}>
          {respostas.length === 0 ? (
            <div style={{ textAlign:'center', padding:'40px 12px', color:'var(--escalab-mute)', fontSize:14 }}>
              Nenhuma resposta recebida ainda. Compartilhe o QR Code com os participantes.
            </div>
          ) : respostas.map((r, i) => (
            <div key={i} style={{ display:'flex', gap:12, padding:'12px 0', borderBottom: i < respostas.length-1 ? '1px solid var(--escalab-line)' : 0 }}>
              <div style={{ flexShrink:0, width:42, height:42, borderRadius:10, background:corNota(Number(r.nota)), color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:17 }}>{r.nota}</div>
              <div style={{ flex:1, minWidth:0 }}>
                {r.comentario ? <div style={{ fontSize:13.5, color:'var(--escalab-ink)', lineHeight:1.5 }}>{r.comentario}</div>
                  : <div style={{ fontSize:13, color:'var(--escalab-mute)', fontStyle:'italic' }}>Sem comentário</div>}
                {r.extras && cfg.extras.filter(e => r.extras[e.id]).map(e => (
                  <div key={e.id} style={{ fontSize:12.5, color:'var(--escalab-slate)', marginTop:6 }}>
                    <span style={{ color:'var(--escalab-mute)' }}>{e.texto}: </span>{r.extras[e.id]}
                  </div>
                ))}
                {r.respondidoEm && <div style={{ fontSize:11, color:'var(--escalab-mute)', marginTop:6 }}>{new Date(r.respondidoEm).toLocaleString('pt-BR')}</div>}
              </div>
            </div>
          ))}
        </div>
        <div style={{ padding:'12px 22px', borderTop:'1px solid var(--escalab-line)', display:'flex', justifyContent:'flex-end', flexShrink:0 }}>
          <Button variant="outline" onClick={onClose}>Fechar</Button>
        </div>
      </div>
    </div>
  );
};

// ── Modal: Editar formulário de NPS (GC) ──────────────────────────────────────

const ModalEditarNpsForm = ({ onClose }) => {
  const [cfg, setCfg] = useState(() => getNpsConfig());
  const set = (k, v) => setCfg(c => ({ ...c, [k]: v }));
  const inp = { width:'100%', border:'1px solid var(--escalab-line)', borderRadius:8, padding:'9px 12px', fontSize:14, fontFamily:'var(--font-sans)', outline:0, boxSizing:'border-box' };

  function addExtra() { setCfg(c => ({ ...c, extras:[ ...c.extras, { id:'Q'+Date.now(), tipo:'texto', texto:'', opcoes:[], obrigatoria:false } ] })); }
  function updExtra(id, patch) { setCfg(c => ({ ...c, extras: c.extras.map(e => e.id === id ? { ...e, ...patch } : e) })); }
  function remExtra(id) { setCfg(c => ({ ...c, extras: c.extras.filter(e => e.id !== id) })); }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,15,18,.55)', backdropFilter:'blur(4px)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:18, width:'100%', maxWidth:560, maxHeight:'90vh', display:'flex', flexDirection:'column', animation:'popIn .22s var(--ease-out)' }}>
        <div style={{ padding:'18px 22px', borderBottom:'1px solid var(--escalab-line)', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:16, fontWeight:700 }}>Editar formulário de NPS</div>
            <div style={{ fontSize:12.5, color:'var(--escalab-mute)', marginTop:2 }}>Aplica-se ao QR Code de todos os treinamentos</div>
          </div>
          <button onClick={onClose} style={{ border:0, background:'transparent', cursor:'pointer', color:'var(--escalab-mute)' }}><Icon name="close" size={18}/></button>
        </div>

        <div style={{ flex:1, overflowY:'auto', padding:'18px 22px', display:'flex', flexDirection:'column', gap:16 }}>
          <Field label="Pergunta da nota (0 a 10)">
            <input value={cfg.npsLabel} onChange={e => set('npsLabel', e.target.value)} style={inp} />
          </Field>
          <Field label="Texto auxiliar abaixo da nota">
            <input value={cfg.npsSublabel} onChange={e => set('npsSublabel', e.target.value)} style={inp} />
          </Field>
          <Field label="Pergunta do comentário">
            <input value={cfg.comentarioLabel} onChange={e => set('comentarioLabel', e.target.value)} style={inp} />
          </Field>
          <label style={{ display:'flex', gap:8, alignItems:'center', cursor:'pointer' }}>
            <input type="checkbox" checked={cfg.comentarioObrigatorio} onChange={e => set('comentarioObrigatorio', e.target.checked)} style={{ width:16, height:16 }} />
            <span style={{ fontSize:13.5, color:'var(--escalab-slate)' }}>Comentário obrigatório</span>
          </label>

          <div style={{ background:'var(--escalab-paper)', border:'1px solid var(--escalab-line)', borderRadius:12, padding:'14px 16px' }}>
            <div style={{ fontSize:12, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase', color:'var(--escalab-mute)', marginBottom:12 }}>Perguntas extras ({cfg.extras.length})</div>
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {cfg.extras.map(e => (
                <div key={e.id} style={{ background:'#fff', border:'1px solid var(--escalab-line)', borderRadius:10, padding:'10px 12px' }}>
                  <div style={{ display:'flex', gap:8, alignItems:'center', marginBottom:8 }}>
                    <select value={e.tipo} onChange={ev => updExtra(e.id, { tipo: ev.target.value })} style={{ border:'1px solid var(--escalab-line)', borderRadius:7, padding:'6px 8px', fontSize:12.5, fontFamily:'var(--font-sans)', outline:0, background:'#fff' }}>
                      <option value="texto">Texto livre</option>
                      <option value="multipla">Múltipla escolha</option>
                    </select>
                    <input value={e.texto} onChange={ev => updExtra(e.id, { texto: ev.target.value })} placeholder="Texto da pergunta..." style={{ flex:1, border:'1px solid var(--escalab-line)', borderRadius:7, padding:'7px 10px', fontSize:13, fontFamily:'var(--font-sans)', outline:0 }} />
                    <button onClick={() => remExtra(e.id)} style={{ border:0, background:'transparent', cursor:'pointer', color:'#B3261E', padding:4 }}><Icon name="close" size={14}/></button>
                  </div>
                  {e.tipo === 'multipla' && (
                    <textarea value={(e.opcoes || []).join('\n')} onChange={ev => updExtra(e.id, { opcoes: ev.target.value.split('\n').map(o => o.trim()).filter(Boolean) })} rows={3} placeholder="Uma opção por linha..." style={{ width:'100%', border:'1px solid var(--escalab-line)', borderRadius:7, padding:'7px 10px', fontSize:13, fontFamily:'var(--font-sans)', outline:0, resize:'vertical', boxSizing:'border-box', marginBottom:8 }} />
                  )}
                  <label style={{ display:'flex', gap:7, alignItems:'center', cursor:'pointer' }}>
                    <input type="checkbox" checked={!!e.obrigatoria} onChange={ev => updExtra(e.id, { obrigatoria: ev.target.checked })} style={{ width:14, height:14 }} />
                    <span style={{ fontSize:12.5, color:'var(--escalab-slate)' }}>Obrigatória</span>
                  </label>
                </div>
              ))}
            </div>
            <button onClick={addExtra} style={{ border:'1px dashed var(--escalab-line)', borderRadius:8, padding:'7px 14px', cursor:'pointer', fontSize:12.5, fontFamily:'var(--font-sans)', color:'var(--escalab-brand)', background:'transparent', display:'flex', alignItems:'center', gap:5, marginTop:10 }}>
              <Icon name="plus" size={12}/> Adicionar pergunta extra
            </button>
          </div>
        </div>

        <div style={{ padding:'12px 22px', borderTop:'1px solid var(--escalab-line)', display:'flex', justifyContent:'space-between', gap:10, flexShrink:0 }}>
          <Button variant="ghost" onClick={() => setCfg({ ...NPS_CONFIG_PADRAO })}>Restaurar padrão</Button>
          <div style={{ display:'flex', gap:10 }}>
            <Button variant="outline" onClick={onClose}>Cancelar</Button>
            <Button variant="primary" onClick={() => { salvarNpsConfig(cfg); onClose(); }}>Salvar formulário</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Tela Principal ─────────────────────────────────────────────────────────

// PDF Site AVD (3): Escalab School · cursos pagos para colabs (custo, NPS, taxa de retorno)
const SCHOOL_KEY = 'escalab_school';
const SCHOOL_SEED = [
  { id: 'SC001', colaboradorId: 1, curso: 'MBA em Gestão de Pessoas · FGV', instituicao: 'FGV', dataInicio: '2025-02-10', dataFim: '2026-02-10', custo: 28500, nps: 88, taxaRetorno: 85, status: 'andamento', observacao: 'Cursando · bom retorno na rotina de people analytics.' },
  { id: 'SC002', colaboradorId: 5, curso: 'Especialização em UX Research', instituicao: 'PUC-Rio', dataInicio: '2024-08-15', dataFim: '2025-08-15', custo: 12000, nps: 92, taxaRetorno: 95, status: 'concluido', observacao: 'Aplicou aprendizados em 3 projetos internos.' },
  { id: 'SC003', colaboradorId: 8, curso: 'Curso de Liderança Avançada', instituicao: 'Falconi', dataInicio: '2025-09-01', dataFim: '2025-12-15', custo: 8500, nps: 76, taxaRetorno: 70, status: 'andamento', observacao: '' },
];
function getEscalabSchool() {
  try {
    const r = localStorage.getItem(SCHOOL_KEY);
    if (r) return JSON.parse(r);
    localStorage.setItem(SCHOOL_KEY, JSON.stringify(SCHOOL_SEED));
    return SCHOOL_SEED;
  } catch { return SCHOOL_SEED; }
}
function salvarEscalabSchool(arr) { try { localStorage.setItem(SCHOOL_KEY, JSON.stringify(arr)); } catch {} }

// ── Configuração do formulário de NPS do Escalab School (editável pelo GC) ──
// Espelha NPS_CONFIG mas com labels específicos de curso (taxaRetornoLabel, etc.)
const SCHOOL_NPS_CONFIG_KEY = 'escalab_school_nps_config';
const SCHOOL_NPS_CONFIG_PADRAO = {
  npsLabel: 'Em uma escala de 0 a 10, como você avalia este curso?',
  npsSublabel: '0 = não recomendo · 10 = mudou minha trajetória',
  taxaRetornoLabel: 'Taxa de retorno · % do que você aprendeu e aplicou no trabalho',
  taxaRetornoObrigatorio: true,
  comentarioLabel: 'Comentário · como o aprendizado virou prática (opcional)',
  comentarioPlaceholder: 'Ex: usei na rotina de processos, treinei o time, virou material interno…',
  comentarioObrigatorio: false,
  extras: [],
};
function getSchoolNpsConfig() {
  try { const r = JSON.parse(localStorage.getItem(SCHOOL_NPS_CONFIG_KEY) || 'null'); return r ? { ...SCHOOL_NPS_CONFIG_PADRAO, ...r } : { ...SCHOOL_NPS_CONFIG_PADRAO }; }
  catch { return { ...SCHOOL_NPS_CONFIG_PADRAO }; }
}
function salvarSchoolNpsConfig(cfg) { try { localStorage.setItem(SCHOOL_NPS_CONFIG_KEY, JSON.stringify(cfg)); } catch {} }

const ScreenTreinamentos = ({ user }) => {
  const [treinos, setTreinos] = useState(() => getTreinamentos());
  const [subaba, setSubaba] = useState('treinamentos');
  const [ano, setAno] = useState(2025);
  const [tipo, setTipo] = useState('todos');
  const [modalNovo, setModalNovo]       = useState(false);
  const [modalDetalhe, setModalDetalhe] = useState(null);
  const [modalConcluir, setModalConcluir] = useState(null);
  const [modalChamada, setModalChamada] = useState(null);
  const [modalNpsForm, setModalNpsForm] = useState(false);
  const [sucesso, setSucesso] = useState('');
  // NPS in-app que o colab esta respondendo (vive aqui no topo pra nao violar
  // a regra de ordem de hooks — gestor/colab e admin compartilham o mesmo
  // componente, ai o useState precisa estar antes do early return).
  const [npsTreino, setNpsTreino] = useState(null);

  function recarregar() { setTreinos(getTreinamentos()); }

  function handleSalvar(t) {
    const lista = [t, ...getTreinamentos()];
    salvarTreinamentos(lista);
    recarregar();
    setSucesso(`Treinamento "${t.titulo}" adicionado!`);
    setTimeout(() => setSucesso(''), 4000);
  }

  function handleConcluir(id, updates) {
    const lista = getTreinamentos().map(t => t.id === id ? { ...t, ...updates } : t);
    salvarTreinamentos(lista);
    recarregar();
    setSucesso('Treinamento concluído com sucesso!');
    setTimeout(() => setSucesso(''), 4000);
  }

  const anosDisponiveis = [...new Set(treinos.map(t => t.ano))].sort((a, b) => b - a);

  const filtrados = treinos.filter(t => t.ano === ano && (tipo === 'todos' || t.tipo === tipo));
  const concluidos = filtrados.filter(t => t.status === 'concluido');

  // KPIs
  const totalAno = filtrados.length;
  const mediaFreqFixos = concluidos.length ? Math.round(concluidos.reduce((s, t) => s + (t.freq_fixos || 0), 0) / concluidos.length) : 0;
  const mediaFreqAssoc = concluidos.length ? Math.round(concluidos.reduce((s, t) => s + (t.freq_assoc || 0), 0) / concluidos.length) : 0;
  const mediaNPS = concluidos.filter(t => t.nps).length ? Math.round(concluidos.reduce((s, t) => s + (t.nps || 0), 0) / concluidos.filter(t => t.nps).length) : 0;
  const mediaFaltas = concluidos.length ? parseFloat(((concluidos.reduce((s, t) => s + (t.total_fixos + t.total_assoc - (t.presentes_fixos || 0) - (t.presentes_assoc || 0)), 0)) / Math.max(concluidos.length, 1)).toFixed(1)) : 0;

  // Setores fixos freq
  const setoresFiltrados = ['Marketing', 'P&D', 'Comercial', 'Administrativo'].map(s => ({ setor: s, pct: 74 + Math.floor(Math.random() * 20) }));

  // NPS últimos 6 treinamentos para gráfico
  const npsUltimos = concluidos.slice(-6).map(t => ({ label: t.titulo.slice(0, 8), nps: t.nps }));

  // Distribuição NPS geral
  const allDetrat = concluidos.reduce((s, t) => s + (t.detratores || 0), 0);
  const allNeutros = concluidos.reduce((s, t) => s + (t.neutros || 0), 0);
  const allPromo = concluidos.reduce((s, t) => s + (t.promotores || 0), 0);
  const totalDist = allDetrat + allNeutros + allPromo || 100;
  const pctDetrat = Math.round(allDetrat / totalDist * 100);
  const pctNeutros = Math.round(allNeutros / totalDist * 100);
  const pctPromo = Math.round(allPromo / totalDist * 100);

  const dataBR = s => {
    if (!s) return '·';
    const [y, m, d] = s.split('-');
    const MESES = ['jan','fev','mar','abr','mai','jun','jul','ago','set','out','nov','dez'];
    return <><strong style={{ display: 'block', fontSize: 16, lineHeight: 1 }}>{d}</strong><span style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>{MESES[parseInt(m) - 1]}</span></>;
  };

  // Gestor e colaborador veem apenas a lista simplificada sem métricas
  if (user.perfil !== 'admin') {
    // Treinos concluidos que tem NPS in-app ativo e o colab ainda nao respondeu
    // tambem aparecem (pra ele responder a avaliacao do curso).
    const visiveis = filtrados.filter(t => {
      if (t.status !== 'concluido') return true;
      if (user.perfil === 'gestor') return true;
      const esperado = !Array.isArray(t.esperadosIds) || t.esperadosIds.length === 0 || t.esperadosIds.includes(user.id);
      return t.npsInAppAtivo && esperado && !jaRespondeuNpsInApp(t.id, user.id);
    });
    const isGestor = user.perfil === 'gestor';
    return (
      <div style={{ animation: 'fadeIn .22s var(--ease-out)' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', flexWrap:'wrap', gap:12, marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-brand)', marginBottom: 4 }}>Gestão de Pessoas</div>
            <h2 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>Treinamentos</h2>
            <p style={{ fontSize: 13, color: 'var(--escalab-slate)', margin: '4px 0 0' }}>Próximos treinamentos e eventos do Escalab</p>
          </div>
          {isGestor && (
            <Button variant="primary" icon="plus" onClick={() => setModalNovo(true)}>Iniciar novo treinamento</Button>
          )}
        </div>
        <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, overflow: 'hidden' }}>
          {visiveis.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px 24px', color: 'var(--escalab-mute)' }}>
              <Icon name="calendar" size={32} />
              <div style={{ marginTop: 10, fontSize: 14 }}>Nenhum treinamento para o período selecionado</div>
            </div>
          ) : visiveis.map((t, i) => {
            const st = STATUS_TREINO[t.status] || STATUS_TREINO.agendado;
            const esperadosIds = Array.isArray(t.esperadosIds) ? t.esperadosIds : [];
            const souEsperado = esperadosIds.length === 0 || esperadosIds.includes(user.id);
            // RSVP do colaborador (intenção) · separado da chamada oficial feita pelo responsável
            let rsvpMap = {};
            try { rsvpMap = JSON.parse(localStorage.getItem('escalab_treino_rsvp') || '{}')[t.id] || {}; } catch {}
            const minhaPresenca = rsvpMap[user.id];
            const podeMarcar = souEsperado && (t.status === 'em_andamento' || t.status === 'agendado' || t.status === 'em_breve');
            function saveRsvp(valor, motivo) {
              try {
                const all = JSON.parse(localStorage.getItem('escalab_treino_rsvp') || '{}');
                all[t.id] = all[t.id] || {};
                all[t.id][user.id] = { confirmado: valor, motivo: motivo || '', em: new Date().toISOString() };
                localStorage.setItem('escalab_treino_rsvp', JSON.stringify(all));
              } catch {}
            }
            function marcarPresenca() {
              saveRsvp(true);
              window.location.reload();
            }
            function marcarAusencia() {
              const motivo = prompt('Por que você não vai poder participar? (opcional)') || '';
              saveRsvp(false, motivo);
              window.location.reload();
            }
            // Botao "Avaliar NPS" — aparece em concluido + formulario in-app ativo + colab e esperado + ainda nao respondeu
            const precisaResponderNps = t.status === 'concluido' && t.npsInAppAtivo && souEsperado && user.perfil === 'colaborador' && !jaRespondeuNpsInApp(t.id, user.id);
            return (
              <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 20px', borderBottom: i < visiveis.length - 1 ? '1px solid var(--escalab-line)' : 0, flexWrap: 'wrap', background: precisaResponderNps ? '#FFF7EB' : '#fff' }}>
                <div style={{ minWidth: 36, textAlign: 'center', background: 'var(--escalab-paper)', borderRadius: 8, padding: '6px 4px' }}>
                  {dataBR(t.data)}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--escalab-ink)' }}>{t.titulo}</div>
                  <div style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>{t.responsavel?.split(' ').slice(0,2).join(' ')} · {t.local}</div>
                  {esperadosIds.length > 0 && souEsperado && (
                    <div style={{ fontSize: 11, color: 'var(--escalab-brand-deep)', fontWeight: 600, marginTop: 3 }}>
                      <Icon name="check" size={11} /> Você está na lista de esperados
                    </div>
                  )}
                  {precisaResponderNps && (
                    <div style={{ fontSize: 11.5, color: '#B56500', fontWeight: 700, marginTop: 4 }}>
                      <Icon name="message" size={11} /> Avaliação NPS disponível pra você responder
                    </div>
                  )}
                </div>
                {precisaResponderNps && (
                  <button onClick={() => setNpsTreino(t)} style={{ border:'1px solid #E89B3B', background:'#E89B3B', color:'#fff', borderRadius:8, padding:'7px 14px', cursor:'pointer', fontSize:12.5, fontWeight:700, fontFamily:'var(--font-sans)', display:'inline-flex', alignItems:'center', gap:6 }}>
                    <Icon name="star" size={12}/> Avaliar treinamento
                  </button>
                )}
                {podeMarcar && (
                  minhaPresenca?.confirmado === true ? (
                    <span style={{ fontSize: 12, fontWeight: 700, padding: '5px 12px', borderRadius: 6, background: '#E6F5F1', color: '#00836B', display: 'flex', alignItems: 'center', gap: 5 }}>
                      <Icon name="check" size={12} /> Você confirmou presença
                    </span>
                  ) : minhaPresenca?.confirmado === false ? (
                    <span style={{ fontSize: 12, fontWeight: 700, padding: '5px 12px', borderRadius: 6, background: '#FDECEC', color: '#B3261E', display: 'flex', alignItems: 'center', gap: 5 }}>
                      <Icon name="close" size={12} /> Você marcou ausência
                    </span>
                  ) : (
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      <button onClick={marcarPresenca} style={{ border: '1px solid var(--escalab-brand-soft)', background: 'var(--escalab-brand-tint)', color: 'var(--escalab-brand-deep)', padding: '6px 12px', borderRadius: 7, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-sans)', display: 'flex', alignItems: 'center', gap: 5 }}>
                        <Icon name="check" size={12} /> Vou
                      </button>
                      <button onClick={marcarAusencia} style={{ border: '1px solid #F4C7C3', background: '#FDECEC', color: '#B3261E', padding: '6px 12px', borderRadius: 7, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-sans)', display: 'flex', alignItems: 'center', gap: 5 }}>
                        <Icon name="close" size={12} /> Não vou
                      </button>
                    </div>
                  )
                )}
                <span style={{ fontSize: 12, fontWeight: 600, padding: '4px 10px', borderRadius: 6, background: st.bg, color: st.cor, whiteSpace: 'nowrap' }}>{st.label}</span>
              </div>
            );
          })}
        </div>
        {modalNovo && <ModalNovoTreinamento onClose={() => setModalNovo(false)} onSalvar={handleSalvar} />}
        {sucesso && <div style={{ marginTop: 16 }}><Banner tone="success" onClose={() => setSucesso('')}>{sucesso}</Banner></div>}
        {npsTreino && (
          <ModalRespostaNpsColab
            treino={npsTreino}
            user={user}
            onClose={() => setNpsTreino(null)}
            onEnviado={() => { setSucesso('Avaliação enviada · obrigado!'); setTimeout(() => setSucesso(''), 4000); recarregar?.(); }}
          />
        )}
      </div>
    );
  }

  return (
    <div style={{ animation: 'fadeIn .22s var(--ease-out)' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-brand)', marginBottom: 4 }}>Gestão de Pessoas</div>
          <h2 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>Treinamentos · Monitoramento</h2>
          <p style={{ fontSize: 13, color: 'var(--escalab-slate)', margin: '4px 0 0' }}>Ano {ano} · atualizado hoje</p>
        </div>
        {subaba === 'treinamentos' && (user.perfil === 'admin' || user.perfil === 'gestor') && (
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            {user.perfil === 'admin' && (
              <Button variant="outline" icon="settings" onClick={() => setModalNpsForm(true)}>Formulário NPS</Button>
            )}
            <Button variant="primary" icon="plus" onClick={() => setModalNovo(true)}>Novo treinamento</Button>
          </div>
        )}
      </div>

      {sucesso && <div style={{ marginBottom: 16 }}><Banner tone="success" onClose={() => setSucesso('')}>{sucesso}</Banner></div>}

      {/* PDF Site AVD (3): Subabas Treinamentos / Escalab School */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 18, borderBottom: '1px solid var(--escalab-line)' }}>
        {[
          { id: 'treinamentos', label: 'Treinamentos', icon: 'calendar' },
          { id: 'school',       label: 'Escalab School', icon: 'star' },
        ].map(t => (
          <button key={t.id} onClick={() => setSubaba(t.id)}
            style={{ border: 0, background: 'transparent', cursor: 'pointer', padding: '10px 16px', fontSize: 13, fontFamily: 'var(--font-sans)', fontWeight: 600,
              color: subaba === t.id ? 'var(--escalab-brand)' : 'var(--escalab-mute)',
              borderBottom: subaba === t.id ? '2px solid var(--escalab-brand)' : '2px solid transparent',
              marginBottom: -1, display: 'flex', gap: 6, alignItems: 'center' }}>
            <Icon name={t.icon} size={13} /> {t.label}
          </button>
        ))}
      </div>

      {subaba === 'school' ? <EscalabSchoolPainel user={user} setSucesso={setSucesso} /> : null}
      {subaba === 'treinamentos' && (<>

      {/* Filtros */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 22, flexWrap: 'wrap', alignItems: 'center' }}>
        <select value={ano} onChange={e => setAno(Number(e.target.value))}
          style={{ border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '8px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, background: '#fff', minWidth: 80 }}>
          {anosDisponiveis.map(a => <option key={a} value={a}>{a}</option>)}
        </select>
        <select value={tipo} onChange={e => setTipo(e.target.value)}
          style={{ border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '8px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, background: '#fff', minWidth: 140 }}>
          {TIPOS_TREINO.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
        </select>
        <button style={{ display: 'flex', gap: 6, alignItems: 'center', border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 8, padding: '8px 14px', cursor: 'pointer', fontSize: 13.5, fontFamily: 'var(--font-sans)', color: 'var(--escalab-slate)' }}>
          <Icon name="download" size={14} /> Exportar
        </button>
      </div>

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 22 }}>
        {[
          { label: 'Treinamentos no ano', val: totalAno, sub: totalAno > 14 ? `+${totalAno - 14} vs ${ano - 1}` : '', cor: 'var(--escalab-brand)', bg: 'var(--escalab-brand-tint)' },
          { label: 'Freq. Fixos',          val: mediaFreqFixos + '%', sub: 'média geral', cor: '#00967B', bg: '#E6F5F1' },
          { label: 'Freq. Associados',     val: mediaFreqAssoc + '%', sub: 'média geral', cor: '#E89B3B', bg: '#FFF7EB' },
          { label: 'NPS Geral',            val: mediaNPS, sub: mediaNPS >= 70 ? 'zona de excelência' : mediaNPS >= 50 ? 'bom' : 'atenção', cor: mediaNPS >= 70 ? '#00967B' : '#E89B3B', bg: mediaNPS >= 70 ? '#E6F5F1' : '#FFF7EB' },
          { label: 'Faltas/Pessoa',        val: mediaFaltas + 'd', sub: 'média no ano', cor: '#B3261E', bg: '#FDECEC' },
        ].map(k => (
          <div key={k.label} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '16px 18px' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 8 }}>{k.label}</div>
            <div style={{ fontSize: 26, fontWeight: 800, color: k.cor, lineHeight: 1, marginBottom: 4 }}>{k.val}</div>
            {k.sub && <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>{k.sub}</div>}
          </div>
        ))}
      </div>

      {/* Gráficos */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 20 }}>
        {/* Frequência por tipo */}
        <Card pad={20}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 14, display: 'flex', gap: 6, alignItems: 'center' }}>
            <Icon name="users" size={12} /> Frequência por Tipo de Colaborador
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              { label: 'Fixos',       pct: mediaFreqFixos, cor: '#00967B' },
              { label: 'Associados',  pct: mediaFreqAssoc, cor: '#E89B3B' },
            ].map(r => (
              <div key={r.label}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                  <span style={{ fontSize: 13, color: 'var(--escalab-ink)' }}>{r.label}</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: r.cor }}>{r.pct}%</span>
                </div>
                <div style={{ height: 8, background: 'var(--escalab-line)', borderRadius: 999 }}>
                  <div style={{ width: r.pct + '%', height: '100%', background: r.cor, borderRadius: 999, transition: 'width .5s' }} />
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--escalab-line)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--escalab-slate)', marginBottom: 10, letterSpacing: '.08em', textTransform: 'uppercase' }}>Por Setor · Fixos</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {[
                { setor: 'P&D',            pct: 92 },
                { setor: 'Marketing',       pct: 88 },
                { setor: 'Comercial',       pct: 80 },
                { setor: 'Administrativo',  pct: 74 },
              ].map(s => (
                <div key={s.setor} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontSize: 12.5, color: 'var(--escalab-slate)', minWidth: 90 }}>{s.setor}</span>
                  <div style={{ flex: 1, height: 6, background: 'var(--escalab-line)', borderRadius: 999 }}>
                    <div style={{ width: s.pct + '%', height: '100%', background: '#1F4A8A', borderRadius: 999, transition: 'width .5s' }} />
                  </div>
                  <span style={{ fontSize: 12, fontWeight: 700, color: '#1F4A8A', minWidth: 32, textAlign: 'right' }}>{s.pct}%</span>
                </div>
              ))}
            </div>
          </div>
        </Card>

        {/* NPS */}
        <Card pad={20}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 14, display: 'flex', gap: 6, alignItems: 'center' }}>
            <Icon name="chart" size={12} /> NPS por Treinamento · Últimos {npsUltimos.length}
          </div>
          {npsUltimos.length === 0 ? (
            <div style={{ color: 'var(--escalab-mute)', fontSize: 13, textAlign: 'center', padding: '20px 0' }}>Sem dados de NPS para o filtro</div>
          ) : (
            <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end', height: 100, marginBottom: 8 }}>
              {npsUltimos.map((n, i) => {
                const h = Math.max(8, (n.nps / 100) * 80);
                const cor = n.nps >= 75 ? '#00967B' : n.nps >= 50 ? '#E89B3B' : '#E05050';
                return (
                  <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: cor }}>{n.nps}</span>
                    <div style={{ width: '100%', background: cor, borderRadius: '4px 4px 0 0', height: h + 'px', transition: 'height .4s' }} />
                    <span style={{ fontSize: 10, color: 'var(--escalab-mute)', textAlign: 'center', maxWidth: 48, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{n.label}</span>
                  </div>
                );
              })}
            </div>
          )}
          <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--escalab-line)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--escalab-slate)', marginBottom: 10, letterSpacing: '.08em', textTransform: 'uppercase' }}>Distribuição NPS Geral</div>
            {concluidos.length > 0 ? (
              <>
                <div style={{ display: 'flex', borderRadius: 6, overflow: 'hidden', height: 14, marginBottom: 8 }}>
                  <div style={{ width: pctDetrat + '%', background: '#E05050' }} />
                  <div style={{ width: pctNeutros + '%', background: '#E89B3B' }} />
                  <div style={{ width: pctPromo + '%', background: '#00967B' }} />
                </div>
                <div style={{ display: 'flex', gap: 12, fontSize: 12 }}>
                  {[
                    { label: pctDetrat + '% detratores', cor: '#E05050' },
                    { label: pctNeutros + '% neutros',   cor: '#E89B3B' },
                    { label: pctPromo + '% promotores',  cor: '#00967B' },
                  ].map(d => (
                    <div key={d.label} style={{ display: 'flex', gap: 5, alignItems: 'center', color: 'var(--escalab-mute)' }}>
                      <div style={{ width: 8, height: 8, borderRadius: '50%', background: d.cor }} />
                      {d.label}
                    </div>
                  ))}
                </div>
              </>
            ) : <div style={{ fontSize: 13, color: 'var(--escalab-mute)', textAlign: 'center', padding: '10px 0' }}>Sem dados</div>}
          </div>
        </Card>
      </div>

      {/* Lista de treinamentos */}
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', display: 'flex', gap: 6, alignItems: 'center' }}>
            <Icon name="calendar" size={13} /> Todos os Treinamentos · {ano}
          </div>
          {user.perfil === 'admin' && (
            <button onClick={() => setModalNovo(true)} style={{ display: 'flex', gap: 6, alignItems: 'center', border: '1px solid var(--escalab-line)', background: 'var(--escalab-paper)', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontSize: 12.5, fontFamily: 'var(--font-sans)', color: 'var(--escalab-brand)', fontWeight: 600 }}>
              <Icon name="plus" size={13} /> Novo treinamento ↗
            </button>
          )}
        </div>

        {filtrados.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 24px', color: 'var(--escalab-mute)' }}>
            <Icon name="calendar" size={32} />
            <div style={{ marginTop: 10, fontSize: 14 }}>Nenhum treinamento para o filtro selecionado</div>
          </div>
        ) : (
          filtrados.map((t, i) => {
            const st = STATUS_TREINO[t.status] || STATUS_TREINO.agendado;
            return (
              <div key={t.id} onClick={() => setModalDetalhe(t)}
                style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 20px', borderBottom: i < filtrados.length - 1 ? '1px solid var(--escalab-line)' : 0, cursor: 'pointer', transition: 'background .12s' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--escalab-paper)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                {/* Data */}
                <div style={{ minWidth: 36, textAlign: 'center', background: t.status === 'em_breve' ? '#EEF3FA' : 'var(--escalab-paper)', borderRadius: 8, padding: '6px 4px' }}>
                  {dataBR(t.data)}
                </div>

                {/* Info */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 3 }}>
                    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--escalab-ink)' }}>{t.titulo}</span>
                    {t.happyhour && <span style={{ fontSize: 10.5, background: '#F4EEFF', color: '#6B3FA0', borderRadius: 4, padding: '1px 5px', fontWeight: 600 }}>happy hour</span>}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>
                    {t.responsavel?.split(' ').slice(0, 2).join(' ')} · {t.local}
                  </div>
                </div>

                {/* Métricas */}
                <div style={{ display: 'flex', gap: 20, alignItems: 'center', flexShrink: 0 }}>
                  <div style={{ textAlign: 'center', minWidth: 38 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: t.freq_fixos ? '#00967B' : 'var(--escalab-mute)' }}>
                      {t.freq_fixos ? t.freq_fixos + '%' : '·'}
                    </div>
                    <div style={{ fontSize: 10.5, color: 'var(--escalab-mute)' }}>fixos</div>
                  </div>
                  <div style={{ textAlign: 'center', minWidth: 42 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: t.freq_assoc ? '#E89B3B' : 'var(--escalab-mute)' }}>
                      {t.freq_assoc ? t.freq_assoc + '%' : '·'}
                    </div>
                    <div style={{ fontSize: 10.5, color: 'var(--escalab-mute)' }}>assoc.</div>
                  </div>
                  <div style={{ textAlign: 'center', minWidth: 32 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: t.nps >= 70 ? '#00967B' : t.nps ? '#E89B3B' : 'var(--escalab-mute)' }}>
                      {t.nps || '·'}
                    </div>
                    <div style={{ fontSize: 10.5, color: 'var(--escalab-mute)' }}>NPS</div>
                  </div>
                  {user.perfil === 'admin' && (t.status === 'em_breve' || t.status === 'agendado') && (
                    <button onClick={e => { e.stopPropagation(); setModalConcluir(t); }}
                      style={{ border:'1px solid var(--escalab-brand-soft)', background:'var(--escalab-brand-tint)', borderRadius:7, padding:'4px 12px', cursor:'pointer', fontSize:12, color:'var(--escalab-brand)', fontFamily:'var(--font-sans)', fontWeight:600, whiteSpace:'nowrap' }}>
                      Concluir
                    </button>
                  )}
                  <span style={{ fontSize: 12, fontWeight: 600, padding: '4px 10px', borderRadius: 6, background: st.bg, color: st.cor, whiteSpace: 'nowrap' }}>
                    {st.label}
                  </span>
                </div>
              </div>
            );
          })
        )}
      </div>

      </>)}

      {modalNovo && <ModalNovoTreinamento onClose={() => setModalNovo(false)} onSalvar={handleSalvar} />}
      {modalDetalhe && <ModalDetalheTreino treino={modalDetalhe} user={user} onClose={() => setModalDetalhe(null)} onChamada={() => { setModalChamada(modalDetalhe); setModalDetalhe(null); }}/>}
      {modalChamada && <ModalChamada treino={modalChamada} onClose={() => setModalChamada(null)} onSalvar={upd => { handleConcluir(modalChamada.id, upd); setSucesso('Chamada salva!'); setTimeout(()=>setSucesso(''),3000); }}/>}
      {modalConcluir && (
        <ModalConcluirTreinamento
          treino={modalConcluir}
          onClose={() => setModalConcluir(null)}
          onConcluir={updates => handleConcluir(modalConcluir.id, updates)}
        />
      )}
      {modalNpsForm && <ModalEditarNpsForm onClose={() => setModalNpsForm(false)} />}
    </div>
  );
};

// ── PDF Site AVD (3): Escalab School · cursos pagos a colabs ─────────────
// Normaliza NPS para escala 0–10 (seeds antigos podem estar em 0–100)
function _npsTo10(v) {
  if (v == null || v === '') return null;
  const n = Number(v);
  if (!isFinite(n)) return null;
  return n > 10 ? Math.round((n / 10) * 10) / 10 : Math.round(n * 10) / 10;
}
function _diasAteFim(dataFim) {
  if (!dataFim) return null;
  return Math.round((new Date(dataFim + 'T00:00:00') - new Date()) / 86400000);
}

const EscalabSchoolPainel = ({ user, setSucesso }) => {
  const [cursos, setCursos] = useState(() => getEscalabSchool());
  const [modal, setModal] = useState(null);       // { ...curso } | { novo: true }
  const [modalFinal, setModalFinal] = useState(null); // curso em finalização
  const [modalRespNps, setModalRespNps] = useState(null); // colab respondendo NPS
  const [modalEditarNps, setModalEditarNps] = useState(false); // admin editando form NPS

  function recarregar() { setCursos(getEscalabSchool()); }
  function handleSalvar(curso) {
    const lista = curso.id ? cursos.map(c => c.id === curso.id ? curso : c) : [{ ...curso, id: 'SC' + Date.now().toString(36).toUpperCase() }, ...cursos];
    salvarEscalabSchool(lista);
    recarregar();
    setModal(null);
    setSucesso && setSucesso(curso.id ? 'Curso atualizado!' : 'Curso adicionado!');
    setTimeout(() => setSucesso && setSucesso(''), 3000);
  }
  function handleFinalizar(curso) {
    // O modal já preparou todas as mudanças no `curso` (status, dataFim, npsFormularioEnviado etc.)
    const lista = cursos.map(c => c.id === curso.id ? curso : c);
    salvarEscalabSchool(lista); recarregar(); setModalFinal(null);
    const msg = curso.npsFormularioEnviado
      ? 'Formulário NPS enviado ao colaborador · aguardando resposta.'
      : 'Curso finalizado · NPS e taxa de retorno registrados.';
    setSucesso && setSucesso(msg);
    setTimeout(() => setSucesso && setSucesso(''), 3500);
  }
  function handleExcluir(id) {
    if (!confirm('Excluir este curso?')) return;
    salvarEscalabSchool(cursos.filter(c => c.id !== id));
    recarregar();
  }

  const isAdmin = user.perfil === 'admin';

  // ── VISÃO DO COLABORADOR ─────────────────────────────────────────────────
  if (!isAdmin) {
    const meusCursos = cursos.filter(c => c.colaboradorId === user.id);
    const pendentes = meusCursos.filter(c => c.npsFormularioEnviado && c.nps == null);
    const finalizados = meusCursos.filter(c => c.status === 'concluido' && c.nps != null);
    const andamento = meusCursos.filter(c => c.status === 'andamento');

    if (meusCursos.length === 0) {
      return (
        <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '32px 24px', textAlign: 'center', color: 'var(--escalab-mute)' }}>
          <Icon name="star" size={32} />
          <div style={{ marginTop: 12, fontSize: 14, fontWeight: 700, color: 'var(--escalab-ink)' }}>Nenhum curso pelo Escalab School ainda</div>
          <div style={{ fontSize: 12.5, marginTop: 4 }}>Quando o RH cadastrar um curso seu, ele aparece aqui.</div>
        </div>
      );
    }

    return (
      <div style={{ animation: 'fadeIn .22s var(--ease-out)' }}>
        {/* Banner de pendência: colab precisa responder NPS */}
        {pendentes.length > 0 && (
          <div style={{ marginBottom: 16 }}>
            <Banner tone="warn">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <strong>Você tem {pendentes.length} curso{pendentes.length === 1 ? '' : 's'} pra avaliar</strong>
                {pendentes.map(p => (
                  <div key={p.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, padding: '6px 0' }}>
                    <span style={{ fontSize: 12.5 }}><strong>{p.curso}</strong> · {p.instituicao}</span>
                    <button onClick={() => setModalRespNps(p)}
                      style={{ border: 0, background: '#E89B3B', color: '#fff', borderRadius: 7, padding: '5px 12px', cursor: 'pointer', fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-sans)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                      <Icon name="star" size={11}/> Avaliar curso
                    </button>
                  </div>
                ))}
              </div>
            </Banner>
          </div>
        )}

        <div style={{ background: '#fff', borderRadius: 12, border: '1px solid var(--escalab-line)', overflow: 'hidden' }}>
          <div style={{ padding: '12px 18px', borderBottom: '1px solid var(--escalab-line)', background: 'var(--escalab-paper)', fontSize: 11.5, fontWeight: 700, color: 'var(--escalab-mute)', textTransform: 'uppercase', letterSpacing: '.08em' }}>
            Meus cursos pelo Escalab School ({meusCursos.length})
          </div>
          {meusCursos.map((c, i) => {
            const aguardandoMinha = c.npsFormularioEnviado && c.nps == null;
            return (
              <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '1fr 110px 140px', gap: 12, padding: '12px 18px', borderBottom: i < meusCursos.length - 1 ? '1px solid var(--escalab-line)' : 0, alignItems: 'center', background: aguardandoMinha ? '#FFF7EB' : '#fff' }}>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--escalab-ink)' }}>{c.curso}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>
                    {c.instituicao} · {c.dataInicio || '·'} → {c.dataFim || '·'}
                  </div>
                </div>
                <Tag tone={c.status === 'concluido' ? 'success' : c.status === 'andamento' ? 'info' : 'warn'} size="xs">
                  {c.status === 'concluido' ? 'Concluído' : c.status === 'andamento' ? 'Em andamento' : 'Cancelado'}
                </Tag>
                {aguardandoMinha ? (
                  <button onClick={() => setModalRespNps(c)}
                    style={{ border: 0, background: '#E89B3B', color: '#fff', borderRadius: 7, padding: '6px 12px', cursor: 'pointer', fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-sans)', display: 'inline-flex', alignItems: 'center', gap: 5, justifyContent: 'center' }}>
                    <Icon name="star" size={11}/> Avaliar
                  </button>
                ) : c.nps != null ? (
                  <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', textAlign: 'right' }}>
                    Sua nota: <strong style={{ color: '#00836B' }}>{c.nps}/10</strong>
                  </div>
                ) : (
                  <span style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>—</span>
                )}
              </div>
            );
          })}
        </div>

        {modalRespNps && (
          <ModalRespostaNpsSchool
            curso={modalRespNps}
            onClose={() => setModalRespNps(null)}
            onEnviado={() => {
              setSucesso && setSucesso('Avaliação enviada · obrigado!');
              setTimeout(() => setSucesso && setSucesso(''), 3500);
              recarregar();
            }}
          />
        )}
      </div>
    );
  }
  // ── /VISÃO DO COLABORADOR ────────────────────────────────────────────────
  const anoAtual = new Date().getFullYear();
  const concluidos = cursos.filter(c => c.status === 'concluido');
  const totalInvest = cursos.reduce((s, c) => s + (Number(c.custo) || 0), 0);
  const npsMedia10 = concluidos.length
    ? Math.round(concluidos.reduce((s, c) => s + (_npsTo10(c.nps) || 0), 0) / concluidos.length * 10) / 10
    : null;
  const retornoMedio = concluidos.length ? Math.round(concluidos.reduce((s, c) => s + (Number(c.taxaRetorno) || 0), 0) / concluidos.length) : 0;
  // PDF · item 3: quantas pessoas foram contempladas no ano corrente (cursos iniciados neste ano · contagem por colaborador único)
  const contempladosAnoIds = new Set(
    cursos.filter(c => c.dataInicio && c.dataInicio.startsWith(String(anoAtual))).map(c => c.colaboradorId)
  );
  const contempladosAno = contempladosAnoIds.size;
  // P9 (backlog 16/06): contemplados por ano · bar chart
  const contempladosPorAno = (() => {
    const mapa = {};
    cursos.forEach(c => {
      if (!c.dataInicio) return;
      const ano = c.dataInicio.slice(0, 4);
      if (!mapa[ano]) mapa[ano] = new Set();
      mapa[ano].add(c.colaboradorId);
    });
    return Object.keys(mapa).sort().map(ano => ({ ano, n: mapa[ano].size }));
  })();
  const nomeColab = (id) => (COLABORADORES.find(c => c.id === id) || {}).nome || '·';

  // Alertas: cursos em andamento com data prevista chegando (≤ 14 dias) ou vencida sem NPS
  const alertas = cursos
    .filter(c => c.status === 'andamento' && c.dataFim)
    .map(c => ({ curso: c, dias: _diasAteFim(c.dataFim) }))
    .filter(x => x.dias != null && x.dias <= 14)
    .sort((a, b) => a.dias - b.dias);

  return (
    <div style={{ animation: 'fadeIn .22s var(--ease-out)' }}>
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '14px 16px', marginBottom: 16, fontSize: 12.5, color: 'var(--escalab-slate)', lineHeight: 1.5 }}>
        <strong>Escalab School</strong> · programa de subsídio de cursos. Cadastre um novo curso ao iniciar e use "Finalizar" quando ele acabar para preencher o NPS (0 a 10) e a taxa de retorno.
      </div>

      {/* Alertas para RH quando data prevista está próxima */}
      {isAdmin && alertas.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <Banner tone="warn">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <strong>Cursos prestes a finalizar · envie o formulário de NPS</strong>
              {alertas.map(({ curso, dias }) => (
                <div key={curso.id} style={{ fontSize: 12.5, display: 'flex', gap: 8, alignItems: 'center' }}>
                  <span style={{ background: dias < 0 ? '#FDECEC' : '#FFF7EB', color: dias < 0 ? '#B3261E' : '#7A4A00', borderRadius: 6, padding: '2px 8px', fontWeight: 700, fontSize: 11 }}>
                    {dias < 0 ? `vencido há ${-dias}d` : dias === 0 ? 'termina hoje' : `em ${dias}d`}
                  </span>
                  <span><strong>{nomeColab(curso.colaboradorId)}</strong> · {curso.curso} ({curso.instituicao})</span>
                  <button onClick={() => setModalFinal({ ...curso })} style={{ marginLeft: 'auto', border: '1px solid var(--escalab-brand)', background: 'var(--escalab-brand-tint)', color: 'var(--escalab-brand-deep)', borderRadius: 6, padding: '3px 10px', cursor: 'pointer', fontSize: 11.5, fontWeight: 700, fontFamily: 'var(--font-sans)' }}>
                    Finalizar curso · enviar NPS
                  </button>
                </div>
              ))}
            </div>
          </Banner>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 18 }} className="mobile-col1">
        {[
          { label: 'Cursos ativos',   val: cursos.filter(c => c.status === 'andamento').length, cor: '#1F4A8A', bg: '#EEF3FA' },
          { label: `Contemplados ${anoAtual}`, val: contempladosAno, cor: '#005E4D', bg: '#E6F5F1' },
          { label: 'Investimento total', val: 'R$ ' + Math.round(totalInvest).toLocaleString('pt-BR'), cor: '#B56500', bg: '#FFF7EB' },
          { label: 'NPS médio',       val: npsMedia10 != null ? `${npsMedia10}/10` : '·', cor: '#00967B', bg: '#E6F5F1' },
          { label: 'Taxa de retorno', val: (retornoMedio || 0) + '%', cor: '#6B3FA0', bg: '#F4EEFF' },
        ].map(k => (
          <div key={k.label} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '14px 16px' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 6 }}>{k.label}</div>
            <div style={{ fontSize: 22, fontWeight: 800, color: k.cor, lineHeight: 1 }}>{k.val}</div>
          </div>
        ))}
      </div>

      {contempladosPorAno.length > 0 && (
        <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '16px 20px', marginBottom: 18 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--escalab-mute)', letterSpacing: '.1em', textTransform: 'uppercase', marginBottom: 14 }}>Contemplados por ano · pessoas distintas</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 18, minHeight: 130 }}>
            {(() => {
              const max = Math.max(1, ...contempladosPorAno.map(x => x.n));
              return contempladosPorAno.map(({ ano, n }) => {
                const h = Math.round((n / max) * 100);
                return (
                  <div key={ano} style={{ flex: 1, textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                    <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--escalab-brand-deep)', marginBottom: 6 }}>{n}</div>
                    <div style={{ width: '70%', maxWidth: 80, height: `${Math.max(8, h)}px`, background: 'linear-gradient(180deg,#00967B,#005E4D)', borderRadius: '6px 6px 0 0' }} />
                    <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--escalab-slate)', marginTop: 6 }}>{ano}</div>
                  </div>
                );
              });
            })()}
          </div>
        </div>
      )}

      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)' }}>Cursos cadastrados</div>
          {isAdmin && (
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <Button variant="outline" size="sm" icon="settings" onClick={() => setModalEditarNps(true)}>Editar formulário de NPS</Button>
              <Button variant="primary" size="sm" icon="plus" onClick={() => setModal({ novo: true })}>Novo curso</Button>
            </div>
          )}
        </div>
        {cursos.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 24px', color: 'var(--escalab-mute)' }}>Sem cursos cadastrados ainda.</div>
        ) : cursos.map((c, i) => {
          const nps10 = _npsTo10(c.nps);
          const dias = _diasAteFim(c.dataFim);
          const proximo = c.status === 'andamento' && dias != null && dias <= 14;
          const aguardandoColab = c.status === 'concluido' && c.npsFormularioEnviado && c.nps == null;
          return (
          <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 90px 70px 70px 110px 130px', gap: 12, padding: '12px 20px', borderBottom: i < cursos.length - 1 ? '1px solid var(--escalab-line)' : 0, alignItems: 'center', fontSize: 13, background: aguardandoColab ? '#FFF7EB' : 'transparent' }}>
            <div>
              <div style={{ fontWeight: 600, color: 'var(--escalab-ink)' }}>{c.curso}</div>
              <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>
                {c.instituicao} · início {c.dataInicio || '·'} · {c.status === 'concluido' ? 'concluído ' + (c.dataFim || '') : 'previsto p/ ' + (c.dataFim || '·')}
                {proximo && <span style={{ marginLeft: 6, background: dias < 0 ? '#FDECEC' : '#FFF7EB', color: dias < 0 ? '#B3261E' : '#7A4A00', borderRadius: 6, padding: '1px 7px', fontWeight: 700 }}>
                  {dias < 0 ? `vencido (${-dias}d)` : dias === 0 ? 'termina hoje' : `em ${dias}d`}
                </span>}
                {aguardandoColab && <span style={{ marginLeft: 6, background: '#FFF7EB', color: '#7A4A00', borderRadius: 6, padding: '1px 7px', fontWeight: 700 }}>
                  aguardando NPS do colab
                </span>}
              </div>
            </div>
            <div style={{ color: 'var(--escalab-slate)' }}>{nomeColab(c.colaboradorId)}</div>
            <div style={{ fontWeight: 700, color: '#B56500' }}>R$ {Math.round(c.custo || 0).toLocaleString('pt-BR')}</div>
            <div style={{ fontWeight: 700, color: nps10 != null && nps10 >= 7 ? '#00967B' : nps10 != null && nps10 >= 5 ? '#E89B3B' : nps10 != null ? '#B3261E' : 'var(--escalab-mute)' }}>{nps10 != null ? `${nps10}/10` : (aguardandoColab ? '⌛' : '·')}</div>
            <div style={{ fontWeight: 700, color: '#6B3FA0' }}>{c.taxaRetorno != null && c.taxaRetorno !== '' ? c.taxaRetorno + '%' : (aguardandoColab ? '⌛' : '·')}</div>
            <Tag tone={c.status === 'concluido' ? 'success' : c.status === 'andamento' ? 'info' : 'warn'} size="xs">{c.status === 'concluido' ? (aguardandoColab ? 'Aguardando' : 'Concluído') : c.status === 'andamento' ? 'Em andamento' : 'Cancelado'}</Tag>
            {isAdmin && (
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
                {c.status === 'andamento' && (
                  <button onClick={() => setModalFinal({ ...c })} title="Finalizar curso · enviar NPS" style={{ border: '1px solid var(--escalab-brand)', background: 'var(--escalab-brand-tint)', color: 'var(--escalab-brand-deep)', borderRadius: 6, padding: '4px 8px', cursor: 'pointer', fontSize: 11, fontFamily: 'var(--font-sans)', fontWeight: 700 }}>Finalizar</button>
                )}
                <button onClick={() => setModal({ ...c })} style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 6, padding: '4px 8px', cursor: 'pointer', fontSize: 11, fontFamily: 'var(--font-sans)' }}>Editar</button>
                <button onClick={() => handleExcluir(c.id)} style={{ border: '1px solid #FDECEC', background: '#FDECEC', borderRadius: 6, padding: '4px 8px', cursor: 'pointer', fontSize: 11, color: '#B3261E', fontFamily: 'var(--font-sans)' }}>X</button>
              </div>
            )}
          </div>
          );
        })}
      </div>

      {modal && <ModalEscalabSchool curso={modal.novo ? null : modal} onClose={() => setModal(null)} onSalvar={handleSalvar} />}
      {modalFinal && <ModalFinalizarEscalabSchool curso={modalFinal} onClose={() => setModalFinal(null)} onSalvar={handleFinalizar} />}
      {modalEditarNps && <ModalEditarSchoolNpsForm onClose={() => setModalEditarNps(false)} />}
    </div>
  );
};

const ModalEscalabSchool = ({ curso, onClose, onSalvar }) => {
  const [form, setForm] = useState(curso || { curso: '', instituicao: '', colaboradorId: '', dataInicio: '', dataFim: '', custo: '', nps: '', taxaRetorno: '', status: 'andamento', observacao: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const valido = form.curso && form.colaboradorId && form.dataFim;

  return (
    <Modal open onClose={onClose} title={curso ? 'Editar curso' : 'Novo curso · Escalab School'} width={560}
      footer={<>
        <Button variant="outline" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" onClick={() => valido && onSalvar({ ...form, colaboradorId: Number(form.colaboradorId), custo: Number(form.custo) || 0, nps: form.nps !== '' ? Number(form.nps) : null, taxaRetorno: form.taxaRetorno !== '' ? Number(form.taxaRetorno) : null })} disabled={!valido}>Salvar</Button>
      </>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <Field label="Nome do colaborador *">
          <SelectInput value={String(form.colaboradorId || '')} onChange={v => set('colaboradorId', v)}
            options={[{ value: '', label: '· selecione ·' }, ...COLABORADORES.map(c => ({ value: String(c.id), label: c.nome }))]} />
        </Field>
        <Field label="Nome do curso *">
          <Input value={form.curso} onChange={v => set('curso', v)} placeholder="Ex: MBA em Gestão de Pessoas" />
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Instituição">
            <Input value={form.instituicao} onChange={v => set('instituicao', v)} placeholder="Ex: FGV" />
          </Field>
          <Field label="Custo (R$)">
            <Input type="number" value={form.custo} onChange={v => set('custo', v)} placeholder="0,00" />
          </Field>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Data de início"><Input type="date" value={form.dataInicio} onChange={v => set('dataInicio', v)} /></Field>
          <Field label="Data prevista de finalização *"><Input type="date" value={form.dataFim} onChange={v => set('dataFim', v)} /></Field>
        </div>
        <Field label="Status *">
          <SelectInput value={form.status} onChange={v => set('status', v)} options={[
            { value: 'andamento', label: 'Em andamento' },
            { value: 'concluido', label: 'Concluído' },
            { value: 'cancelado', label: 'Cancelado' },
          ]} />
        </Field>
        {form.status === 'concluido' && (
          <div style={{ background: 'var(--escalab-paper)', borderRadius: 8, padding: 12, fontSize: 12, color: 'var(--escalab-slate)' }}>
            Para preencher NPS e taxa de retorno, use o botão <strong>Finalizar</strong> na lista de cursos. O alerta para o RH é disparado automaticamente quando faltarem ≤ 14 dias para a data prevista.
          </div>
        )}
        <Field label="Observação">
          <textarea value={form.observacao} onChange={e => set('observacao', e.target.value)} rows={3}
            style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }} />
        </Field>
      </div>
    </Modal>
  );
};

// Modal de finalização · RH envia formulário NPS pro colaborador (in-app)
// O colaborador responde dentro da plataforma; NPS e taxa de retorno são
// gravados automaticamente quando ele submete. RH pode também preencher
// manualmente como fallback (compat com fluxo antigo).
const ModalFinalizarEscalabSchool = ({ curso, onClose, onSalvar }) => {
  const [modo, setModo] = useState(curso.npsFormularioEnviado ? 'manual' : 'enviar'); // 'enviar' | 'manual'
  const [form, setForm] = useState({ ...curso, nps: '', taxaRetorno: '', dataFim: curso.dataFim || new Date().toISOString().slice(0,10), observacao: curso.observacao || '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const npsNum = Number(form.nps);
  const taxaNum = Number(form.taxaRetorno);
  const npsValido = form.nps !== '' && npsNum >= 0 && npsNum <= 10;
  const taxaValida = form.taxaRetorno !== '' && taxaNum >= 0 && taxaNum <= 100;
  const validoManual = npsValido && taxaValida;
  const colab = COLABORADORES.find(c => c.id === curso.colaboradorId);

  function enviarFormulario() {
    // Marca o curso como concluído com formulário pendente — o NPS/Taxa virão da resposta do colab.
    onSalvar({
      ...curso,
      status: 'concluido',
      dataFim: form.dataFim,
      npsFormularioEnviado: true,
      npsEnviadoEm: new Date().toISOString(),
      // Não popular nps/taxaRetorno aqui — o colab responde dentro do app
      nps: null,
      taxaRetorno: null,
    });
  }

  return (
    <Modal open onClose={onClose} title={`Finalizar curso · ${curso.curso}`} width={560}
      footer={<>
        <Button variant="outline" onClick={onClose}>Cancelar</Button>
        {modo === 'enviar' ? (
          <Button variant="primary" onClick={enviarFormulario}>Enviar formulário ao colaborador</Button>
        ) : (
          <Button variant="primary" onClick={() => validoManual && onSalvar({ ...form, nps: npsNum, taxaRetorno: taxaNum, status: 'concluido', npsFormularioEnviado: false })} disabled={!validoManual}>Salvar manualmente</Button>
        )}
      </>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Banner tone="info">
          <strong>{colab?.nome || '·'}</strong> concluiu o curso <strong>{curso.curso}</strong>. Você pode enviar o formulário de NPS pra ele responder dentro da plataforma (recomendado) — os dados serão calculados automaticamente. Ou pode preencher manualmente.
        </Banner>

        {/* Toggle modo */}
        <div style={{ display: 'flex', gap: 0, border: '1px solid var(--escalab-line)', borderRadius: 10, overflow: 'hidden', background: 'var(--escalab-paper)' }}>
          {[
            { id: 'enviar', label: 'Enviar formulário ao colaborador', icon: 'send', recomendado: true },
            { id: 'manual', label: 'Preencher manualmente', icon: 'edit' },
          ].map(o => (
            <button key={o.id} onClick={() => setModo(o.id)}
              style={{
                flex: 1, border: 0, padding: '10px 12px',
                background: modo === o.id ? '#fff' : 'transparent',
                color: modo === o.id ? 'var(--escalab-brand)' : 'var(--escalab-slate)',
                fontWeight: modo === o.id ? 700 : 600, fontSize: 12.5,
                cursor: 'pointer', fontFamily: 'var(--font-sans)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                borderBottom: modo === o.id ? '2px solid var(--escalab-brand)' : '2px solid transparent',
              }}>
              <Icon name={o.icon} size={12} />
              {o.label}
              {o.recomendado && <span style={{ fontSize: 9.5, background: 'var(--escalab-brand-tint)', color: 'var(--escalab-brand-deep)', padding: '1px 6px', borderRadius: 999, letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 700 }}>recomendado</span>}
            </button>
          ))}
        </div>

        <Field label="Data efetiva de finalização">
          <Input type="date" value={form.dataFim} onChange={v => set('dataFim', v)} />
        </Field>

        {modo === 'enviar' ? (
          <div style={{ background: 'var(--escalab-brand-tint)', border: '1px solid var(--escalab-brand-soft)', borderRadius: 10, padding: '14px 16px', fontSize: 13, color: 'var(--escalab-brand-deep)', lineHeight: 1.5 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, fontWeight: 700 }}>
              <Icon name="send" size={13} /> Como funciona o envio?
            </div>
            <ul style={{ margin: 0, paddingLeft: 18 }}>
              <li>O curso vira <strong>"concluído · aguardando resposta"</strong>.</li>
              <li><strong>{colab?.nome?.split(' ')[0] || 'O colaborador'}</strong> vê um banner no painel de Treinamentos com botão <em>"Avaliar curso · NPS"</em>.</li>
              <li>Ao responder (NPS 0-10 + taxa de retorno + observação), os dados aparecem aqui automaticamente.</li>
              <li>Se ele demorar, você pode preencher manualmente trocando o modo acima.</li>
            </ul>
          </div>
        ) : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="NPS · nota do colaborador (0 a 10) *">
                <Input type="number" min={0} max={10} step={0.1} value={form.nps} onChange={v => set('nps', v)} placeholder="Ex: 8" />
              </Field>
              <Field label="Taxa de retorno (%) *">
                <Input type="number" min={0} max={100} value={form.taxaRetorno} onChange={v => set('taxaRetorno', v)} placeholder="Ex: 80" />
              </Field>
            </div>
            <Field label="Observação · como o aprendizado virou prática">
              <textarea value={form.observacao} onChange={e => set('observacao', e.target.value)} rows={3}
                placeholder="Ex: aplicou em 2 projetos internos, treinou o time…"
                style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }} />
            </Field>
          </>
        )}
      </div>
    </Modal>
  );
};

// Modal de resposta NPS · COLABORADOR responde dentro do app
const ModalRespostaNpsSchool = ({ curso, onClose, onEnviado }) => {
  const cfg = getSchoolNpsConfig();
  const [nps, setNps] = useState(null);
  const [taxa, setTaxa] = useState('');
  const [obs, setObs] = useState('');
  const [extras, setExtras] = useState({});
  const taxaOk = !cfg.taxaRetornoObrigatorio || (taxa !== '' && Number(taxa) >= 0 && Number(taxa) <= 100);
  const comentarioOk = !cfg.comentarioObrigatorio || obs.trim().length > 0;
  const extrasOk = (cfg.extras || []).every(e => !e.obrigatoria || (extras[e.id] != null && String(extras[e.id]).trim() !== ''));
  const valido = nps != null && taxaOk && comentarioOk && extrasOk;
  function enviar() {
    if (!valido) return;
    const lista = getEscalabSchool();
    const atualizada = lista.map(c => c.id === curso.id ? {
      ...c,
      status: 'concluido',
      nps: Number(nps),
      taxaRetorno: taxa !== '' ? Number(taxa) : null,
      observacao: obs || c.observacao || '',
      extras: extras || {},
      npsRespondidoEm: new Date().toISOString(),
      npsRespondidoPor: curso.colaboradorId,
    } : c);
    salvarEscalabSchool(atualizada);
    onEnviado?.();
    onClose?.();
  }
  return (
    <Modal open onClose={onClose} title={`Avaliar curso · ${curso.curso}`} width={520}
      footer={<>
        <Button variant="outline" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" onClick={enviar} disabled={!valido}>Enviar avaliação</Button>
      </>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Banner tone="info">
          Você concluiu o curso <strong>{curso.curso}</strong> ({curso.instituicao}). Sua avaliação é confidencial e ajuda o RH a entender o impacto do Escalab School.
        </Banner>

        <div>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--escalab-ink)', marginBottom: 4 }}>
            {cfg.npsLabel} <span style={{ color:'#B3261E' }}>*</span>
          </div>
          {cfg.npsSublabel && <div style={{ fontSize: 11.5, color:'var(--escalab-mute)', marginBottom: 10 }}>{cfg.npsSublabel}</div>}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[0,1,2,3,4,5,6,7,8,9,10].map(n => {
              const sel = nps === n;
              const cor = n <= 6 ? '#B3261E' : n <= 8 ? '#E89B3B' : '#00836B';
              const bg  = n <= 6 ? '#FDECEC' : n <= 8 ? '#FFF7EB' : '#E6F5F1';
              return (
                <button key={n} onClick={() => setNps(n)}
                  style={{
                    width: 38, height: 38, borderRadius: 8,
                    border: sel ? `2px solid ${cor}` : '1px solid var(--escalab-line)',
                    background: sel ? bg : '#fff',
                    color: sel ? cor : 'var(--escalab-ink)',
                    cursor: 'pointer', fontWeight: 700, fontSize: 14,
                    fontFamily: 'var(--font-sans)',
                  }}>
                  {n}
                </button>
              );
            })}
          </div>
        </div>

        <Field label={`${cfg.taxaRetornoLabel}${cfg.taxaRetornoObrigatorio ? ' *' : ''}`}>
          <Input type="number" min={0} max={100} value={taxa} onChange={v => setTaxa(v)} placeholder="Ex: 80" />
        </Field>

        <Field label={`${cfg.comentarioLabel}${cfg.comentarioObrigatorio ? ' *' : ''}`}>
          <textarea value={obs} onChange={e => setObs(e.target.value)} rows={3}
            placeholder={cfg.comentarioPlaceholder || ''}
            style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }} />
        </Field>

        {/* Perguntas extras configuradas pelo RH */}
        {(cfg.extras || []).map(e => (
          <Field key={e.id} label={`${e.texto}${e.obrigatoria ? ' *' : ''}`}>
            {e.tipo === 'multipla' ? (
              <select value={extras[e.id] || ''} onChange={ev => setExtras(s => ({ ...s, [e.id]: ev.target.value }))}
                style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, background: '#fff', boxSizing: 'border-box' }}>
                <option value="">Selecione…</option>
                {(e.opcoes || []).map(op => <option key={op} value={op}>{op}</option>)}
              </select>
            ) : (
              <textarea value={extras[e.id] || ''} onChange={ev => setExtras(s => ({ ...s, [e.id]: ev.target.value }))} rows={2}
                style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }} />
            )}
          </Field>
        ))}
      </div>
    </Modal>
  );
};

// ── Modal: Editar formulário de NPS do Escalab School (GC) ────────────────────
const ModalEditarSchoolNpsForm = ({ onClose }) => {
  const [cfg, setCfg] = useState(() => getSchoolNpsConfig());
  const set = (k, v) => setCfg(c => ({ ...c, [k]: v }));
  const inp = { width:'100%', border:'1px solid var(--escalab-line)', borderRadius:8, padding:'9px 12px', fontSize:14, fontFamily:'var(--font-sans)', outline:0, boxSizing:'border-box' };
  function addExtra() { setCfg(c => ({ ...c, extras:[ ...(c.extras||[]), { id:'Q'+Date.now(), tipo:'texto', texto:'', opcoes:[], obrigatoria:false } ] })); }
  function updExtra(id, patch) { setCfg(c => ({ ...c, extras: (c.extras||[]).map(e => e.id === id ? { ...e, ...patch } : e) })); }
  function remExtra(id) { setCfg(c => ({ ...c, extras: (c.extras||[]).filter(e => e.id !== id) })); }
  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,15,18,.55)', backdropFilter:'blur(4px)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:18, width:'100%', maxWidth:560, maxHeight:'90vh', display:'flex', flexDirection:'column', animation:'popIn .22s var(--ease-out)' }}>
        <div style={{ padding:'18px 22px', borderBottom:'1px solid var(--escalab-line)', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:16, fontWeight:700 }}>Editar formulário de NPS · Escalab School</div>
            <div style={{ fontSize:12.5, color:'var(--escalab-mute)', marginTop:2 }}>Aplica-se a todas as avaliações de curso enviadas aos colaboradores</div>
          </div>
          <button onClick={onClose} style={{ border:0, background:'transparent', cursor:'pointer', color:'var(--escalab-mute)' }}><Icon name="close" size={18}/></button>
        </div>

        <div style={{ flex:1, overflowY:'auto', padding:'18px 22px', display:'flex', flexDirection:'column', gap:16 }}>
          <Field label="Pergunta da nota (0 a 10)">
            <input value={cfg.npsLabel} onChange={e => set('npsLabel', e.target.value)} style={inp} />
          </Field>
          <Field label="Texto auxiliar abaixo da nota">
            <input value={cfg.npsSublabel} onChange={e => set('npsSublabel', e.target.value)} style={inp} />
          </Field>
          <Field label="Pergunta da taxa de retorno">
            <input value={cfg.taxaRetornoLabel} onChange={e => set('taxaRetornoLabel', e.target.value)} style={inp} />
          </Field>
          <label style={{ display:'flex', gap:8, alignItems:'center', cursor:'pointer' }}>
            <input type="checkbox" checked={cfg.taxaRetornoObrigatorio} onChange={e => set('taxaRetornoObrigatorio', e.target.checked)} style={{ width:16, height:16 }} />
            <span style={{ fontSize:13.5, color:'var(--escalab-slate)' }}>Taxa de retorno obrigatória</span>
          </label>
          <Field label="Pergunta do comentário">
            <input value={cfg.comentarioLabel} onChange={e => set('comentarioLabel', e.target.value)} style={inp} />
          </Field>
          <Field label="Texto de exemplo dentro do comentário (placeholder)">
            <input value={cfg.comentarioPlaceholder} onChange={e => set('comentarioPlaceholder', e.target.value)} style={inp} />
          </Field>
          <label style={{ display:'flex', gap:8, alignItems:'center', cursor:'pointer' }}>
            <input type="checkbox" checked={cfg.comentarioObrigatorio} onChange={e => set('comentarioObrigatorio', e.target.checked)} style={{ width:16, height:16 }} />
            <span style={{ fontSize:13.5, color:'var(--escalab-slate)' }}>Comentário obrigatório</span>
          </label>

          <div style={{ background:'var(--escalab-paper)', border:'1px solid var(--escalab-line)', borderRadius:12, padding:'14px 16px' }}>
            <div style={{ fontSize:12, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase', color:'var(--escalab-mute)', marginBottom:12 }}>Perguntas extras ({(cfg.extras||[]).length})</div>
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {(cfg.extras||[]).map(e => (
                <div key={e.id} style={{ background:'#fff', border:'1px solid var(--escalab-line)', borderRadius:10, padding:'10px 12px' }}>
                  <div style={{ display:'flex', gap:8, alignItems:'center', marginBottom:8 }}>
                    <select value={e.tipo} onChange={ev => updExtra(e.id, { tipo: ev.target.value })} style={{ border:'1px solid var(--escalab-line)', borderRadius:7, padding:'6px 8px', fontSize:12.5, fontFamily:'var(--font-sans)', outline:0, background:'#fff' }}>
                      <option value="texto">Texto livre</option>
                      <option value="multipla">Múltipla escolha</option>
                    </select>
                    <input value={e.texto} onChange={ev => updExtra(e.id, { texto: ev.target.value })} placeholder="Texto da pergunta..." style={{ flex:1, border:'1px solid var(--escalab-line)', borderRadius:7, padding:'7px 10px', fontSize:13, fontFamily:'var(--font-sans)', outline:0 }} />
                    <button onClick={() => remExtra(e.id)} style={{ border:0, background:'transparent', cursor:'pointer', color:'#B3261E', padding:4 }}><Icon name="close" size={14}/></button>
                  </div>
                  {e.tipo === 'multipla' && (
                    <textarea value={(e.opcoes || []).join('\n')} onChange={ev => updExtra(e.id, { opcoes: ev.target.value.split('\n').map(o => o.trim()).filter(Boolean) })} rows={3} placeholder="Uma opção por linha..." style={{ width:'100%', border:'1px solid var(--escalab-line)', borderRadius:7, padding:'7px 10px', fontSize:13, fontFamily:'var(--font-sans)', outline:0, resize:'vertical', boxSizing:'border-box', marginBottom:8 }} />
                  )}
                  <label style={{ display:'flex', gap:7, alignItems:'center', cursor:'pointer' }}>
                    <input type="checkbox" checked={!!e.obrigatoria} onChange={ev => updExtra(e.id, { obrigatoria: ev.target.checked })} style={{ width:14, height:14 }} />
                    <span style={{ fontSize:12.5, color:'var(--escalab-slate)' }}>Obrigatória</span>
                  </label>
                </div>
              ))}
            </div>
            <button onClick={addExtra} style={{ border:'1px dashed var(--escalab-line)', borderRadius:8, padding:'7px 14px', cursor:'pointer', fontSize:12.5, fontFamily:'var(--font-sans)', color:'var(--escalab-brand)', background:'transparent', display:'flex', alignItems:'center', gap:5, marginTop:10 }}>
              <Icon name="plus" size={12}/> Adicionar pergunta extra
            </button>
          </div>
        </div>

        <div style={{ padding:'12px 22px', borderTop:'1px solid var(--escalab-line)', display:'flex', justifyContent:'space-between', gap:10, flexShrink:0 }}>
          <Button variant="ghost" onClick={() => setCfg({ ...SCHOOL_NPS_CONFIG_PADRAO })}>Restaurar padrão</Button>
          <div style={{ display:'flex', gap:10 }}>
            <Button variant="outline" onClick={onClose}>Cancelar</Button>
            <Button variant="primary" onClick={() => { salvarSchoolNpsConfig(cfg); onClose(); }}>Salvar formulário</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ScreenTreinamentos = ScreenTreinamentos;
