// ═══════════════════════════════════════════════════════════════
// SCREEN · AVD & Feedback · Módulo Completo
// ═══════════════════════════════════════════════════════════════

// ── Dados do módulo AVD ──────────────────────────────────────────────────────

const AVD_BLOCOS = [
  { id: 'tecnico',        label: 'Técnico',         cor: '#1F4A8A', num: 1 },
  { id: 'comportamental', label: 'Comportamental',  cor: '#7A4A00', num: 2 },
  { id: 'metas',          label: 'Metas',            cor: '#005E4D', num: 3 },
  { id: 'lideranca',      label: 'Liderança',        cor: '#6B3FA0', num: 4 },
];

const AVD_BANCO = {
  default: {
    tecnico: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente',   pergunta: 'Domínio técnico das ferramentas e processos da área' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente',   pergunta: 'Qualidade e acurácia das entregas produzidas' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Com que frequência entrega dentro do prazo e com a qualidade esperada?' },
    ],
    comportamental: [
      { tipo: 'choice', opcoes: ['Sempre proativa', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Como você avalia a proatividade na busca por soluções quando surgem obstáculos?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'],           pergunta: 'A comunicação com a equipe é clara, colaborativa e respeitosa?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente',   pergunta: 'Abertura a feedbacks e disposição para aprendizado contínuo' },
    ],
    metas: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Superou',     pergunta: 'As metas do período foram cumpridas dentro do prazo e com qualidade esperada?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Superou',     pergunta: 'Alinhamento com os OKRs e objetivos estratégicos do trimestre' },
      { tipo: 'text',  opcional: true,                           pergunta: 'Cite um resultado concreto que este colaborador entregou neste ciclo.' },
    ],
    lideranca: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente',   pergunta: 'Como você avalia a capacidade de delegação e acompanhamento de tarefas da equipe?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'O colaborador promove um ambiente de trabalho colaborativo e psicologicamente seguro?' },
      { tipo: 'text',  opcional: true,                           pergunta: 'Descreva um exemplo recente de liderança positiva deste colaborador.' },
    ],
  },
};

// ── Tipos de avaliação (eixos da AVD) ────────────────────────────────────────
// Cada tipo tem seu próprio banco padrão + edição independente por RH.
// O bug anterior: FormAVD ignorava o tipo e mostrava sempre o mesmo formulário.
const AVD_TIPOS = [
  { id: 'auto',          label: 'Autoavaliação',         cor: '#005E4D', icon: 'user' },
  { id: 'pares',         label: 'Setor (pares)',         cor: '#1F4A8A', icon: 'users' },
  { id: 'superior',      label: 'Líder',                 cor: '#6B3FA0', icon: 'trend_up' },
  { id: 'intersetorial', label: 'Intersetorial',         cor: '#B56500', icon: 'org' },
];

// Banco padrão por tipo. Cada tipo tem sua redação específica, focada
// no ponto de vista correto (eu mesmo / um colega meu / meu líder / colega de outro setor).
const AVD_BANCO_POR_TIPO = {
  auto: {
    tecnico: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Como você avalia seu domínio técnico das ferramentas e processos da sua área?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Como você avalia a qualidade e acurácia das suas entregas neste ciclo?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Com que frequência você entrega dentro do prazo e com a qualidade esperada?' },
    ],
    comportamental: [
      { tipo: 'choice', opcoes: ['Sempre proativa', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Como você avalia sua proatividade na busca por soluções diante de obstáculos?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Sua comunicação com a equipe é clara, colaborativa e respeitosa?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Sua abertura a feedbacks e disposição para aprendizado contínuo' },
    ],
    metas: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Superou', pergunta: 'Você cumpriu suas metas do período no prazo e com qualidade?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Superou', pergunta: 'Você se sente alinhado(a) com os OKRs e objetivos estratégicos do ciclo?' },
      { tipo: 'text',  opcional: true, pergunta: 'Cite um resultado concreto que você entregou neste ciclo.' },
    ],
    lideranca: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Como você avalia sua capacidade de delegação e acompanhamento da equipe?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Você promove um ambiente colaborativo e psicologicamente seguro?' },
      { tipo: 'text',  opcional: true, pergunta: 'Descreva um exemplo recente em que você exerceu liderança positiva.' },
    ],
  },
  pares: {
    tecnico: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Domínio técnico do colega nas ferramentas e processos da área' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Qualidade e acurácia das entregas do colega' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'O colega entrega dentro do prazo e com a qualidade esperada?' },
    ],
    comportamental: [
      { tipo: 'choice', opcoes: ['Sempre proativa', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Como você avalia a proatividade do colega na busca por soluções?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'A comunicação do colega é clara, colaborativa e respeitosa?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Abertura do colega a feedbacks e aprendizado contínuo' },
    ],
    metas: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Superou', pergunta: 'O colega cumpriu as metas combinadas com qualidade?' },
      { tipo: 'text',  opcional: true, pergunta: 'Cite uma entrega concreta deste colega neste ciclo (opcional).' },
    ],
    lideranca: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'O colega assume responsabilidades que vão além do papel formal?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'O colega cria espaço para outros se desenvolverem?' },
    ],
  },
  superior: {
    tecnico: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Seu líder demonstra domínio técnico da área?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Seu líder traz clareza técnica para decisões do dia a dia?' },
    ],
    comportamental: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Como avalia a clareza de comunicação do seu líder?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Seu líder dá feedback estruturado e construtivo?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Seu líder cria um ambiente psicologicamente seguro?' },
    ],
    metas: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Superou', pergunta: 'Seu líder ajuda você a destravar metas e prioridades?' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Seu líder define expectativas claras de entrega?' },
    ],
    lideranca: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Capacidade do seu líder de delegar e acompanhar' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Seu líder reconhece os esforços e resultados do time?' },
      { tipo: 'text',  opcional: true, pergunta: 'O que seu líder pode fazer diferente no próximo ciclo? (opcional)' },
    ],
  },
  intersetorial: {
    tecnico: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Domínio técnico nas interações com outros setores' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Traz informações precisas e completas nas interfaces entre áreas?' },
    ],
    comportamental: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Disponibilidade para colaborar com setores diferentes do dele' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Comunica-se de forma clara e respeitosa fora da sua própria área?' },
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Capacidade de ouvir e considerar pontos de vista de outras áreas' },
    ],
    metas: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Superou', pergunta: 'Cumprimento de prazos e combinados em projetos intersetoriais' },
      { tipo: 'text',  opcional: true, pergunta: 'Cite um projeto/entrega intersetorial em que essa pessoa atuou com você (opcional).' },
    ],
    lideranca: [
      { tipo: 'scale', min: 'Muito abaixo', max: 'Excelente', pergunta: 'Influência positiva em iniciativas que envolvem outros setores' },
      { tipo: 'choice', opcoes: ['Sempre', 'Na maioria das vezes', 'Às vezes', 'Raramente'], pergunta: 'Defende soluções considerando o todo da empresa, não só sua área?' },
    ],
  },
};

// Normaliza o "tipo" vindo da UI (algumas telas chamam 'setor', o admin chama 'pares', etc.)
function normalizarTipoAvd(tipo) {
  if (!tipo) return 'auto';
  if (tipo === 'setor') return 'pares';
  if (tipo === 'lider') return 'superior';
  if (tipo === 'liderado') return 'pares';
  return tipo;
}

function getBancoPadrao(tipo) {
  const t = normalizarTipoAvd(tipo);
  return AVD_BANCO_POR_TIPO[t] || AVD_BANCO_POR_TIPO.auto;
}

function getPerguntas(cargo, tipo) {
  // Mantida por compatibilidade. Sem `tipo`, devolve o banco padrão (auto).
  return getBancoPadrao(tipo);
}

// Mock de status de avaliações por colaborador no ciclo ativo
const AVD_STATUS_KEY = 'escalab_avd_status';

function getAVDStatus() {
  try {
    const raw = localStorage.getItem(AVD_STATUS_KEY);
    if (raw) return JSON.parse(raw);
    const inicial = {};
    COLABORADORES.forEach(c => {
      inicial[c.id] = {
        avaliado_por: {},
        auto: null,
        blocos_respondidos: {},
        nota_geral: null,
        nota_por_bloco: {},
        nota_por_fonte: {},
        liberado: false,
      };
    });
    localStorage.setItem(AVD_STATUS_KEY, JSON.stringify(inicial));
    return inicial;
  } catch { return {}; }
}

function salvarAVDStatus(data) {
  try { localStorage.setItem(AVD_STATUS_KEY, JSON.stringify(data)); } catch {}
}

// Mock de dados de histórico (scores por ciclo por colaborador)
const AVD_HISTORICO = {
  15: [
    { ciclo: 'Jun 24', nota: 7.4, tipo: 'Avaliação individual' },
    { ciclo: 'Dez 24', nota: 8.1, tipo: 'Avaliação individual' },
    { ciclo: 'Jun 25', nota: 8.6, tipo: 'Avaliação individual' },
  ],
  10: [
    { ciclo: 'Jun 24', nota: 8.2, tipo: 'Avaliação individual' },
    { ciclo: 'Dez 24', nota: 8.7, tipo: 'Avaliação individual' },
    { ciclo: 'Jun 25', nota: 9.2, tipo: 'Avaliação individual' },
  ],
  14: [
    { ciclo: 'Jun 24', nota: 7.8, tipo: 'Avaliação individual' },
    { ciclo: 'Dez 24', nota: 8.3, tipo: 'Avaliação individual' },
    { ciclo: 'Jun 25', nota: 8.9, tipo: 'Avaliação individual' },
  ],
};

// Mock feedbacks registrados por colaborador
const FEEDBACKS_ARQUIVOS_KEY = 'escalab_feedbacks_arquivos';

const FEEDBACKS_MOCK_FILES = {
  15: [
    { id: 'fb1', data: '2025-06-12', responsavel: 'Marcus Ferreira Neto',        arquivo: 'Feedback_Colab_Jun2025.pdf', status: 'realizado' },
    { id: 'fb2', data: '2024-12-18', responsavel: 'Marcus Ferreira Neto',        arquivo: 'Feedback_Colab_Dez2024.pdf', status: 'realizado' },
    { id: 'fb3', data: '2024-07-05', responsavel: 'Marcus Ferreira Neto',        arquivo: null, nota: 'Feedback realizado presencialmente', status: 'sem_arquivo' },
  ],
  10: [
    { id: 'fb4', data: '2025-06-10', responsavel: 'Carlos Eduardo Mendes Costa', arquivo: 'Feedback_Coord_Jun2025.pdf', status: 'realizado' },
    { id: 'fb5', data: '2024-12-15', responsavel: 'Carlos Eduardo Mendes Costa', arquivo: 'Feedback_Coord_Dez2024.pdf', status: 'realizado' },
  ],
  14: [
    { id: 'fb6', data: '2025-06-08', responsavel: 'Ana Carolina Lima Santos',    arquivo: 'Feedback_Lider_Jun2025.pdf', status: 'realizado' },
  ],
};

// ── Configuração de pesos das competências ──────────────────────────────────
const AVD_PESOS_KEY = 'escalab_avd_pesos';
const PESOS_DEFAULT = { tecnico: 25, comportamental: 25, metas: 30, lideranca: 20 };
const PESOS_LABELS = { tecnico: 'Técnico', comportamental: 'Comportamental', metas: 'Metas / Resultados', lideranca: 'Liderança' };

function getPesosAvd() {
  try { return { ...PESOS_DEFAULT, ...JSON.parse(localStorage.getItem(AVD_PESOS_KEY) || '{}') }; } catch { return PESOS_DEFAULT; }
}
function salvarPesosAvd(p) {
  try { localStorage.setItem(AVD_PESOS_KEY, JSON.stringify(p)); } catch {}
}

const ModalConfigPesos = ({ onClose }) => {
  const [pesos, setPesos] = useState(getPesosAvd);
  const total = Object.values(pesos).reduce((s, v) => s + Number(v || 0), 0);
  const ok = total === 100;
  function salvar() {
    if (!ok) return;
    salvarPesosAvd(pesos);
    onClose();
  }
  return (
    <div onClick={onClose} className="modal-overlay" 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:14, width:'100%', maxWidth:440, padding:'18px 22px', animation:'popIn .22s var(--ease-out)' }}>
        <div style={{ fontSize:16, fontWeight:700, marginBottom:6 }}>Configurar pesos das competências</div>
        <div style={{ fontSize:12.5, color:'var(--escalab-mute)', marginBottom:14 }}>A soma precisa fechar em 100%.</div>
        <div style={{ display:'flex', flexDirection:'column', gap:11 }}>
          {Object.keys(PESOS_DEFAULT).map(k => (
            <div key={k} style={{ display:'grid', gridTemplateColumns:'1fr 80px 20px', alignItems:'center', gap:10 }}>
              <span style={{ fontSize:13, fontWeight:600 }}>{PESOS_LABELS[k]}</span>
              <input type="number" min={0} max={100} value={pesos[k]} onChange={e => setPesos(p => ({ ...p, [k]: Number(e.target.value) }))}
                style={{ border:'1px solid var(--escalab-line)', borderRadius:7, padding:'5px 9px', fontSize:13, textAlign:'right', outline:'none' }} />
              <span style={{ fontSize:12, color:'var(--escalab-mute)' }}>%</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop:14, padding:'9px 12px', borderRadius:8, background: ok ? '#E6F5F1' : '#FDECEC', color: ok ? '#00836B' : '#B3261E', fontSize:13, fontWeight:700, textAlign:'center' }}>
          Total: {total}% {ok ? '✓' : '· ajuste para fechar em 100%'}
        </div>
        <div style={{ display:'flex', gap:8, justifyContent:'flex-end', marginTop:14 }}>
          <Button variant="outline" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" onClick={salvar} disabled={!ok}>Salvar</Button>
        </div>
      </div>
    </div>
  );
};

// ── Avaliadores múltiplos por colaborador ──────────────────────────────────
const AVALIADORES_MULTI_KEY = id => `escalab_avaliadores_${id}`;
function getAvaliadoresMulti(colabId) {
  try {
    const raw = JSON.parse(localStorage.getItem(AVALIADORES_MULTI_KEY(colabId)) || '{"lideres":[], "pares":[], "pesos":{}}');
    if (!raw.pesos) raw.pesos = {};
    return raw;
  } catch { return { lideres:[], pares:[], pesos:{} }; }
}
function salvarAvaliadoresMulti(colabId, dados) { try { localStorage.setItem(AVALIADORES_MULTI_KEY(colabId), JSON.stringify(dados)); } catch {} }

const ModalAvaliadoresMulti = ({ colab, onClose }) => {
  const [config, setConfig] = useState(() => getAvaliadoresMulti(colab.id));
  const [busca, setBusca] = useState('');

  function toggle(grupo, id) {
    setConfig(c => {
      const jaTem = c[grupo].includes(id);
      const lista = jaTem ? c[grupo].filter(x => x !== id) : [...c[grupo], id];
      const novosPesos = { ...c.pesos };
      if (!jaTem && novosPesos[id] == null) novosPesos[id] = 1; // peso padrão
      return { ...c, [grupo]: lista, pesos: novosPesos };
    });
  }
  function setPeso(id, peso) {
    setConfig(c => ({ ...c, pesos: { ...c.pesos, [id]: peso } }));
  }
  function salvar() {
    salvarAvaliadoresMulti(colab.id, config);
    onClose();
  }

  const candidatos = COLABORADORES
    .filter(c => c.id !== colab.id)
    .filter(c => !busca || c.nome.toLowerCase().includes(busca.toLowerCase()) || c.setor?.toLowerCase().includes(busca.toLowerCase()))
    .slice(0, 40);

  return (
    <div onClick={onClose} className="modal-overlay" 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:14, width:'100%', maxWidth:540, maxHeight:'92vh', overflow:'auto', padding:'18px 22px', animation:'popIn .22s var(--ease-out)' }}>
        <div style={{ fontSize:16, fontWeight:700, marginBottom:4 }}>Avaliadores de {colab.nome.split(' ')[0]}</div>
        <div style={{ fontSize:12.5, color:'var(--escalab-mute)', marginBottom:14 }}>
          Selecione quem avalia como <strong>líder</strong> ou como <strong>par</strong> nesta AVD. Para colaboradores com mais de um líder, marque todos. O campo <strong>peso</strong> ao lado permite dar maior importância à nota do gestor direto (ex: peso 2 = nota dele vale o dobro).
        </div>
        <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar nome ou setor…"
          style={{ width:'100%', border:'1px solid var(--escalab-line)', borderRadius:8, padding:'8px 12px', fontSize:13, fontFamily:'var(--font-sans)', outline:'none', marginBottom:10, boxSizing:'border-box' }} />
        <div style={{ display:'flex', flexDirection:'column', gap:6, maxHeight:340, overflowY:'auto' }}>
          {candidatos.map(c => {
            const isLider = config.lideres.includes(c.id);
            const isPar = config.pares.includes(c.id);
            const sel = isLider || isPar;
            const peso = config.pesos?.[c.id] ?? 1;
            return (
              <div key={c.id} style={{ display:'grid', gridTemplateColumns:'1fr auto auto 90px', gap:8, alignItems:'center', padding:'7px 10px', border:'1px solid var(--escalab-line)', borderRadius:8 }}>
                <div style={{ display:'flex', alignItems:'center', gap:8, minWidth:0 }}>
                  <div style={{ width:26, height:26, borderRadius:'50%', background:c.cor, color:'#fff', fontWeight:700, fontSize:10, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>{c.iniciais}</div>
                  <div style={{ minWidth:0 }}>
                    <div style={{ fontSize:13, fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{c.nome.split(' ').slice(0,3).join(' ')}</div>
                    <div style={{ fontSize:11, color:'var(--escalab-mute)' }}>{c.setor}</div>
                  </div>
                </div>
                <label style={{ display:'flex', alignItems:'center', gap:5, fontSize:12, cursor:'pointer', color: isLider ? '#00836B' : 'var(--escalab-slate)' }}>
                  <input type="checkbox" checked={isLider} onChange={() => toggle('lideres', c.id)} />
                  Líder
                </label>
                <label style={{ display:'flex', alignItems:'center', gap:5, fontSize:12, cursor:'pointer', color: isPar ? '#1F4A8A' : 'var(--escalab-slate)' }}>
                  <input type="checkbox" checked={isPar} onChange={() => toggle('pares', c.id)} />
                  Par
                </label>
                {sel ? (
                  <div style={{ display:'flex', alignItems:'center', gap:4 }}>
                    <span style={{ fontSize:10.5, color:'var(--escalab-mute)' }}>peso</span>
                    <input type="number" min={0.1} max={10} step={0.1} value={peso}
                      onChange={e => setPeso(c.id, Number(e.target.value))}
                      style={{ width:54, border:'1px solid var(--escalab-line)', borderRadius:6, padding:'3px 6px', fontSize:12, textAlign:'right', outline:'none' }} title="Peso desse avaliador (ex: 2x = nota dele vale o dobro)" />
                  </div>
                ) : <span />}
              </div>
            );
          })}
        </div>
        <div style={{ marginTop:12, padding:'9px 12px', background:'var(--escalab-paper)', borderRadius:8, fontSize:12, color:'var(--escalab-slate)' }}>
          <strong>{config.lideres.length}</strong> líder(es) · <strong>{config.pares.length}</strong> par(es). Eles receberão a avaliação automaticamente quando o ciclo for aberto.
        </div>
        <div style={{ display:'flex', gap:8, justifyContent:'flex-end', marginTop:14 }}>
          <Button variant="outline" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" onClick={salvar}>Salvar avaliadores</Button>
        </div>
      </div>
    </div>
  );
};

// ── Menu de Ciclo (abrir/fechar + pesos) ────────────────────────────────────

const CicloMenu = ({ ciclo, onMudouStatus }) => {
  const [open, setOpen] = useState(false);
  const [modalPesos, setModalPesos] = useState(false);
  if (!ciclo) return null;
  const cicloAvdAberto = getCicloAvdAberto();
  const aberto = !!cicloAvdAberto && cicloAvdAberto.cicloId === ciclo.id;
  const label = aberto ? 'Ciclo aberto · colaboradores podem responder' : 'Ciclo fechado · respostas bloqueadas';
  const tone = aberto ? 'success' : 'warn';

  function alternar() {
    if (aberto) { fecharCicloAvd(); } else { abrirCicloAvd(ciclo.id); }
    setOpen(false);
    onMudouStatus?.();
  }

  return (
    <div style={{ display: 'flex', gap: 8, position: 'relative' }}>
      <Tag tone={tone} size="xs">{label}</Tag>
      <button onClick={() => setOpen(o => !o)} style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 7, padding: '5px 10px', cursor: 'pointer', color: 'var(--escalab-mute)' }}>···</button>
      {open && (
        <div style={{ position: 'absolute', right: 0, top: '100%', marginTop: 6, background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 10, boxShadow: '0 12px 32px rgba(0,0,0,.12)', minWidth: 220, zIndex: 50, overflow: 'hidden' }}>
          <button onClick={alternar} style={{ width: '100%', textAlign: 'left', border: 0, background: '#fff', cursor: 'pointer', padding: '10px 14px', fontSize: 13, fontFamily: 'var(--font-sans)', display: 'flex', alignItems: 'center', gap: 8, color: aberto ? '#B3261E' : '#00836B' }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--escalab-paper)'}
            onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
            <Icon name={aberto ? 'lock' : 'unlock'} size={13} />
            {aberto ? 'Fechar ciclo' : 'Abrir ciclo'}
          </button>
          <button onClick={() => { setOpen(false); setModalPesos(true); }} style={{ width: '100%', textAlign: 'left', border: 0, borderTop:'1px solid var(--escalab-line)', background: '#fff', cursor: 'pointer', padding: '10px 14px', fontSize: 13, fontFamily: 'var(--font-sans)', display: 'flex', alignItems: 'center', gap: 8, color: 'var(--escalab-slate)' }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--escalab-paper)'}
            onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
            <Icon name="settings" size={13} /> Configurar pesos das competências
          </button>
          <div style={{ padding: '8px 14px', fontSize: 11, color: 'var(--escalab-mute)', borderTop: '1px solid var(--escalab-line)' }}>
            Quando fechado, ninguém pode mais responder.
          </div>
        </div>
      )}
      {modalPesos && <ModalConfigPesos onClose={() => setModalPesos(false)} />}
    </div>
  );
};

function getFeedbacksArquivos(colaboradorId) {
  try {
    const raw = localStorage.getItem(FEEDBACKS_ARQUIVOS_KEY);
    const all = raw ? JSON.parse(raw) : FEEDBACKS_MOCK_FILES;
    return all[colaboradorId] || FEEDBACKS_MOCK_FILES[colaboradorId] || [];
  } catch { return FEEDBACKS_MOCK_FILES[colaboradorId] || []; }
}
function salvarFeedbacksArquivos(colaboradorId, lista) {
  try {
    const raw = localStorage.getItem(FEEDBACKS_ARQUIVOS_KEY);
    const all = raw ? JSON.parse(raw) : { ...FEEDBACKS_MOCK_FILES };
    all[colaboradorId] = lista;
    localStorage.setItem(FEEDBACKS_ARQUIVOS_KEY, JSON.stringify(all));
  } catch {}
}
function addFeedbackArquivo(colaboradorId, fb) {
  const lista = [...getFeedbacksArquivos(colaboradorId), fb];
  salvarFeedbacksArquivos(colaboradorId, lista);
}

// Mock notas por colaborador para exibição de resultados
const AVD_NOTAS_MOCK = {
  15: { geral: 8.6, lider: 8.9, pares: 8.4, auto: 8.1, intersetorial: 9.2, blocos: { tecnico: 9.2, comportamental: 8.8, metas: 8.0, lideranca: 8.4 }, status: 'concluida', mediaSetor: 7.9 },
  10: { geral: 9.2, lider: 9.0, pares: 9.1, auto: 9.0, intersetorial: 9.5, blocos: { tecnico: 9.5, comportamental: 9.0, metas: 9.3, lideranca: 9.0 }, status: 'concluida', mediaSetor: 8.4 },
  14: { geral: 8.9, lider: 8.7, pares: 9.0, auto: 8.6, intersetorial: 9.1, blocos: { tecnico: 9.0, comportamental: 8.8, metas: 8.7, lideranca: 9.0 }, status: 'concluida', mediaSetor: 8.1 },
  16: { geral: null, lider: null, pares: null, auto: null, intersetorial: null, blocos: {}, status: 'pendente', mediaSetor: 7.9 },
  17: { geral: null, lider: null, pares: null, auto: null, intersetorial: null, blocos: {}, status: 'em_andamento', mediaSetor: 8.2 },
};

function getNotaColab(id) {
  return AVD_NOTAS_MOCK[id] || { geral: null, status: 'pendente', blocos: {}, mediaSetor: 0 };
}

// ── Seletor de perguntas por colaborador (visão do GC) ────────────────────────

const AVD_PERGUNTAS_SEL_KEY = 'escalab_avd_perguntas_sel';

// Storage keyed por tipo. Estrutura: { [colabId]: { [tipo]: { [blocoId_idx]: bool } } }
// Migração: se encontrar shape antiga ({ [colabId]: { [blocoId_idx]: bool } }), aplica a todos os 4 tipos.
function _carregarSelStore() {
  try {
    const raw = JSON.parse(localStorage.getItem(AVD_PERGUNTAS_SEL_KEY) || '{}');
    let mudou = false;
    Object.entries(raw).forEach(([colabId, val]) => {
      if (val && typeof val === 'object') {
        const keys = Object.keys(val);
        // shape antiga: chaves são "blocoId_idx" (não 'auto'/'pares'/...)
        const ehAntigo = keys.length > 0 && !AVD_TIPOS.some(t => t.id in val) && keys.every(k => /^[a-z]+_\d+$/i.test(k));
        if (ehAntigo) {
          raw[colabId] = { auto: val, pares: val, superior: val, intersetorial: val };
          mudou = true;
        }
      }
    });
    if (mudou) {
      try { localStorage.setItem(AVD_PERGUNTAS_SEL_KEY, JSON.stringify(raw)); } catch {}
    }
    return raw;
  } catch { return {}; }
}

function getPerguntasSel(colaboradorId, tipo) {
  const all = _carregarSelStore();
  const t = normalizarTipoAvd(tipo);
  const node = all[colaboradorId];
  if (!node) return {};
  return node[t] || {};
}

function salvarPerguntasSel(colaboradorId, tipo, selecionadas) {
  try {
    const all = _carregarSelStore();
    const t = normalizarTipoAvd(tipo);
    if (!all[colaboradorId]) all[colaboradorId] = {};
    all[colaboradorId][t] = selecionadas;
    localStorage.setItem(AVD_PERGUNTAS_SEL_KEY, JSON.stringify(all));
  } catch {}
}

function _customKey(colabId, tipo) { return `escalab_avd_custom_${colabId}_${normalizarTipoAvd(tipo)}`; }

function getCustomPerguntas(colabId, tipo) {
  try {
    const k = _customKey(colabId, tipo);
    const novo = localStorage.getItem(k);
    if (novo) return JSON.parse(novo);
    // Migração: se existe a chave antiga sem tipo, copia para todos os 4 tipos.
    const antigo = localStorage.getItem(`escalab_avd_custom_${colabId}`);
    if (antigo) {
      const parsed = JSON.parse(antigo);
      AVD_TIPOS.forEach(t => {
        try { localStorage.setItem(_customKey(colabId, t.id), antigo); } catch {}
      });
      return parsed;
    }
    return {};
  } catch { return {}; }
}

function setCustomPerguntas(colabId, tipo, custom) {
  try { localStorage.setItem(_customKey(colabId, tipo), JSON.stringify(custom)); } catch {}
}

// Detecta se a avaliação intersetorial é "setor inteiro" vs "pessoa avalia pessoa".
// Setor inteiro: colab.id é uma string que começa com 'intersetor_'.
function ehAvaliacaoSetorInteiro(colab) {
  return typeof colab?.id === 'string' && colab.id.startsWith('intersetor_');
}

// Converte uma pergunta do INTER_FORM (que tem .texto) no shape esperado pelo FormAVD (.pergunta).
function _mapearPerguntaInter(p, escalaMin, escalaMax) {
  if (p.tipo === 'choice') {
    return { tipo: 'choice', pergunta: p.texto, opcoes: p.opcoes || [] };
  }
  if (p.tipo === 'text') {
    return { tipo: 'text', pergunta: p.texto, opcional: false };
  }
  // scale (default)
  return { tipo: 'scale', pergunta: p.texto, min: '', max: '', escalaMin, escalaMax };
}

// Devolve o conjunto efetivo de perguntas que o colaborador vai responder.
// — Para tipos auto/pares/superior: banco padrão por tipo + sel + customs (por colab).
// — Para tipo intersetorial: usa o formulário GLOBAL configurado pelo RH em
//   AVD → Intersetorial → Configuração (INTER_FORM_KEY). Diferencia entre
//   "individual" (pessoa avalia pessoa) e "setor" (setor inteiro).
function getPerguntasEfetivas(colab, tipo) {
  const tipoNorm = normalizarTipoAvd(tipo);

  if (tipoNorm === 'intersetorial') {
    const cfg = getInterForm();
    const secao = ehAvaliacaoSetorInteiro(colab) ? cfg.setor : cfg.individual;
    const lista = (secao?.perguntas || []).map(p => _mapearPerguntaInter(p, secao.escalaMin, secao.escalaMax));
    // Renderiza tudo num único bloco "intersetorial".
    return { intersetorial: lista };
  }

  const banco = getBancoPadrao(tipoNorm);
  const sel = getPerguntasSel(colab.id, tipoNorm);
  const custom = getCustomPerguntas(colab.id, tipoNorm);
  const result = {};
  Object.keys(banco).forEach(blocoId => {
    const padrao = banco[blocoId].filter((_, i) => sel[`${blocoId}_${i}`] !== false);
    const customMapped = (custom[blocoId] || []).map(c => ({
      tipo: c.tipo || 'scale',
      pergunta: c.texto,
      opcoes: c.opcoes,
      min: c.minLabel,
      max: c.maxLabel,
      escalaMin: c.escalaMin,
      escalaMax: c.escalaMax,
    }));
    result[blocoId] = [...padrao, ...customMapped];
  });
  return result;
}

const SeletorPerguntasAdmin = ({ colab }) => {
  // Tipo da avaliação que está sendo configurada (auto / pares / superior / intersetorial)
  const [tipoAtivo, setTipoAtivo] = useState('auto');
  const perguntas     = getBancoPadrao(tipoAtivo);
  const temLideranca  = colab.nivel !== 'liderado';
  const blocos        = temLideranca ? AVD_BLOCOS : AVD_BLOCOS.filter(b => b.id !== 'lideranca');

  // Estado: { [blocoId_idx]: true/false } · true = incluída · escopo: tipoAtivo
  const [sel, setSel] = useState(() => {
    const saved = getPerguntasSel(colab.id, tipoAtivo);
    const padrao = {};
    blocos.forEach(b => {
      (perguntas[b.id] || []).forEach((_, i) => {
        padrao[`${b.id}_${i}`] = saved[`${b.id}_${i}`] !== undefined ? saved[`${b.id}_${i}`] : true;
      });
    });
    return padrao;
  });

  // Perguntas customizadas por bloco · escopo: tipoAtivo
  const [custom, setCustom] = useState(() => getCustomPerguntas(colab.id, tipoAtivo));

  // Reseta o estado quando troca de tipo (cada tipo tem sua configuração independente).
  React.useEffect(() => {
    const banco = getBancoPadrao(tipoAtivo);
    const saved = getPerguntasSel(colab.id, tipoAtivo);
    const padrao = {};
    blocos.forEach(b => {
      (banco[b.id] || []).forEach((_, i) => {
        padrao[`${b.id}_${i}`] = saved[`${b.id}_${i}`] !== undefined ? saved[`${b.id}_${i}`] : true;
      });
    });
    setSel(padrao);
    setCustom(getCustomPerguntas(colab.id, tipoAtivo));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tipoAtivo, colab.id]);
  const [addingBloco, setAddingBloco] = useState(null);
  const [novaP, setNovaP] = useState('');
  const [novaPTipo, setNovaPTipo] = useState('scale');
  const [novaPOpcoes, setNovaPOpcoes] = useState('');
  const [novaPScaleMin, setNovaPScaleMin] = useState(1);
  const [novaPScaleMax, setNovaPScaleMax] = useState(5);
  const [novaPScaleMinLabel, setNovaPScaleMinLabel] = useState('Muito abaixo');
  const [novaPScaleMaxLabel, setNovaPScaleMaxLabel] = useState('Excelente');
  const [salvo, setSalvo] = useState(false);

  function toggle(key) { setSel(s => ({ ...s, [key]: !s[key] })); setSalvo(false); }

  function toggleBloco(bId, valor) {
    setSel(s => {
      const novo = { ...s };
      (perguntas[bId] || []).forEach((_, i) => { novo[`${bId}_${i}`] = valor; });
      return novo;
    });
    setSalvo(false);
  }

  function addCustom(bId) {
    if (!novaP.trim()) return;
    const entry = { texto: novaP.trim(), tipo: novaPTipo || 'scale' };
    if (entry.tipo === 'choice') entry.opcoes = (novaPOpcoes || 'Sempre,Na maioria das vezes,Às vezes,Raramente').split(',').map(o => o.trim()).filter(Boolean);
    if (entry.tipo === 'scale') {
      const minN = Math.max(0, Math.min(10, Number(novaPScaleMin)));
      const maxN = Math.max(minN + 1, Math.min(10, Number(novaPScaleMax)));
      entry.escalaMin = minN;
      entry.escalaMax = maxN;
      entry.minLabel = novaPScaleMinLabel || '';
      entry.maxLabel = novaPScaleMaxLabel || '';
    }
    const novo = { ...(custom[bId] ? { ...custom } : custom), [bId]: [...(custom[bId] || []), entry] };
    setCustom(novo);
    setCustomPerguntas(colab.id, tipoAtivo, novo);
    setNovaP(''); setNovaPTipo('scale'); setNovaPOpcoes('');
    setNovaPScaleMin(1); setNovaPScaleMax(5);
    setAddingBloco(null);
    setSalvo(false);
  }

  function removeCustom(bId, idx) {
    const novo = { ...custom, [bId]: (custom[bId] || []).filter((_, i) => i !== idx) };
    setCustom(novo);
    setCustomPerguntas(colab.id, tipoAtivo, novo);
    setSalvo(false);
  }

  function handleSalvar() {
    salvarPerguntasSel(colab.id, tipoAtivo, sel);
    setSalvo(true);
    setTimeout(() => setSalvo(false), 3000);
  }

  const totalPergs = blocos.reduce((s, b) => s + (perguntas[b.id] || []).length + (custom[b.id]?.length || 0), 0);
  const totalSel   = blocos.reduce((s, b) => {
    const padrao = (perguntas[b.id] || []).filter((_, i) => sel[`${b.id}_${i}`] !== false).length;
    const cust   = (custom[b.id] || []).length;
    return s + padrao + cust;
  }, 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      {/* Header */}
      <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 18, paddingBottom: 16, borderBottom: '1px solid var(--escalab-line)' }}>
        <Avatar nome={colab.nome} cor={colab.cor} iniciais={colab.iniciais} size={38} />
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--escalab-ink)' }}>{colab.nome.split(' ').slice(0,3).join(' ')}</div>
          <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 1 }}>{colab.cargo}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>
            {tipoAtivo === 'intersetorial' ? 'Formulário' : 'Perguntas selecionadas'}
          </div>
          <div style={{ fontSize: 16, fontWeight: 800, color: tipoAtivo === 'intersetorial' ? 'var(--escalab-mute)' : (totalSel > 0 ? 'var(--escalab-brand)' : '#E89B3B') }}>
            {tipoAtivo === 'intersetorial' ? 'Global · vide painel' : `${totalSel}/${totalPergs}`}
          </div>
        </div>
      </div>

      {/* Seletor de TIPO de avaliação — cada tipo tem perguntas independentes */}
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 8 }}>
          Tipo de avaliação
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {AVD_TIPOS.map(t => {
            const ativo = tipoAtivo === t.id;
            return (
              <button key={t.id} onClick={() => setTipoAtivo(t.id)} style={{
                display: 'flex', alignItems: 'center', gap: 7,
                border: `1.5px solid ${ativo ? t.cor : 'var(--escalab-line)'}`,
                background: ativo ? t.cor + '15' : '#fff',
                color: ativo ? t.cor : 'var(--escalab-slate)',
                borderRadius: 9, padding: '8px 14px', cursor: 'pointer',
                fontSize: 13, fontWeight: ativo ? 700 : 500, fontFamily: 'var(--font-sans)',
                transition: 'all .15s',
              }}>
                <Icon name={t.icon} size={13} />
                {t.label}
              </button>
            );
          })}
        </div>
      </div>

      {tipoAtivo === 'intersetorial' ? (
        <Banner tone="warn" style={{ marginBottom: 16 }}>
          <strong>O formulário intersetorial é configurado globalmente</strong> (vale para toda a empresa), não por colaborador. Para editar, vá em <strong>AVD → Intersetorial → Configuração do formulário</strong>. Lá você define as perguntas que aparecem quando alguém avalia <em>{colab.nome.split(' ')[0]}</em> (ou qualquer outro colega) na etapa intersetorial.
        </Banner>
      ) : (
        <Banner tone="info" style={{ marginBottom: 16 }}>
          Configurando as perguntas de <strong>{AVD_TIPOS.find(t => t.id === tipoAtivo)?.label}</strong> para {colab.nome.split(' ')[0]}. Cada tipo (auto, setor, líder) é independente — selecione quais perguntas vão aparecer e adicione personalizadas por bloco.
        </Banner>
      )}

      {/* Blocos (não renderiza para intersetorial — config global) */}
      <div style={{ display: tipoAtivo === 'intersetorial' ? 'none' : 'flex', flexDirection: 'column', gap: 18 }}>
        {blocos.map((b) => {
          const psBloco  = perguntas[b.id] || [];
          const custBloco= custom[b.id] || [];
          const todasSel = psBloco.every((_, i) => sel[`${b.id}_${i}`] !== false);
          const nenhumaSel = psBloco.every((_, i) => sel[`${b.id}_${i}`] === false) && custBloco.length === 0;
          const selCount = psBloco.filter((_, i) => sel[`${b.id}_${i}`] !== false).length + custBloco.length;

          return (
            <div key={b.id} style={{ border: `1.5px solid ${b.cor}30`, borderRadius: 14, overflow: 'hidden' }}>
              {/* Header do bloco */}
              <div style={{ background: b.cor + '12', padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: `1px solid ${b.cor}20` }}>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: b.cor, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name={b.id === 'tecnico' ? 'clipboard' : b.id === 'comportamental' ? 'users' : b.id === 'metas' ? 'trend_up' : 'star'} size={13} />
                  </div>
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: b.cor }}>Bloco {b.num} · {b.label}</span>
                  <span style={{ fontSize: 11.5, color: b.cor, background: b.cor + '20', borderRadius: 10, padding: '1px 8px', fontWeight: 600 }}>
                    {selCount} selecionada{selCount !== 1 ? 's' : ''}
                  </span>
                </div>
                {/* Marcar/desmarcar tudo */}
                <div style={{ display: 'flex', gap: 6 }}>
                  <button onClick={() => toggleBloco(b.id, true)}
                    style={{ border: `1px solid ${b.cor}40`, background: '#fff', borderRadius: 7, padding: '4px 10px', cursor: 'pointer', fontSize: 11.5, color: b.cor, fontFamily: 'var(--font-sans)', fontWeight: 600 }}>
                    Todas
                  </button>
                  <button onClick={() => toggleBloco(b.id, false)}
                    style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 7, padding: '4px 10px', cursor: 'pointer', fontSize: 11.5, color: 'var(--escalab-mute)', fontFamily: 'var(--font-sans)' }}>
                    Nenhuma
                  </button>
                </div>
              </div>

              {/* Perguntas padrão */}
              <div style={{ padding: '8px 16px' }}>
                {psBloco.map((p, i) => {
                  const ativa = sel[`${b.id}_${i}`] !== false;
                  return (
                    <div key={i} onClick={() => toggle(`${b.id}_${i}`)}
                      style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '10px 8px', borderRadius: 9, cursor: 'pointer', transition: 'background .12s', marginBottom: 2, background: ativa ? '#fff' : '#F8F8F8' }}
                      onMouseEnter={e => e.currentTarget.style.background = ativa ? b.cor + '08' : '#F0F0F0'}
                      onMouseLeave={e => e.currentTarget.style.background = ativa ? '#fff' : '#F8F8F8'}>
                      {/* Toggle visual */}
                      <div style={{ width: 22, height: 22, borderRadius: 6, border: `2px solid ${ativa ? b.cor : '#C0CAD8'}`, background: ativa ? b.cor : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1, transition: 'all .15s' }}>
                        {ativa && <Icon name="check" size={11} />}
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13.5, color: ativa ? 'var(--escalab-ink)' : 'var(--escalab-mute)', lineHeight: 1.4, textDecoration: ativa ? 'none' : 'line-through' }}>
                          {p.pergunta}
                        </div>
                        <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginTop: 3 }}>
                          {p.tipo === 'scale' ? '⬡ Escala 1–5' : p.tipo === 'choice' ? '◉ Múltipla escolha' : '📝 Texto livre'}
                          {p.opcional && ' · Opcional'}
                        </div>
                      </div>
                    </div>
                  );
                })}

                {/* Perguntas customizadas */}
                {custBloco.map((p, ci) => (
                  <div key={`c${ci}`} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '10px 8px', borderRadius: 9, background: b.cor + '08', marginBottom: 2, border: `1px dashed ${b.cor}40` }}>
                    <div style={{ width: 22, height: 22, borderRadius: 6, background: b.cor, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                      <Icon name="check" size={11} />
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, color: 'var(--escalab-ink)', lineHeight: 1.4 }}>{p.texto}</div>
                      <div style={{ fontSize: 11.5, color: b.cor, marginTop: 3, fontWeight: 600 }}>✨ Pergunta personalizada</div>
                    </div>
                    <button onClick={() => removeCustom(b.id, ci)}
                      style={{ border: 0, background: 'transparent', cursor: 'pointer', color: '#B3261E', padding: 4, flexShrink: 0 }}>
                      <Icon name="close" size={13} />
                    </button>
                  </div>
                ))}

                {/* Adicionar pergunta customizada */}
                {addingBloco === b.id ? (
                  <div style={{ padding: '8px 8px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <textarea
                      value={novaP}
                      onChange={e => setNovaP(e.target.value)}
                      placeholder="Digite a nova pergunta…"
                      rows={2}
                      style={{ width: '100%', border: `1.5px solid ${b.cor}`, borderRadius: 8, padding: '8px 10px', fontSize: 13, fontFamily: 'var(--font-sans)', outline: 0, resize: 'vertical', boxSizing: 'border-box' }}
                      autoFocus
                    />
                    {/* Seletor de tipo */}
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      {[
                        { id:'scale',  label:'Escala (1-4)' },
                        { id:'choice', label:'Múltipla escolha' },
                        { id:'text',   label:'Texto livre' },
                      ].map(t => {
                        const sel = novaPTipo === t.id;
                        return (
                          <button key={t.id} onClick={() => setNovaPTipo(t.id)} style={{
                            border: `1px solid ${sel ? b.cor : 'var(--escalab-line)'}`,
                            background: sel ? b.cor + '15' : '#fff',
                            color: sel ? b.cor : 'var(--escalab-slate)',
                            borderRadius: 7, padding: '5px 11px', cursor: 'pointer', fontSize: 12, fontWeight: sel ? 700 : 500, fontFamily: 'var(--font-sans)',
                          }}>{t.label}</button>
                        );
                      })}
                    </div>
                    {novaPTipo === 'choice' && (
                      <input value={novaPOpcoes} onChange={e => setNovaPOpcoes(e.target.value)}
                        placeholder="Opções separadas por vírgula. Ex: Sempre, Às vezes, Raramente"
                        style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '7px 10px', fontSize: 12.5, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box' }} />
                    )}
                    {novaPTipo === 'scale' && (
                      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1.5fr 1.5fr', gap:6 }}>
                        <label style={{ display:'flex', flexDirection:'column', gap:3 }}>
                          <span style={{ fontSize:10.5, color:'var(--escalab-mute)', fontWeight:600 }}>Mín (0-10)</span>
                          <input type="number" min={0} max={10} value={novaPScaleMin} onChange={e => setNovaPScaleMin(Number(e.target.value))}
                            style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '5px 8px', fontSize: 12.5, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box' }} />
                        </label>
                        <label style={{ display:'flex', flexDirection:'column', gap:3 }}>
                          <span style={{ fontSize:10.5, color:'var(--escalab-mute)', fontWeight:600 }}>Máx (0-10)</span>
                          <input type="number" min={1} max={10} value={novaPScaleMax} onChange={e => setNovaPScaleMax(Number(e.target.value))}
                            style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '5px 8px', fontSize: 12.5, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box' }} />
                        </label>
                        <label style={{ display:'flex', flexDirection:'column', gap:3 }}>
                          <span style={{ fontSize:10.5, color:'var(--escalab-mute)', fontWeight:600 }}>Label mín</span>
                          <input value={novaPScaleMinLabel} onChange={e => setNovaPScaleMinLabel(e.target.value)} placeholder="Ex: Muito abaixo"
                            style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '5px 8px', fontSize: 12.5, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box' }} />
                        </label>
                        <label style={{ display:'flex', flexDirection:'column', gap:3 }}>
                          <span style={{ fontSize:10.5, color:'var(--escalab-mute)', fontWeight:600 }}>Label máx</span>
                          <input value={novaPScaleMaxLabel} onChange={e => setNovaPScaleMaxLabel(e.target.value)} placeholder="Ex: Excelente"
                            style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '5px 8px', fontSize: 12.5, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box' }} />
                        </label>
                      </div>
                    )}
                    <div style={{ display: 'flex', gap: 7, justifyContent: 'flex-end' }}>
                      <Button size="sm" variant="ghost" onClick={() => { setAddingBloco(null); setNovaP(''); }}>Cancelar</Button>
                      <Button size="sm" variant="primary" onClick={() => addCustom(b.id)} disabled={!novaP.trim()}>Adicionar</Button>
                    </div>
                  </div>
                ) : (
                  <button onClick={() => { setAddingBloco(b.id); setNovaP(''); }}
                    style={{ display: 'flex', gap: 7, alignItems: 'center', border: `1px dashed ${b.cor}50`, background: 'transparent', borderRadius: 9, padding: '7px 12px', cursor: 'pointer', fontSize: 12.5, color: b.cor, fontFamily: 'var(--font-sans)', fontWeight: 600, marginTop: 6, width: '100%', transition: 'background .15s' }}
                    onMouseEnter={e => e.currentTarget.style.background = b.cor + '08'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <Icon name="plus" size={13} /> Adicionar pergunta personalizada para este bloco
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Salvar (escondido para intersetorial — config é global no painel próprio) */}
      {tipoAtivo !== 'intersetorial' && (
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--escalab-line)' }}>
          <Button variant="primary" onClick={handleSalvar} disabled={totalSel === 0}>
            Salvar configuração de perguntas
          </Button>
          {salvo && (
            <span style={{ fontSize: 13, color: '#00836B', display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="check" size={14} /> Configuração salva com sucesso
            </span>
          )}
          {totalSel === 0 && (
            <span style={{ fontSize: 12.5, color: '#B3261E' }}>Selecione ao menos uma pergunta</span>
          )}
        </div>
      )}
    </div>
  );
};

// ── Componentes de perguntas ───────────────────────────────────────────────

const ScaleAVD = ({ value, onChange, min = 'Muito abaixo', max = 'Excelente', escalaMin = 1, escalaMax = 5 }) => {
  const lo = Math.max(0, Math.min(10, Number(escalaMin)));
  const hi = Math.max(lo + 1, Math.min(10, Number(escalaMax)));
  const opts = [];
  for (let i = lo; i <= hi; i++) opts.push(i);
  // tamanho do botão diminui se a escala for grande (até 11 itens)
  const w = opts.length > 6 ? 36 : 44;
  return (
    <div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
        {opts.map(n => (
          <button key={n} onClick={() => onChange && onChange(n)} style={{
            width: w, height: w, border: `2px solid ${value === n ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
            borderRadius: 8, background: value === n ? 'var(--escalab-brand)' : '#fff',
            color: value === n ? '#fff' : 'var(--escalab-slate)', fontWeight: 700, fontSize: 15,
            cursor: onChange ? 'pointer' : 'default', transition: 'all .15s', fontFamily: 'var(--font-sans)',
          }}>{n}</button>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--escalab-mute)' }}>
        <span>{min}</span><span>{max}</span>
      </div>
    </div>
  );
};

const ChoiceAVD = ({ value, onChange, opcoes }) => (
  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
    {opcoes.map(op => (
      <button key={op} onClick={() => onChange && onChange(op)} style={{
        border: `1.5px solid ${value === op ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
        background: value === op ? 'var(--escalab-brand-tint)' : '#fff',
        color: value === op ? 'var(--escalab-brand-deep)' : 'var(--escalab-slate)',
        borderRadius: 8, padding: '7px 14px', fontSize: 13, cursor: onChange ? 'pointer' : 'default',
        fontFamily: 'var(--font-sans)', fontWeight: value === op ? 600 : 400, transition: 'all .15s',
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        {value === op && <span style={{ fontSize: 11 }}>✓</span>}
        {op}
      </button>
    ))}
  </div>
);

// ── Componente Formulário de Avaliação ─────────────────────────────────────

const FormAVD = ({ colab, tipo, onSalvar, onBack, readOnly = false }) => {
  const perguntas = getPerguntasEfetivas(colab, tipo);
  const tipoNorm  = normalizarTipoAvd(tipo);
  const tipoCfg   = AVD_TIPOS.find(t => t.id === tipoNorm) || AVD_TIPOS[0];
  const temLideranca = colab.nivel !== 'liderado';
  // Intersetorial = bloco único (formulário plano configurado pelo RH em INTER_FORM).
  // Outros tipos = blocos clássicos da AVD (técnico/comportamental/metas/liderança).
  const blocos = tipoNorm === 'intersetorial'
    ? [{ id: 'intersetorial', label: 'Avaliação intersetorial', cor: '#B56500', num: 1 }]
    : (temLideranca ? AVD_BLOCOS : AVD_BLOCOS.filter(b => b.id !== 'lideranca'));
  const [blocoIdx, setBlocoIdx] = useState(0);
  const [respostas, setRespostas] = useState({});
  const [salvado, setSalvado] = useState(false);

  const bloco = blocos[blocoIdx];
  const pergsBloco = perguntas[bloco?.id] || [];
  const respondidas = blocos.reduce((s, b) => s + (perguntas[b.id] || []).filter((_, i) => respostas[`${b.id}_${i}`] != null).length, 0);
  const totalPergs = blocos.reduce((s, b) => s + (perguntas[b.id] || []).filter(p => !p.opcional).length, 0);

  function isBlocoCompleto(bId) {
    const ps = (perguntas[bId] || []).filter(p => !p.opcional);
    return ps.every((_, i) => respostas[`${bId}_${i}`] != null);
  }

  function calcNota() {
    const notas = {};
    blocos.forEach(b => {
      const ps = (perguntas[b.id] || []).filter(p => p.tipo === 'scale');
      const vals = ps.map((p, i) => typeof respostas[`${b.id}_${i}`] === 'number' ? respostas[`${b.id}_${i}`] : null).filter(v => v != null);
      notas[b.id] = vals.length ? (vals.reduce((s, v) => s + v, 0) / vals.length) * 2 : null;
    });
    const validos = Object.values(notas).filter(v => v != null);
    const media = validos.length ? validos.reduce((s, v) => s + v, 0) / validos.length : 0;
    return { blocos: notas, geral: parseFloat(media.toFixed(1)) };
  }

  const [resultado, setResultado] = useState(null); // { blocos, geral } pós-conclusão

  function handleSalvar() {
    const { blocos: notasBlocos, geral } = calcNota();
    onSalvar({ colab, tipo, blocos: notasBlocos, nota: geral, respostas });
    setResultado({ blocos: notasBlocos, geral });
    setSalvado(true);
  }

  if (salvado) {
    // Auto vs avaliando o liderado: o user pediu pra mostrar a nota DO LIDERADO no fim,
    // não a sua própria nota. "auto" continua sem exibir nota (anti-comparativo).
    const mostrarNota = tipo !== 'auto' && resultado;
    const geral = resultado?.geral;
    const corNota = geral >= 8 ? '#00836B' : geral >= 6 ? '#E89B3B' : '#B3261E';
    return (
      <div style={{ textAlign: 'center', padding: '36px 16px' }}>
        <div style={{ color: 'var(--escalab-brand)', marginBottom: 12 }}><Icon name="check" size={44} /></div>
        <div style={{ fontSize: 17, fontWeight: 700, marginBottom: 6 }}>Avaliação concluída!</div>
        <div style={{ fontSize: 13.5, color: 'var(--escalab-mute)', marginBottom: 22 }}>
          A avaliação de {colab.nome.split(' ')[0]} foi salva com sucesso neste ciclo.
        </div>

        {mostrarNota && (
          <div style={{ maxWidth: 420, margin: '0 auto 22px', background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, padding: '18px 22px', boxShadow: '0 4px 14px rgba(0,0,0,.06)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)' }}>
              Nota final · {colab.nome.split(' ').slice(0,2).join(' ')}
            </div>
            <div style={{ fontSize: 42, fontWeight: 900, color: corNota, lineHeight: 1.05, marginTop: 4 }}>
              {geral?.toFixed(1)}<span style={{ fontSize: 18, color: 'var(--escalab-mute)', fontWeight: 700 }}>/10</span>
            </div>
            {/* Quebra por bloco */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(110px, 1fr))', gap: 10, marginTop: 14 }}>
              {Object.entries(resultado.blocos).filter(([, v]) => v != null).map(([id, v]) => {
                const def = AVD_BLOCOS.find(b => b.id === id);
                return (
                  <div key={id} style={{ background: 'var(--escalab-paper)', borderRadius: 8, padding: '8px 10px', textAlign: 'left' }}>
                    <div style={{ fontSize: 10.5, fontWeight: 700, color: def?.cor || 'var(--escalab-mute)', textTransform: 'uppercase', letterSpacing: '.06em' }}>{def?.label || id}</div>
                    <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--escalab-ink)' }}>{v.toFixed(1)}<span style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>/10</span></div>
                  </div>
                );
              })}
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginTop: 12, lineHeight: 1.4 }}>
              Esta é a nota que <strong>você</strong> deu para {colab.nome.split(' ')[0]} nesta etapa do ciclo. A nota oficial cruza todas as fontes (líder, pares, autoavaliação, intersetorial).
            </div>
          </div>
        )}

        <Button variant="outline" onClick={onBack}>Voltar à lista</Button>
      </div>
    );
  }

  return (
    <div>
      {/* Cabeçalho do colaborador */}
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 18 }}>
        <Avatar nome={colab.nome} cor={colab.cor} iniciais={colab.iniciais} size={38} />
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--escalab-ink)' }}>{colab.nome}</div>
          <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 1 }}>{colab.cargo}</div>
          {tipoCfg && (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 6, padding: '3px 9px', borderRadius: 999, background: tipoCfg.cor + '15', color: tipoCfg.cor, fontSize: 11, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase' }}>
              <Icon name={tipoCfg.icon} size={10} /> {tipoCfg.label}
            </div>
          )}
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>Progresso</div>
          <div style={{ fontSize: 13, fontWeight: 700, color: respondidas >= totalPergs ? 'var(--escalab-brand)' : '#E89B3B' }}>
            {blocos.filter(b => isBlocoCompleto(b.id)).length}/{blocos.length} respondidas
          </div>
        </div>
      </div>

      {/* Tabs de blocos */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 20, flexWrap: 'wrap' }}>
        {blocos.map((b, i) => {
          const done = isBlocoCompleto(b.id);
          const isAtual = i === blocoIdx;
          return (
            <button key={b.id} onClick={() => setBlocoIdx(i)} style={{
              display: 'flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 8,
              border: `1.5px solid ${isAtual ? b.cor : done ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
              background: isAtual ? b.cor + '15' : done ? 'var(--escalab-brand-tint)' : '#fff',
              color: isAtual ? b.cor : done ? 'var(--escalab-brand-deep)' : 'var(--escalab-mute)',
              cursor: 'pointer', fontSize: 12.5, fontWeight: isAtual ? 700 : 500,
              fontFamily: 'var(--font-sans)', transition: 'all .15s',
            }}>
              {done ? <Icon name="check" size={12} /> : <span style={{ fontSize: 11, fontWeight: 700 }}>{i + 1}·</span>}
              {b.label}
            </button>
          );
        })}
      </div>

      {/* Título do bloco */}
      <div style={{ fontSize: 13, fontWeight: 600, color: bloco?.cor, marginBottom: 20, background: bloco?.cor + '10', borderRadius: 8, padding: '8px 12px' }}>
        Bloco {blocoIdx + 1} · {bloco?.label}
      </div>

      {/* Perguntas */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
        {pergsBloco.map((p, i) => (
          <div key={i} style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '16px 18px' }}>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--escalab-ink)', marginBottom: 14, lineHeight: 1.5 }}>
              {i + 1}. {p.pergunta}
              {p.opcional && <span style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginLeft: 8, fontStyle: 'italic' }}>(opcional)</span>}
            </div>
            {p.tipo === 'scale' && (
              <ScaleAVD
                value={respostas[`${bloco.id}_${i}`]}
                onChange={v => !readOnly && setRespostas(r => ({ ...r, [`${bloco.id}_${i}`]: v }))}
                min={p.min} max={p.max}
                escalaMin={p.escalaMin} escalaMax={p.escalaMax}
              />
            )}
            {p.tipo === 'choice' && (
              <ChoiceAVD
                value={respostas[`${bloco.id}_${i}`]}
                onChange={v => !readOnly && setRespostas(r => ({ ...r, [`${bloco.id}_${i}`]: v }))}
                opcoes={p.opcoes}
              />
            )}
            {p.tipo === 'text' && (
              <textarea
                value={respostas[`${bloco.id}_${i}`] || ''}
                onChange={e => !readOnly && setRespostas(r => ({ ...r, [`${bloco.id}_${i}`]: e.target.value }))}
                rows={3} placeholder="Descreva aqui…"
                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' }}
              />
            )}
          </div>
        ))}
      </div>

      {/* Navegação */}
      {!readOnly && (
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 24, paddingTop: 20, borderTop: '1px solid var(--escalab-line)' }}>
          <Button variant="outline" size="sm" icon="chev_left" onClick={() => setBlocoIdx(b => Math.max(0, b - 1))} disabled={blocoIdx === 0}>
            {blocoIdx > 0 ? blocos[blocoIdx - 1].label : 'Anterior'}
          </Button>
          {blocoIdx < blocos.length - 1
            ? <Button variant="primary" size="sm" onClick={() => setBlocoIdx(b => b + 1)}>
                {blocos[blocoIdx + 1].label} →
              </Button>
            : <Button variant="primary" size="sm" icon="check" onClick={handleSalvar}>
                Concluir avaliação
              </Button>
          }
        </div>
      )}
    </div>
  );
};

// ── Card de resultado de avaliação ─────────────────────────────────────────

const ResultadoCard = ({ colab, onIrFeedback }) => {
  const notas = getNotaColab(colab.id);
  const hist = AVD_HISTORICO[colab.id] || [];
  if (!notas.geral) return (
    <div style={{ textAlign: 'center', padding: '48px 24px', color: 'var(--escalab-mute)' }}>
      <Icon name="clock" size={36} />
      <div style={{ marginTop: 12, fontSize: 14 }}>Avaliação ainda não concluída neste ciclo</div>
    </div>
  );

  const corNota = notas.geral >= 8.5 ? '#00967B' : notas.geral >= 7 ? '#E89B3B' : '#B3261E';
  const destaque = notas.geral >= 8.5 ? 'Destaque' : notas.geral >= 7 ? 'Bom' : 'Atenção';
  const maxHist = Math.max(...hist.map(h => h.nota), notas.geral || 0);
  const crescimento = hist.length >= 2 ? (hist[hist.length - 1].nota - hist[0].nota).toFixed(1) : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Header resultado */}
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, padding: '20px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 20 }}>
          <Avatar nome={colab.nome} cor={colab.cor} iniciais={colab.iniciais} size={44} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--escalab-ink)' }}>{colab.nome}</div>
            <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginTop: 2 }}>
              {colab.cargo} · {colab.setor}
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
              <Tag tone="brand" size="xs">Ciclo 1º sem 2025</Tag>
              <Tag tone="success" size="xs">Avaliação concluída</Tag>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--escalab-mute)', textTransform: 'uppercase', letterSpacing: '.1em', marginBottom: 4 }}>Nota geral</div>
            <div style={{ fontSize: 44, fontWeight: 800, color: corNota, lineHeight: 1 }}>{notas.geral.toFixed(1)}</div>
            <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 2 }}>de 10,0</div>
            <div style={{ marginTop: 6 }}>
              <Tag tone={notas.geral >= 8.5 ? 'success' : notas.geral >= 7 ? 'warn' : 'danger'} size="xs">{destaque}</Tag>
            </div>
          </div>
        </div>

        {/* Notas por fonte */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
          {[
            { label: 'Líder avaliou',    val: notas.lider,          cor: '#1F4A8A' },
            { label: 'Pares avaliaram',  val: notas.pares,          cor: '#6B3FA0' },
            { label: 'Autoavaliação',    val: notas.auto,           cor: '#005E4D' },
            { label: 'Intersetorial',    val: notas.intersetorial,  cor: '#E89B3B' },
          ].map(f => (
            <div key={f.label} style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '12px 14px', textAlign: 'center' }}>
              <div style={{ fontSize: 11, color: 'var(--escalab-mute)', marginBottom: 6 }}>{f.label}</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: f.cor }}>{f.val ? f.val.toFixed(1) : '·'}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Nota por competência + Nota por fonte */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '18px 20px' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 14 }}>Nota por Competência</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {AVD_BLOCOS.filter(b => notas.blocos[b.id]).map(b => {
              const n = notas.blocos[b.id];
              const pct = (n / 10) * 100;
              const cor = n >= 8.5 ? '#00967B' : n >= 7 ? '#E89B3B' : '#B3261E';
              return (
                <div key={b.id}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                    <span style={{ fontSize: 13, color: 'var(--escalab-ink)', fontWeight: 500 }}>{b.label}</span>
                    <span style={{ fontSize: 13, fontWeight: 700, color: cor }}>{n.toFixed(1)}</span>
                  </div>
                  <div style={{ height: 7, background: 'var(--escalab-line)', borderRadius: 999 }}>
                    <div style={{ width: pct + '%', height: '100%', background: cor, borderRadius: 999, transition: 'width .5s' }} />
                  </div>
                </div>
              );
            })}
            <div style={{ marginTop: 6, paddingTop: 12, borderTop: '1px solid var(--escalab-line)', fontSize: 12, color: 'var(--escalab-mute)' }}>
              Pesos configurados pelo admin
              <button style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-brand)', fontSize: 12, marginLeft: 8, padding: 0 }}>Ver pesos</button>
            </div>
          </div>
        </div>

        <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '18px 20px' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 14 }}>Nota por Fonte de Avaliação</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              { icon: 'trend_up', label: 'Avaliação do líder',        sub: 'peso 40%', val: notas.lider        },
              { icon: 'users',   label: 'Pares (intersetorial)',      sub: '2 avaliadores · peso 20%', val: notas.pares   },
              { icon: 'user',    label: 'Autoavaliação',               sub: 'Própria colaboradora · peso 20%', val: notas.auto   },
              { icon: 'star',    label: 'Intersetorial recebida',     sub: '1 avaliador externo · peso 20%', val: notas.intersetorial },
            ].filter(f => f.val).map(f => (
              <div key={f.label} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <div style={{ color: 'var(--escalab-brand)', flexShrink: 0 }}><Icon name={f.icon} size={14} /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--escalab-ink)' }}>{f.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>{f.sub}</div>
                </div>
                <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--escalab-brand-deep)' }}>{f.val.toFixed(1)}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Evolução histórica */}
      {hist.length > 0 && (
        <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '18px 20px' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 14 }}>
            Evolução Histórica · Últimos {hist.length} Ciclos
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end', marginBottom: 12 }}>
            {[...hist, { ciclo: 'Dez 25', nota: null }].map((h, i) => {
              const pct = h.nota ? Math.max(20, (h.nota / 10) * 100) : 0;
              const cor = !h.nota ? 'var(--escalab-line)' : h.nota === Math.max(...hist.map(x => x.nota)) ? '#00967B' : '#F5A623';
              const isAtual = h.ciclo === hist[hist.length - 1]?.ciclo;
              return (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                  {h.nota && <div style={{ fontSize: 12.5, fontWeight: 700, color: cor }}>{h.nota.toFixed(1)}</div>}
                  <div style={{
                    width: '100%', background: cor, borderRadius: '6px 6px 0 0',
                    height: h.nota ? pct + 'px' : 20, maxHeight: 80, minHeight: 8,
                    opacity: h.nota ? 1 : 0.2,
                    border: isAtual ? `2px solid ${cor}` : 'none',
                  }} />
                  <div style={{ fontSize: 11, color: isAtual ? 'var(--escalab-ink)' : 'var(--escalab-mute)', fontWeight: isAtual ? 600 : 400 }}>
                    {h.ciclo}{isAtual ? ' ·atual' : ''}
                  </div>
                </div>
              );
            })}
          </div>
          {crescimento && (
            <div style={{ fontSize: 12.5, color: '#00967B', display: 'flex', gap: 5, alignItems: 'center' }}>
              <Icon name="trend_up" size={13} />
              Crescimento de <strong>+{crescimento} pontos</strong> no último ano · tendência positiva
            </div>
          )}
        </div>
      )}

      {/* Comparativo com setor */}
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '18px 20px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)' }}>
            Comparativo com o Setor · {colab.setor}
          </div>
          {notas.geral > notas.mediaSetor && (
            <span style={{ fontSize: 11.5, fontWeight: 600, color: '#00967B', background: '#E6F5F1', borderRadius: 5, padding: '2px 8px' }}>
              Acima da média
            </span>
          )}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginBottom: 14 }}>
          {[
            { label: colab.nome.split(' ')[0], val: notas.geral, cor: '#00967B' },
            { label: 'Média do setor', val: notas.mediaSetor, cor: 'var(--escalab-mute)' },
            { label: 'Diferença', val: notas.geral - notas.mediaSetor, cor: notas.geral > notas.mediaSetor ? '#00967B' : '#B3261E', prefix: '+' },
          ].map(r => (
            <div key={r.label} style={{ textAlign: 'center', background: 'var(--escalab-paper)', borderRadius: 9, padding: '12px 8px' }}>
              <div style={{ fontSize: 11, color: 'var(--escalab-mute)', marginBottom: 4 }}>{r.label}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: r.cor }}>
                {r.prefix && r.val > 0 ? r.prefix : ''}{r.val?.toFixed(1)}
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { label: colab.nome.split(' ')[0], val: notas.geral, cor: '#00967B' },
            { label: 'Média setor', val: notas.mediaSetor, cor: '#8A95A0' },
          ].map(r => (
            <div key={r.label} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <div style={{ width: 10, height: 10, borderRadius: 2, background: r.cor, flexShrink: 0 }} />
              <div style={{ flex: 1, height: 7, background: 'var(--escalab-line)', borderRadius: 999 }}>
                <div style={{ width: (r.val / 10 * 100) + '%', height: '100%', background: r.cor, borderRadius: 999, transition: 'width .5s' }} />
              </div>
              <span style={{ fontSize: 12, fontWeight: 700, color: r.cor, minWidth: 28 }}>{r.val?.toFixed(1)}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Ações */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <button style={{ display: 'flex', gap: 7, alignItems: 'center', border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 8, padding: '9px 16px', cursor: 'pointer', fontSize: 13, fontFamily: 'var(--font-sans)', color: 'var(--escalab-slate)' }}>
          <Icon name="download" size={14} /> Exportar PDF
        </button>
        {onIrFeedback && (
          <button onClick={onIrFeedback} style={{ display: 'flex', gap: 7, alignItems: 'center', border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 8, padding: '9px 16px', cursor: 'pointer', fontSize: 13, fontFamily: 'var(--font-sans)', color: 'var(--escalab-slate)' }}>
            <Icon name="message" size={14} /> Ir para feedback
          </button>
        )}
        <button style={{ display: 'flex', gap: 7, alignItems: 'center', border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 8, padding: '9px 16px', cursor: 'pointer', fontSize: 13, fontFamily: 'var(--font-sans)', color: 'var(--escalab-slate)' }}>
          <Icon name="eye" size={14} /> Ver respostas completas
        </button>
      </div>
    </div>
  );
};

// ── Seção de Feedbacks do Colaborador ──────────────────────────────────────

const FeedbackColabSection = ({ colab, user }) => {
  const hist = AVD_HISTORICO[colab.id] || [];
  const [arquivosLocal, setArquivosLocal] = useState(() => getFeedbacksArquivos(colab.id));
  const [showAdd, setShowAdd] = useState(false);
  const [addForm, setAddForm] = useState({ data: new Date().toISOString().slice(0,10), nota: '', arquivo: '' });
  const setF = (k,v) => setAddForm(f=>({...f,[k]:v}));

  function handleAdd(e) {
    e.preventDefault();
    if (!addForm.data) return;
    const fb = {
      id: 'FB' + Date.now(),
      data: addForm.data,
      responsavel: user.nome || user.cargo,
      gestorId: user.id,
      nota: addForm.nota,
      arquivo: addForm.arquivo || null,
      arquivoData: addForm.arquivoData || null,
      status: addForm.arquivo ? 'realizado' : 'sem_arquivo',
    };
    addFeedbackArquivo(colab.id, fb);
    setArquivosLocal(getFeedbacksArquivos(colab.id));
    setShowAdd(false); setAddForm({ data: new Date().toISOString().slice(0,10), nota:'', arquivo:'', arquivoData: '' });
  }
  function handleFileChange(e) {
    const file = e.target.files[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) { alert('Arquivo muito grande (máx 5MB).'); return; }
    const r = new FileReader();
    r.onload = ev => {
      setAddForm(f => ({ ...f, arquivo: file.name, arquivoData: ev.target.result }));
    };
    r.readAsDataURL(file);
  }

  const dataFmt = 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 `${d} ${MESES[parseInt(m) - 1]} ${y}`;
  };

  const maxNota = hist.length ? Math.max(...hist.map(h => h.nota)) : 10;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Avaliações históricas */}
      {hist.length > 0 && (
        <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '18px 20px' }}>
          <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={13} /> Avaliações de Desempenho
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {hist.slice().reverse().map((h, i) => {
              const pct = (h.nota / 10) * 100;
              const cor = h.nota >= 8.5 ? '#00967B' : h.nota >= 7 ? '#E89B3B' : '#B3261E';
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ fontSize: 11.5, color: 'var(--escalab-mute)', minWidth: 52, fontWeight: 500 }}>{h.ciclo}</span>
                  <div style={{ background: cor + '20', borderRadius: 6, padding: '2px 8px', minWidth: 34, textAlign: 'center' }}>
                    <span style={{ fontSize: 13, fontWeight: 700, color: cor }}>{h.nota.toFixed(1)}</span>
                  </div>
                  <div style={{ flex: 1, height: 8, background: 'var(--escalab-line)', borderRadius: 999 }}>
                    <div style={{ width: pct + '%', height: '100%', background: cor, borderRadius: 999, transition: 'width .6s' }} />
                  </div>
                  <span style={{ fontSize: 11, color: 'var(--escalab-mute)', minWidth: 100, textAlign: 'right' }}>{h.tipo}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Feedbacks registrados */}
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '18px 20px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', display: 'flex', gap: 6, alignItems: 'center' }}>
            <Icon name="clipboard" size={13} /> Feedbacks Registrados
          </div>
          {(user?.perfil === 'admin' || user?.perfil === 'gestor') && (
            <button onClick={() => setShowAdd(v=>!v)} style={{ display: 'flex', gap: 6, alignItems: 'center', border: '1px solid var(--escalab-line)', background: showAdd ? 'var(--escalab-brand-tint)' : '#fff', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontSize: 12.5, fontFamily: 'var(--font-sans)', color: showAdd ? 'var(--escalab-brand)' : 'var(--escalab-slate)' }}>
              <Icon name="plus" size={13} /> Registrar feedback
            </button>
          )}
          {showAdd && (
            <form onSubmit={handleAdd} style={{ background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: '14px', marginTop: 8, display: 'flex', flexDirection: 'column', gap: 10, width: '100%' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--escalab-ink)', marginBottom: 2 }}>Registrar feedback para: <span style={{ color: 'var(--escalab-brand)' }}>{colab.nome}</span></div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--escalab-slate)' }}>Data *</span>
                  <input type="date" value={addForm.data} onChange={e=>setF('data',e.target.value)} required style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '7px 10px', fontSize: 13, fontFamily: 'var(--font-sans)', outline: 'none' }}/>
                </label>
                <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--escalab-slate)' }}>Arquivo (nome)</span>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 6, border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '7px 10px', cursor: 'pointer', fontSize: 13, background: '#fff', color: addForm.arquivo ? 'var(--escalab-brand)' : 'var(--escalab-mute)' }}>
                    <Icon name="upload" size={13}/> {addForm.arquivo || 'Selecionar arquivo'}
                    <input type="file" accept=".pdf,.doc,.docx" onChange={handleFileChange} style={{ display: 'none' }}/>
                  </label>
                </label>
              </div>
              <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--escalab-slate)' }}>Observações</span>
                <textarea value={addForm.nota} onChange={e=>setF('nota',e.target.value)} rows={2} placeholder="Comentários sobre o feedback..." style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '7px 10px', fontSize: 13, fontFamily: 'var(--font-sans)', outline: 'none', resize: 'vertical' }}/>
              </label>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                <button type="button" onClick={() => setShowAdd(false)} style={{ padding: '6px 14px', border: '1px solid var(--escalab-line)', borderRadius: 7, background: '#fff', cursor: 'pointer', fontSize: 12, fontFamily: 'var(--font-sans)' }}>Cancelar</button>
                <button type="submit" style={{ padding: '6px 14px', border: 0, borderRadius: 7, background: 'var(--escalab-brand)', color: '#fff', cursor: 'pointer', fontWeight: 600, fontSize: 12, fontFamily: 'var(--font-sans)' }}>Salvar</button>
              </div>
            </form>
          )}
        </div>

        {arquivosLocal.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '24px', color: 'var(--escalab-mute)', fontSize: 13 }}>
            Nenhum feedback registrado ainda.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {arquivosLocal.map((fb, i) => (
              <div key={fb.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: i < arquivosLocal.length - 1 ? '1px solid var(--escalab-line)' : 0 }}>
                <div style={{ flexShrink: 0 }}>
                  {fb.arquivo ? (
                    <div style={{ width: 34, height: 34, borderRadius: 8, background: '#FDECEC', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: '#B3261E' }}>PDF</div>
                    </div>
                  ) : (
                    <div style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--escalab-paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px dashed var(--escalab-line)' }}>
                      <div style={{ color: 'var(--escalab-mute)' }}><Icon name="file" size={14} /></div>
                    </div>
                  )}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  {fb.arquivo
                    ? <div style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--escalab-ink)' }}>{fb.arquivo}</div>
                    : <div style={{ fontSize: 13, color: 'var(--escalab-mute)', fontStyle: 'italic' }}>{fb.nota || 'Sem arquivo anexado'}</div>
                  }
                  <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginTop: 2 }}>
                    {fb.responsavel?.split(' ').slice(0,2).join(' ')} · {dataFmt(fb.data)}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
                  <span style={{
                    fontSize: 11.5, fontWeight: 600, borderRadius: 6, padding: '3px 10px',
                    background: fb.status === 'realizado' ? '#E6F5F1' : '#FFF7EB',
                    color: fb.status === 'realizado' ? '#00836B' : '#B56500',
                  }}>
                    {fb.status === 'realizado' ? 'Realizado' : 'Sem arquivo'}
                  </span>
                  {fb.arquivo && (
                    fb.arquivoData ? (
                      <a href={fb.arquivoData} download={fb.arquivo} title="Baixar arquivo"
                        style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 7, padding: '4px 8px', cursor: 'pointer', color: 'var(--escalab-slate)', display: 'inline-flex', alignItems: 'center' }}>
                        <Icon name="download" size={13} />
                      </a>
                    ) : (
                      <button title="Arquivo de demonstração — sem conteúdo anexado" disabled
                        style={{ border: '1px solid var(--escalab-line)', background: '#F5F7FA', borderRadius: 7, padding: '4px 8px', cursor: 'not-allowed', color: 'var(--escalab-mute)' }}>
                        <Icon name="download" size={13} />
                      </button>
                    )
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// ── Visão Admin (gestão do ciclo) ──────────────────────────────────────────

const AdminAVDView = ({ user }) => {
  const ciclo = CICLOS.find(c => c.status === 'ativo') || CICLOS[CICLOS.length - 1];
  const [busca, setBusca] = useState('');
  const [colabSel, setColabSel] = useState(null);
  const [painel, setPainel] = useState('form'); // 'form' | 'resultado' | 'feedback'
  const [concluidas, setConcluidas] = useState([]);
  const [notasLiberadas, setNotasLiberadas] = useState(() => getNotasLiberadasIds());
  const [feedbackLiberacao, setFeedbackLiberacao] = useState('');
  const [modalAvalMulti, setModalAvalMulti] = useState(null);

  function liberarNota(id) {
    const ok = liberarNotasColaborador(id);
    setNotasLiberadas(getNotasLiberadasIds());
    const c = COLABORADORES.find(x => x.id === id);
    const nome = c?.nome.split(' ')[0] || 'colaborador';
    setFeedbackLiberacao(
      ok
        ? `✓ Nota de ${nome} liberada · ${nome} já consegue ver no próximo login (ou agora se já estiver logado).`
        : `⚠ Não consegui confirmar a liberação de ${nome}. Tente novamente.`
    );
    setTimeout(() => setFeedbackLiberacao(''), 5000);
  }
  function bloquearNota(id) {
    const ok = bloquearNotasColaborador(id);
    setNotasLiberadas(getNotasLiberadasIds());
    const c = COLABORADORES.find(x => x.id === id);
    const nome = c?.nome.split(' ')[0] || 'colaborador';
    setFeedbackLiberacao(
      ok ? `✓ Nota de ${nome} bloqueada novamente.` : `⚠ Não consegui confirmar o bloqueio de ${nome}.`
    );
    setTimeout(() => setFeedbackLiberacao(''), 4000);
  }
  function liberarTodas() {
    COLABORADORES.forEach(c => liberarNotasColaborador(c.id));
    setNotasLiberadas(getNotasLiberadasIds());
    setFeedbackLiberacao('Notas liberadas para todos os colaboradores.');
    setTimeout(() => setFeedbackLiberacao(''), 3500);
  }
  function bloquearTodas() {
    if (!confirm('Bloquear as notas de todos os colaboradores?')) return;
    COLABORADORES.forEach(c => bloquearNotasColaborador(c.id));
    setNotasLiberadas(getNotasLiberadasIds());
    setFeedbackLiberacao('Todas as notas foram bloqueadas.');
    setTimeout(() => setFeedbackLiberacao(''), 3500);
  }

  const lista = useMemo(() =>
    COLABORADORES.filter(c => !busca || c.nome.toLowerCase().includes(busca.toLowerCase()) || c.cargo.toLowerCase().includes(busca.toLowerCase()))
  , [busca]);

  const totalLib = notasLiberadas.size;
  const totalBloq = COLABORADORES.length - totalLib;
  const pctLib = COLABORADORES.length > 0 ? Math.round(totalLib / COLABORADORES.length * 100) : 0;

  const totalConc = COLABORADORES.filter(c => {
    const n = getNotaColab(c.id);
    return n.status === 'concluida' || concluidas.some(x => x.colab.id === c.id);
  }).length;
  const totalPend = COLABORADORES.length - totalConc;
  const pct = Math.round((totalConc / COLABORADORES.length) * 100);

  function getStatusColab(c) {
    if (concluidas.some(x => x.colab.id === c.id)) return 'concluida';
    return getNotaColab(c.id).status;
  }

  const statusCfg = {
    concluida:    { label: 'Concluída',    tone: 'success', cor: '#00836B' },
    em_andamento: { label: 'Em andamento', tone: 'warn',    cor: '#B56500' },
    pendente:     { label: 'Pendente',     tone: 'neutral', cor: 'var(--escalab-mute)' },
  };

  return (
    <div>
      {/* ── Liberação de notas · DESTACADO ── */}
      <div style={{
        background: totalLib === COLABORADORES.length
          ? 'linear-gradient(135deg, #E6F5F1 0%, #D5F0E8 100%)'
          : totalLib === 0
            ? 'linear-gradient(135deg, #FDECEC 0%, #FCE0E0 100%)'
            : 'linear-gradient(135deg, #FFF7EB 0%, #FCE9C8 100%)',
        border: `2px solid ${totalLib === COLABORADORES.length ? '#00836B' : totalLib === 0 ? '#B3261E' : '#B56500'}`,
        borderRadius: 14,
        padding: '18px 22px',
        marginBottom: 18,
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        flexWrap: 'wrap',
        gap: 14,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, flex: 1, minWidth: 280 }}>
          <div style={{ width: 48, height: 48, borderRadius: 12, background: totalLib === COLABORADORES.length ? '#00836B' : totalLib === 0 ? '#B3261E' : '#B56500', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name={totalLib === COLABORADORES.length ? 'eye' : 'lock'} size={22} />
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: totalLib === COLABORADORES.length ? '#005C4A' : totalLib === 0 ? '#7A1818' : '#7A4400', marginBottom: 4 }}>
              Liberação de notas · {pctLib}%
            </div>
            <div style={{ fontSize: 15, fontWeight: 800, color: totalLib === COLABORADORES.length ? '#005C4A' : totalLib === 0 ? '#7A1818' : '#7A4400' }}>
              {totalLib === COLABORADORES.length
                ? `Todas as ${COLABORADORES.length} notas estão liberadas`
                : totalLib === 0
                  ? `Nenhuma nota liberada · colaboradores não conseguem ver`
                  : `${totalLib} liberada${totalLib !== 1 ? 's' : ''} · ${totalBloq} bloqueada${totalBloq !== 1 ? 's' : ''}`}
            </div>
            <div style={{ fontSize: 12.5, color: totalLib === COLABORADORES.length ? '#005C4A' : totalLib === 0 ? '#7A1818' : '#7A4400', marginTop: 3, opacity: .85 }}>
              {totalLib === 0
                ? 'Libere abaixo (todos de uma vez, ou pessoa a pessoa na lista).'
                : totalLib === COLABORADORES.length
                  ? 'Toda a equipe consegue ver suas notas de AVD agora.'
                  : 'Selecione um colaborador na lista para liberar individualmente, ou use o botão à direita para liberar todos.'}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
          {totalBloq > 0 && (
            <Button variant="primary" icon="eye" onClick={liberarTodas}>
              Liberar para todos ({totalBloq})
            </Button>
          )}
          {totalLib > 0 && (
            <Button variant="outline" icon="lock" onClick={bloquearTodas}>
              Bloquear todos
            </Button>
          )}
        </div>
      </div>

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

      {/* Header ciclo */}
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '18px 24px', marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14, flexWrap: 'wrap', gap: 10 }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--escalab-ink)' }}>Avaliações de desempenho</div>
            <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginTop: 3 }}>
              Ciclo ativo: {ciclo?.nome} · Encerra em {ciclo?.fim ? ciclo.fim.split('-').reverse().join('/') : '·'}
            </div>
          </div>
          <CicloMenu ciclo={ciclo} onMudouStatus={() => window.location.reload()} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
          {[
            { label: 'Total de colaboradores', val: COLABORADORES.length, cor: 'var(--escalab-ink)' },
            { label: 'Concluídas',              val: totalConc,             cor: '#00967B' },
            { label: 'Pendentes',               val: totalPend,             cor: '#E89B3B' },
            { label: 'Progresso do ciclo',       val: pct + '%',             cor: 'var(--escalab-brand)' },
          ].map(k => (
            <div key={k.label} style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '14px 16px' }}>
              <div style={{ fontSize: 11, color: 'var(--escalab-mute)', marginBottom: 6 }}>{k.label}</div>
              <div style={{ fontSize: 26, fontWeight: 800, color: k.cor, lineHeight: 1, marginBottom: k.label === 'Progresso do ciclo' ? 8 : 0 }}>{k.val}</div>
              {k.label === 'Progresso do ciclo' && (
                <div style={{ height: 5, background: 'var(--escalab-line)', borderRadius: 999 }}>
                  <div style={{ width: pct + '%', height: '100%', background: 'var(--escalab-brand)', borderRadius: 999, transition: 'width .5s' }} />
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Layout split */}
      <div style={{ display: 'grid', gridTemplateColumns: colabSel ? '280px 1fr' : '1fr', gap: 16 }}>
        {/* Lista colaboradores */}
        <div>
          <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 10 }}>Lista de Colaboradores</div>
          <div style={{ position: 'relative', marginBottom: 10 }}>
            <div style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--escalab-mute)', pointerEvents: 'none' }}>
              <Icon name="search" size={14} />
            </div>
            <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar colaborador…"
              style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '8px 10px 8px 30px', fontSize: 13, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box' }} />
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 500, overflowY: 'auto' }}>
            {lista.map(c => {
              const st = getStatusColab(c);
              const cfg = statusCfg[st];
              const isAtual = colabSel?.id === c.id;
              const isLib = notasLiberadas.has(c.id);
              return (
                <div key={c.id} onClick={() => { setColabSel(c); setPainel('form'); }}
                  style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: isAtual ? 'var(--escalab-brand-tint)' : '#fff', border: `1px solid ${isAtual ? 'var(--escalab-brand-soft)' : 'var(--escalab-line)'}`, borderRadius: 10, cursor: 'pointer', transition: 'all .12s' }}>
                  <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={32} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--escalab-ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {c.nome.split(' ').slice(0, 3).join(' ')}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--escalab-mute)', marginTop: 1 }}>{c.cargo.replace(/ [IVX]+$/, '')}</div>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'flex-end', flexShrink: 0 }}>
                    <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 7px', borderRadius: 5, whiteSpace: 'nowrap', background: st === 'concluida' ? '#E6F5F1' : st === 'em_andamento' ? '#FFF7EB' : 'var(--escalab-paper)', color: cfg.cor }}>
                      {cfg.label}
                    </span>
                    <span title={isLib ? 'Nota liberada para esse colaborador' : 'Nota bloqueada'} style={{ fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 4, whiteSpace: 'nowrap', background: isLib ? '#00836B' : '#B3261E', color: '#fff', display: 'flex', alignItems: 'center', gap: 3 }}>
                      <Icon name={isLib ? 'eye' : 'lock'} size={9} /> {isLib ? 'NOTA LIBERADA' : 'NOTA BLOQUEADA'}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Painel direito */}
        {colabSel && (
          <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '20px 24px' }}>
            {/* Header com botão de liberar/bloquear nota */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, paddingBottom: 14, borderBottom: '1px solid var(--escalab-line)', gap: 12, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Avatar nome={colabSel.nome} cor={colabSel.cor} iniciais={colabSel.iniciais} size={38} />
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--escalab-ink)' }}>{colabSel.nome.split(' ').slice(0, 3).join(' ')}</div>
                  <div style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>{colabSel.cargo} · {colabSel.setor}</div>
                </div>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                <Button size="sm" variant="outline" icon="users" onClick={() => setModalAvalMulti(colabSel)}>
                  Avaliadores
                </Button>
                {notasLiberadas.has(colabSel.id) ? (
                  <>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 700, background: '#E6F5F1', color: '#00836B', border: '1px solid #A3D9CE', borderRadius: 7, padding: '5px 11px' }}>
                      <Icon name="eye" size={12} /> Nota liberada
                    </span>
                    <Button size="sm" variant="outline" icon="lock" onClick={() => bloquearNota(colabSel.id)}>Bloquear</Button>
                  </>
                ) : (
                  <Button variant="primary" icon="eye" onClick={() => liberarNota(colabSel.id)}>
                    Liberar nota para {colabSel.nome.split(' ')[0]}
                  </Button>
                )}
              </div>
            </div>

            {/* Sub-tabs */}
            <div style={{ display: 'flex', gap: 4, marginBottom: 20, borderBottom: '1px solid var(--escalab-line)', paddingBottom: 0 }}>
              {[
                { id: 'form',      label: 'Perguntas' },
                { id: 'resultado', label: 'Resultado' },
                { id: 'feedback',  label: 'Feedbacks' },
              ].map(t => (
                <button key={t.id} onClick={() => setPainel(t.id)} style={{
                  border: 0, background: 'transparent', cursor: 'pointer', padding: '7px 14px', fontSize: 13,
                  fontFamily: 'var(--font-sans)', fontWeight: painel === t.id ? 600 : 400,
                  color: painel === t.id ? 'var(--escalab-brand)' : 'var(--escalab-mute)',
                  borderBottom: `2px solid ${painel === t.id ? 'var(--escalab-brand)' : 'transparent'}`,
                  marginBottom: -1,
                }}>{t.label}</button>
              ))}
            </div>

            {painel === 'form' && (
              <SeletorPerguntasAdmin colab={colabSel} />
            )}
            {painel === 'resultado' && (
              <ResultadoCard colab={colabSel} onIrFeedback={() => setPainel('feedback')} />
            )}
            {painel === 'feedback' && (
              <FeedbackColabSection colab={colabSel} user={user} />
            )}
          </div>
        )}

        {!colabSel && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--escalab-paper)', borderRadius: 12, border: '1px dashed var(--escalab-line)', minHeight: 320, color: 'var(--escalab-mute)', flexDirection: 'column', gap: 10 }}>
            <Icon name="users" size={32} />
            <span style={{ fontSize: 14 }}>Selecione um colaborador para iniciar ou ver avaliação</span>
          </div>
        )}
      </div>
      {modalAvalMulti && <ModalAvaliadoresMulti colab={modalAvalMulti} onClose={() => setModalAvalMulti(null)} />}
    </div>
  );
};

// ── Visão Líder/Gestor ─────────────────────────────────────────────────────

const LiderAVDView = ({ user }) => {
  const ciclo = CICLOS.find(c => c.status === 'ativo');
  const [aba, setAba] = useState('liderados');
  const [colabSel, setColabSel] = useState(null);
  const [concluidas, setConcluidas] = useState([]);
  const [intersetorialColabs, setIntersetorialColabs] = useState([]);
  const [interselSel, setInterselSel] = useState(null);
  const [modoLiderados, setModoLiderados] = useState('pessoas');
  const [setorGestorAvaliando, setSetorGestorAvaliando] = useState(false);
  const [modoIntersetorialL, setModoIntersetorialL] = useState('pessoas');
  const [interSetorLSel, setInterSetorLSel] = useState(null);
  const [interSetorLConcluidos, setInterSetorLConcluidos] = useState([]);

  const diretores = COLABORADORES.filter(c => c.nivel === 'diretor');
  const liderados = COLABORADORES.filter(c => c.gestorNome === user.nome);
  const outrosSetores = COLABORADORES.filter(c => c.setor !== user.setor && c.id !== user.id);

  function getStatusL(c, tipo) {
    if (concluidas.find(x => x.colab.id === c.id && x.tipo === tipo)) return 'concluida';
    const av = AVALIACOES.find(a => a.avaliadorId === user.id && a.avaliadoId === c.id);
    return av?.status === 'concluida' ? 'concluida' : av ? 'em_andamento' : 'pendente';
  }

  const diretConc = diretores.filter(c => getStatusL(c, 'superior') === 'concluida').length;
  const lidConc   = liderados.filter(c => getStatusL(c, 'liderado') === 'concluida').length;
  const autoConc  = concluidas.find(x => x.tipo === 'auto') || AVALIACOES.find(a => a.avaliadorId === user.id && a.tipo === 'auto');
  const interConc = intersetorialColabs.filter(c => concluidas.find(x => x.colab.id === c.id && x.tipo === 'intersetorial')).length;

  const colabsPorAba = {
    diretores: diretores,
    liderados: liderados,
    auto: [user],
    intersetorial: intersetorialColabs,
  }[aba] || [];

  const tipoAba = aba === 'diretores' ? 'superior' : aba === 'auto' ? 'auto' : aba === 'intersetorial' ? 'intersetorial' : 'liderado';

  const statusCor = { concluida: '#00967B', em_andamento: '#E89B3B', pendente: 'var(--escalab-mute)' };
  const statusBg  = { concluida: '#E6F5F1', em_andamento: '#FFF7EB', pendente: 'var(--escalab-paper)' };
  const statusLbl = { concluida: 'OK',     em_andamento: 'Atual',   pendente: '·' };

  return (
    <div>
      {/* Header painel */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--escalab-ink)', marginBottom: 3 }}>Meu painel de avaliações</div>
        <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)' }}>
          Ciclo {ciclo?.nome} · Como: <strong>Líder de setor</strong>
        </div>
      </div>

      {/* KPIs do painel */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
        {[
          { label: 'Avaliar Diretores',  val: `${diretConc}/${diretores.length}`, pct: diretores.length ? diretConc / diretores.length : 0, cor: '#1F4A8A' },
          { label: 'Avaliar Liderados',  val: `${lidConc}/${liderados.length}`,   pct: liderados.length ? lidConc / liderados.length : 0,   cor: '#E89B3B' },
          { label: 'Autoavaliação',       val: autoConc ? 'Concluída' : 'Pendente', pct: autoConc ? 1 : 0,                                   cor: '#00967B' },
          { label: 'Intersetorial',       val: `${interConc}/·`,                   pct: 0,                                                   cor: '#6B3FA0' },
        ].map(k => (
          <div key={k.label} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: '14px 16px' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 8 }}>{k.label}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: k.cor, marginBottom: 8 }}>{k.val}</div>
            <div style={{ height: 4, background: 'var(--escalab-line)', borderRadius: 999 }}>
              <div style={{ width: (k.pct * 100) + '%', height: '100%', background: k.cor, borderRadius: 999, transition: 'width .4s' }} />
            </div>
          </div>
        ))}
      </div>

      {/* Abas */}
      <div style={{ display: 'flex', gap: 0, marginBottom: 20, borderBottom: '1px solid var(--escalab-line)' }}>
        {[
          { id: 'diretores',     label: 'Avaliar diretores' },
          { id: 'liderados',     label: 'Avaliar liderados' },
          { id: 'auto',          label: 'Autoavaliação' },
          { id: 'resultados',    label: '📊 Resultados do time' },
          { id: 'intersetorial', label: '☆ Intersetorial', opcional: true },
        ].map(t => (
          <button key={t.id} onClick={() => { setAba(t.id); setColabSel(null); setInterselSel(null); setInterSetorLSel(null); }} style={{
            border: 0, background: 'transparent', cursor: 'pointer', padding: '9px 16px', fontSize: 13,
            fontFamily: 'var(--font-sans)', fontWeight: aba === t.id ? 600 : 400,
            color: aba === t.id ? 'var(--escalab-brand)' : t.opcional ? '#B56500' : 'var(--escalab-mute)',
            borderBottom: `2px solid ${aba === t.id ? 'var(--escalab-brand)' : 'transparent'}`,
            marginBottom: -1, display: 'flex', gap: 6, alignItems: 'center',
          }}>
            {t.label}
            {t.opcional && <span style={{ fontSize: 10.5, background: '#FFF7EB', color: '#B56500', borderRadius: 4, padding: '1px 5px' }}>Opcional</span>}
          </button>
        ))}
      </div>

      {/* Intersetorial · igual à visão do colaborador */}
      {aba === 'intersetorial' && (
        <div style={{ animation: 'fadeIn .2s' }}>
          {interselSel ? (
            <Card pad={22}>
              <button onClick={() => setInterselSel(null)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
                <Icon name="chev_left" size={14} /> Voltar
              </button>
              {concluidas.find(x => x.colab.id === interselSel.id && x.tipo === 'intersetorial') ? (
                <div style={{ textAlign: 'center', padding: '40px 0' }}>
                  <div style={{ color: 'var(--escalab-brand)', marginBottom: 12 }}><Icon name="check" size={40} /></div>
                  <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 6 }}>Avaliação concluída!</div>
                  <div style={{ fontSize: 13.5, color: 'var(--escalab-mute)' }}>A avaliação de {interselSel.nome.split(' ')[0]} já foi respondida neste ciclo.</div>
                </div>
              ) : (
                <ColabAvaliarPessoa user={user} colab={interselSel} tipo="intersetorial" onConcluir={dados => { setConcluidas(p => [...p, dados]); setInterselSel(null); }} />
              )}
            </Card>
          ) : interSetorLSel ? (
            <Card pad={22}>
              <button onClick={() => setInterSetorLSel(null)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
                <Icon name="chev_left" size={14} /> Voltar
              </button>
              {interSetorLConcluidos.includes(interSetorLSel) ? (
                <div style={{ textAlign: 'center', padding: '40px 0' }}>
                  <div style={{ color: 'var(--escalab-brand)', marginBottom: 12 }}><Icon name="check" size={40} /></div>
                  <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 6 }}>Avaliação concluída!</div>
                  <div style={{ fontSize: 13.5, color: 'var(--escalab-mute)' }}>O setor {interSetorLSel} já foi avaliado neste ciclo.</div>
                </div>
              ) : (
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--escalab-ink)', marginBottom: 16 }}>Avaliação do setor · {interSetorLSel}</div>
                  <FormAVD
                    colab={{ id: 'intersetor_' + interSetorLSel, nome: interSetorLSel, cargo: 'Analista', nivel: 'liderado', iniciais: (interSetorLSel || '').substring(0, 2).toUpperCase(), cor: 'var(--escalab-brand)', setor: interSetorLSel }}
                    tipo="intersetorial"
                    onSalvar={() => { setInterSetorLConcluidos(p => [...p, interSetorLSel]); setInterSetorLSel(null); }}
                    onBack={() => setInterSetorLSel(null)}
                  />
                </div>
              )}
            </Card>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ background: '#F4EEFF', border: '1px solid #C9A0E8', borderRadius: 12, padding: '12px 16px', fontSize: 13, color: '#4A0080', display: 'flex', gap: 9 }}>
                <Icon name="info" size={15} />
                <div><strong>Avaliação intersetorial é opcional.</strong> Avalie colaboradores de outros setores com quem você trabalhou neste ciclo.</div>
              </div>

              {/* Toggle Por pessoa / Setor inteiro */}
              <div style={{ display: 'flex', gap: 8, background: 'var(--escalab-paper)', borderRadius: 10, padding: 4, width: 'fit-content' }}>
                {[{ id: 'pessoas', label: 'Por pessoa' }, { id: 'setores', label: 'Setor inteiro' }].map(m => (
                  <button key={m.id} onClick={() => setModoIntersetorialL(m.id)} style={{
                    border: 0, borderRadius: 7, padding: '7px 16px', cursor: 'pointer', fontSize: 13,
                    fontFamily: 'var(--font-sans)', fontWeight: modoIntersetorialL === m.id ? 600 : 400,
                    background: modoIntersetorialL === m.id ? '#fff' : 'transparent',
                    color: modoIntersetorialL === m.id ? 'var(--escalab-brand)' : 'var(--escalab-mute)',
                    boxShadow: modoIntersetorialL === m.id ? '0 1px 4px rgba(0,0,0,.10)' : 'none',
                    transition: 'all .15s',
                  }}>{m.label}</button>
                ))}
              </div>

              {/* Modo por pessoa */}
              {modoIntersetorialL === 'pessoas' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {[...new Set(outrosSetores.map(c => c.setor))].sort().map(setor => {
                    const membros = outrosSetores.filter(c => c.setor === setor);
                    return (
                      <div key={setor} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, overflow: 'hidden' }}>
                        <div style={{ padding: '10px 16px', background: 'var(--escalab-paper)', borderBottom: '1px solid var(--escalab-line)', fontSize: 12.5, fontWeight: 700, color: 'var(--escalab-ink)', display: 'flex', alignItems: 'center', gap: 8 }}>
                          <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--escalab-brand)' }} />
                          {setor} <span style={{ fontSize: 11, color: 'var(--escalab-mute)', fontWeight: 400 }}>({membros.length})</span>
                        </div>
                        <div>
                          {membros.map((c, i) => {
                            const concl = concluidas.find(x => x.colab.id === c.id && x.tipo === 'intersetorial');
                            return (
                              <div key={c.id} onClick={() => setInterselSel(c)}
                                style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px', borderBottom: i < membros.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'}>
                                <PhotoAvatar colaborador={c} size={32} />
                                <div style={{ flex: 1 }}>
                                  <div style={{ fontSize: 13, fontWeight: 600 }}>{c.nome.split(' ').slice(0, 3).join(' ')}</div>
                                  <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>{c.cargo}</div>
                                </div>
                                {concl ? <Tag tone="success" size="xs">Concluída</Tag> : <span style={{ fontSize: 12, color: 'var(--escalab-brand)', fontWeight: 600 }}>Avaliar →</span>}
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Modo setor inteiro */}
              {modoIntersetorialL === 'setores' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {[...new Set(outrosSetores.map(c => c.setor))].sort().map(setor => {
                    const membros = outrosSetores.filter(c => c.setor === setor);
                    const concluido = interSetorLConcluidos.includes(setor);
                    return (
                      <div key={setor} onClick={() => !concluido && setInterSetorLSel(setor)}
                        style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '18px 20px', background: '#fff', border: `1px solid ${concluido ? 'var(--escalab-brand-soft)' : 'var(--escalab-line)'}`, borderRadius: 14, cursor: concluido ? 'default' : 'pointer', transition: 'all .15s' }}
                        onMouseEnter={e => { if (!concluido) { e.currentTarget.style.boxShadow = '0 4px 14px rgba(0,0,0,.08)'; e.currentTarget.style.transform = 'translateY(-1px)'; } }}
                        onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
                        <div style={{ width: 48, height: 48, borderRadius: 12, background: concluido ? 'var(--escalab-brand-tint)' : 'var(--escalab-paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                          <Icon name="users" size={22} />
                        </div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--escalab-ink)' }}>{setor}</div>
                          <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 2 }}>{membros.length} colaboradores</div>
                        </div>
                        {concluido
                          ? <Tag tone="success" size="xs">Concluída</Tag>
                          : <span style={{ fontSize: 12, color: 'var(--escalab-brand)', fontWeight: 600 }}>Avaliar setor →</span>
                        }
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* Toggle setor inteiro · apenas aba liderados */}
      {aba === 'liderados' && !colabSel && !setorGestorAvaliando && (
        <div style={{ display: 'flex', gap: 8, marginBottom: 16, background: 'var(--escalab-paper)', borderRadius: 10, padding: 4, width: 'fit-content' }}>
          {[{ id: 'pessoas', label: 'Por colaborador' }, { id: 'geral', label: 'Setor inteiro' }].map(m => (
            <button key={m.id} onClick={() => setModoLiderados(m.id)} style={{
              border: 0, borderRadius: 7, padding: '7px 16px', cursor: 'pointer', fontSize: 13,
              fontFamily: 'var(--font-sans)', fontWeight: modoLiderados === m.id ? 600 : 400,
              background: modoLiderados === m.id ? '#fff' : 'transparent',
              color: modoLiderados === m.id ? 'var(--escalab-brand)' : 'var(--escalab-mute)',
              boxShadow: modoLiderados === m.id ? '0 1px 4px rgba(0,0,0,.10)' : 'none',
              transition: 'all .15s',
            }}>{m.label}</button>
          ))}
        </div>
      )}

      {/* Modo setor inteiro · liderados */}
      {aba === 'liderados' && modoLiderados === 'geral' && (
        setorGestorAvaliando ? (
          <Card pad={22}>
            <button onClick={() => setSetorGestorAvaliando(false)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
              <Icon name="chev_left" size={14} /> Voltar
            </button>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 16 }}>Avaliação do setor · {user.setor}</div>
            <FormAVD
              colab={{ id: 'setor_' + user.setor, nome: user.setor, cargo: 'Analista', nivel: 'liderado', iniciais: (user.setor || '').substring(0, 2).toUpperCase(), cor: 'var(--escalab-brand)', setor: user.setor }}
              tipo="setor"
              onSalvar={() => setSetorGestorAvaliando(false)}
              onBack={() => setSetorGestorAvaliando(false)}
            />
          </Card>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Banner tone="info">Avalie os liderados como grupo · uma única avaliação coletiva para o setor.</Banner>
            <div onClick={() => setSetorGestorAvaliando(true)}
              style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '20px 22px', background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, cursor: 'pointer', transition: 'all .15s' }}
              onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 14px rgba(0,0,0,.08)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
              onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
              <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--escalab-brand-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="users" size={24} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--escalab-ink)' }}>{user.setor}</div>
                <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginTop: 3 }}>{liderados.length} liderados · avaliação coletiva do grupo</div>
              </div>
              <Button variant="primary">Avaliar setor →</Button>
            </div>
          </div>
        )
      )}

      {/* Layout split */}
      {(aba !== 'intersetorial') && (aba !== 'liderados' || modoLiderados === 'pessoas') && (
        <div style={{ display: 'grid', gridTemplateColumns: colabSel ? '240px 1fr' : '1fr', gap: 16 }}>
          {/* Lista */}
          <div>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 10 }}>
              {aba === 'liderados' ? 'Liderados do Setor' : aba === 'diretores' ? 'Diretores' : aba === 'auto' ? 'Autoavaliação' : 'Intersetorial'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {colabsPorAba.length === 0 ? (
                <div style={{ padding: '20px', textAlign: 'center', color: 'var(--escalab-mute)', fontSize: 13, background: 'var(--escalab-paper)', borderRadius: 10 }}>
                  Nenhum colaborador nesta categoria
                </div>
              ) : colabsPorAba.map(c => {
                const st = getStatusL(c, tipoAba);
                const isAtual = colabSel?.id === c.id;
                return (
                  <div key={c.id} onClick={() => setColabSel(c)}
                    style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: isAtual ? 'var(--escalab-brand-tint)' : '#fff', border: `1px solid ${isAtual ? 'var(--escalab-brand-soft)' : 'var(--escalab-line)'}`, borderRadius: 10, cursor: 'pointer', transition: 'all .12s' }}>
                    <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={32} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--escalab-ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {c.nome.split(' ').slice(0, 2).join(' ')}
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--escalab-mute)', marginTop: 1 }}>{c.cargo.replace(/ [IVX]+$/, '')}</div>
                    </div>
                    <span style={{ fontSize: 12, fontWeight: 700, padding: '2px 8px', borderRadius: 5, background: statusBg[st], color: statusCor[st] }}>
                      {statusLbl[st]}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Formulário */}
          {colabSel ? (
            <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '20px 24px' }}>
              {getStatusL(colabSel, tipoAba) === 'concluida' ? (
                <div style={{ textAlign: 'center', padding: '40px 0' }}>
                  <div style={{ color: 'var(--escalab-brand)', marginBottom: 12 }}><Icon name="check" size={40} /></div>
                  <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 6 }}>Avaliação concluída!</div>
                  <div style={{ fontSize: 13.5, color: 'var(--escalab-mute)' }}>
                    A avaliação de {colabSel.nome.split(' ')[0]} já foi respondida neste ciclo.
                  </div>
                </div>
              ) : (
                <FormAVD
                  colab={colabSel}
                  tipo={tipoAba}
                  onSalvar={dados => { setConcluidas(p => [...p, dados]); setColabSel(null); }}
                  onBack={() => setColabSel(null)}
                />
              )}
            </div>
          ) : !colabSel && colabsPorAba.length > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--escalab-paper)', borderRadius: 12, border: '1px dashed var(--escalab-line)', minHeight: 280, color: 'var(--escalab-mute)', flexDirection: 'column', gap: 8 }}>
              <Icon name="clipboard" size={28} />
              <span style={{ fontSize: 14 }}>Selecione um colaborador para avaliar</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ── Feedbacks Admin View ────────────────────────────────────────────────────

const FeedbacksAdminView = ({ user }) => {
  const [colabSel, setColabSel] = useState(null);
  const [trimestre, setTrimestre] = useState('');
  const [setor, setSetor] = useState('');
  const [busca, setBusca] = useState('');

  const setores = [...new Set(COLABORADORES.map(c => c.setor))].sort();
  const trimestres = ['1T2025', '4T2024', '3T2024', '2T2024', '1T2024'];

  const lista = useMemo(() => COLABORADORES.filter(c => {
    const q = busca.toLowerCase();
    return (!busca || c.nome.toLowerCase().includes(q)) && (!setor || c.setor === setor);
  }), [busca, setor]);

  const getFeedbacks = (id) => FEEDBACKS_MOCK_FILES[id] || [];

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: colabSel ? '280px 1fr' : '1fr', gap: 16 }}>
        {/* Lista */}
        <div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
            <div style={{ position: 'relative', flex: '1 1 160px' }}>
              <div style={{ position: 'absolute', left: 9, top: '50%', transform: 'translateY(-50%)', color: 'var(--escalab-mute)', pointerEvents: 'none' }}>
                <Icon name="search" size={13} />
              </div>
              <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar…"
                style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '7px 10px 7px 27px', fontSize: 12.5, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box' }} />
            </div>
            <select value={setor} onChange={e => setSetor(e.target.value)}
              style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '7px 10px', fontSize: 12.5, fontFamily: 'var(--font-sans)', outline: 0, background: '#fff', flex: '1 1 120px' }}>
              <option value="">Todos os setores</option>
              {setores.map(s => <option key={s}>{s}</option>)}
            </select>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 520, overflowY: 'auto' }}>
            {lista.map(c => {
              const fbs = getFeedbacks(c.id);
              const temAtrasado = fbs.length === 0;
              const isAtual = colabSel?.id === c.id;
              return (
                <div key={c.id} onClick={() => setColabSel(c)}
                  style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: isAtual ? 'var(--escalab-brand-tint)' : '#fff', border: `1px solid ${isAtual ? 'var(--escalab-brand-soft)' : 'var(--escalab-line)'}`, borderRadius: 10, cursor: 'pointer', transition: 'all .12s' }}>
                  <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={30} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--escalab-ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {c.nome.split(' ').slice(0, 3).join(' ')}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>{fbs.length} feedback(s)</div>
                  </div>
                  {temAtrasado && <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#E89B3B', flexShrink: 0 }} title="Sem feedbacks" />}
                </div>
              );
            })}
          </div>
        </div>

        {/* Painel feedback */}
        {colabSel ? (
          <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '20px 24px' }}>
            <FeedbackColabSection colab={colabSel} user={user} />
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--escalab-paper)', borderRadius: 12, border: '1px dashed var(--escalab-line)', minHeight: 280, color: 'var(--escalab-mute)', flexDirection: 'column', gap: 8 }}>
            <Icon name="message" size={28} />
            <span style={{ fontSize: 14 }}>Selecione um colaborador para ver os feedbacks</span>
          </div>
        )}
      </div>
    </div>
  );
};

// ── Visão do Colaborador · tabs: Auto / Setor / Líder / Intersetorial / Histórico ──

const ColabHistorico = ({ user }) => {
  const avaliacoes = getAvaliacoesColaborador(user.id);
  const hist = (AVD_HISTORICO[user.id] || []).slice().reverse();

  const notasPorBloco = {};
  AVD_BLOCOS.forEach(b => {
    const avs = avaliacoes.filter(a => a.blocos[b.id] != null);
    notasPorBloco[b.id] = avs.length ? (avs.reduce((s, a) => s + a.blocos[b.id], 0) / avs.length).toFixed(1) : null;
  });
  const media = avaliacoes.length ? (avaliacoes.reduce((s, a) => s + (a.nota || 0), 0) / avaliacoes.length).toFixed(1) : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Nota geral */}
      {media && (
        <Card pad={22}>
          <div style={{ display: 'flex', gap: 22, alignItems: 'center' }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 44, fontWeight: 800, color: Number(media) >= 4 ? '#00967B' : Number(media) >= 3 ? '#E89B3B' : '#B3261E', lineHeight: 1 }}>{media}</div>
              <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 4 }}>de 5,0 · nota geral</div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 12 }}>Por Segmento</div>
              {AVD_BLOCOS.map(b => {
                const n = notasPorBloco[b.id];
                if (!n) return null;
                const pct = (Number(n) / 5) * 100;
                const cor = Number(n) >= 4 ? '#00967B' : Number(n) >= 3 ? '#E89B3B' : '#B3261E';
                return (
                  <div key={b.id} style={{ marginBottom: 10 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span style={{ fontSize: 13, color: 'var(--escalab-ink)', fontWeight: 500 }}>{b.label}</span>
                      <span style={{ fontSize: 13, fontWeight: 700, color: cor }}>{n}</span>
                    </div>
                    <div style={{ height: 7, background: 'var(--escalab-line)', borderRadius: 999 }}>
                      <div style={{ width: pct + '%', height: '100%', background: cor, borderRadius: 999, transition: 'width .5s' }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </Card>
      )}
      {/* Evolução histórica */}
      {hist.length > 0 && (
        <Card pad={22}>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 14 }}>Evolução por Ciclo</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {hist.map((h, i) => {
              const cor = h.nota >= 8.5 ? '#00967B' : h.nota >= 7 ? '#E89B3B' : '#B3261E';
              const pct = (h.nota / 10) * 100;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ fontSize: 12.5, color: 'var(--escalab-mute)', minWidth: 55 }}>{h.ciclo}</span>
                  <div style={{ flex: 1, height: 8, background: 'var(--escalab-line)', borderRadius: 999 }}>
                    <div style={{ width: pct + '%', height: '100%', background: cor, borderRadius: 999, transition: 'width .6s' }} />
                  </div>
                  <span style={{ fontSize: 13, fontWeight: 700, color: cor, minWidth: 32 }}>{h.nota}</span>
                </div>
              );
            })}
          </div>
        </Card>
      )}
      {!media && hist.length === 0 && (
        <Banner tone="info">Nenhuma avaliação registrada ainda. Seu histórico aparecerá aqui quando o GC liberar as notas.</Banner>
      )}
    </div>
  );
};

const ColabAvaliarPessoa = ({ user, colab, tipo, onConcluir }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
    <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 18, padding: '14px 0', borderBottom: '1px solid var(--escalab-line)' }}>
      <PhotoAvatar colaborador={colab} size={44} />
      <div>
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--escalab-ink)' }}>{colab.nome.split(' ').slice(0, 3).join(' ')}</div>
        <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginTop: 2 }}>{colab.cargo} · {colab.setor}</div>
      </div>
    </div>
    <FormAVD colab={colab} tipo={tipo} onSalvar={onConcluir} onBack={onConcluir} />
  </div>
);

const AVD_INTRO_VISTA_KEY = 'escalab_avd_intro_vista';

const ModalIntroAVD = ({ onClose, user }) => {
  const passos = [
    { n: 1, icon: 'user',      titulo: 'Autoavaliação',          desc: 'A autoavaliação é feita em três eixos: técnico, comportamental e de metas. Cada eixo é avaliado em uma escala de 1 a 5. Você se avalia.',                                       cor: '#00967B', bg: '#E0F4EE' },
    { n: 2, icon: 'users',     titulo: 'Avaliação do Setor',     desc: 'Avalie quem trabalha com você no dia a dia. Essa avaliação pode ser feita pessoa a pessoa, ou considerando o setor como um conjunto, dependendo de como o ciclo for configurado.', cor: '#1F4A8A', bg: '#E8EFF9' },
    { n: 3, icon: 'trend_up',  titulo: 'Seu Líder',              desc: 'Aqui você avalia como tem sido a liderança recebida.',                                                                                                                          cor: '#6B3FA0', bg: '#F0E8FB' },
    { n: 4, icon: 'org',       titulo: 'Intersetorial',          desc: 'Avaliação entre setores diferentes. Essa avaliação é para avaliar pessoas de outros setores que você tem contato direto com recorrência. A avaliação pode ser individual ou do setor como um todo.', cor: '#B56500', bg: '#FFF4E0' },
    { n: 5, icon: 'star',      titulo: 'Feedback Estruturado',   desc: 'Seu líder prepara o feedback após o resultado da avaliação, organizando pontos positivos e pontos construtivos. A dinâmica é bilateral, em que você também traz feedbacks para o líder.', cor: '#B3261E', bg: '#FCE6E6' },
  ];
  const primeiroNome = user?.nome?.split(' ')[0] || '';
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,15,18,.62)', backdropFilter: 'blur(8px)', zIndex: 1100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, animation: 'fadeIn .2s' }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: '#fff',
        borderRadius: 24,
        width: '100%',
        maxWidth: 640,
        maxHeight: '92vh',
        overflow: 'hidden',
        animation: 'popIn .28s var(--ease-out)',
        boxShadow: '0 32px 96px rgba(0,0,0,.28), 0 0 0 1px rgba(255,255,255,.05)',
        display: 'flex',
        flexDirection: 'column',
      }}>
        {/* ── Hero com gradiente + decorativos ── */}
        <div style={{
          background: 'linear-gradient(135deg, #007A5E 0%, #005E4A 50%, #143966 100%)',
          color: '#fff',
          padding: '32px 36px 30px',
          position: 'relative',
          overflow: 'hidden',
          flexShrink: 0,
        }}>
          {/* círculos decorativos (bem sutis, não afetam contraste) */}
          <div style={{ position: 'absolute', top: -60, right: -40, width: 200, height: 200, borderRadius: '50%', background: 'rgba(255,255,255,.05)', pointerEvents: 'none' }} />
          <div style={{ position: 'absolute', bottom: -80, right: 70, width: 150, height: 150, borderRadius: '50%', background: 'rgba(255,255,255,.04)', pointerEvents: 'none' }} />

          {/* close */}
          <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, border: '1px solid rgba(255,255,255,.4)', background: 'rgba(0,0,0,.25)', borderRadius: 10, cursor: 'pointer', width: 32, height: 32, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}>
            <Icon name="close" size={15} />
          </button>

          {/* badge · fundo sólido para contraste forte */}
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: '#fff', color: '#005E4A', borderRadius: 999, padding: '6px 13px', fontSize: 10.5, fontWeight: 800, letterSpacing: '.14em', textTransform: 'uppercase', marginBottom: 18 }}>
            <Icon name="star" size={11} />
            Como funciona a AVD
          </div>

          {/* título editorial */}
          <h2 style={{ fontFamily: 'var(--font-sans)', fontSize: 'clamp(28px, 4vw, 38px)', fontWeight: 800, margin: 0, letterSpacing: '-.02em', lineHeight: 1.15, color: '#fff' }}>
            {primeiroNome ? <>Bem-vindo(a), <span style={{ fontWeight: 800 }}>{primeiroNome}</span></> : <>Avaliação de <span style={{ fontWeight: 800 }}>Desempenho</span></>}
          </h2>
          <p style={{ fontSize: 14.5, color: '#fff', marginTop: 12, lineHeight: 1.55, maxWidth: 460, fontWeight: 500, textShadow: '0 1px 2px rgba(0,0,0,.25)' }}>
            Um ciclo por semestre para olhar pra trás, conversar sobre o presente e construir o próximo capítulo · juntos.
          </p>

          {/* mini stepper · opaco para destaque */}
          <div style={{ display: 'flex', gap: 6, marginTop: 22 }}>
            {passos.map(p => (
              <div key={p.n} style={{ flex: 1, height: 3, borderRadius: 999, background: 'rgba(255,255,255,.6)' }} />
            ))}
          </div>
        </div>

        {/* ── Passos ── */}
        <div style={{ padding: '26px 30px 24px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
          {passos.map((p, i) => (
            <div key={p.n} style={{
              display: 'flex',
              gap: 16,
              alignItems: 'flex-start',
              padding: '14px 16px',
              background: '#fff',
              border: '1px solid var(--escalab-line)',
              borderRadius: 14,
              transition: 'all .15s',
              position: 'relative',
            }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = p.cor + '60'; e.currentTarget.style.boxShadow = `0 4px 14px ${p.cor}18`; e.currentTarget.style.transform = 'translateX(2px)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--escalab-line)'; e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
              {/* ícone colorido */}
              <div style={{
                width: 42, height: 42, borderRadius: 12,
                background: p.bg,
                color: p.cor,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
                position: 'relative',
              }}>
                <Icon name={p.icon} size={18} />
                <span style={{ position: 'absolute', bottom: -5, right: -5, width: 18, height: 18, borderRadius: '50%', background: p.cor, color: '#fff', fontSize: 10, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2px solid #fff' }}>
                  {p.n}
                </span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--escalab-ink)', letterSpacing: '-.005em', marginBottom: 4 }}>{p.titulo}</div>
                <div style={{ fontSize: 13.5, color: 'var(--escalab-ink)', lineHeight: 1.6, opacity: 0.92 }}>{p.desc}</div>
              </div>
            </div>
          ))}

          {/* destaque novidade */}
          <div style={{
            background: 'linear-gradient(135deg, #E0F4EE 0%, #F0E8FB 100%)',
            border: '2px solid var(--escalab-brand)',
            borderRadius: 14,
            padding: '14px 18px',
            display: 'flex',
            gap: 12,
            alignItems: 'flex-start',
            marginTop: 4,
          }}>
            <div style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--escalab-brand)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="info" size={15} />
            </div>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 800, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--escalab-brand-deep)', marginBottom: 4 }}>Novidade neste ciclo</div>
              <div style={{ fontSize: 13.5, color: 'var(--escalab-ink)', lineHeight: 1.6, fontWeight: 500 }}>
                Agora o líder precisa <strong style={{ color: 'var(--escalab-brand-deep)' }}>preparar o feedback</strong> antes de registrar · qualidade vem antes de quantidade. E a AVD só fica aberta enquanto o GC habilita o ciclo.
              </div>
            </div>
          </div>
        </div>

        {/* ── Footer ── */}
        <div style={{ padding: '16px 30px 22px', borderTop: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0, background: 'var(--escalab-paper)', gap: 12 }}>
          <span style={{ fontSize: 12.5, color: 'var(--escalab-slate)', fontWeight: 500 }}>
            Você pode rever isso a qualquer momento no botão <strong style={{ color: 'var(--escalab-ink)' }}>“Como funciona?”</strong>.
          </span>
          <button onClick={() => { try { localStorage.setItem(AVD_INTRO_VISTA_KEY, '1'); } catch {} onClose(); }} style={{
            border: 0,
            background: 'linear-gradient(135deg, var(--escalab-brand) 0%, var(--escalab-brand-deep) 100%)',
            color: '#fff',
            padding: '11px 24px',
            borderRadius: 10,
            fontFamily: 'var(--font-sans)',
            fontSize: 13.5,
            fontWeight: 700,
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: 7,
            boxShadow: '0 6px 18px rgba(0,150,123,.32)',
            transition: 'transform .12s, box-shadow .12s',
          }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 10px 24px rgba(0,150,123,.42)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 6px 18px rgba(0,150,123,.32)'; }}>
            Entendi, começar
            <Icon name="chev_right" size={13} />
          </button>
        </div>
      </div>
    </div>
  );
};

const ColabAVDView = ({ user }) => {
  const [aba, setAba] = useState('auto');
  const [colegaSel, setColegaSel] = useState(null);
  const [liderAvaliando, setLiderAvaliando] = useState(false);
  const [interselSel, setInterselSel] = useState(null);
  const [modoSetor, setModoSetor] = useState('pessoas');
  const [setorAvaliandoGeral, setSetorAvaliandoGeral] = useState(false);
  const [modoIntersetorial, setModoIntersetorial] = useState('pessoas');
  const [interSetorSel, setInterSetorSel] = useState(null);
  const [interSetorConcluidos, setInterSetorConcluidos] = useState([]);
  const [showIntro, setShowIntro] = useState(() => {
    try { return !localStorage.getItem(AVD_INTRO_VISTA_KEY); } catch { return true; }
  });
  const cicloAberto = getCicloAvdAberto();

  const colegas = COLABORADORES.filter(c => c.setor === user.setor && c.id !== user.id && c.nivel !== 'diretor');
  const meuLider = COLABORADORES.find(c => c.nome === user.gestorNome);

  // Intersetorial: livre vs. por programa
  const modoInterRH = getModoIntersetorial();
  const programasAtivos = getProgramasInterAtivosPara(user.setor);
  const setoresLiberados = modoInterRH === 'programa'
    ? [...new Set(programasAtivos.flatMap(p => p.setores))].filter(s => s !== user.setor)
    : null; // null = sem restrição
  const outrosSetores = COLABORADORES.filter(c => c.setor !== user.setor && c.nivel !== 'diretor' && (!setoresLiberados || setoresLiberados.includes(c.setor)));

  const tabs = [
    { id: 'auto',          label: 'Autoavaliação',   icon: 'user' },
    { id: 'setor',         label: 'Meu Setor',        icon: 'users',    count: colegas.length },
    { id: 'lider',         label: 'Meu Líder',        icon: 'trend_up' },
    { id: 'intersetorial', label: 'Intersetorial',    icon: 'org' },
    { id: 'historico',     label: 'Meu Histórico',    icon: 'star' },
    { id: 'feedbacks',     label: 'Feedbacks',        icon: 'message' },
  ];

  // Tela de "ciclo fechado" padrão (visual igual ao da PCO) · quando o GC não abriu nenhum ciclo, o colaborador vê só isso.
  if (!cicloAberto) {
    return (
      <div style={{ animation: 'fadeIn .2s' }}>
        {showIntro && <ModalIntroAVD onClose={() => setShowIntro(false)} user={user} />}
        <div style={{ background: 'linear-gradient(135deg, var(--escalab-brand-tint), #fff)', border: '1px solid var(--escalab-brand-soft)', borderRadius: 14, padding: '22px 26px', marginBottom: 16 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--escalab-brand)', marginBottom: 6 }}>AVD · Avaliação de Desempenho</div>
          <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--escalab-brand-deep)', marginBottom: 6 }}>Como está seu desempenho neste ciclo?</div>
          <div style={{ fontSize: 13, color: 'var(--escalab-brand-deep)', lineHeight: 1.6 }}>
            Quando o GC abrir um novo ciclo, a avaliação aparece aqui para você responder.
          </div>
        </div>
        <div style={{ textAlign: 'center', padding: '48px 20px', color: 'var(--escalab-mute)', background: '#fff', border: '2px dashed var(--escalab-line)', borderRadius: 14 }}>
          <Icon name="info" size={28} />
          <div style={{ marginTop: 10, fontSize: 14 }}>Nenhuma AVD aberta no momento.</div>
          <div style={{ fontSize: 12, marginTop: 4 }}>Quando o GC abrir um novo ciclo de AVD, ela aparecerá aqui para você responder.</div>
          <button onClick={() => setShowIntro(true)} style={{ marginTop: 14, border:'1px solid var(--escalab-line)', background:'#fff', cursor:'pointer', color:'var(--escalab-slate)', borderRadius:8, padding:'7px 14px', fontSize:12.5, fontFamily:'var(--font-sans)', display:'inline-flex', alignItems:'center', gap:5, fontWeight:600 }}>
            <Icon name="info" size={12} /> Como funciona a AVD?
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      {showIntro && <ModalIntroAVD onClose={() => setShowIntro(false)} user={user} />}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14, flexWrap: 'wrap', gap: 10 }}>
        <div style={{ flex: 1, fontSize: 12.5, color: 'var(--escalab-mute)' }}>
          <Icon name="check" size={12} /> Ciclo aberto: <strong>{cicloAberto.nome}</strong>
        </div>
        <button onClick={() => setShowIntro(true)} style={{ border:'1px solid var(--escalab-line)', background:'#fff', cursor:'pointer', color:'var(--escalab-mute)', borderRadius:8, padding:'6px 12px', fontSize:12.5, fontFamily:'var(--font-sans)', display:'flex', alignItems:'center', gap:5, fontWeight:600 }}>
          <Icon name="info" size={12} /> Como funciona a AVD?
        </button>
      </div>
      <Tabs tabs={tabs} active={aba} onChange={v => { setAba(v); setColegaSel(null); setLiderAvaliando(false); setInterselSel(null); setInterSetorSel(null); }} />
      <div style={{ paddingTop: 22, opacity: cicloAberto ? 1 : 0.55, pointerEvents: cicloAberto ? 'auto' : 'none' }}>

        {/* Autoavaliação */}
        {aba === 'auto' && (
          <Card pad={22}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--escalab-ink)', marginBottom: 14 }}>Autoavaliação · Ciclo 1º sem 2025</div>
            <FormAVD colab={user} tipo="auto" onSalvar={() => {}} onBack={() => {}} />
          </Card>
        )}

        {/* Avaliar pessoas do setor */}
        {aba === 'setor' && (
          <div style={{ animation: 'fadeIn .2s' }}>
            {/* Toggle modo */}
            {!colegaSel && !setorAvaliandoGeral && (
              <div style={{ display: 'flex', gap: 8, marginBottom: 16, background: 'var(--escalab-paper)', borderRadius: 10, padding: 4, width: 'fit-content' }}>
                {[{ id:'pessoas', label:'Por colaborador' }, { id:'geral', label:'Setor inteiro' }].map(m => (
                  <button key={m.id} onClick={() => setModoSetor(m.id)} style={{
                    border: 0, borderRadius: 7, padding: '7px 16px', cursor: 'pointer', fontSize: 13,
                    fontFamily: 'var(--font-sans)', fontWeight: modoSetor === m.id ? 600 : 400,
                    background: modoSetor === m.id ? '#fff' : 'transparent',
                    color: modoSetor === m.id ? 'var(--escalab-brand)' : 'var(--escalab-mute)',
                    boxShadow: modoSetor === m.id ? '0 1px 4px rgba(0,0,0,.10)' : 'none',
                    transition: 'all .15s',
                  }}>{m.label}</button>
                ))}
              </div>
            )}

            {/* Modo: por colaborador */}
            {modoSetor === 'pessoas' && (
              colegaSel ? (
                <Card pad={22}>
                  <button onClick={() => setColegaSel(null)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
                    <Icon name="chev_left" size={14} /> Voltar para a lista
                  </button>
                  <ColabAvaliarPessoa user={user} colab={colegaSel} tipo="pares" onConcluir={() => setColegaSel(null)} />
                </Card>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <Banner tone="info">Avalie seus colegas de setor no ciclo atual. Suas avaliações são anônimas para eles.</Banner>
                  {colegas.length === 0 ? (
                    <Banner tone="neutral">Nenhum colega no mesmo setor para avaliar.</Banner>
                  ) : colegas.map(c => (
                    <div key={c.id} onClick={() => setColegaSel(c)}
                      style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px', background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, cursor: 'pointer', transition: 'all .15s' }}
                      onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 14px rgba(0,0,0,.08)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
                      onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
                      <PhotoAvatar colaborador={c} size={40} />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--escalab-ink)' }}>{c.nome.split(' ').slice(0, 3).join(' ')}</div>
                        <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 2 }}>{c.cargo}</div>
                      </div>
                      <Button size="sm" variant="outline">Avaliar →</Button>
                    </div>
                  ))}
                </div>
              )
            )}

            {/* Modo: setor inteiro */}
            {modoSetor === 'geral' && (
              setorAvaliandoGeral ? (
                <Card pad={22}>
                  <button onClick={() => setSetorAvaliandoGeral(false)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
                    <Icon name="chev_left" size={14} /> Voltar
                  </button>
                  <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 16 }}>Avaliação do setor · {user.setor}</div>
                  <FormAVD
                    colab={{ id: 'setor_' + user.setor, nome: user.setor, cargo: 'Analista', nivel: 'liderado', iniciais: (user.setor||'').substring(0,2).toUpperCase(), cor: 'var(--escalab-brand)', setor: user.setor }}
                    tipo="setor"
                    onSalvar={() => setSetorAvaliandoGeral(false)}
                    onBack={() => setSetorAvaliandoGeral(false)}
                  />
                </Card>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <Banner tone="info">Avalie o setor como um todo · uma única avaliação coletiva para o grupo.</Banner>
                  <div onClick={() => setSetorAvaliandoGeral(true)}
                    style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '20px 22px', background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, cursor: 'pointer', transition: 'all .15s' }}
                    onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 14px rgba(0,0,0,.08)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
                    onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
                    <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--escalab-brand-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <Icon name="users" size={24} />
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--escalab-ink)' }}>{user.setor}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', marginTop: 3 }}>{colegas.length + 1} colaboradores · avaliação coletiva do grupo</div>
                    </div>
                    <Button variant="primary">Avaliar setor →</Button>
                  </div>
                </div>
              )
            )}
          </div>
        )}

        {/* Avaliar líder */}
        {aba === 'lider' && (
          <div style={{ animation: 'fadeIn .2s' }}>
            {!meuLider ? (
              <Banner tone="info">Nenhum gestor direto cadastrado para você.</Banner>
            ) : liderAvaliando ? (
              <Card pad={22}>
                <button onClick={() => setLiderAvaliando(false)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
                  <Icon name="chev_left" size={14} /> Voltar
                </button>
                <ColabAvaliarPessoa user={user} colab={meuLider} tipo="superior" onConcluir={() => setLiderAvaliando(false)} />
              </Card>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <Banner tone="info">Avalie seu líder direto de forma anônima e construtiva.</Banner>
                <div onClick={() => setLiderAvaliando(true)}
                  style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '18px 20px', background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, cursor: 'pointer', transition: 'all .15s' }}
                  onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 14px rgba(0,0,0,.08)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
                  onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
                  <PhotoAvatar colaborador={meuLider} size={52} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 700 }}>{meuLider.nome.split(' ').slice(0, 3).join(' ')}</div>
                    <div style={{ fontSize: 13, color: 'var(--escalab-mute)', marginTop: 2 }}>{meuLider.cargo} · {meuLider.setor}</div>
                  </div>
                  <Button variant="primary">Avaliar meu líder →</Button>
                </div>
              </div>
            )}
          </div>
        )}

        {/* Intersetorial (opcional) */}
        {aba === 'intersetorial' && (
          <div style={{ animation: 'fadeIn .2s' }}>
            {interselSel ? (
              <Card pad={22}>
                <button onClick={() => setInterselSel(null)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
                  <Icon name="chev_left" size={14} /> Voltar
                </button>
                <ColabAvaliarPessoa user={user} colab={interselSel} tipo="intersetorial" onConcluir={() => setInterselSel(null)} />
              </Card>
            ) : interSetorSel ? (
              <Card pad={22}>
                <button onClick={() => setInterSetorSel(null)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 18 }}>
                  <Icon name="chev_left" size={14} /> Voltar
                </button>
                {interSetorConcluidos.includes(interSetorSel) ? (
                  <div style={{ textAlign: 'center', padding: '40px 0' }}>
                    <div style={{ color: 'var(--escalab-brand)', marginBottom: 12 }}><Icon name="check" size={40} /></div>
                    <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 6 }}>Avaliação concluída!</div>
                    <div style={{ fontSize: 13.5, color: 'var(--escalab-mute)' }}>O setor {interSetorSel} já foi avaliado neste ciclo.</div>
                  </div>
                ) : (
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--escalab-ink)', marginBottom: 16 }}>Avaliação do setor · {interSetorSel}</div>
                    <FormAVD
                      colab={{ id: 'intersetor_' + interSetorSel, nome: interSetorSel, cargo: 'Analista', nivel: 'liderado', iniciais: (interSetorSel || '').substring(0, 2).toUpperCase(), cor: 'var(--escalab-brand)', setor: interSetorSel }}
                      tipo="intersetorial"
                      onSalvar={() => { setInterSetorConcluidos(p => [...p, interSetorSel]); setInterSetorSel(null); }}
                      onBack={() => setInterSetorSel(null)}
                    />
                  </div>
                )}
              </Card>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                {modoInterRH === 'programa' ? (
                  programasAtivos.length === 0 ? (
                    <Banner tone="warn">
                      <strong>Avaliação intersetorial fechada para o seu setor.</strong> O GC ainda não abriu programas envolvendo <strong>{user.setor}</strong>. Aguarde a abertura de um projeto/programa para liberar.
                    </Banner>
                  ) : (
                    <div style={{ background: '#F4EEFF', border: '1px solid #C9A0E8', borderRadius: 12, padding: '12px 16px', fontSize: 13, color: '#4A0080' }}>
                      <Icon name="info" size={14} /> <strong>Programa{programasAtivos.length > 1 ? 's' : ''} ativo{programasAtivos.length > 1 ? 's' : ''}:</strong>
                      <div style={{ marginTop: 6, display: 'flex', flexDirection: 'column', gap: 4 }}>
                        {programasAtivos.map(p => (
                          <div key={p.id} style={{ fontSize: 12.5 }}>
                            • <strong>{p.nome}</strong> · setores: {p.setores.join(', ')}{p.prazoFim ? ` · até ${p.prazoFim.split('-').reverse().join('/')}` : ''}
                          </div>
                        ))}
                      </div>
                    </div>
                  )
                ) : (
                  <div style={{ background: '#F4EEFF', border: '1px solid #C9A0E8', borderRadius: 12, padding: '12px 16px', fontSize: 13, color: '#4A0080', display: 'flex', gap: 9 }}>
                    <Icon name="info" size={15} />
                    <div><strong>Avaliação intersetorial é opcional.</strong> Avalie outros setores com quem você trabalhou neste ciclo.</div>
                  </div>
                )}

                {/* Toggle Por pessoa / Setor inteiro */}
                <div style={{ display: 'flex', gap: 8, background: 'var(--escalab-paper)', borderRadius: 10, padding: 4, width: 'fit-content' }}>
                  {[{ id: 'pessoas', label: 'Por pessoa' }, { id: 'setores', label: 'Setor inteiro' }].map(m => (
                    <button key={m.id} onClick={() => setModoIntersetorial(m.id)} style={{
                      border: 0, borderRadius: 7, padding: '7px 16px', cursor: 'pointer', fontSize: 13,
                      fontFamily: 'var(--font-sans)', fontWeight: modoIntersetorial === m.id ? 600 : 400,
                      background: modoIntersetorial === m.id ? '#fff' : 'transparent',
                      color: modoIntersetorial === m.id ? 'var(--escalab-brand)' : 'var(--escalab-mute)',
                      boxShadow: modoIntersetorial === m.id ? '0 1px 4px rgba(0,0,0,.10)' : 'none',
                      transition: 'all .15s',
                    }}>{m.label}</button>
                  ))}
                </div>

                {/* Modo por pessoa */}
                {modoIntersetorial === 'pessoas' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {[...new Set(outrosSetores.map(c => c.setor))].sort().map(setor => {
                      const membros = outrosSetores.filter(c => c.setor === setor);
                      return (
                        <div key={setor} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, overflow: 'hidden' }}>
                          <div style={{ padding: '10px 16px', background: 'var(--escalab-paper)', borderBottom: '1px solid var(--escalab-line)', fontSize: 12.5, fontWeight: 700, color: 'var(--escalab-ink)', display: 'flex', alignItems: 'center', gap: 8 }}>
                            <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--escalab-brand)' }} />
                            {setor} <span style={{ fontSize: 11, color: 'var(--escalab-mute)', fontWeight: 400 }}>({membros.length})</span>
                          </div>
                          <div>
                            {membros.map((c, i) => (
                              <div key={c.id} onClick={() => setInterselSel(c)}
                                style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px', borderBottom: i < membros.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'}>
                                <PhotoAvatar colaborador={c} size={32} />
                                <div style={{ flex: 1 }}>
                                  <div style={{ fontSize: 13, fontWeight: 600 }}>{c.nome.split(' ').slice(0, 3).join(' ')}</div>
                                  <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>{c.cargo}</div>
                                </div>
                                <span style={{ fontSize: 12, color: 'var(--escalab-brand)', fontWeight: 600 }}>Avaliar →</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}

                {/* Modo setor inteiro */}
                {modoIntersetorial === 'setores' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {[...new Set(outrosSetores.map(c => c.setor))].sort().map(setor => {
                      const membros = outrosSetores.filter(c => c.setor === setor);
                      const concluido = interSetorConcluidos.includes(setor);
                      return (
                        <div key={setor} onClick={() => !concluido && setInterSetorSel(setor)}
                          style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '18px 20px', background: '#fff', border: `1px solid ${concluido ? 'var(--escalab-brand-soft)' : 'var(--escalab-line)'}`, borderRadius: 14, cursor: concluido ? 'default' : 'pointer', transition: 'all .15s' }}
                          onMouseEnter={e => { if (!concluido) { e.currentTarget.style.boxShadow = '0 4px 14px rgba(0,0,0,.08)'; e.currentTarget.style.transform = 'translateY(-1px)'; } }}
                          onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
                          <div style={{ width: 48, height: 48, borderRadius: 12, background: concluido ? 'var(--escalab-brand-tint)' : 'var(--escalab-paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                            <Icon name="users" size={22} />
                          </div>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--escalab-ink)' }}>{setor}</div>
                            <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 2 }}>{membros.length} colaboradores</div>
                          </div>
                          {concluido
                            ? <Tag tone="success" size="xs">Concluída</Tag>
                            : <span style={{ fontSize: 12, color: 'var(--escalab-brand)', fontWeight: 600 }}>Avaliar setor →</span>
                          }
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Resultados do time (líder) */}
        {aba === 'resultados' && (
          <div style={{ animation: 'fadeIn .2s' }}>
            <div style={{ fontSize: 13, color: 'var(--escalab-mute)', marginBottom: 16 }}>Notas consolidadas do ciclo ativo para seus liderados.</div>
            {liderados.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '48px', color: 'var(--escalab-mute)', fontSize: 14 }}>Nenhum liderado encontrado.</div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(260px,1fr))', gap: 14 }}>
                {liderados.map(c => {
                  const notas = getNotaColab(c.id);
                  const cor = !notas.geral ? 'var(--escalab-mute)' : notas.geral >= 8.5 ? '#00967B' : notas.geral >= 7 ? '#E89B3B' : '#B3261E';
                  const statusLbl = { concluida: 'Concluída', em_andamento: 'Em andamento', pendente: 'Pendente' }[notas.status] || 'Pendente';
                  return (
                    <div key={c.id} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, padding: '18px 20px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                        <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={34}/>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--escalab-ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.nome.split(' ').slice(0,2).join(' ')}</div>
                          <div style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>{c.cargo}</div>
                        </div>
                        <span style={{ fontSize: 11, fontWeight: 600, borderRadius: 5, padding: '2px 8px', background: notas.status === 'concluida' ? '#E6F5F1' : '#FFF7EB', color: notas.status === 'concluida' ? '#00836B' : '#B56500' }}>{statusLbl}</span>
                      </div>
                      {notas.geral ? (
                        <>
                          <div style={{ fontSize: 30, fontWeight: 900, color: cor, lineHeight: 1, marginBottom: 8 }}>{notas.geral.toFixed(1)} <span style={{ fontSize: 13, fontWeight: 400, color: 'var(--escalab-mute)' }}>/ 10</span></div>
                          <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                            {[['lider','Avaliação líder'],['pares','Pares'],['auto','Autoavaliação']].map(([k,l]) => notas[k] != null && (
                              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                <span style={{ fontSize: 11.5, color: 'var(--escalab-mute)', minWidth: 110 }}>{l}</span>
                                <div style={{ flex: 1, height: 5, background: 'var(--escalab-line)', borderRadius: 999 }}>
                                  <div style={{ width: (notas[k]/10*100)+'%', height: '100%', background: cor, borderRadius: 999 }}/>
                                </div>
                                <span style={{ fontSize: 12, fontWeight: 700, color: cor, minWidth: 28 }}>{notas[k].toFixed(1)}</span>
                              </div>
                            ))}
                          </div>
                        </>
                      ) : (
                        <div style={{ fontSize: 13, color: 'var(--escalab-mute)', fontStyle: 'italic' }}>Avaliação não concluída.</div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}

        {/* Meu Histórico */}
        {aba === 'historico' && <ColabHistorico user={user} />}

        {/* Feedbacks */}
        {aba === 'feedbacks' && <FeedbackColabSection colab={user} user={user} />}

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

// ── Tela principal ─────────────────────────────────────────────────────────

// ── Configuração do formulário intersetorial (GC) ──────────────────────────
const INTER_FORM_KEY = 'escalab_avd_intersetorial_form';
const INTER_FORM_PADRAO = {
  individual: { ativo: true, escalaMin: 1, escalaMax: 5,
    perguntas: [
      { tipo: 'scale', texto: 'Como foi a colaboração desta pessoa nas iniciativas conjuntas?' },
      { tipo: 'scale', texto: 'A comunicação foi clara, respeitosa e tempestiva?' },
      { tipo: 'text',  texto: 'Em uma frase, descreva um ponto forte e um ponto a desenvolver.' },
    ],
  },
  setor: { ativo: true, escalaMin: 1, escalaMax: 5,
    perguntas: [
      { tipo: 'scale', texto: 'No geral, como avalia o setor com quem você trabalhou?' },
      { tipo: 'choice', opcoes: ['Sempre','Na maioria das vezes','Às vezes','Raramente'], texto: 'O setor entregou no prazo combinado?' },
      { tipo: 'text', texto: 'Sugestões para a equipe do setor.' },
    ],
  },
};
function getInterForm() {
  try {
    const raw = JSON.parse(localStorage.getItem(INTER_FORM_KEY) || 'null');
    return raw ? { individual: { ...INTER_FORM_PADRAO.individual, ...(raw.individual || {}) }, setor: { ...INTER_FORM_PADRAO.setor, ...(raw.setor || {}) } } : INTER_FORM_PADRAO;
  } catch { return INTER_FORM_PADRAO; }
}
function salvarInterForm(cfg) { try { localStorage.setItem(INTER_FORM_KEY, JSON.stringify(cfg)); } catch {} }

// ── Resultados intersetoriais (visão GC) ─────────────────────────────────────
// Mostra para o setor de Gente e Cultura as notas intersetoriais recebidas por
// cada colaborador, no mesmo formato da AVD individual (AdminAVDView).
const AdminIntersetorialResultados = ({ user, onVerPerfil }) => {
  const ciclo = CICLOS.find(c => c.status === 'ativo') || CICLOS[CICLOS.length - 1];
  const [busca, setBusca] = useState('');
  const [colabSel, setColabSel] = useState(null);

  const lista = COLABORADORES
    .map(c => ({ c, n: getNotaColab(c.id) }))
    .filter(x => x.n.intersetorial != null)
    .filter(x => !busca || x.c.nome.toLowerCase().includes(busca.toLowerCase()) || x.c.setor.toLowerCase().includes(busca.toLowerCase()) || x.c.cargo.toLowerCase().includes(busca.toLowerCase()))
    .sort((a, b) => (b.n.intersetorial || 0) - (a.n.intersetorial || 0));

  const totalAvaliados = lista.length;
  const mediaGeral = lista.length
    ? lista.reduce((s, x) => s + (x.n.intersetorial || 0), 0) / lista.length
    : 0;
  const destaques = lista.filter(x => x.n.intersetorial >= 9).length;
  const atencao   = lista.filter(x => x.n.intersetorial < 7).length;

  if (colabSel) {
    const colab = colabSel;
    const notas = getNotaColab(colab.id);
    return (
      <div>
        <button onClick={() => setColabSel(null)} style={{ border: 0, background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--escalab-mute)', fontSize: 13, padding: 0, marginBottom: 16, fontFamily: 'var(--font-sans)' }}>
          <Icon name="chev_left" size={14} /> Voltar à lista
        </button>
        <ResultadoCard colab={colab} onIrFeedback={() => onVerPerfil && onVerPerfil(colab)} />
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, padding: '18px 22px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <Icon name="org" size={16} />
          <div style={{ fontSize: 14, fontWeight: 700 }}>Resultados intersetoriais · {ciclo?.nome}</div>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', lineHeight: 1.5 }}>
          Visão consolidada (GC) das notas intersetoriais recebidas por cada colaborador.
          Clique numa linha para abrir o detalhamento completo (igual à AVD individual).
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 10 }}>
        {[
          { label: 'Avaliados',   val: totalAvaliados,           cor: '#1F4A8A', bg: '#EEF3FA' },
          { label: 'Média geral', val: totalAvaliados ? mediaGeral.toFixed(1) : '·', cor: '#005E4D', bg: '#E6F5F1' },
          { label: 'Destaques (≥9)', val: destaques,             cor: '#00836B', bg: '#E6F5F1' },
          { label: 'Atenção (<7)',   val: atencao,               cor: '#B3261E', bg: '#FDECEC' },
        ].map(k => (
          <div key={k.label} style={{ background: k.bg, border: `1px solid ${k.cor}33`, borderRadius: 12, padding: '14px 16px' }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: k.cor }}>{k.label}</div>
            <div style={{ fontSize: 24, fontWeight: 800, color: k.cor, marginTop: 4 }}>{k.val}</div>
          </div>
        ))}
      </div>

      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, padding: '16px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 13, fontWeight: 700, flex: 1 }}>Por colaborador</div>
          <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar por nome, setor ou cargo…"
            style={{ width: 280, border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '7px 11px', fontSize: 13, outline: 'none', fontFamily: 'var(--font-sans)' }} />
        </div>
        {lista.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '36px 20px', color: 'var(--escalab-mute)', fontSize: 13.5 }}>
            <Icon name="clock" size={24} /><br />Nenhuma avaliação intersetorial concluída ainda.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {lista.map(({ c, n }) => {
              const cor = n.intersetorial >= 9 ? '#00967B' : n.intersetorial >= 7 ? '#E89B3B' : '#B3261E';
              return (
                <button key={c.id} onClick={() => setColabSel(c)}
                  style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto auto', gap: 14, alignItems: 'center', background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 12, padding: '12px 16px', cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-sans)', transition: 'all .15s' }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--escalab-paper)'}
                  onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                  <Avatar nome={c.nome} cor={c.cor} iniciais={c.iniciais} size={34} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--escalab-ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.nome}</div>
                    <div style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>{c.cargo} · {c.setor}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 10.5, color: 'var(--escalab-mute)', fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase' }}>Intersetorial</div>
                    <div style={{ fontSize: 22, fontWeight: 800, color: cor, lineHeight: 1 }}>{n.intersetorial.toFixed(1)}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--escalab-mute)' }}>de 10,0</div>
                  </div>
                  <Icon name="chev_right" size={14} />
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

const AdminIntersetorialConfig = ({ user }) => {
  const [cfg, setCfg] = useState(() => getInterForm());
  const [aba, setAba] = useState('individual');
  const [salvo, setSalvo] = useState(false);

  function atualizar(secao, patch) {
    setCfg(c => ({ ...c, [secao]: { ...c[secao], ...patch } }));
  }
  function addPergunta(secao) {
    setCfg(c => ({ ...c, [secao]: { ...c[secao], perguntas: [...c[secao].perguntas, { tipo: 'scale', texto: '' }] } }));
  }
  function updPergunta(secao, idx, patch) {
    setCfg(c => ({ ...c, [secao]: { ...c[secao], perguntas: c[secao].perguntas.map((p, i) => i === idx ? { ...p, ...patch } : p) } }));
  }
  function remPergunta(secao, idx) {
    setCfg(c => ({ ...c, [secao]: { ...c[secao], perguntas: c[secao].perguntas.filter((_, i) => i !== idx) } }));
  }
  function salvar() {
    salvarInterForm(cfg);
    setSalvo(true);
    setTimeout(() => setSalvo(false), 3000);
  }

  const secaoCfg = cfg[aba];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, padding: '18px 22px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
          <Icon name="org" size={16} />
          <div style={{ fontSize: 14, fontWeight: 700 }}>Avaliação intersetorial</div>
          {salvo && <span style={{ fontSize: 12, color: '#00836B', fontWeight: 700 }}>✓ Salvo</span>}
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--escalab-mute)', lineHeight: 1.5 }}>
          Configure o formulário usado quando alguém avalia outra pessoa ou outro setor inteiro num programa intersetorial.
          Cada modo tem perguntas e escala próprias.
        </div>
      </div>

      {/* Sub-tabs */}
      <div style={{ display: 'flex', gap: 8, borderBottom: '1px solid var(--escalab-line)' }}>
        {[
          { id: 'individual', label: 'Pessoa avalia pessoa' },
          { id: 'setor',      label: 'Setor inteiro' },
        ].map(t => (
          <button key={t.id} onClick={() => setAba(t.id)} style={{
            border: 0, background: 'transparent', cursor: 'pointer', padding: '9px 14px', fontSize: 13.5,
            fontFamily: 'var(--font-sans)', fontWeight: aba === t.id ? 700 : 500,
            color: aba === t.id ? 'var(--escalab-brand)' : 'var(--escalab-mute)',
            borderBottom: `2px solid ${aba === t.id ? 'var(--escalab-brand)' : 'transparent'}`, marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>

      {/* Config da seção atual */}
      <div style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: 9, cursor: 'pointer' }}>
          <input type="checkbox" checked={!!secaoCfg.ativo} onChange={e => atualizar(aba, { ativo: e.target.checked })} style={{ width: 16, height: 16 }} />
          <span style={{ fontSize: 13.5, color: 'var(--escalab-slate)', fontWeight: 600 }}>Habilitar este modo no ciclo atual</span>
        </label>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={{ fontSize: 11.5, color: 'var(--escalab-mute)', fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase' }}>Escala mín</label>
            <input type="number" min={0} max={10} value={secaoCfg.escalaMin} onChange={e => atualizar(aba, { escalaMin: Number(e.target.value) })}
              style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '7px 10px', fontSize: 13.5, marginTop: 4, outline: 'none', boxSizing: 'border-box' }} />
          </div>
          <div>
            <label style={{ fontSize: 11.5, color: 'var(--escalab-mute)', fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase' }}>Escala máx</label>
            <input type="number" min={1} max={10} value={secaoCfg.escalaMax} onChange={e => atualizar(aba, { escalaMax: Number(e.target.value) })}
              style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '7px 10px', fontSize: 13.5, marginTop: 4, outline: 'none', boxSizing: 'border-box' }} />
          </div>
        </div>

        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 9 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--escalab-slate)', textTransform: 'uppercase', letterSpacing: '.08em', flex: 1 }}>Perguntas ({secaoCfg.perguntas.length})</div>
            <button onClick={() => addPergunta(aba)} style={{ border: '1px dashed var(--escalab-line)', background: '#fff', color: 'var(--escalab-brand)', borderRadius: 8, padding: '5px 11px', cursor: 'pointer', fontSize: 12, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <Icon name="plus" size={11} /> Adicionar pergunta
            </button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {secaoCfg.perguntas.map((p, i) => (
              <div key={i} style={{ background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <select value={p.tipo} onChange={e => updPergunta(aba, i, { tipo: e.target.value })} style={{ border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '5px 8px', fontSize: 12, background: '#fff' }}>
                    <option value="scale">Escala</option>
                    <option value="choice">Múltipla escolha</option>
                    <option value="text">Texto livre</option>
                  </select>
                  <input value={p.texto} onChange={e => updPergunta(aba, i, { texto: e.target.value })} placeholder="Texto da pergunta"
                    style={{ flex: 1, border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '6px 10px', fontSize: 13, outline: 'none' }} />
                  <button onClick={() => remPergunta(aba, i)} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: '#B3261E', padding: 4 }} title="Remover">
                    <Icon name="close" size={12} />
                  </button>
                </div>
                {p.tipo === 'choice' && (
                  <input value={(p.opcoes || []).join(', ')} onChange={e => updPergunta(aba, i, { opcoes: e.target.value.split(',').map(o => o.trim()).filter(Boolean) })}
                    placeholder="Opções separadas por vírgula"
                    style={{ width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 7, padding: '5px 9px', fontSize: 12, outline: 'none', boxSizing: 'border-box' }} />
                )}
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button variant="primary" onClick={salvar}>Salvar formulário intersetorial</Button>
        </div>
      </div>
    </div>
  );
};

// Wrapper que junta Resultados + Configuração do formulário num único painel com sub-tabs
const AdminIntersetorialPanel = ({ user, onVerPerfil }) => {
  const [subAba, setSubAba] = useState('resultados');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--escalab-line)' }}>
        {[
          { id: 'resultados',   label: 'Resultados',                icon: 'chart' },
          { id: 'configuracao', label: 'Configuração do formulário', icon: 'settings' },
        ].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 === 'resultados'   && <AdminIntersetorialResultados user={user} onVerPerfil={onVerPerfil} />}
      {subAba === 'configuracao' && <AdminIntersetorialConfig user={user} />}
    </div>
  );
};

const ScreenAVD = ({ user, onVerPerfil }) => {
  const isAdmin = user.perfil === 'admin';
  const isGestor = user.perfil === 'gestor';
  // Financeiro nas pesquisas (AVD/Feedback/Censo) e colab normal: ve so a propria nota
  // e nao gerencia ciclo. Em Admissao/Recrutamento ele ve tudo (regra global separada).
  const isColab = user.perfil === 'colaborador' || user.perfil === 'financeiro';

  const [aba, setAba] = useState('avaliacoes');

  const tabsAdmin = [
    { id: 'avaliacoes',     label: 'Avaliações',      icon: 'star'      },
    { id: 'intersetorial',  label: 'Intersetorial',   icon: 'org'       },
    { id: 'feedbacks',      label: 'Feedbacks',       icon: 'message'   },
  ];

  const tabsGestor = [
    { id: 'avaliacoes', label: 'Minhas Avaliações', icon: 'star' },
    { id: 'feedbacks',  label: 'Feedbacks',          icon: 'message' },
  ];

  return (
    <div style={{ animation: 'fadeIn .22s var(--ease-out)' }}>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <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 }}>AVD & Feedback</h2>
        <p style={{ fontSize: 13.5, color: 'var(--escalab-slate)', margin: '4px 0 0' }}>
          {isAdmin ? 'Gestão do ciclo avaliativo e feedbacks de todos os colaboradores' : 'Suas avaliações e feedbacks do ciclo atual'}
        </p>
      </div>

      {/* Tabs */}
      {(isAdmin || isGestor) && (
        <>
          <Tabs tabs={isAdmin ? tabsAdmin : tabsGestor} active={aba} onChange={setAba} />
          <div style={{ paddingTop: 22 }}>
            {aba === 'avaliacoes' && (
              isAdmin ? <AdminAVDView user={user} /> : <LiderAVDView user={user} />
            )}
            {aba === 'intersetorial' && isAdmin && <AdminIntersetorialPanel user={user} onVerPerfil={onVerPerfil} />}
            {aba === 'feedbacks' && (
              isAdmin ? <FeedbacksAdminView user={user} /> : <FeedbackColabSection colab={user} user={user} />
            )}
          </div>
        </>
      )}

      {/* Colaborador · visão completa com avaliação do setor, líder e histórico */}
      {isColab && <ColabAVDView user={user} />}
    </div>
  );
};

window.ScreenAVD = ScreenAVD;
