// ═══════════════════════════════════════════════════════════════
// SCREEN · Organograma · Por Área + Por Setor
// ═══════════════════════════════════════════════════════════════

// ── Modal de edição de colaborador (admin edita tudo) ────────────────────────

const CORES_COLAB = ['#00967B','#1F4A8A','#6B3FA0','#E89B3B','#B3261E','#005E4D','#00836B','#7A4A00','#4A5560','#B56500','#1F8A4C','#C03434'];

const ModalEditarColab = ({ pessoa, onClose, onSalvar, user }) => {
  const podeEditarTudo = user?.perfil === 'admin';
  const podeEditarBio  = podeEditarTudo || (user?.nivel === 'lider' && user?.setor === pessoa.setor);

  const [form, setForm] = useState({
    nome:        pessoa.nome      || '',
    cargo:       pessoa.cargo     || '',
    nivel:       pessoa.nivel     || 'liderado',
    setor:       pessoa.setor     || '',
    email:       pessoa.email     || '',
    bio:         pessoa.bio       || '',
    academico:   pessoa.academico || '',
    gestorNome:  pessoa.gestorNome|| '',
    cor:         pessoa.cor       || '#00967B',
  });
  function up(k, v) { setForm(f => ({ ...f, [k]: v })); }

  function handleSalvar() {
    const updates = {};
    if (podeEditarBio) updates.bio = form.bio;
    if (podeEditarTudo) {
      updates.nome       = form.nome;
      updates.cargo      = form.cargo;
      updates.nivel      = form.nivel;
      updates.setor      = form.setor;
      updates.email      = form.email;
      updates.academico  = form.academico;
      updates.gestorNome = form.gestorNome || null;
      updates.cor        = form.cor;
      // Regenera iniciais quando o nome muda
      if (form.nome !== pessoa.nome) {
        updates.iniciais = form.nome.split(' ').filter(Boolean).slice(0, 2).map(n => n[0]).join('').toUpperCase();
      }
    }
    onSalvar(pessoa.id, updates);
    onClose();
  }

  const inp = { width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box', background: '#fff' };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,15,18,.55)', backdropFilter: 'blur(4px)', zIndex: 1100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 560, maxHeight: '92vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', animation: 'popIn .22s var(--ease-out)' }}>
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>Editar · {pessoa.nome.split(' ')[0]}</div>
            <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginTop: 2 }}>{podeEditarTudo ? 'Admin · pode editar todos os campos' : 'Líder · pode editar apenas a bio'}</div>
          </div>
          <button onClick={onClose} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-mute)' }}><Icon name="close" size={18} /></button>
        </div>
        <div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14, overflowY: 'auto', flex: 1 }}>
          {podeEditarTudo && (
            <>
              <Field label="Nome completo">
                <input value={form.nome} onChange={e => up('nome', e.target.value)} style={inp} />
              </Field>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="Cargo">
                  <input value={form.cargo} onChange={e => up('cargo', e.target.value)} placeholder="Ex: Coordenador(a)" style={inp} />
                </Field>
                <Field label="Nível hierárquico">
                  <select value={form.nivel} onChange={e => up('nivel', e.target.value)} style={inp}>
                    <option value="diretor">Diretor(a)</option>
                    <option value="lider">Líder / Especialista</option>
                    <option value="liderado">Colaborador</option>
                  </select>
                </Field>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="Setor">
                  <select value={form.setor} onChange={e => up('setor', e.target.value)} style={inp}>
                    {SETORES.filter(s => s !== 'Diretoria').map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </Field>
                <Field label="Gestor direto">
                  <select value={form.gestorNome} onChange={e => up('gestorNome', e.target.value)} style={inp}>
                    <option value="">· Sem gestor ·</option>
                    {COLABORADORES.filter(c => c.id !== pessoa.id && (c.nivel === 'lider' || c.nivel === 'diretor')).map(c => (
                      <option key={c.id} value={c.nome}>{c.nome}</option>
                    ))}
                  </select>
                </Field>
              </div>
              <Field label="E-mail">
                <input type="email" value={form.email} onChange={e => up('email', e.target.value)} style={inp} />
              </Field>
              <Field label="Formação acadêmica">
                <input value={form.academico} onChange={e => up('academico', e.target.value)} placeholder="Ex: Bacharel em Administração · FGV" style={inp} />
              </Field>
              <Field label="Cor do avatar">
                <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap', marginTop: 2 }}>
                  {CORES_COLAB.map(c => (
                    <button key={c} type="button" onClick={() => up('cor', c)}
                      style={{ width: 28, height: 28, borderRadius: '50%', background: c, border: form.cor === c ? '3px solid var(--escalab-ink)' : '2px solid var(--escalab-line)', cursor: 'pointer', padding: 0 }}
                      title={c} />
                  ))}
                </div>
              </Field>
            </>
          )}
          {podeEditarBio && (
            <Field label="O que faz no Escalab (bio)">
              <textarea value={form.bio} onChange={e => up('bio', e.target.value)} rows={3}
                style={{ ...inp, resize: 'vertical', lineHeight: 1.5 }} />
            </Field>
          )}
        </div>
        <div style={{ padding: '12px 22px 18px', display: 'flex', gap: 10, justifyContent: 'flex-end', borderTop: '1px solid var(--escalab-line)' }}>
          <Button variant="outline" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" onClick={handleSalvar}>Salvar alterações</Button>
        </div>
      </div>
    </div>
  );
};

// ── Modal de detalhe ───────────────────────────────────────────────────────────

const ModalPessoa = ({ pessoa, onClose, user, onEditar }) => {
  if (!pessoa) return null;
  const gestor = COLABORADORES.find(c => c.nome === pessoa.gestorNome);
  const nivelLabel = { diretor: 'Diretor(a)', lider: 'Líder / Especialista', liderado: 'Colaborador' }[pessoa.nivel] || pessoa.nivel;
  const nivelTone  = { diretor: 'dark', lider: 'brand', liderado: 'neutral' }[pessoa.nivel];
  const anos = pessoa.tempoEmpresa >= 12 ? Math.floor(pessoa.tempoEmpresa / 12) : null;
  const meses = pessoa.tempoEmpresa % 12;
  const tempoStr = anos
    ? `${anos} ano${anos > 1 ? 's' : ''}${meses > 0 ? ` e ${meses} meses` : ''}`
    : `${pessoa.tempoEmpresa} meses`;
  const liderados = COLABORADORES.filter(c => c.gestorNome === pessoa.nome);
  const cat = getCategoriaColaborador(pessoa.id);
  const isAdmin = user?.perfil === 'admin';
  const isGestor = user?.perfil === 'gestor';
  const podeEditar = isAdmin || (isGestor && user?.setor === pessoa.setor);
  const cargoDisplay = getCargoDisplay(pessoa, isAdmin);

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,15,18,.55)', backdropFilter: 'blur(4px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 18, width: '100%', maxWidth: 520, animation: 'popIn .22s var(--ease-out)', overflow: 'hidden', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}>
        {/* Header colorido */}
        <div style={{ background: `linear-gradient(135deg, ${pessoa.cor}, ${pessoa.cor}cc)`, padding: '24px 24px 28px', flexShrink: 0, position: 'relative' }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 14, right: 14, border: 0, background: 'rgba(255,255,255,.2)', borderRadius: 8, cursor: 'pointer', padding: '4px 8px', color: '#fff' }}>
            <Icon name="close" size={16} />
          </button>
          {podeEditar && (
            <button onClick={() => onEditar(pessoa)} style={{ position: 'absolute', top: 14, right: 52, border: 0, background: 'rgba(255,255,255,.2)', borderRadius: 8, cursor: 'pointer', padding: '4px 8px', color: '#fff', fontFamily: 'var(--font-sans)', fontSize: 12, display: 'flex', alignItems: 'center', gap: 5 }}>
              <Icon name="settings" size={12} /> Editar
            </button>
          )}
          <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
            <PhotoAvatar colaborador={pessoa} size={60} canEdit={podeEditar} />
            <div>
              <h3 style={{ color: '#fff', fontSize: 18, fontWeight: 700, margin: '0 0 3px', lineHeight: 1.2 }}>{pessoa.nome}</h3>
              <div style={{ color: 'rgba(255,255,255,.92)', fontSize: 13, fontWeight: 500 }}>{cargoDisplay}</div>
            </div>
          </div>
        </div>

        {/* Tags e conteúdo */}
        <div style={{ overflowY: 'auto', flex: 1 }}>
          <div style={{ padding: '14px 22px 4px', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <Tag tone={nivelTone}>{nivelLabel}</Tag>
            <Tag tone="neutral">{pessoa.setor}</Tag>
            {cat.categoria !== 'fixo' && <Tag tone="info">{CATEGORIA_LABEL[`associado_${cat.tipoAssociado}`] || 'Associado'}</Tag>}
          </div>

          <div style={{ padding: '4px 22px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ background: 'var(--escalab-paper)', borderRadius: 10, padding: '12px 16px', borderLeft: `3px solid ${pessoa.cor}` }}>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--escalab-mute)', marginBottom: 5 }}>O que faz no Escalab</div>
              <p style={{ fontSize: 13.5, color: 'var(--escalab-ink)', margin: 0, lineHeight: 1.6 }}>{pessoa.bio}</p>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
              {[
                { label: 'E-mail',           val: pessoa.email,      icon: 'user'     },
                { label: 'Tempo na empresa', val: tempoStr,          icon: 'calendar' },
                { label: 'Formação',         val: pessoa.academico,  icon: 'clipboard'},
                gestor && { label: 'Gestor direto', val: gestor.nome, icon: 'trend_up' },
              ].filter(Boolean).map((row, i, arr) => (
                <div key={row.label} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '10px 0', borderBottom: i < arr.length - 1 || liderados.length > 0 ? '1px solid var(--escalab-line)' : 0 }}>
                  <div style={{ color: pessoa.cor, flexShrink: 0, marginTop: 1 }}><Icon name={row.icon} size={14} /></div>
                  <span style={{ fontSize: 12, color: 'var(--escalab-mute)', minWidth: 115, flexShrink: 0 }}>{row.label}</span>
                  <span style={{ fontSize: 13, color: 'var(--escalab-ink)', fontWeight: 500 }}>{row.val}</span>
                </div>
              ))}
              {liderados.length > 0 && (
                <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '10px 0' }}>
                  <div style={{ color: pessoa.cor, flexShrink: 0, marginTop: 1 }}><Icon name="users" size={14} /></div>
                  <span style={{ fontSize: 12, color: 'var(--escalab-mute)', minWidth: 115, flexShrink: 0 }}>{`Liderados (${liderados.length})`}</span>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, flex: 1 }}>
                    {liderados.map(l => (
                      <span key={l.id} style={{ fontSize: 12, color: 'var(--escalab-ink)', background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 999, padding: '3px 10px', fontWeight: 500 }}>
                        {l.nome}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Row de membro no setor ─────────────────────────────────────────────────────

const SetorMemberRow = ({ m, isLast, onSelecionar, user }) => {
  const [hov, setHov] = useState(false);
  // PDF Site AVD 5 · item 18: mostrar descrição ("o que a pessoa faz") visível no organograma
  const descricao = (m.bio || '').trim();
  return (
    <div onClick={() => onSelecionar(m)}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '12px 18px', borderBottom: isLast ? 0 : '1px solid var(--escalab-line)', cursor: 'pointer', background: hov ? 'var(--escalab-paper)' : '#fff', transition: 'background .12s' }}>
      <PhotoAvatar colaborador={m} size={34} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--escalab-ink)', lineHeight: 1.3 }}>
          {m.nome}
        </div>
        <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 2 }}>{getCargoDisplay(m, user?.perfil === 'admin')}</div>
        {descricao && (
          <div style={{ fontSize: 12, color: 'var(--escalab-slate)', marginTop: 6, lineHeight: 1.45, paddingLeft: 8, borderLeft: `2px solid ${m.cor || 'var(--escalab-line)'}` }}>
            {descricao.length > 140 ? descricao.slice(0, 140).trim() + '…' : descricao}
          </div>
        )}
      </div>
      <div style={{ flexShrink: 0, marginTop: 3 }}>
        <span style={{ fontSize: 11.5, color: 'var(--escalab-mute)', background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 5, padding: '2px 8px', whiteSpace: 'nowrap' }}>
          {m.setor}
        </span>
      </div>
    </div>
  );
};

// ── Estrutura por área ─────────────────────────────────────────────────────────

const AREAS_ORG_KEY = 'escalab_areas_org_v2'; // v2 = pos refactor pro organograma real
const AREAS_ORG_KEY_LEGACY = 'escalab_areas_org_v1';
function getAreasOrg() {
  try {
    const raw = localStorage.getItem(AREAS_ORG_KEY);
    if (raw) return JSON.parse(raw);
    // Migracao: apaga a estrutura antiga pra nao confundir
    if (localStorage.getItem(AREAS_ORG_KEY_LEGACY)) {
      localStorage.removeItem(AREAS_ORG_KEY_LEGACY);
    }
  } catch {}
  return AREAS_ORG_DEFAULT;
}
function salvarAreasOrg(arr) {
  try { localStorage.setItem(AREAS_ORG_KEY, JSON.stringify(arr)); } catch {}
}
function resetAreasOrg() {
  try { localStorage.removeItem(AREAS_ORG_KEY); } catch {}
}

// cardWidthKey: chave do preset de largura (ver WIDTH_PRESETS abaixo).
// cardHeight:   altura em px (livre, ajustada pelo handle).
// Esses campos viajam junto com a estrutura no localStorage `escalab_areas_org_v1`
// — quando o backend Supabase entrar (project_backend_supabase.md), automaticamente
// passa a sincronizar pra todos os usuários junto com o restante da estrutura.

const AREAS_ORG_DEFAULT = [
  {
    id: 'vendas',
    label: 'Área de Vendas',
    cor: '#1F4A8A',
    cardWidthKey: '50', cardHeight: 480,
    responsaveisNomes: ['Fabiano Gomes Ferreira De Paula', 'Maria Paula Duarte De Oliveira'],
    equipes: [
      { nome: 'Prospecção e Inteligência de Mercado', responsaveisNomes: ['Vanessa Vital França'],                                  setores: ['Prospecção E Inteligência De Mercado'] },
      { nome: 'Carteira de Leads e Marketing',         responsaveisNomes: ['Jorge Filipe De Souza Santos'],                          setores: ['Carteira De Leads E Marketing'] },
      { nome: 'Propostas e Fechamento',                responsaveisNomes: ['Ingrid Fernandes Silva', 'Rafaela Leal Pereira'],         setores: ['Propostas E Fechamento'] },
      { nome: 'Editais de Fomento',                    responsaveisNomes: ['Gustavo Spagnol Campos'],                                 setores: ['Editais De Fomento'] },
    ],
  },
  {
    id: 'suporte',
    label: 'Área de Suporte',
    cor: '#00836B',
    cardWidthKey: '50', cardHeight: 480,
    responsaveisNomes: ['Maria Paula Duarte De Oliveira'],
    equipes: [
      { nome: 'Adm e Financeiro', responsaveisNomes: ['Letícia Santos Bahia Silva'], setores: ['Administrativo Financeiro'] },
      { nome: 'Gente e Cultura',  responsaveisNomes: ['Maria Paula Duarte De Oliveira'], setores: ['Gente E Cultura'] },
    ],
  },
  {
    id: 'pos_vendas',
    label: 'Área de Pós Vendas',
    cor: '#6B3FA0',
    cardWidthKey: '50', cardHeight: 480,
    responsaveisNomes: ['Breno Germano De Freitas Oliveira'],
    equipes: [
      { nome: 'Fidelização P&D & Escalonamento',      responsaveisNomes: ['Carolina Maria De Lima Alves'],  setores: ['Fidelização E Gestão De Entregas- P&d & Escaloname'] },
      { nome: 'Fidelização NN e Viabilidade',         responsaveisNomes: ['Rafaela Leal Pereira'],          setores: ['Fidelização E Gestão De Entregas  Nn E Viabilidade'] },
      { nome: 'PMO',                                   responsaveisNomes: ['Yasmim Rodrigues Dos Santos'],   setores: ['Pmo'] },
      { nome: 'P&D e Escalonamento',                   responsaveisNomes: ['Ana Paula De Carvalho Teixeira'],setores: ['P&d E Escalonamento'] },
      { nome: 'NNE & EVT',                             responsaveisNomes: ['Eduarda Rezende Barbosa'],       setores: ['Novos Negócios E Evt'] },
      { nome: 'Associados de Projetos',                responsaveisNomes: ['Clara Cardoso Costa'],           setores: ['Associados De Projetos'] },
      { nome: 'Associados de Editais',                 responsaveisNomes: ['Gabriela Campos De Oliveira'],   setores: ['Associados De Editais (ana P E Rochel)'] },
    ],
  },
  {
    id: 'expansao',
    label: 'Área de Expansão',
    cor: '#E89B3B',
    cardWidthKey: '50', cardHeight: 480,
    responsaveisNomes: ['Fabiano Gomes Ferreira De Paula'],
    equipes: [
      { nome: 'Venture Builder', responsaveisNomes: ['Rochel Montero Lago', 'Fabiano Gomes Ferreira De Paula'], setores: ['Vb'] },
      { nome: 'Redes',           responsaveisNomes: ['Rochel Montero Lago'],                                     setores: ['Redes'] },
      { nome: 'Nanofood',        responsaveisNomes: ['Davyston Carvalho Pedersoli'],                             setores: ['Nanofood'] },
    ],
  },
];

// ── Equipe card (com suporte a múltiplos responsáveis e subEquipes) ─────────────

// Cores fixas para destacar papéis (independentes da cor da área)
const COR_LIDER_AREA   = '#C8A24B';  // dourado · líder da área
const COR_LIDER_AREA_BG = '#FFF6E0';
const COR_GESTOR_SETOR = '#1F4A8A';  // azul escuro · gestor do setor

const EquipeCard = ({ equipe, cor, onSelecionar, isSubEquipe, modoEdicao, podeSubir, podeDescer, onSubir, onDescer }) => {
  const responsaveis = (equipe.responsaveisNomes || []).map(n => COLABORADORES.find(c => c.nome === n)).filter(Boolean);
  // Considera setores extras (pessoa em mais de um setor) · fica em ambas as caixinhas
  const pertenceAoSetor = (c) =>
    equipe.setores.includes(c.setor) ||
    (Array.isArray(c.setoresExtras) && c.setoresExtras.some(s => equipe.setores.includes(s)));
  const membros = COLABORADORES.filter(c =>
    pertenceAoSetor(c) &&
    !equipe.responsaveisNomes?.includes(c.nome) &&
    c.nivel !== 'diretor'
  );

  // Líderes internos: dentro do setor, alguém pode ser nivel 'lider' e ser gestor de outros membros (hierarquia interna).
  const lideresInternos = membros.filter(m => m.nivel === 'lider' && membros.some(x => x.id !== m.id && x.gestorNome === m.nome));
  const liderados = membros.filter(m => !lideresInternos.some(l => l.id === m.id));

  // Chip do gestor do setor (responsável da equipe) · destaque com avatar + nome
  const GestorChip = ({ p }) => (
    <div onClick={() => onSelecionar(p)} title={p.cargo} style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      background: '#fff', border: `1.5px solid ${COR_GESTOR_SETOR}`,
      borderRadius: 999, padding: '3px 11px 3px 3px', cursor: 'pointer',
      boxShadow: '0 1px 2px rgba(15,30,55,.08)',
    }}>
      <PhotoAvatar colaborador={p} size={22} />
      <span style={{ fontSize: 11.5, fontWeight: 700, color: COR_GESTOR_SETOR, whiteSpace: 'nowrap' }}>
        {p.nome}
      </span>
    </div>
  );

  // Chip de membro · claro, com avatar pequeno
  const MembroChip = ({ p }) => (
    <span onClick={() => onSelecionar(p)} title={p.cargo} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      fontSize: 11.5, fontWeight: 500, cursor: 'pointer',
      background: '#fff', color: 'var(--escalab-ink)',
      border: '1px solid var(--escalab-line)',
      borderRadius: 999, padding: '2px 10px 2px 2px', lineHeight: 1.35,
      whiteSpace: 'nowrap',
    }}>
      <PhotoAvatar colaborador={p} size={18} />
      {p.nome}
    </span>
  );

  if (equipe.subEquipes) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: equipe.fullWidth ? '0 0 100%' : undefined, minWidth: 0 }}>
        {/* Gestor do setor */}
        {responsaveis.length > 0 && (
          <div style={{ display: 'flex', gap: 6, justifyContent: 'center', flexWrap: 'wrap' }}>
            {responsaveis.map(r => <GestorChip key={r.id} p={r} />)}
          </div>
        )}
        {/* Box principal com sub-equipes dentro */}
        <div style={{ background: '#fff', border: `1.5px solid ${cor}`, borderTop: `4px solid ${cor}`, borderRadius: 12, padding: '14px 16px', boxShadow: '0 1px 3px rgba(15,30,55,.06)' }}>
          <div style={{ fontSize: 12.5, fontWeight: 800, color: cor, textAlign: 'center', marginBottom: 12, letterSpacing: '.02em', textTransform: 'uppercase' }}>{equipe.nome}</div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center', alignItems: 'flex-start' }}>
            {equipe.subEquipes.map(sub => (
              <EquipeCard key={sub.nome} equipe={sub} cor={cor} onSelecionar={onSelecionar} isSubEquipe />
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0, flex: equipe.fullWidth ? '0 0 100%' : '1 1 160px', maxWidth: '100%' }}>
      {/* Gestor do setor · destaque acima da caixa */}
      {responsaveis.length > 0 && (
        <div style={{ display: 'flex', gap: 6, justifyContent: 'center', flexWrap: 'wrap', minHeight: 26 }}>
          {responsaveis.map(r => <GestorChip key={r.id} p={r} />)}
        </div>
      )}
      {/* Caixa da equipe · fundo branco, header colorido */}
      <div style={{ background: '#fff', border: modoEdicao && !isSubEquipe ? `1.5px dashed ${cor}` : `1px solid ${cor}33`, borderRadius: 10, overflow: 'hidden', boxShadow: '0 1px 2px rgba(15,30,55,.05)' }}>
        <div style={{ background: cor, padding: '7px 12px', display: 'flex', alignItems: 'center', justifyContent: modoEdicao && !isSubEquipe ? 'space-between' : 'center', gap: 6, minHeight: 24 }}>
          {/* Botões de reordenação inline · só em modoEdicao e em equipes de topo (não subEquipes) */}
          {modoEdicao && !isSubEquipe ? (
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); onSubir?.(); }}
              disabled={!podeSubir}
              title="Mover equipe para cima"
              style={{
                border: 0, background: podeSubir ? 'rgba(255,255,255,.25)' : 'rgba(255,255,255,.08)',
                color: '#fff', borderRadius: 6, padding: '2px 7px', cursor: podeSubir ? 'pointer' : 'not-allowed',
                fontSize: 12, fontWeight: 800, lineHeight: 1, fontFamily: 'var(--font-sans)',
                opacity: podeSubir ? 1 : .4,
              }}>↑</button>
          ) : <span />}
          <span style={{ fontSize: isSubEquipe ? 11.5 : 12.5, fontWeight: 700, color: '#fff', letterSpacing: '.02em', flex: modoEdicao && !isSubEquipe ? 1 : 'initial', textAlign: 'center' }}>
            {equipe.nome}
          </span>
          {modoEdicao && !isSubEquipe ? (
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); onDescer?.(); }}
              disabled={!podeDescer}
              title="Mover equipe para baixo"
              style={{
                border: 0, background: podeDescer ? 'rgba(255,255,255,.25)' : 'rgba(255,255,255,.08)',
                color: '#fff', borderRadius: 6, padding: '2px 7px', cursor: podeDescer ? 'pointer' : 'not-allowed',
                fontSize: 12, fontWeight: 800, lineHeight: 1, fontFamily: 'var(--font-sans)',
                opacity: podeDescer ? 1 : .4,
              }}>↓</button>
          ) : <span />}
        </div>
        {membros.length > 0 ? (
          lideresInternos.length > 0 ? (
            <div style={{ padding: '10px 10px', display: 'flex', flexDirection: 'column', gap: 8 }}>
              {/* Linha de líderes internos (pares lideram juntos) */}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'center' }}>
                {lideresInternos.map(l => (
                  <span key={l.id} onClick={() => onSelecionar(l)} title={l.cargo} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    fontSize: 11.5, fontWeight: 700, cursor: 'pointer',
                    background: '#fff', color: COR_GESTOR_SETOR,
                    border: `1.5px solid ${COR_GESTOR_SETOR}`,
                    borderRadius: 999, padding: '2px 11px 2px 2px', lineHeight: 1.35,
                  }}>
                    <PhotoAvatar colaborador={l} size={20} />
                    {l.nome.split(' ').slice(0,2).join(' ')}
                  </span>
                ))}
              </div>
              {/* Conector visual */}
              <div style={{ height: 14, position: 'relative', textAlign: 'center' }}>
                <div style={{ position:'absolute', top:0, bottom:0, left:'50%', width:1, background: cor + '70' }} />
              </div>
              {/* Liderados */}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, justifyContent: 'center' }}>
                {liderados.map(m => <MembroChip key={m.id} p={m} />)}
              </div>
            </div>
          ) : (
            <div style={{ padding: '10px 10px', display: 'flex', flexWrap: 'wrap', gap: 5, justifyContent: 'center' }}>
              {membros.map(m => <MembroChip key={m.id} p={m} />)}
            </div>
          )
        ) : (
          <div style={{ padding: '8px 12px', fontSize: 11, color: 'var(--escalab-mute)', fontStyle: 'italic', textAlign: 'center' }}>
            sem membros
          </div>
        )}
      </div>
    </div>
  );
};

const AreaQuadrant = ({ area, onSelecionar, modoEdicao, onDragStart, onResizeStart, onLarguraMenor, onLarguraMaior, presetLargura, onMoverEquipe }) => {
  const responsaveis = area.responsaveisNomes.map(n => COLABORADORES.find(c => c.nome === n)).filter(Boolean);
  return (
    <div style={{ position: 'relative', height: '100%', background: '#fff', border: modoEdicao ? `2px dashed ${area.cor}` : '1px solid var(--escalab-line)', borderRadius: 14, overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: '0 2px 4px rgba(15,30,55,.06)' }}>
      {/* Header da área · também serve como handle de arrastar quando modoEdicao está ativo */}
      <div
        onMouseDown={modoEdicao ? onDragStart : undefined}
        style={{
          background: `linear-gradient(135deg, ${area.cor}, ${area.cor}dd)`,
          padding: '14px 20px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 14, flexWrap: 'wrap',
          cursor: modoEdicao ? 'grab' : 'default',
          userSelect: modoEdicao ? 'none' : 'auto',
        }}>
        {modoEdicao && (
          <span title="Arraste pra reordenar entre as áreas" style={{ color: '#fff', opacity: .85, fontSize: 14, lineHeight: 1, marginRight: -4 }}>⋮⋮</span>
        )}
        <span style={{ fontSize: 14, fontWeight: 800, color: '#fff', letterSpacing: '.02em', textTransform: 'uppercase' }}>{area.label}</span>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
          {responsaveis.map(r => (
            <div key={r.id} onClick={() => onSelecionar(r)} title={r.cargo || r.nome} style={{
              display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer',
              background: COR_LIDER_AREA_BG, border: `1.5px solid ${COR_LIDER_AREA}`,
              borderRadius: 999, padding: '3px 12px 3px 3px',
              boxShadow: '0 1px 3px rgba(0,0,0,.12)',
            }}>
              <PhotoAvatar colaborador={r} size={26} />
              <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
                <span style={{ fontSize: 9, fontWeight: 800, color: COR_LIDER_AREA, letterSpacing: '.08em', textTransform: 'uppercase' }}>
                  Líder de Área
                </span>
                <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--escalab-ink)', whiteSpace: 'nowrap' }}>{r.nome}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ padding: '18px 20px', paddingBottom: modoEdicao ? 24 : 18, display: 'flex', flexWrap: 'wrap', gap: 16, flex: 1, alignItems: 'flex-start', overflowY: 'auto', overflowX: 'hidden', minHeight: 0 }}>
        {area.equipes.map((eq, idx) => (
          <EquipeCard
            key={eq.nome + '_' + idx}
            equipe={eq}
            cor={area.cor}
            onSelecionar={onSelecionar}
            modoEdicao={modoEdicao}
            podeSubir={idx > 0}
            podeDescer={idx < area.equipes.length - 1}
            onSubir={() => onMoverEquipe?.(idx, -1)}
            onDescer={() => onMoverEquipe?.(idx, +1)}
          />
        ))}
      </div>
      {/* Controles de tamanho — só no modo edição */}
      {modoEdicao && (
        <>
          {/* Botões de largura (canto superior-direito) — sob o header */}
          <div style={{
            position: 'absolute', top: 8, right: 8, display: 'flex', gap: 4,
            background: 'rgba(255,255,255,.95)', borderRadius: 8, padding: '3px 4px',
            boxShadow: '0 2px 6px rgba(0,0,0,.15)', zIndex: 6,
          }}>
            <button onClick={(e) => { e.stopPropagation(); onLarguraMenor?.(); }} title="Diminuir largura" style={{
              border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-slate)',
              padding: '3px 7px', fontSize: 13, fontFamily: 'var(--font-sans)', fontWeight: 700, lineHeight: 1, borderRadius: 5,
            }}>−</button>
            <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--escalab-slate)', padding: '3px 4px', minWidth: 24, textAlign: 'center', borderLeft: '1px solid var(--escalab-line)', borderRight: '1px solid var(--escalab-line)' }}>{presetLargura?.label || '½'}</span>
            <button onClick={(e) => { e.stopPropagation(); onLarguraMaior?.(); }} title="Aumentar largura" style={{
              border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-slate)',
              padding: '3px 7px', fontSize: 13, fontFamily: 'var(--font-sans)', fontWeight: 700, lineHeight: 1, borderRadius: 5,
            }}>+</button>
          </div>
          {/* Handle de altura (borda inferior inteira) */}
          <div
            onMouseDown={onResizeStart}
            title="Arraste pra ajustar a altura"
            style={{
              position: 'absolute', left: 0, right: 0, bottom: 0,
              height: 10, cursor: 'ns-resize',
              background: `linear-gradient(0deg, ${area.cor}88, transparent)`,
              borderBottomLeftRadius: 13, borderBottomRightRadius: 13,
              display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
              userSelect: 'none', zIndex: 5, touchAction: 'none',
            }}>
            <div style={{ width: 32, height: 3, background: '#fff', borderRadius: 999, marginBottom: 2, boxShadow: '0 1px 2px rgba(0,0,0,.2)' }} />
          </div>
        </>
      )}
    </div>
  );
};

// ── Layout responsivo (mede o container REAL via ResizeObserver) ─────────────
//
// Cada area carrega `cardWidthKey` (preset de largura: 33/50/66/100) e
// `cardHeight` (px) DENTRO da propria estrutura AREAS_ORG. Isso significa que
// quando o admin reorganiza, a alteracao e salva via `salvarAreasOrg` — o mesmo
// fluxo do "Editar estrutura". Hoje isso ainda e localStorage (cada navegador
// tem sua copia), mas quando o backend Supabase entrar (proximo marco do
// projeto), automaticamente todos os usuarios passam a ver a versao do admin
// porque a estrutura inteira ja foi feita pra sincronizar via essa mesma chave.
//
// Por que ResizeObserver em vez de flex/calc(): com `flex 1 1 calc(50% - 8px)`
// + `minWidth: 280`, em telas estreitas o minWidth vence o calc e os cards
// estouram a largura da pagina. Aqui a gente calcula a largura em PX a partir
// da medicao real do container — nunca passa do container, ponto.

const WIDTH_PRESETS = [
  { id: '33',  label: '1/3', fracao: 1/3 },
  { id: '50',  label: '1/2', fracao: 1/2 },
  { id: '66',  label: '2/3', fracao: 2/3 },
  { id: '100', label: '1/1', fracao: 1   },
];
function presetDe(area) {
  const k = String(area?.cardWidthKey || '50');
  return WIDTH_PRESETS.find(p => p.id === k) || WIDTH_PRESETS[1];
}
function alturaDe(area) {
  return Math.max(240, Number(area?.cardHeight) || 480);
}
function proximoPresetW(atualId, dir) {
  const idx = WIDTH_PRESETS.findIndex(p => p.id === atualId);
  const novo = Math.min(WIDTH_PRESETS.length - 1, Math.max(0, idx + dir));
  return WIDTH_PRESETS[novo].id;
}

const ORG_GAP = 16;
const ORG_MIN_CARD = 240; // largura minima absoluta de um card

// Pega o preset salvo e devolve o efetivo, colapsando em telas estreitas.
function presetEfetivo(presetSalvo, containerW) {
  if (!containerW) return presetSalvo;
  if (containerW < 640) return WIDTH_PRESETS[3];                            // mobile → 1/1
  if (containerW < 880 && presetSalvo.id === '33') return WIDTH_PRESETS[1]; // tablet → 1/3 vira 1/2
  return presetSalvo;
}

// Largura em PX, sempre <= containerW. Devolve null antes da primeira medicao.
function larguraPx(presetEfet, containerW) {
  if (!containerW) return null;
  const cols = Math.max(1, Math.round(1 / presetEfet.fracao)); // 3, 2, 1
  const gaps = ORG_GAP * Math.max(0, cols - 1);
  const ideal = Math.floor((containerW - gaps) * presetEfet.fracao);
  // Garante minimo, mas nunca passa do container (no caso de container minusculo).
  return Math.min(containerW, Math.max(Math.min(ORG_MIN_CARD, containerW), ideal));
}

const AreaView = ({ onSelecionar, versao, isAdmin, onAreasChange }) => {
  const [areas, setAreas] = useState(() => getAreasOrg());
  const [modoEdicao, setModoEdicao] = useState(false);
  const [arrastando, setArrastando] = useState(null); // { id, modo:'reorder'|'resizeH', startY, baseH }
  const [reorderTarget, setReorderTarget] = useState(null);
  const [containerW, setContainerW] = useState(0);
  const containerRef = useRef(null);

  // Sincroniza com a versao externa (ex: depois que o modal "Editar estrutura" salva)
  useEffect(() => { setAreas(getAreasOrg()); }, [versao]);

  // Mede a largura REAL do container. ResizeObserver pega tudo — resize de
  // janela, sidebar abrindo, zoom, qualquer reflow. Fallback no window resize
  // por seguranca em navegadores antigos.
  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const measure = () => setContainerW(el.clientWidth);
    measure();
    let ro;
    if (typeof ResizeObserver !== 'undefined') {
      ro = new ResizeObserver(measure);
      ro.observe(el);
    }
    window.addEventListener('resize', measure);
    return () => {
      if (ro) ro.disconnect();
      window.removeEventListener('resize', measure);
    };
  }, []);

  function persistir(novas) {
    setAreas(novas);
    salvarAreasOrg(novas);
    onAreasChange?.();
  }
  function patchArea(id, patch) {
    persistir(areas.map(a => a.id === id ? { ...a, ...patch } : a));
  }
  function ciclarLarguraArea(id, dir) {
    const a = areas.find(x => x.id === id);
    if (!a) return;
    patchArea(id, { cardWidthKey: proximoPresetW(presetDe(a).id, dir) });
  }
  function moverArea(fromIdx, toIdx) {
    if (fromIdx === toIdx || toIdx < 0 || toIdx >= areas.length) return;
    const novas = [...areas];
    const [movida] = novas.splice(fromIdx, 1);
    novas.splice(toIdx, 0, movida);
    persistir(novas);
  }
  function moverEquipe(areaId, equipeIdx, dir) {
    const novas = areas.map(a => {
      if (a.id !== areaId) return a;
      const eqs = [...a.equipes];
      const novoIdx = equipeIdx + dir;
      if (novoIdx < 0 || novoIdx >= eqs.length) return a;
      [eqs[equipeIdx], eqs[novoIdx]] = [eqs[novoIdx], eqs[equipeIdx]];
      return { ...a, equipes: eqs };
    });
    persistir(novas);
  }

  // ── Reorder via drag no header ─────────────────────────────────────────────
  function iniciarReorder(areaId, e) {
    if (!isAdmin || !modoEdicao) return;
    e.preventDefault();
    setArrastando({ id: areaId, modo: 'reorder' });
  }
  function iniciarResizeH(areaId, e) {
    if (!isAdmin || !modoEdicao) return;
    e.preventDefault(); e.stopPropagation();
    const a = areas.find(x => x.id === areaId);
    setArrastando({ id: areaId, modo: 'resizeH', startY: e.clientY, baseH: alturaDe(a) });
  }

  useEffect(() => {
    if (!arrastando) return;
    function onMove(ev) {
      if (arrastando.modo === 'reorder') {
        // Detecta sobre qual card o cursor esta passando — usa data-area-card no DOM
        const el = document.elementFromPoint(ev.clientX, ev.clientY);
        const card = el && el.closest('[data-area-card]');
        const sobre = card?.getAttribute('data-area-card');
        if (sobre && sobre !== arrastando.id) setReorderTarget(sobre);
        else if (!card) setReorderTarget(null);
      } else if (arrastando.modo === 'resizeH') {
        const dy = ev.clientY - arrastando.startY;
        const novaH = Math.max(240, arrastando.baseH + dy);
        patchArea(arrastando.id, { cardHeight: novaH });
      }
    }
    function onUp() {
      if (arrastando.modo === 'reorder' && reorderTarget) {
        const fromIdx = areas.findIndex(a => a.id === arrastando.id);
        const toIdx   = areas.findIndex(a => a.id === reorderTarget);
        moverArea(fromIdx, toIdx);
      }
      setArrastando(null);
      setReorderTarget(null);
    }
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
  }, [arrastando, reorderTarget, areas]);

  function resetLayoutLocal() {
    if (!window.confirm('Resetar largura, altura e ordem de todas as áreas pro padrão?')) return;
    const novas = areas.map((a) => {
      const padrao = AREAS_ORG_DEFAULT.find(d => d.id === a.id);
      return { ...a, cardWidthKey: padrao?.cardWidthKey || '50', cardHeight: padrao?.cardHeight || 480 };
    });
    persistir(novas);
  }

  return (
    <div style={{ animation: 'fadeIn .2s' }}>
      {isAdmin && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, flexWrap: 'wrap' }}>
          <button onClick={() => setModoEdicao(v => !v)} style={{
            border: `1px solid ${modoEdicao ? 'var(--escalab-brand)' : 'var(--escalab-line)'}`,
            background: modoEdicao ? 'var(--escalab-brand)' : '#fff',
            color: modoEdicao ? '#fff' : 'var(--escalab-slate)',
            borderRadius: 9, padding: '7px 14px', cursor: 'pointer', fontSize: 12.5, fontWeight: 700, fontFamily: 'var(--font-sans)',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name={modoEdicao ? 'check' : 'settings'} size={12} />
            {modoEdicao ? 'Sair do modo reorganizar' : 'Reorganizar layout'}
          </button>
          {modoEdicao && (
            <>
              <span style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>
                Arraste o header da área pra reordenar áreas · use ↑/↓ no header de cada equipe pra reordenar equipes dentro da área · botões de tamanho + handle inferior ajustam dimensões.
              </span>
              <button onClick={resetLayoutLocal} style={{ border: '1px solid var(--escalab-line)', background: '#fff', color: 'var(--escalab-slate)', borderRadius: 9, padding: '7px 12px', cursor: 'pointer', fontSize: 12, marginLeft: 'auto' }}>
                Resetar layout
              </button>
            </>
          )}
        </div>
      )}

      {/* Container FLEX responsivo · largura em PX calculada do container real */}
      <div ref={containerRef} className="organograma-container" style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: ORG_GAP,
        alignItems: 'stretch',
        width: '100%',
        maxWidth: '100%',
        boxSizing: 'border-box',
        userSelect: arrastando ? 'none' : 'auto',
      }}>
        {areas.map((a) => {
          const presetSalvo = presetDe(a);
          const presetEfet  = presetEfetivo(presetSalvo, containerW);
          const wPx         = larguraPx(presetEfet, containerW);
          const altura = alturaDe(a);
          const sendoArrastado = arrastando?.id === a.id;
          const ehAlvoReorder  = reorderTarget === a.id && arrastando?.modo === 'reorder';
          return (
            <div key={a.id}
              data-area-card={a.id}
              style={{
                // Antes da primeira medicao: 100% (1 coluna). Depois: px exatos.
                width: wPx != null ? `${wPx}px` : '100%',
                maxWidth: '100%',
                flex: '0 0 auto',
                boxSizing: 'border-box',
                height: altura,
                position: 'relative',
                transition: sendoArrastado ? 'none' : 'height .2s, opacity .15s',
                opacity: sendoArrastado ? .55 : 1,
                outline: ehAlvoReorder ? `3px dashed ${a.cor}` : 'none',
                outlineOffset: ehAlvoReorder ? 4 : 0,
                borderRadius: 14,
              }}>
              <AreaQuadrant
                area={a}
                onSelecionar={onSelecionar}
                modoEdicao={modoEdicao && isAdmin}
                onDragStart={e => iniciarReorder(a.id, e)}
                onResizeStart={e => iniciarResizeH(a.id, e)}
                onLarguraMenor={() => ciclarLarguraArea(a.id, -1)}
                onLarguraMaior={() => ciclarLarguraArea(a.id, +1)}
                presetLargura={presetSalvo}
                onMoverEquipe={(idx, dir) => moverEquipe(a.id, idx, dir)}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ── Modal · Editar estrutura (áreas e equipes) — admin only ─────────────────

const CORES_AREA = ['#1F4A8A','#00836B','#6B3FA0','#E89B3B','#B3261E','#005E4D','#7A4A00','#4A5560','#1F8A4C'];

const ModalEditarEstrutura = ({ onClose, onSalvo }) => {
  const [areas, setAreas] = useState(() => JSON.parse(JSON.stringify(getAreasOrg())));
  const [areaSel, setAreaSel] = useState(areas[0]?.id || null);

  const areaAtual = areas.find(a => a.id === areaSel);
  const setoresDisponiveis = useMemo(() => [...new Set(COLABORADORES.map(c => c.setor).filter(Boolean))].sort(), []);
  const lideresDisponiveis = useMemo(() => COLABORADORES.filter(c => c.nivel === 'lider' || c.nivel === 'diretor').sort((a,b) => a.nome.localeCompare(b.nome)), []);

  function patchArea(id, patch) {
    setAreas(arr => arr.map(a => a.id === id ? { ...a, ...patch } : a));
  }
  function addArea() {
    const id = 'area_' + Date.now();
    const novaCor = CORES_AREA[areas.length % CORES_AREA.length];
    setAreas([...areas, { id, label: 'Nova Área', cor: novaCor, responsaveisNomes: [], equipes: [] }]);
    setAreaSel(id);
  }
  function rmArea(id) {
    if (!window.confirm('Remover esta área e todas as equipes dentro dela?')) return;
    const novo = areas.filter(a => a.id !== id);
    setAreas(novo);
    if (areaSel === id) setAreaSel(novo[0]?.id || null);
  }
  function patchEquipe(areaId, idx, patch) {
    setAreas(arr => arr.map(a => a.id !== areaId ? a : ({ ...a, equipes: a.equipes.map((e, i) => i === idx ? { ...e, ...patch } : e) })));
  }
  function addEquipe(areaId) {
    setAreas(arr => arr.map(a => a.id !== areaId ? a : ({ ...a, equipes: [...a.equipes, { nome: 'Nova equipe', responsaveisNomes: [], setores: [] }] })));
  }
  function rmEquipe(areaId, idx) {
    if (!window.confirm('Remover esta equipe?')) return;
    setAreas(arr => arr.map(a => a.id !== areaId ? a : ({ ...a, equipes: a.equipes.filter((_, i) => i !== idx) })));
  }
  function moveEquipe(areaId, idx, dir) {
    setAreas(arr => arr.map(a => {
      if (a.id !== areaId) return a;
      const eqs = [...a.equipes];
      const novo = idx + dir;
      if (novo < 0 || novo >= eqs.length) return a;
      [eqs[idx], eqs[novo]] = [eqs[novo], eqs[idx]];
      return { ...a, equipes: eqs };
    }));
  }
  function toggleSetor(areaId, idx, setor) {
    setAreas(arr => arr.map(a => {
      if (a.id !== areaId) return a;
      const eqs = a.equipes.map((e, i) => {
        if (i !== idx) return e;
        const setores = e.setores.includes(setor) ? e.setores.filter(s => s !== setor) : [...e.setores, setor];
        return { ...e, setores };
      });
      return { ...a, equipes: eqs };
    }));
  }
  function toggleResponsavelArea(areaId, nome) {
    setAreas(arr => arr.map(a => {
      if (a.id !== areaId) return a;
      const r = a.responsaveisNomes.includes(nome) ? a.responsaveisNomes.filter(n => n !== nome) : [...a.responsaveisNomes, nome];
      return { ...a, responsaveisNomes: r };
    }));
  }
  function toggleResponsavelEquipe(areaId, idx, nome) {
    setAreas(arr => arr.map(a => {
      if (a.id !== areaId) return a;
      const eqs = a.equipes.map((e, i) => {
        if (i !== idx) return e;
        const r = e.responsaveisNomes.includes(nome) ? e.responsaveisNomes.filter(n => n !== nome) : [...e.responsaveisNomes, nome];
        return { ...e, responsaveisNomes: r };
      });
      return { ...a, equipes: eqs };
    }));
  }

  function salvar() {
    salvarAreasOrg(areas);
    onSalvo?.();
    onClose();
  }
  function restaurarPadrao() {
    if (!window.confirm('Restaurar a estrutura padrão das 4 áreas? Suas edições serão perdidas.')) return;
    resetAreasOrg();
    setAreas(JSON.parse(JSON.stringify(AREAS_ORG_DEFAULT)));
    setAreaSel(AREAS_ORG_DEFAULT[0]?.id || null);
  }

  const inp = { width: '100%', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '7px 10px', fontSize: 13, fontFamily: 'var(--font-sans)', outline: 0, boxSizing: 'border-box', background: '#fff' };
  const lbl = { fontSize: 10.5, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--escalab-slate)', marginBottom: 5, display: 'block' };
  const Chip = ({ label, on, cor, onClick }) => (
    <button type="button" onClick={onClick} style={{
      border: on ? `1.5px solid ${cor || 'var(--escalab-brand)'}` : '1px solid var(--escalab-line)',
      background: on ? (cor ? cor + '15' : 'var(--escalab-brand-tint)') : '#fff',
      color: on ? (cor || 'var(--escalab-brand-deep)') : 'var(--escalab-slate)',
      borderRadius: 999, padding: '4px 11px', fontSize: 11.5, fontWeight: on ? 700 : 500,
      cursor: 'pointer', fontFamily: 'var(--font-sans)', whiteSpace: 'nowrap',
    }}>{label}</button>
  );

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,15,18,.6)', backdropFilter: 'blur(4px)', zIndex: 1100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 980, maxHeight: '94vh', overflow: 'hidden', animation: 'popIn .22s var(--ease-out)', display: 'flex', flexDirection: 'column' }}>
        {/* Header */}
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
          <div>
            <div style={{ fontWeight: 800, fontSize: 16 }}>Editar estrutura organizacional</div>
            <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', marginTop: 2 }}>Configure áreas, equipes, responsáveis e os setores que pertencem a cada equipe.</div>
          </div>
          <button onClick={onClose} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-mute)' }}><Icon name="close" size={18} /></button>
        </div>

        {/* Body 2 colunas */}
        <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }} className="estr-body">
          {/* Coluna esquerda: lista de áreas */}
          <div style={{ width: 260, borderRight: '1px solid var(--escalab-line)', background: 'var(--escalab-paper)', display: 'flex', flexDirection: 'column', flexShrink: 0 }} className="estr-side">
            <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--escalab-line)' }}>
              <button onClick={addArea} style={{ width: '100%', border: 0, background: 'var(--escalab-brand)', color: '#fff', borderRadius: 8, padding: '8px 12px', cursor: 'pointer', fontSize: 12.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                <Icon name="plus" size={12} /> Nova área
              </button>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: '8px' }}>
              {areas.map(a => (
                <div key={a.id} onClick={() => setAreaSel(a.id)}
                  style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 11px', borderRadius: 8, cursor: 'pointer', marginBottom: 4,
                    background: areaSel === a.id ? '#fff' : 'transparent', border: areaSel === a.id ? `1px solid ${a.cor}` : '1px solid transparent' }}>
                  <div style={{ width: 12, height: 12, borderRadius: 4, background: a.cor, flexShrink: 0 }} />
                  <div style={{ flex: 1, fontSize: 12.5, fontWeight: areaSel === a.id ? 700 : 500, color: 'var(--escalab-ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.label}</div>
                  <span style={{ fontSize: 10.5, color: 'var(--escalab-mute)', background: 'var(--escalab-line)', borderRadius: 999, padding: '1px 7px' }}>{a.equipes.length}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Coluna direita: editor da área selecionada */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>
            {!areaAtual ? (
              <div style={{ padding: '32px 20px', textAlign: 'center', color: 'var(--escalab-mute)', fontSize: 13 }}>Nenhuma área selecionada. Crie uma nova ou escolha à esquerda.</div>
            ) : (
              <>
                {/* Header da área */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 16 }}>
                  <div style={{ flex: 1 }}>
                    <label style={lbl}>Nome da área</label>
                    <input value={areaAtual.label} onChange={e => patchArea(areaAtual.id, { label: e.target.value })} style={{ ...inp, fontSize: 15, fontWeight: 700 }} />
                  </div>
                  <button onClick={() => rmArea(areaAtual.id)} title="Remover esta área"
                    style={{ border: '1px solid #F4C7C3', background: '#FDECEC', color: '#B3261E', borderRadius: 8, padding: '8px 12px', cursor: 'pointer', fontSize: 12, fontWeight: 700, alignSelf: 'flex-end', display: 'flex', alignItems: 'center', gap: 5 }}>
                    <Icon name="close" size={12} /> Remover área
                  </button>
                </div>

                {/* Cor */}
                <div style={{ marginBottom: 16 }}>
                  <label style={lbl}>Cor da área</label>
                  <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
                    {CORES_AREA.map(c => (
                      <button key={c} type="button" onClick={() => patchArea(areaAtual.id, { cor: c })}
                        style={{ width: 30, height: 30, borderRadius: 8, background: c, border: areaAtual.cor === c ? '3px solid var(--escalab-ink)' : '2px solid var(--escalab-line)', cursor: 'pointer', padding: 0 }} />
                    ))}
                  </div>
                </div>

                {/* Líderes da área */}
                <div style={{ marginBottom: 18 }}>
                  <label style={lbl}>Líderes da área <span style={{ fontWeight: 500, color: 'var(--escalab-mute)', textTransform: 'none', letterSpacing: 0 }}>· clique pra adicionar/remover (selecionado: {areaAtual.responsaveisNomes.length})</span></label>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, padding: '10px', background: 'var(--escalab-paper)', borderRadius: 9, maxHeight: 120, overflowY: 'auto' }}>
                    {lideresDisponiveis.map(c => (
                      <Chip key={c.id} label={c.nome.split(' ').slice(0,2).join(' ')} on={areaAtual.responsaveisNomes.includes(c.nome)} cor={areaAtual.cor} onClick={() => toggleResponsavelArea(areaAtual.id, c.nome)} />
                    ))}
                  </div>
                </div>

                {/* Equipes */}
                <div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <label style={{ ...lbl, marginBottom: 0 }}>Equipes da área ({areaAtual.equipes.length})</label>
                  <button onClick={() => addEquipe(areaAtual.id)}
                    style={{ border: 0, background: areaAtual.cor, color: '#fff', borderRadius: 8, padding: '6px 14px', cursor: 'pointer', fontSize: 12, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 5 }}>
                    <Icon name="plus" size={11} /> Adicionar equipe
                  </button>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {areaAtual.equipes.length === 0 && (
                    <div style={{ padding: '20px', textAlign: 'center', color: 'var(--escalab-mute)', fontSize: 12.5, background: 'var(--escalab-paper)', borderRadius: 9, fontStyle: 'italic' }}>
                      Nenhuma equipe ainda. Clique em "Adicionar equipe" pra começar.
                    </div>
                  )}
                  {areaAtual.equipes.map((eq, idx) => (
                    <div key={idx} style={{ border: '1px solid var(--escalab-line)', borderRadius: 10, padding: '14px 16px', background: '#fff' }}>
                      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 10 }}>
                        <input value={eq.nome} onChange={e => patchEquipe(areaAtual.id, idx, { nome: e.target.value })}
                          placeholder="Nome da equipe" style={{ ...inp, flex: 1, fontWeight: 700 }} />
                        <button onClick={() => moveEquipe(areaAtual.id, idx, -1)} disabled={idx === 0} title="Subir" style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 6, padding: '6px 8px', cursor: idx === 0 ? 'not-allowed' : 'pointer', color: idx === 0 ? '#CCC' : 'var(--escalab-slate)' }}>↑</button>
                        <button onClick={() => moveEquipe(areaAtual.id, idx, +1)} disabled={idx === areaAtual.equipes.length - 1} title="Descer" style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 6, padding: '6px 8px', cursor: idx === areaAtual.equipes.length - 1 ? 'not-allowed' : 'pointer', color: idx === areaAtual.equipes.length - 1 ? '#CCC' : 'var(--escalab-slate)' }}>↓</button>
                        <button onClick={() => rmEquipe(areaAtual.id, idx)} title="Remover equipe"
                          style={{ border: '1px solid #F4C7C3', background: '#FDECEC', color: '#B3261E', borderRadius: 6, padding: '6px 8px', cursor: 'pointer' }}>
                          <Icon name="close" size={12} />
                        </button>
                      </div>

                      {/* Responsáveis do setor */}
                      <div style={{ marginBottom: 10 }}>
                        <label style={lbl}>Responsáveis (gestor do setor) — selecionados: {eq.responsaveisNomes.length}</label>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, padding: '8px', background: 'var(--escalab-paper)', borderRadius: 8, maxHeight: 100, overflowY: 'auto' }}>
                          {lideresDisponiveis.map(c => (
                            <Chip key={c.id} label={c.nome.split(' ').slice(0,2).join(' ')} on={eq.responsaveisNomes.includes(c.nome)} cor={areaAtual.cor} onClick={() => toggleResponsavelEquipe(areaAtual.id, idx, c.nome)} />
                          ))}
                        </div>
                      </div>

                      {/* Setores que pertencem à equipe */}
                      <div>
                        <label style={lbl}>Setores que pertencem a esta equipe — selecionados: {eq.setores.length}</label>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, padding: '8px', background: 'var(--escalab-paper)', borderRadius: 8, maxHeight: 100, overflowY: 'auto' }}>
                          {setoresDisponiveis.map(s => (
                            <Chip key={s} label={s} on={eq.setores.includes(s)} cor={areaAtual.cor} onClick={() => toggleSetor(areaAtual.id, idx, s)} />
                          ))}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', gap: 10, background: 'var(--escalab-paper)', flexShrink: 0 }}>
          <button onClick={restaurarPadrao} style={{ border: '1px solid var(--escalab-line)', background: '#fff', borderRadius: 9, padding: '8px 14px', cursor: 'pointer', fontSize: 12.5, color: 'var(--escalab-slate)' }}>
            Restaurar padrão
          </button>
          <div style={{ display: 'flex', gap: 10 }}>
            <Button variant="outline" onClick={onClose}>Cancelar</Button>
            <Button variant="primary" onClick={salvar}>Salvar estrutura</Button>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 720px) {
          .estr-body { flex-direction: column !important; }
          .estr-side { width: 100% !important; max-height: 160px; }
        }
      `}</style>
    </div>
  );
};

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

const ScreenOrganograma = ({ user, onRefresh }) => {
  const [aba, setAba] = useState('area');
  const [busca, setBusca] = useState('');
  const [selecionado, setSelecionado] = useState(null);
  const [editando, setEditando] = useState(null);
  const [editandoEstrutura, setEditandoEstrutura] = useState(false);
  const [versaoEstrutura, setVersaoEstrutura] = useState(0);
  const isAdmin = user?.perfil === 'admin';

  const setoresUnicos = [...new Set(COLABORADORES.map(c => c.setor))].sort();
  const porSetor = setoresUnicos.map(s => ({
    setor: s,
    membros: COLABORADORES.filter(c => c.setor === s),
  })).filter(g => g.membros.length > 0);

  const totalColab     = COLABORADORES.length;
  const totalDiretores = COLABORADORES.filter(c => c.nivel === 'diretor').length;
  const totalLideres   = COLABORADORES.filter(c => c.nivel === 'lider').length;

  const catCounts = {};
  COLABORADORES.forEach(c => {
    const key = getCategoriaKey(c.id);
    catCounts[key] = (catCounts[key] || 0) + 1;
  });

  const tabs = [
    { id: 'area',  label: 'Por Área',  icon: 'org'   },
    { id: 'setor', label: 'Por Setor', icon: 'users' },
  ];

  function handleSalvar(id, updates) {
    atualizarColaborador(id, updates);
    // Atualiza pessoa selecionada em memória
    setSelecionado(prev => prev && prev.id === id ? { ...prev, ...updates } : prev);
    onRefresh?.();
  }

  return (
    <div style={{ animation: 'fadeIn .22s var(--ease-out)' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-brand)', marginBottom: 4 }}>Gestão de Pessoas</div>
          <h2 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>Organograma</h2>
          <p style={{ fontSize: 13, color: 'var(--escalab-slate)', margin: '4px 0 0' }}>
            {isAdmin ? 'Clique em qualquer pessoa para editar · use "Editar estrutura" pra mexer em áreas e equipes.' : 'Clique em qualquer pessoa para ver o perfil completo.'}
          </p>
        </div>
        {isAdmin && aba === 'area' && (
          <button onClick={() => setEditandoEstrutura(true)}
            style={{ border: '1px solid var(--escalab-brand)', background: 'var(--escalab-brand-tint)', color: 'var(--escalab-brand-deep)', borderRadius: 9, padding: '9px 16px', cursor: 'pointer', fontSize: 13, fontWeight: 700, fontFamily: 'var(--font-sans)', display: 'flex', alignItems: 'center', gap: 7 }}>
            <Icon name="settings" size={13} /> Editar estrutura
          </button>
        )}
      </div>

      {/* KPIs */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
        {[
          { label: 'Total',     val: totalColab,                              cor: 'var(--escalab-brand-deep)', bg: 'var(--escalab-brand-tint)' },
          { label: 'Diretores', val: totalDiretores,                          cor: '#1F4A8A', bg: '#EEF3FA' },
          { label: 'Líderes',   val: totalLideres,                            cor: '#00836B', bg: '#E6F5F1' },
          { label: 'Colabs.',   val: totalColab - totalDiretores - totalLideres, cor: '#4A5560', bg: 'var(--escalab-paper)' },
        ].map(k => (
          <div key={k.label} style={{ background: k.bg, border: '1px solid var(--escalab-line)', borderRadius: 10, padding: '10px 18px', display: 'flex', gap: 10, alignItems: 'center' }}>
            <span style={{ fontSize: 20, fontWeight: 800, color: k.cor }}>{k.val}</span>
            <span style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>{k.label}</span>
          </div>
        ))}
      </div>

      {/* Busca (só no setor) */}
      {aba === 'setor' && (
        <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
          <div style={{ flex: 1, maxWidth: 360, display: 'flex', alignItems: 'center', gap: 8, background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 8, padding: '0 12px' }}>
            <div style={{ color: 'var(--escalab-mute)' }}><Icon name="search" size={14} /></div>
            <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar nome, cargo ou setor…"
              style={{ border: 0, outline: 0, flex: 1, padding: '9px 0', fontSize: 13.5, fontFamily: 'var(--font-sans)', background: 'transparent' }} />
            {busca && <button onClick={() => setBusca('')} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--escalab-mute)', padding: 0 }}><Icon name="close" size={13} /></button>}
          </div>
        </div>
      )}

      <Tabs tabs={tabs} active={aba} onChange={v => { setAba(v); setBusca(''); }} />
      <div style={{ paddingTop: 16 }}>

        {/* ── POR ÁREA ── */}
        {aba === 'area' && <AreaView onSelecionar={setSelecionado} versao={versaoEstrutura} isAdmin={isAdmin} />}

        {/* ── POR SETOR ── */}
        {aba === 'setor' && (
          <div style={{ animation: 'fadeIn .2s', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {porSetor
              .filter(g => !busca || g.setor.toLowerCase().includes(busca.toLowerCase()) || g.membros.some(m => m.nome.toLowerCase().includes(busca.toLowerCase())))
              .map(g => (
              <div key={g.setor} style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 14, overflow: 'hidden' }}>
                <div style={{ padding: '12px 18px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--escalab-paper)' }}>
                  <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--escalab-brand)', flexShrink: 0 }} />
                  <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--escalab-ink)' }}>{g.setor}</span>
                  <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--escalab-mute)', background: 'var(--escalab-line)', borderRadius: 999, padding: '1px 8px' }}>{g.membros.length}</span>
                </div>
                <div>
                  {g.membros.map((m, i) => (
                    <SetorMemberRow key={m.id} m={m} isLast={i === g.membros.length - 1} onSelecionar={setSelecionado} user={user} />
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}

      </div>

      {/* Legenda */}
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center', borderTop: '1px solid var(--escalab-line)', paddingTop: 14, marginTop: 20 }}>
        <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--escalab-mute)' }}>Legenda:</span>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--escalab-slate)' }}>
          <span style={{ background: COR_LIDER_AREA_BG, border: `1.5px solid ${COR_LIDER_AREA}`, borderRadius: 999, padding: '2px 9px', fontSize: 10, fontWeight: 800, color: COR_LIDER_AREA, textTransform: 'uppercase', letterSpacing: '.06em' }}>
            Líder de Área
          </span>
        </div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--escalab-slate)' }}>
          <span style={{ background: '#fff', border: `1.5px solid ${COR_GESTOR_SETOR}`, borderRadius: 999, padding: '2px 9px', fontSize: 10, fontWeight: 800, color: COR_GESTOR_SETOR, textTransform: 'uppercase', letterSpacing: '.06em' }}>
            Gestor do Setor
          </span>
        </div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--escalab-slate)' }}>
          <span style={{ background: '#fff', border: '1px solid var(--escalab-line)', borderRadius: 999, padding: '2px 9px', fontSize: 10.5, fontWeight: 600, color: 'var(--escalab-ink)' }}>Membro</span>
        </div>
      </div>

      {selecionado && (
        <ModalPessoa
          pessoa={selecionado}
          onClose={() => setSelecionado(null)}
          user={user}
          onEditar={p => { setSelecionado(null); setEditando(p); }}
        />
      )}
      {editando && (
        <ModalEditarColab
          pessoa={editando}
          onClose={() => setEditando(null)}
          onSalvar={handleSalvar}
          user={user}
        />
      )}
      {editandoEstrutura && (
        <ModalEditarEstrutura
          onClose={() => setEditandoEstrutura(false)}
          onSalvo={() => { setVersaoEstrutura(v => v + 1); onRefresh?.(); }}
        />
      )}
    </div>
  );
};

window.ScreenOrganograma = ScreenOrganograma;
