// ═══════════════════════════════════════════════════════════════
// SCREEN · Lista de Colaboradores
// ═══════════════════════════════════════════════════════════════

const DIREITOS_DEF = [
  { key: 'avisoPrevio',    label: 'Aviso prévio' },
  { key: 'comissao',       label: 'Comissão' },
  { key: 'plr',            label: 'PLR' },
  { key: 'decimoTerceiro', label: '13º proporcional' },
];

// ── Editor do formulário de desligamento: motivos de saída + campos extras ─────
const MOTIVO_CORES = ['#1F4A8A', '#6B3FA0', '#B3261E', '#E89B3B', '#7A0000', '#00836B', '#4A5560', '#0A7E8C'];
const EditorFormularioDeslig = ({ campos, motivos, onClose, onSalvar }) => {
  const [lista, setLista] = useState(() => campos.map(c => ({ ...c })));
  const [mots, setMots] = useState(() => (motivos || []).map(m => ({ ...m })));
  function add() { setLista(l => [...l, { id: 'cf' + Date.now().toString(36), label: '' }]); }
  function upd(i, label) { setLista(l => l.map((c, idx) => idx === i ? { ...c, label } : c)); }
  function rem(i) { setLista(l => l.filter((_, idx) => idx !== i)); }
  function addMot() { setMots(l => [...l, { id: 'mt' + Date.now().toString(36), label: '', cor: MOTIVO_CORES[l.length % MOTIVO_CORES.length] }]); }
  function updMot(i, label) { setMots(l => l.map((m, idx) => idx === i ? { ...m, label } : m)); }
  function remMot(i) { setMots(l => l.filter((_, idx) => idx !== i)); }
  function salvar() {
    onSalvar({
      campos: lista.filter(c => c.label.trim()),
      motivos: mots.filter(m => m.label.trim()).map(m => ({ ...m, cor: m.cor || '#4A5560' })),
    });
  }
  return (
    <Modal open onClose={onClose} title="Personalizar formulário de desligamento" width={480}
      footer={<>
        <Button variant="ghost" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" onClick={salvar}>Salvar</Button>
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 8 }}>Motivos de saída</div>
          <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginBottom: 10 }}>Edite, adicione ou remova os motivos disponíveis na hora de desligar.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {mots.map((m, i) => (
              <div key={m.id} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <div style={{ width: 12, height: 12, borderRadius: 3, background: m.cor || '#4A5560', flexShrink: 0 }} />
                <div style={{ flex: 1 }}><Input value={m.label} onChange={v => updMot(i, v)} placeholder="Nome do motivo" /></div>
                <button onClick={() => remMot(i)} title="Remover" style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 8, padding: '8px 10px', cursor: 'pointer', color: '#B3261E' }}><Icon name="close" size={14} /></button>
              </div>
            ))}
            <Button variant="outline" size="sm" icon="plus" onClick={addMot}>Adicionar motivo</Button>
          </div>
        </div>
        <div style={{ borderTop: '1px solid var(--escalab-line)', paddingTop: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 8 }}>Campos extras</div>
          <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginBottom: 10 }}>Campos extras aparecem no formulário e se aplicam a todos os desligamentos futuros.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {lista.length === 0 && <div style={{ fontSize: 13, color: 'var(--escalab-mute)', padding: '4px 0' }}>Nenhum campo extra ainda.</div>}
            {lista.map((c, i) => (
              <div key={c.id} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <div style={{ flex: 1 }}><Input value={c.label} onChange={v => upd(i, v)} placeholder="Nome do campo" /></div>
                <button onClick={() => rem(i)} title="Remover" style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 8, padding: '8px 10px', cursor: 'pointer', color: '#B3261E' }}><Icon name="close" size={14} /></button>
              </div>
            ))}
            <Button variant="outline" size="sm" icon="plus" onClick={add}>Adicionar campo</Button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

// ── Modal: desligar colaborador ────────────────────────────────────────────────
// Motivos primários (mesmo enum usado em screen-dashboard tipoPrimarioDe)
const TIPOS_PRIMARIOS_DESLIG = [
  { id: 'pedido',  label: 'Pedido do colaborador', cor: '#1F4A8A' },
  { id: 'empresa', label: 'Saída por parte da empresa', cor: '#B3261E' },
  { id: 'acordo',  label: 'Acordo entre as partes', cor: '#6B3FA0' },
];
const ModalDesligamento = ({ colaborador, user, onClose, onSalvar }) => {
  const [campos, setCampos] = useState(() => getCamposDesligForm());
  const [motivos, setMotivos] = useState(() => getMotivosDeslig());
  const [showEditor, setShowEditor] = useState(false);
  const [form, setForm] = useState(() => ({
    dataSaida: '', ultimoMes: '', tipoDesligamento: '', motivoId: '', motivoTexto: '',
    direitos: direitosVazios(), feedback: '', entrevistaDoc: null, entrevistaNome: '', extra: {},
  }));

  const isAdmin = user?.perfil === 'admin';
  const valido = form.dataSaida && form.tipoDesligamento && form.motivoId && (form.motivoId !== 'outro' || form.motivoTexto.trim());

  function setD(key, patch) { setForm(f => ({ ...f, direitos: { ...f.direitos, [key]: { ...f.direitos[key], ...patch } } })); }
  function handleArquivo(e) {
    const file = e.target.files[0]; if (!file) return;
    const r = new FileReader();
    r.onload = ev => setForm(f => ({ ...f, entrevistaDoc: ev.target.result, entrevistaNome: file.name }));
    r.readAsDataURL(file);
  }
  function salvar() {
    onSalvar({
      id: gerarIdDeslig(), colaboradorId: colaborador.id,
      nome: colaborador.nome, setor: colaborador.setor, cargo: colaborador.cargo,
      categoriaKey: getCategoriaKey(colaborador.id),
      dataSaida: form.dataSaida, ultimoMes: form.ultimoMes,
      tipoDesligamento: form.tipoDesligamento,
      motivoId: form.motivoId, motivoTexto: form.motivoTexto,
      direitos: form.direitos, feedback: form.feedback,
      entrevistaDoc: form.entrevistaDoc, entrevistaNome: form.entrevistaNome,
      checklist: { inicio: true, documentos: false, entrevista: false, retiradaAcesso: false, finalizado: false },
      camposExtra: campos.map(c => ({ label: c.label, valor: form.extra[c.id] || '' })),
      registradoEm: new Date().toISOString().slice(0, 10),
    });
  }

  return (
    <Modal open onClose={onClose} title={`Desligar · ${colaborador.nome.split(' ').slice(0, 3).join(' ')}`} width={620}
      footer={<>
        <Button variant="ghost" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" onClick={salvar} disabled={!valido}>Confirmar desligamento</Button>
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <Banner tone="warn">O colaborador será movido para <b>Inativos</b>. Você pode reativá-lo depois, se necessário.</Banner>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Data de saída"><Input type="date" value={form.dataSaida} onChange={v => setForm(f => ({ ...f, dataSaida: v }))} /></Field>
          <Field label="Último mês trabalhado"><Input type="month" value={form.ultimoMes} onChange={v => setForm(f => ({ ...f, ultimoMes: v }))} /></Field>
        </div>

        <Field label="Motivo primário">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {TIPOS_PRIMARIOS_DESLIG.map(t => {
              const sel = form.tipoDesligamento === t.id;
              return (
                <button key={t.id} onClick={() => setForm(f => ({ ...f, tipoDesligamento: t.id }))} style={{
                  border: `1px solid ${sel ? t.cor : 'var(--escalab-line)'}`, background: sel ? t.cor + '15' : '#fff', color: sel ? t.cor : 'var(--escalab-slate)',
                  borderRadius: 999, padding: '7px 14px', cursor: 'pointer', fontSize: 13, fontFamily: 'var(--font-sans)', fontWeight: sel ? 700 : 500,
                }}>{t.label}</button>
              );
            })}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginTop: 6 }}>Classificação macro · alimenta o gráfico de motivos do painel.</div>
        </Field>

        <Field label="Motivo secundário · detalhado">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {motivos.map(m => {
              const sel = form.motivoId === m.id;
              return (
                <button key={m.id} onClick={() => setForm(f => ({ ...f, motivoId: m.id }))} style={{
                  border: `1px solid ${sel ? m.cor : 'var(--escalab-line)'}`, background: sel ? m.cor + '15' : '#fff', color: sel ? m.cor : 'var(--escalab-slate)',
                  borderRadius: 999, padding: '7px 14px', cursor: 'pointer', fontSize: 13, fontFamily: 'var(--font-sans)', fontWeight: sel ? 700 : 500,
                }}>{m.label}</button>
              );
            })}
          </div>
          {form.motivoId === 'outro' && <div style={{ marginTop: 10 }}><Input placeholder="Descreva o motivo" value={form.motivoTexto} onChange={v => setForm(f => ({ ...f, motivoTexto: v }))} /></div>}
        </Field>

        <Field label="Direitos a receber">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {DIREITOS_DEF.map(dr => {
              const st = form.direitos[dr.key];
              return (
                <div key={dr.key} style={{ display: 'flex', alignItems: 'center', gap: 12, border: '1px solid var(--escalab-line)', borderRadius: 10, padding: '8px 12px', background: st.ativo ? 'var(--escalab-brand-tint)' : '#fff' }}>
                  <button onClick={() => setD(dr.key, { ativo: !st.ativo })} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, flex: 1, fontFamily: 'var(--font-sans)' }}>
                    <div style={{ width: 18, height: 18, borderRadius: 5, border: `2px solid ${st.ativo ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`, background: st.ativo ? 'var(--escalab-brand)' : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: '#fff' }}>
                      {st.ativo && <Icon name="check" size={12} />}
                    </div>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--escalab-ink)' }}>{dr.label}</span>
                  </button>
                  {st.ativo && <div style={{ width: 160 }}><Input type="number" prefix="R$" value={st.valor || ''} onChange={v => setD(dr.key, { valor: Number(v) || 0 })} placeholder="0,00" /></div>}
                </div>
              );
            })}
          </div>
        </Field>

        {campos.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            {campos.map(c => (
              <Field key={c.id} label={c.label}>
                <Input value={form.extra[c.id] || ''} onChange={v => setForm(f => ({ ...f, extra: { ...f.extra, [c.id]: v } }))} />
              </Field>
            ))}
          </div>
        )}

        <Field label="Feedback sobre o desligamento">
          <textarea value={form.feedback} onChange={e => setForm(f => ({ ...f, feedback: e.target.value }))} rows={3}
            placeholder="Observações, contexto, aprendizados…"
            style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '10px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }} />
        </Field>

        <Field label="Documento · entrevista de desligamento">
          {form.entrevistaDoc ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '8px 12px' }}>
              <Icon name="file" size={15} />
              <span style={{ fontSize: 13, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{form.entrevistaNome || 'Documento anexado'}</span>
              <button onClick={() => setForm(f => ({ ...f, entrevistaDoc: null, entrevistaNome: '' }))} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-mute)' }}><Icon name="close" size={14} /></button>
            </div>
          ) : (
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, border: '1px dashed var(--escalab-line)', borderRadius: 8, padding: '10px 12px', cursor: 'pointer', color: 'var(--escalab-mute)', fontSize: 13 }}>
              <Icon name="upload" size={14} /> Anexar documento (PDF, imagem…)
              <input type="file" style={{ display: 'none' }} onChange={handleArquivo} />
            </label>
          )}
        </Field>

        {isAdmin && (
          <button onClick={() => setShowEditor(true)} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-brand-deep)', fontSize: 12.5, fontFamily: 'var(--font-sans)', display: 'flex', alignItems: 'center', gap: 6, alignSelf: 'flex-start' }}>
            <Icon name="settings" size={13} /> Personalizar formulário (motivos e campos)
          </button>
        )}
      </div>

      {showEditor && <EditorFormularioDeslig campos={campos} motivos={motivos} onClose={() => setShowEditor(false)} onSalvar={({ campos: nc, motivos: nm }) => { setCampos(nc); salvarCamposDesligForm(nc); setMotivos(nm); salvarMotivosDeslig(nm); setShowEditor(false); }} />}
    </Modal>
  );
};

// ── Modal: detalhe do colaborador inativo (checklist + feedback) ──────────────
const ModalInativo = ({ desligamento: d, podeEditar, onClose, onChange, onReativar }) => {
  const [feedback, setFeedback] = useState(d.feedback || '');
  const motivo = getMotivoDeslig(d.motivoId);
  const direitosAtivos = DIREITOS_DEF.filter(dr => d.direitos?.[dr.key]?.ativo);
  const totalDireitos = direitosAtivos.reduce((s, dr) => s + (Number(d.direitos[dr.key].valor) || 0), 0);
  const feitas = DESLIG_ETAPAS.filter(e => d.checklist?.[e.id]).length;
  const pct = Math.round(feitas / DESLIG_ETAPAS.length * 100);
  const catLabel = CATEGORIA_LABEL[d.categoriaKey] || (d.categoriaKey === 'fixo' ? 'Fixo' : 'Associado');
  const fmt = v => 'R$ ' + (Number(v) || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2 });

  return (
    <Modal open onClose={onClose} title={d.nome} width={620}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <Tag tone={d.categoriaKey === 'fixo' ? 'brand' : 'neutral'} size="sm">{catLabel}</Tag>
          {motivo && <Tag tone="neutral" size="sm">{motivo.label}{d.motivoId === 'outro' && d.motivoTexto ? `: ${d.motivoTexto}` : ''}</Tag>}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          {[
            { l: 'Setor', v: d.setor },
            { l: 'Data de saída', v: d.dataSaida ? d.dataSaida.split('-').reverse().join('/') : '·' },
            { l: 'Último mês', v: d.ultimoMes ? d.ultimoMes.split('-').reverse().join('/') : '·' },
          ].map(x => (
            <div key={x.l}><div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--escalab-mute)', marginBottom: 3 }}>{x.l}</div><div style={{ fontSize: 13.5, color: 'var(--escalab-ink)', fontWeight: 500 }}>{x.v}</div></div>
          ))}
        </div>

        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <span style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--escalab-mute)', flex: 1 }}>Checklist de desligamento</span>
            <span style={{ fontSize: 12, fontWeight: 700, color: pct === 100 ? 'var(--escalab-brand-deep)' : '#E89B3B' }}>{feitas}/{DESLIG_ETAPAS.length}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {DESLIG_ETAPAS.map(e => {
              const on = !!d.checklist?.[e.id];
              return (
                <button key={e.id} onClick={() => podeEditar && onChange({ checklist: { ...d.checklist, [e.id]: !on } })} disabled={!podeEditar} style={{
                  display: 'flex', alignItems: 'center', gap: 10, border: '1px solid var(--escalab-line)', borderRadius: 10, padding: '10px 12px',
                  background: on ? 'var(--escalab-brand-tint)' : '#fff', cursor: podeEditar ? 'pointer' : 'default', fontFamily: 'var(--font-sans)', textAlign: 'left', width: '100%',
                }}>
                  <div style={{ width: 20, height: 20, borderRadius: 6, border: `2px solid ${on ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`, background: on ? 'var(--escalab-brand)' : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: '#fff' }}>
                    {on && <Icon name="check" size={13} />}
                  </div>
                  <span style={{ fontSize: 13.5, fontWeight: on ? 600 : 500, color: on ? 'var(--escalab-brand-deep)' : 'var(--escalab-ink)' }}>{e.label}</span>
                </button>
              );
            })}
          </div>
        </div>

        {direitosAtivos.length > 0 && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--escalab-mute)', marginBottom: 10 }}>Direitos a receber</div>
            <div style={{ border: '1px solid var(--escalab-line)', borderRadius: 10, overflow: 'hidden' }}>
              {direitosAtivos.map(dr => (
                <div key={dr.key} style={{ display: 'flex', justifyContent: 'space-between', padding: '9px 14px', borderBottom: '1px solid var(--escalab-line)', fontSize: 13.5 }}>
                  <span style={{ color: 'var(--escalab-slate)' }}>{dr.label}</span>
                  <span style={{ fontWeight: 700, color: 'var(--escalab-ink)' }}>{fmt(d.direitos[dr.key].valor)}</span>
                </div>
              ))}
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 14px', background: 'var(--escalab-paper)', fontSize: 14 }}>
                <span style={{ fontWeight: 700 }}>Total</span>
                <span style={{ fontWeight: 800, color: 'var(--escalab-brand-deep)' }}>{fmt(totalDireitos)}</span>
              </div>
            </div>
          </div>
        )}

        {d.entrevistaDoc && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--escalab-mute)', marginBottom: 8 }}>Entrevista de desligamento</div>
            <a href={d.entrevistaDoc} download={d.entrevistaNome || 'entrevista-desligamento'} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '8px 12px', textDecoration: 'none', color: 'var(--escalab-brand-deep)', fontSize: 13, fontWeight: 600 }}>
              <Icon name="download" size={14} /> {d.entrevistaNome || 'Baixar documento'}
            </a>
          </div>
        )}

        <div>
          <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--escalab-mute)', marginBottom: 8 }}>Feedback sobre o desligamento</div>
          {podeEditar ? (
            <textarea value={feedback} onChange={e => setFeedback(e.target.value)} onBlur={() => feedback !== d.feedback && onChange({ feedback })} rows={3}
              placeholder="Observações, contexto, aprendizados…"
              style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '10px 12px', fontSize: 14, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }} />
          ) : (
            <div style={{ fontSize: 13.5, color: d.feedback ? 'var(--escalab-ink)' : 'var(--escalab-mute)', lineHeight: 1.5 }}>{d.feedback || 'Sem feedback.'}</div>
          )}
        </div>

        {(d.camposExtra || []).filter(c => c.valor).length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {d.camposExtra.filter(c => c.valor).map((c, i) => (
              <div key={i}><div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--escalab-mute)', marginBottom: 3 }}>{c.label}</div><div style={{ fontSize: 13.5, color: 'var(--escalab-ink)' }}>{c.valor}</div></div>
            ))}
          </div>
        )}

        {podeEditar && d.colaboradorId != null && (
          <div style={{ borderTop: '1px solid var(--escalab-line)', paddingTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
            <Button variant="outline" size="sm" icon="unlock" onClick={onReativar}>Reativar colaborador</Button>
          </div>
        )}
      </div>
    </Modal>
  );
};

const ScreenColaboradores = ({ user, onVerPerfil, podeVerNotas }) => {
  const [busca, setBusca] = useState('');
  const [filtroSetor, setFiltroSetor] = useState('');
  const [filtroNivel, setFiltroNivel] = useState('');
  const [aba, setAba] = useState('ativos');           // ativos | inativos
  const [versao, setVersao] = useState(0);            // força refresh após desligar
  const [modalDeslig, setModalDeslig] = useState(null); // colaborador a desligar
  const [inativoSel, setInativoSel] = useState(null);   // registro de desligamento aberto
  // Lista real do Supabase (null = ainda nao carregou ou indisponivel - usa seed local)
  const [colabsSb, setColabsSb] = useState(null);
  useEffect(() => {
    let cancelado = false;
    (async () => {
      if (typeof getColaboradoresSupabase !== 'function') return;
      const arr = await getColaboradoresSupabase();
      if (!cancelado && arr) setColabsSb(arr);
    })();
    return () => { cancelado = true; };
  }, []);

  const podeDesligar = user.perfil === 'admin' || user.perfil === 'financeiro';
  function refresh() { setVersao(v => v + 1); }

  const inativos = useMemo(() => {
    const q = busca.toLowerCase();
    return getDesligamentos().filter(d => {
      const matchBusca = !busca || (d.nome || '').toLowerCase().includes(q) || (d.cargo || '').toLowerCase().includes(q);
      const matchSetor = !filtroSetor || d.setor === filtroSetor;
      return matchBusca && matchSetor;
    });
  }, [busca, filtroSetor, versao]);

  // Visão completa de Colaboradores: RH (admin) e Financeiro. Diretoria já entra como admin.
  // Gestor vê SOMENTE seus liderados (+ ele próprio + seu líder direto), sem o resto da empresa.
  const lista = useMemo(() => {
    // Se o Supabase trouxe a lista, usamos ela (RLS ja filtrou). Senao, seed local.
    const ativos = colabsSb
      ? colabsSb.filter(c => c.ativo !== false)
      : getColaboradoresAtivos();
    let universo = ativos;
    if (user?.perfil === 'gestor') {
      const meuLider  = ativos.find(c => c.nome === user.gestorNome);
      const meusSubs  = ativos.filter(c => c.gestorNome === user.nome);
      const eu        = ativos.find(c => c.id === user.id);
      universo = [...(meuLider ? [meuLider] : []), ...(eu ? [eu] : []), ...meusSubs]
        .filter((c, i, a) => a.findIndex(x => x.id === c.id) === i);
    }
    const filtrado = universo.filter(c => {
      const q = busca.toLowerCase();
      const matchBusca = !busca || c.nome.toLowerCase().includes(q) || c.cargo.toLowerCase().includes(q);
      const matchSetor = !filtroSetor || c.setor === filtroSetor;
      const matchNivel = !filtroNivel || c.nivel === filtroNivel;
      return matchBusca && matchSetor && matchNivel;
    });
    // Para gestor (com filtros): mantém ordem líder → eu → liderados
    if (user?.perfil === 'gestor' && !busca && !filtroSetor && !filtroNivel) {
      const meuLider = filtrado.find(c => c.nome === user.gestorNome);
      const meusSubs = filtrado.filter(c => c.gestorNome === user.nome);
      const eu       = filtrado.find(c => c.id === user.id);
      return [...(meuLider ? [meuLider] : []), ...(eu ? [eu] : []), ...meusSubs]
        .filter((c, i, a) => a.findIndex(x => x.id === c.id) === i);
    }
    return filtrado;
  }, [busca, filtroSetor, filtroNivel, versao, user, colabsSb]);

  function getUltimaAv(id) {
    const avs = getAvaliacoesColaborador(id).sort((a, b) => (b.data || '').localeCompare(a.data || ''));
    return avs[0] || null;
  }

  function getNivelLabel(nivel) {
    return { diretor: 'Diretor(a)', lider: 'Líder', liderado: 'Colaborador' }[nivel] || nivel;
  }

  const nivelTone = { diretor: 'dark', lider: 'brand', liderado: 'neutral' };

  const TIPO_LABEL = { projetos: 'Projetos', editais: 'Editais', redes: 'Redes', vb: 'VB' };
  function getCatTag(id) {
    const { categoria, tipoAssociado } = getCategoriaColaborador(id);
    if (categoria === 'fixo') return { label: 'Fixo', tone: 'brand' };
    return { label: `Assoc. ${TIPO_LABEL[tipoAssociado] || ''}`, tone: 'neutral' };
  }

  return (
    <div style={{ animation: 'fadeIn .22s var(--ease-out)' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 24, gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-brand)', marginBottom: 4 }}>Pessoas</div>
          <h2 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>Colaboradores</h2>
          <p style={{ fontSize: 13.5, color: 'var(--escalab-slate)', margin: '4px 0 0' }}>
            {aba === 'inativos' ? `${inativos.length} desligado${inativos.length !== 1 ? 's' : ''}` : `${lista.length} colaborador${lista.length !== 1 ? 'es' : ''} ativo${lista.length !== 1 ? 's' : ''}`}
          </p>
        </div>
        {podeDesligar && (
          <div style={{ display: 'flex', gap: 4, background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: 3 }}>
            {[{ id: 'ativos', label: 'Ativos', n: lista.length }, { id: 'inativos', label: 'Inativos', n: getDesligamentos().length }].map(o => (
              <button key={o.id} onClick={() => setAba(o.id)} style={{
                border: 0, borderRadius: 8, padding: '7px 16px', cursor: 'pointer', fontSize: 13, fontFamily: 'var(--font-sans)',
                fontWeight: aba === o.id ? 700 : 500,
                background: aba === o.id ? '#fff' : 'transparent',
                color: aba === o.id ? 'var(--escalab-ink)' : 'var(--escalab-mute)',
                boxShadow: aba === o.id ? '0 1px 6px rgba(0,0,0,.1)' : 'none', transition: 'all .15s',
                display: 'flex', alignItems: 'center', gap: 7,
              }}>
                {o.label}
                <span style={{ fontSize: 11, fontWeight: 700, background: aba === o.id ? 'var(--escalab-brand-tint)' : 'var(--escalab-line)', color: aba === o.id ? 'var(--escalab-brand-deep)' : 'var(--escalab-mute)', borderRadius: 999, padding: '1px 7px' }}>{o.n}</span>
              </button>
            ))}
          </div>
        )}
      </div>

      <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
        <div style={{ position: 'relative', flex: '1 1 220px' }}>
          <div style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', color: 'var(--escalab-mute)', pointerEvents: 'none' }}>
            <Icon name="search" size={15} />
          </div>
          <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar por nome ou cargo…"
            style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px 9px 34px', fontSize: 14, fontFamily: 'var(--font-sans)', outline: 0, background: '#fff' }} />
        </div>
        <SelectInput value={filtroSetor} onChange={setFiltroSetor} placeholder="Todos os setores"
          options={SETORES.map(s => ({ value: s, label: s }))} />
        <SelectInput value={filtroNivel} onChange={setFiltroNivel} placeholder="Todos os níveis"
          options={[{ value: 'diretor', label: 'Diretor(a)' }, { value: 'lider', label: 'Líder' }, { value: 'liderado', label: 'Colaborador' }]} />
        {(busca || filtroSetor || filtroNivel) && (
          <Button variant="ghost" size="sm" icon="close" onClick={() => { setBusca(''); setFiltroSetor(''); setFiltroNivel(''); }}>Limpar</Button>
        )}
      </div>

      {/* Para gestor: seção destacada do seu círculo (líder + liderados) — desativada porque a lista
          completa já é restrita ao círculo. Mantido o código atrás de uma flag (false) caso o time
          decida voltar a mostrar como banner separado. */}
      {false && user?.perfil === 'gestor' && !busca && !filtroSetor && !filtroNivel && (() => {
        const meuLider   = COLABORADORES.find(c => c.nome === user.gestorNome);
        const meusSubs   = COLABORADORES.filter(c => c.gestorNome === user.nome);
        const eu         = COLABORADORES.find(c => c.id === user.id);
        const destaque   = [...(meuLider ? [meuLider] : []), ...(eu ? [eu] : []), ...meusSubs].filter((c,i,a) => a.findIndex(x=>x.id===c.id)===i);
        if (destaque.length === 0) return null;
        return (
          <div style={{ background:'linear-gradient(135deg, #E6F5F1 0%, #F0FBF7 100%)', border:'2px solid var(--escalab-brand-soft)', borderRadius:16, padding:'16px 20px', marginBottom:14 }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
              <div style={{ width:24, height:24, borderRadius:6, background:'var(--escalab-brand)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="users" size={13} />
              </div>
              <span style={{ fontSize:12, fontWeight:700, color:'var(--escalab-brand-deep)', textTransform:'uppercase', letterSpacing:'.1em' }}>
                Seu Círculo
              </span>
              <span style={{ fontSize:11, color:'var(--escalab-brand)', background:'var(--escalab-brand-tint)', borderRadius:10, padding:'1px 8px', fontWeight:600 }}>
                {destaque.length} pessoa{destaque.length > 1 ? 's' : ''}
              </span>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:8 }}>
              {destaque.map(c => {
                const isMeuLider = c.nome === user.gestorNome;
                const isMim      = c.id === user.id;
                const isLiderado = c.gestorNome === user.nome;
                const papel      = isMeuLider ? 'Meu líder' : isMim ? 'Você' : 'Seu liderado';
                const papelCor   = isMeuLider ? '#1F4A8A' : isMim ? '#00836B' : '#6B3FA0';
                const papelBg    = isMeuLider ? '#EEF3FA' : isMim ? '#E6F5F1' : '#F4EEFF';
                return (
                  <div key={c.id} onClick={() => onVerPerfil(c)}
                    style={{ display:'flex', gap:10, alignItems:'center', padding:'10px 14px', background:'#fff', borderRadius:12, cursor:'pointer', border:`1px solid ${papelCor}30`, boxShadow:`0 2px 8px ${papelCor}12`, transition:'all .15s' }}
                    onMouseEnter={e => { e.currentTarget.style.boxShadow=`0 6px 20px ${papelCor}25`; e.currentTarget.style.transform='translateY(-1px)'; }}
                    onMouseLeave={e => { e.currentTarget.style.boxShadow=`0 2px 8px ${papelCor}12`; e.currentTarget.style.transform='none'; }}>
                    <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={36} />
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:13, fontWeight:600, color:'var(--escalab-ink)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{c.nome.split(' ').slice(0,3).join(' ')}</div>
                      <div style={{ fontSize:11.5, color:'var(--escalab-mute)', marginTop:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{c.setor}</div>
                    </div>
                    <span style={{ fontSize:10.5, fontWeight:700, background:papelBg, color:papelCor, borderRadius:6, padding:'2px 8px', flexShrink:0 }}>{papel}</span>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })()}

      {aba === 'ativos' ? (
      <Card pad={0}>
        <table>
          <thead>
            <tr>
              <th>Colaborador</th>
              <th>Setor</th>
              <th>Nível</th>
              <th>Tempo empresa</th>
              <th>Última avaliação</th>
              <th>Nota</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {lista.length === 0 ? (
              <tr><td colSpan={7} style={{ textAlign: 'center', padding: 32, color: 'var(--escalab-mute)' }}>Nenhum colaborador encontrado</td></tr>
            ) : lista.map(c => {
              const av = getUltimaAv(c.id);
              const anos = Math.floor(c.tempoEmpresa / 12);
              const mesesRest = c.tempoEmpresa % 12;
              const tempoStr = anos >= 1
                ? `${anos} ano${anos > 1 ? 's' : ''}${mesesRest > 0 ? ` ${mesesRest}m` : ''}`
                : `${c.tempoEmpresa} meses`;
              const verNota = podeVerNotas ? podeVerNotas(c.id) : (user?.perfil === 'admin');
              // Highlight para gestor
              const isLideradoDele = user?.perfil === 'gestor' && c.gestorNome === user.nome;
              const isLiderDele    = user?.perfil === 'gestor' && c.nome === user.gestorNome;
              const rowBg = isLiderDele ? '#EEF3FA' : isLideradoDele ? '#F4EEFF' : 'transparent';
              return (
                <tr key={c.id} onClick={() => onVerPerfil(c)} style={{ cursor: 'pointer', background: rowBg }}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                      <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={34} />
                      <div>
                        <div style={{ fontWeight: 500, fontSize: 13.5, color: 'var(--escalab-ink)' }}>
                          {c.nome}
                          {isLiderDele && <span style={{ fontSize:10.5, background:'#EEF3FA', color:'#1F4A8A', borderRadius:5, padding:'1px 7px', marginLeft:7, fontWeight:700 }}>Meu líder</span>}
                          {isLideradoDele && <span style={{ fontSize:10.5, background:'#F4EEFF', color:'#6B3FA0', borderRadius:5, padding:'1px 7px', marginLeft:7, fontWeight:700 }}>Liderado</span>}
                        </div>
                        <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 1 }}>{c.cargo}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ color: 'var(--escalab-slate)', fontSize: 13 }}>{c.setor}</td>
                  <td>
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                    <Tag tone={nivelTone[c.nivel]} size="xs">{getNivelLabel(c.nivel)}</Tag>
                    {(() => { const ct = getCatTag(c.id); return <Tag tone={ct.tone} size="xs">{ct.label}</Tag>; })()}
                  </div>
                </td>
                  <td style={{ color: 'var(--escalab-slate)', fontSize: 13 }}>{tempoStr}</td>
                  <td style={{ color: 'var(--escalab-slate)', fontSize: 12.5 }}>{av ? av.cicloId.replace('C', '') : '·'}</td>
                  <td>
                    {!verNota ? (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)' }}>
                        <Icon name="lock" size={13} />
                        <span style={{ fontSize: 12 }}>Bloqueada</span>
                      </div>
                    ) : av?.nota != null ? (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <div style={{ flex: 1, minWidth: 60, height: 5, background: 'var(--escalab-line)', borderRadius: 999 }}>
                          <div style={{ width: (av.nota / 5 * 100) + '%', height: '100%', background: av.nota >= 4 ? 'var(--escalab-brand)' : av.nota >= 3 ? '#E89B3B' : '#E05050', borderRadius: 999 }} />
                        </div>
                        <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--escalab-brand-deep)' }}>{av.nota.toFixed(1)}</span>
                      </div>
                    ) : <span style={{ color: 'var(--escalab-mute)', fontSize: 12 }}>Sem dados</span>}
                  </td>
                  <td>
                    <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end', alignItems: 'center' }}>
                      {podeDesligar && (
                        <button onClick={e => { e.stopPropagation(); setModalDeslig(c); }} title="Desligar colaborador"
                          style={{ border: '1px solid #F4C7C3', background: '#fff', color: '#B3261E', borderRadius: 7, padding: '5px 10px', cursor: 'pointer', fontSize: 12, fontFamily: 'var(--font-sans)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap' }}
                          onMouseEnter={e => { e.currentTarget.style.background = '#FDECEC'; }}
                          onMouseLeave={e => { e.currentTarget.style.background = '#fff'; }}>
                          <Icon name="logout" size={12} /> Desligar
                        </button>
                      )}
                      <Button variant="ghost" size="sm" icon="chev_right" onClick={e => { e.stopPropagation(); onVerPerfil(c); }}>Ver perfil</Button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
      ) : (
      <Card pad={0}>
        <table>
          <thead>
            <tr>
              <th>Colaborador</th>
              <th>Setor</th>
              <th>Categoria</th>
              <th>Motivo</th>
              <th>Data de saída</th>
              <th>Processo</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {inativos.length === 0 ? (
              <tr><td colSpan={7} style={{ textAlign: 'center', padding: 32, color: 'var(--escalab-mute)' }}>Nenhum colaborador desligado</td></tr>
            ) : inativos.map(d => {
              const motivo = getMotivoDeslig(d.motivoId);
              const feitas = DESLIG_ETAPAS.filter(e => d.checklist?.[e.id]).length;
              const pct = Math.round(feitas / DESLIG_ETAPAS.length * 100);
              const catLabel = CATEGORIA_LABEL[d.categoriaKey] || (d.categoriaKey === 'fixo' ? 'Fixo' : 'Associado');
              return (
                <tr key={d.id} onClick={() => setInativoSel(d)} style={{ cursor: 'pointer' }}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                      <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--escalab-line)', color: 'var(--escalab-mute)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="user" size={16} /></div>
                      <div>
                        <div style={{ fontWeight: 500, fontSize: 13.5, color: 'var(--escalab-ink)' }}>{d.nome}</div>
                        <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 1 }}>{d.cargo}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ color: 'var(--escalab-slate)', fontSize: 13 }}>{d.setor}</td>
                  <td><Tag tone={d.categoriaKey === 'fixo' ? 'brand' : 'neutral'} size="xs">{catLabel}</Tag></td>
                  <td>{motivo ? <Tag tone="neutral" size="xs">{motivo.label}</Tag> : '·'}</td>
                  <td style={{ color: 'var(--escalab-slate)', fontSize: 13 }}>{d.dataSaida ? d.dataSaida.split('-').reverse().join('/') : '·'}</td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ flex: 1, minWidth: 60, height: 5, background: 'var(--escalab-line)', borderRadius: 999 }}>
                        <div style={{ width: pct + '%', height: '100%', background: pct === 100 ? 'var(--escalab-brand)' : '#E89B3B', borderRadius: 999 }} />
                      </div>
                      <span style={{ fontSize: 12, color: 'var(--escalab-mute)', whiteSpace: 'nowrap' }}>{feitas}/{DESLIG_ETAPAS.length}</span>
                    </div>
                  </td>
                  <td><Button variant="ghost" size="sm" icon="chev_right" onClick={e => { e.stopPropagation(); setInativoSel(d); }}>Detalhes</Button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
      )}

      {modalDeslig && (
        <ModalDesligamento
          colaborador={modalDeslig}
          user={user}
          onClose={() => setModalDeslig(null)}
          onSalvar={rec => {
            salvarDesligamento(rec);
            // Pedido Maria/docx (3): criar card automático no kanban "Desligamento"
            // da nova Movimentação Profissional para que o Financeiro receba o aviso.
            try {
              criarMovDesligamentoAuto({
                colaborador: modalDeslig,
                registroDeslig: rec,
                atorNome:  user?.nome,
                atorEmail: user?.email,
              });
            } catch (err) { console.warn('Falha ao criar card auto de desligamento:', err); }
            setModalDeslig(null);
            setAba('inativos');
            refresh();
          }}
        />
      )}
      {inativoSel && (
        <ModalInativo
          desligamento={inativoSel}
          podeEditar={podeDesligar}
          onClose={() => setInativoSel(null)}
          onChange={upd => { atualizarDesligamento(inativoSel.id, upd); setInativoSel(s => ({ ...s, ...upd })); refresh(); }}
          onReativar={() => { if (inativoSel.colaboradorId != null) { reativarColaborador(inativoSel.colaboradorId); setInativoSel(null); setAba('ativos'); refresh(); } }}
        />
      )}
    </div>
  );
};

window.ScreenColaboradores = ScreenColaboradores;
