/* screen_admin_users_detail.jsx — drawer 720px de edição.
   7 tabs: Identidade · Empresas · Permissões · Acesso Portal · Apollo · Conversas Digi · Audit log.
   Sticky header, prev/next entre filtrados, auto-save mock (state local).
*/
const AdminUserDrawer = ({ user: initial, currentUserTipo, onClose, onPrev, onNext }) => {
  const D  = window.AdminUsersData;
  const UI = window.AdminUsers;
  const [user, setUser]       = React.useState(initial);
  const [tab, setTab]         = React.useState('identidade');
  const [permExpanded, setPermExpanded] = React.useState(false);
  const [savedAt, setSavedAt] = React.useState(null);
  const dirtyRef = React.useRef(false);

  React.useEffect(() => { setUser(initial); setTab('identidade'); setSavedAt(null); }, [initial?.id]);

  // ESC fecha · ←/→ navegam
  React.useEffect(() => {
    const h = (e) => {
      if (e.key === 'Escape') { onClose(); return; }
      if (e.target.matches('input, textarea, select')) return;
      if (e.key === 'ArrowLeft' && onPrev) onPrev();
      if (e.key === 'ArrowRight' && onNext) onNext();
    };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose, onPrev, onNext]);

  // Auto-save mock — qualquer mudança em `user` marca "Guardado há Xs"
  const update = (patch) => {
    setUser(prev => ({ ...prev, ...patch }));
    dirtyRef.current = true;
    clearTimeout(update._t);
    update._t = setTimeout(() => {
      setSavedAt(new Date());
      dirtyRef.current = false;
    }, 600);
  };

  const tabs = [
    { id: 'identidade',  label: 'Identidade',     icon: 'user' },
    { id: 'empresas',    label: 'Empresas',       icon: 'building' },
    { id: 'permissoes',  label: 'Permissões',     icon: 'layers' },
    { id: 'portal',      label: 'Acesso Portal',  icon: 'link' },
    { id: 'apollo',      label: 'Apollo',         icon: 'sparkle' },
    { id: 'conversas',   label: 'Conversas Digi', icon: 'chat' },
    { id: 'audit',       label: 'Audit log',      icon: 'history' },
  ];

  const auditLog = D.auditLogFor(user);
  const sessions = D.sessionsFor(user);
  const conversas = D.conversasMensal(user);
  const def = D.TIPOS_DEFAULTS[user.tipo_utilizador];
  const cur = user.permissoes || def;
  const hasOverride = JSON.stringify({...cur, modos: undefined}) !== JSON.stringify({...def, modos: undefined});

  // Indicadores de tab (badges)
  const indicator = {
    permissoes: hasOverride ? '!' : null,
    portal:     user.portal_activo ? '●' : '○',
    apollo:     user.apollo_enriched ? '✓' : '∅',
    audit:      auditLog.length > 0 ? auditLog.length : null,
  };

  return (
    <>
      {/* Overlay */}
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 1300,
        background: 'rgba(0,0,0,0.42)',
        backdropFilter: 'blur(2px)',
        animation: 'fadeIn 160ms ease-out',
      }} />

      {/* Drawer */}
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 1301,
        width: 720, maxWidth: '96vw',
        background: 'var(--bg)',
        borderLeft: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-12px 0 40px rgba(0,0,0,0.18)',
        animation: 'slideInRight 220ms cubic-bezier(0.4, 0, 0.2, 1)',
        fontFamily: 'var(--font-sans)',
      }}>

        {/* ═══ STICKY HEADER ═══ */}
        <header style={{
          padding: '16px 24px',
          borderBottom: '1px solid var(--border)',
          background: 'var(--bg-elev)',
          flexShrink: 0,
        }}>
          {/* top row: avatar + name + actions + close */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <UI.Avatar user={user} size={48} />

            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                <h2 className="font-display" style={{
                  margin: 0, fontSize: 18, fontWeight: 600,
                  letterSpacing: '-0.01em', color: 'var(--text)',
                }}>{user.nome_apresentar}</h2>
                <UI.TipoBadge tipo={user.tipo_utilizador} />
                <UI.PortalBadge activo={user.portal_activo} />
                <UI.ApolloBadge enriched={user.apollo_enriched} />
              </div>
              <div style={{
                fontSize: 11.5, color: 'var(--text-dim)',
                fontFamily: 'var(--font-mono)', marginTop: 3,
              }}>
                <span>{user.email_profissional}</span>
                {user.telemovel && <><span style={{ margin: '0 8px', opacity: 0.4 }}>·</span><span>{user.telemovel}</span></>}
              </div>
            </div>

            {/* prev/next */}
            <div style={{ display: 'flex', gap: 4 }}>
              <button onClick={onPrev} className="btn btn-sm btn-ghost" title="Anterior (←)">
                <Icon name="arrowUp" size={12} style={{ transform: 'rotate(-90deg)' }} />
              </button>
              <button onClick={onNext} className="btn btn-sm btn-ghost" title="Seguinte (→)">
                <Icon name="arrowUp" size={12} style={{ transform: 'rotate(90deg)' }} />
              </button>
            </div>
            <button onClick={onClose} className="btn btn-sm btn-ghost" title="Fechar (Esc)">
              <Icon name="close" size={14} />
            </button>
          </div>

          {/* meta strip */}
          <div style={{
            display: 'flex', gap: 16, marginTop: 12,
            fontSize: 11, fontFamily: 'var(--font-mono)',
            color: 'var(--text-muted)', flexWrap: 'wrap',
          }}>
            <span>ID: <strong style={{ color: 'var(--text)' }}>{user.id}</strong></span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span>Empresas: <UI.EmpresaTags user={user} /></span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span>Modo: <ModoDigiInline modo={user.modo_digi} /></span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span>Última: <UI.RelativeTime iso={user.ultima_interacao_digi} /></span>
            {savedAt && (
              <span style={{ marginLeft: 'auto', color: 'var(--ok)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <Icon name="check" size={11} />
                Guardado {fmtSavedAt(savedAt)}
              </span>
            )}
          </div>

          {/* tabs */}
          <nav style={{
            display: 'flex', gap: 2, marginTop: 14, marginBottom: -1,
            borderBottom: '1px solid transparent',
            overflowX: 'auto',
          }} className="scrollbar">
            {tabs.map(t => {
              const active = t.id === tab;
              return (
                <button key={t.id} onClick={() => setTab(t.id)} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '8px 12px',
                  border: 'none', background: 'transparent',
                  borderBottom: `2px solid ${active ? 'var(--ai-500)' : 'transparent'}`,
                  color: active ? 'var(--text)' : 'var(--text-muted)',
                  fontSize: 12, fontWeight: active ? 600 : 500,
                  cursor: 'pointer', whiteSpace: 'nowrap',
                  transition: 'color 100ms, border-color 100ms',
                  fontFamily: 'var(--font-sans)',
                }}>
                  <Icon name={t.icon} size={12} />
                  {t.label}
                  {indicator[t.id] && (
                    <span style={{
                      fontSize: 9, padding: '0 4px', borderRadius: 99,
                      minWidth: 14, textAlign: 'center',
                      background: t.id === 'permissoes' && indicator[t.id] === '!'
                        ? 'color-mix(in oklch, var(--warn) 20%, transparent)'
                        : 'var(--bg-sunken)',
                      color: t.id === 'permissoes' && indicator[t.id] === '!'
                        ? 'var(--warn)' : 'var(--text-muted)',
                      fontFamily: 'var(--font-mono)', fontWeight: 600,
                    }}>{indicator[t.id]}</span>
                  )}
                </button>
              );
            })}
          </nav>
        </header>

        {/* ═══ BODY (scrollable) ═══ */}
        <div className="scrollbar" style={{
          flex: 1, overflowY: 'auto',
          padding: '20px 24px',
        }}>
          {tab === 'identidade' && <IdentidadeTab user={user} update={update} />}
          {tab === 'empresas'   && <EmpresasTab user={user} update={update} currentUserTipo={currentUserTipo} />}
          {tab === 'permissoes' && <PermissoesTab user={user} update={update} expanded={permExpanded} setExpanded={setPermExpanded} />}
          {tab === 'portal'     && <PortalTab user={user} update={update} sessions={sessions} />}
          {tab === 'apollo'     && <ApolloTab user={user} update={update} />}
          {tab === 'conversas'  && <ConversasTab user={user} conversas={conversas} />}
          {tab === 'audit'      && <AuditTab auditLog={auditLog} />}
        </div>

        {/* ═══ STICKY FOOTER ═══ */}
        <footer style={{
          padding: '12px 24px',
          borderTop: '1px solid var(--border)',
          background: 'var(--bg-elev)',
          display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0,
        }}>
          <button className="btn btn-sm btn-ghost" style={{ color: 'var(--err)' }}>
            <Icon name="warning" size={12} />Suspender utilizador
          </button>
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
            Auto-save activo · alterações registadas em <code style={{ background: 'var(--bg-sunken)', padding: '1px 4px', borderRadius: 3 }}>colaboradores_audit</code>
          </span>
          <button onClick={onClose} className="btn btn-sm">Fechar</button>
        </footer>
      </aside>
    </>
  );
};

// ════════════════════════════════════════════════════════════════
// TAB 1 · IDENTIDADE
// ════════════════════════════════════════════════════════════════
const IdentidadeTab = ({ user, update }) => {
  const D  = window.AdminUsersData;
  const UI = window.AdminUsers;
  return (
    <div>
      <UI.SectionHeader title="Nome" subtitle="Sync Microsoft Graph · readonly" />
      <UI.FieldRow label="Nome completo"       value={user.nome_completo}    source="MS Graph" editable={false} />
      <UI.FieldRow label="Nome próprio"        value={user.nome_proprio}     source="MS Graph" editable={false} />
      <UI.FieldRow label="Apelido"             value={user.apelido}          source="MS Graph" editable={false} />
      <UI.FieldRow label="Nome a apresentar"   value={user.nome_apresentar}  onChange={v => update({ nome_apresentar: v })} />

      <div style={{ height: 24 }} />
      <UI.SectionHeader title="Contactos" />
      <UI.FieldRow label="Email profissional"  value={user.email_profissional} source="MS Graph" editable={false} />
      <UI.FieldRow label="Telemóvel"           value={user.telemovel}          onChange={v => update({ telemovel: v })} />
      <UI.FieldRow label="LinkedIn URL"        value={user.linkedin_url}       onChange={v => update({ linkedin_url: v })} />

      <div style={{ height: 24 }} />
      <UI.SectionHeader title="Localização" />
      <UI.FieldRow label="País"                value={user.pais}               type="select" options={D.PAISES} onChange={v => update({ pais: v })} />
      <UI.FieldRow label="Localidade"          value={user.localidade}         onChange={v => update({ localidade: v })} />
      <UI.FieldRow label="Distrito"            value={user.distrito}           onChange={v => update({ distrito: v })} />
      <UI.FieldRow label="Código postal"       value={user.codigo_postal}      onChange={v => update({ codigo_postal: v })} />
      <UI.FieldRow label="Office"              value={user.office}             type="select" options={D.OFFICES} onChange={v => update({ office: v })} />

      <div style={{ height: 24 }} />
      <UI.SectionHeader title="Perfil profissional" />
      <UI.FieldRow label="Cargo (genérico)"    value={user.perfil_cargo}       onChange={v => update({ perfil_cargo: v })} />
      <UI.FieldRow label="Função"              value={user.funcao}             onChange={v => update({ funcao: v })} />
      <UI.FieldRow label="Tipo utilizador"     value={user.tipo_utilizador}    type="select"
        options={D.TIPOS.map(t => ({ id: t.id, label: t.label }))}
        onChange={v => update({ tipo_utilizador: v })} />
      <UI.FieldRow label="Seniority"           value={user.seniority}          type="select" options={D.SENIORITIES} onChange={v => update({ seniority: v })} />
      <UI.FieldRow label="Nível técnico"       value={user.nivel_tecnico}      type="select" options={['básico','médio','avançado','expert']} onChange={v => update({ nivel_tecnico: v })} />

      <div style={{ height: 24 }} />
      <UI.SectionHeader title="Preferências Digi" />
      <UI.FieldRow label="Modo Digi default"   value={user.modo_digi}          type="select" options={D.MODOS_DIGI.map(m => ({ id: m.id, label: m.label }))} onChange={v => update({ modo_digi: v })} />
      <UI.FieldRow label="Idioma preferido"    value={user.idioma_preferido}   type="select" options={D.IDIOMAS} onChange={v => update({ idioma_preferido: v })} />
      <UI.FieldRow label="Tom preferido"       value={user.tom_preferido}      onChange={v => update({ tom_preferido: v })} />

      <div style={{ height: 24 }} />
      <UI.SectionHeader title="Notas (free-text)" />
      <UI.FieldRow label="Áreas de expertise"  value={user.areas_expertise}    multiline onChange={v => update({ areas_expertise: v })} />
      <UI.FieldRow label="Resumo de perfil"    value={user.perfil_resumo}      multiline onChange={v => update({ perfil_resumo: v })} />
      <UI.FieldRow label="Personalidade"       value={user.personalidade_notas} multiline onChange={v => update({ personalidade_notas: v })} />
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// TAB 2 · EMPRESAS
// ════════════════════════════════════════════════════════════════
const EmpresasTab = ({ user, update, currentUserTipo }) => {
  const UI = window.AdminUsers;
  return (
    <div>
      <UI.SectionHeader
        title="Vínculos a empresas"
        subtitle={`Junction colaborador_empresa · ${user.empresas.length} ${user.empresas.length === 1 ? 'vínculo' : 'vínculos'}`}
      />
      <UI.EmpresaJunctionTable
        user={user}
        currentUserTipo={currentUserTipo}
        onChange={(empresas) => update({ empresas })}
      />

      <div style={{
        marginTop: 18, padding: '12px 14px',
        background: 'color-mix(in oklch, var(--ai-500) 5%, transparent)',
        border: '1px solid color-mix(in oklch, var(--ai-500) 18%, transparent)',
        borderRadius: 8, fontSize: 12, color: 'var(--text-muted)',
        display: 'flex', alignItems: 'flex-start', gap: 10,
      }}>
        <Icon name="sparkle" size={14} style={{ color: 'var(--ai-500)', marginTop: 1 }} />
        <div style={{ lineHeight: 1.55 }}>
          <strong style={{ color: 'var(--text)' }}>Multi-empresa.</strong> Um colaborador pode pertencer a múltiplas empresas do Grupo Farben Consulting.
          A empresa <em>primária</em> é a que aparece no header. As outras dão acesso aos respectivos dados (clientes, leads, etc.) via permissões.
        </div>
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// TAB 3 · PERMISSÕES
// ════════════════════════════════════════════════════════════════
const PermissoesTab = ({ user, update, expanded, setExpanded }) => {
  const D  = window.AdminUsersData;
  const UI = window.AdminUsers;
  const def = D.TIPOS_DEFAULTS[user.tipo_utilizador] || { dados: [], marcas: [], skills: [], features: [], modos: [] };
  const cur = user.permissoes || def;

  return (
    <div>
      <div style={{
        padding: '12px 14px', marginBottom: 16,
        background: 'var(--bg-sunken)', border: '1px solid var(--border)',
        borderRadius: 8, display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <UI.TipoBadge tipo={user.tipo_utilizador} />
        <div style={{ flex: 1, fontSize: 12, color: 'var(--text-muted)' }}>
          As permissões deste utilizador herdam dos defaults do tipo{' '}
          <strong style={{ color: 'var(--text)' }}>{D.getTipo(user.tipo_utilizador)?.label}</strong>.
          Podes adicionar overrides pontuais — ficam marcados na lista.
        </div>
      </div>

      <UI.SectionHeader title="Permissões — RBAC" subtitle="Dados · Marcas · Skills · Features" />
      <UI.PermissoesEditor
        user={{ ...user, permissoes: cur }}
        onChange={(permissoes) => update({ permissoes })}
        expanded={expanded}
        setExpanded={setExpanded}
      />

      <div style={{ height: 22 }} />
      <UI.SectionHeader title="Modos de Acesso Digi" subtitle="Em que vistas o utilizador pode entrar" />
      <UI.ModosAcessoEditor
        value={cur.modos || def.modos}
        onChange={(modos) => update({ permissoes: { ...cur, modos } })}
      />

      <div style={{ height: 22 }} />
      <UI.SectionHeader title="Verificação efectiva" />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <PermCheck label="Pode editar OPs"       passed={cur.features?.includes('crm_write')} />
        <PermCheck label="Pode prospectar"        passed={cur.features?.includes('prospecting')} />
        <PermCheck label="Pode ver financeiro"    passed={cur.dados?.includes('financeiro')} />
        <PermCheck label="Acesso painel admin"    passed={cur.features?.includes('admin_panel')} />
        <PermCheck label="Pode gerir users"       passed={cur.features?.includes('user_management')} />
        <PermCheck label="Acesso Apollo"          passed={cur.skills?.includes('apollo')} />
      </div>
    </div>
  );
};
const PermCheck = ({ label, passed }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 8,
    padding: '8px 10px', borderRadius: 6,
    background: passed ? 'color-mix(in oklch, var(--ok) 8%, transparent)' : 'var(--bg-sunken)',
    border: `1px solid ${passed ? 'color-mix(in oklch, var(--ok) 25%, transparent)' : 'var(--border)'}`,
    fontSize: 12,
  }}>
    <span style={{
      width: 16, height: 16, borderRadius: 4,
      display: 'grid', placeItems: 'center', flexShrink: 0,
      background: passed ? 'var(--ok)' : 'transparent',
      border: passed ? '0' : '1.5px solid var(--text-dim)',
      color: '#fff', fontFamily: 'var(--font-mono)', fontSize: 10,
    }}>{passed ? '✓' : ''}</span>
    <span style={{ color: passed ? 'var(--text)' : 'var(--text-dim)' }}>{label}</span>
  </div>
);

// ════════════════════════════════════════════════════════════════
// TAB 4 · PORTAL
// ════════════════════════════════════════════════════════════════
const PortalTab = ({ user, update, sessions }) => {
  const UI = window.AdminUsers;
  return (
    <div>
      <UI.SectionHeader title="Acesso ao Portal Digi" subtitle="Username · password · SSO Microsoft 365" />
      <UI.PortalAccessCard user={user} onChange={(patch) => update(patch)} />

      <div style={{ height: 24 }} />
      <UI.SectionHeader title="Sessões recentes" subtitle="Últimas 5 sessões registadas" />
      <UI.SessionsList sessions={sessions} />
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// TAB 5 · APOLLO
// ════════════════════════════════════════════════════════════════
const ApolloTab = ({ user, update }) => {
  const UI = window.AdminUsers;
  if (!user.apollo_enriched) {
    return (
      <div>
        <UI.SectionHeader title="Apollo · enriquecimento" />
        <div style={{
          padding: 32, textAlign: 'center',
          border: '1px dashed var(--border)', borderRadius: 8,
          color: 'var(--text-muted)',
        }}>
          <Icon name="sparkle" size={28} style={{ color: 'var(--text-dim)', marginBottom: 10 }} />
          <div style={{ fontSize: 13, marginBottom: 4 }}>Utilizador <strong>não enriquecido</strong></div>
          <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginBottom: 16 }}>
            O enriquecimento via Apollo.io adiciona dados de LinkedIn, perfil profissional e empresa anterior.
          </div>
          <button className="btn btn-sm" onClick={() => update({ apollo_enriched: true })}>
            <Icon name="sparkle" size={12} />Enriquecer agora
          </button>
        </div>
      </div>
    );
  }
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <UI.SectionHeader title="Apollo · enriquecimento" />
      </div>
      <UI.FieldRow label="Status"               value="Enriched" source="Apollo.io" editable={false} badge={<UI.ApolloBadge enriched={true} />} />
      <UI.FieldRow label="LinkedIn URL"         value={user.linkedin_url} source="Apollo" editable={false} />
      <UI.FieldRow label="Áreas de expertise"   value={user.areas_expertise} source="Apollo" multiline editable={false} />
      <UI.FieldRow label="Personalidade (notas)" value={user.personalidade_notas} source="Apollo" multiline editable={false} />
      <UI.FieldRow label="Resumo perfil"        value={user.perfil_resumo} source="Apollo" multiline editable={false} />
      <UI.FieldRow label="Last enrichment"      value="14 Mar 2026" source="Apollo" editable={false} />

      <div style={{
        marginTop: 18, padding: '10px 14px',
        background: 'var(--bg-sunken)', border: '1px solid var(--border)',
        borderRadius: 6, fontSize: 11.5, color: 'var(--text-muted)',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <Icon name="circle" size={11} style={{ color: 'var(--text-dim)' }} />
        Os campos sync via Apollo são read-only nesta vista. Para editar, faz override em Identidade.
        <button className="btn btn-sm btn-ghost" style={{ marginLeft: 'auto' }}>
          <Icon name="refresh" size={11} />Re-enriquecer
        </button>
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// TAB 6 · CONVERSAS
// ════════════════════════════════════════════════════════════════
const ConversasTab = ({ user, conversas }) => {
  const UI = window.AdminUsers;
  if (!user.portal_activo) {
    return (
      <div>
        <UI.SectionHeader title="Conversas Digi · mensal" />
        <div style={{
          padding: 32, textAlign: 'center',
          border: '1px dashed var(--border)', borderRadius: 8,
          color: 'var(--text-muted)',
        }}>
          <Icon name="chat" size={28} style={{ color: 'var(--text-dim)', marginBottom: 10 }} />
          <div style={{ fontSize: 13 }}>Portal inactivo</div>
          <div style={{ fontSize: 11.5, color: 'var(--text-dim)', marginTop: 4 }}>
            Sem conversas porque o utilizador não tem acesso ao portal.
          </div>
        </div>
      </div>
    );
  }
  const total = conversas.reduce((s, c) => s + c.count, 0);
  return (
    <div>
      <UI.SectionHeader title="Conversas Digi · mensal" subtitle={`${total} interacções nos últimos 4 meses`} />
      <UI.ConversasList conversas={conversas} />
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// TAB 7 · AUDIT
// ════════════════════════════════════════════════════════════════
const AuditTab = ({ auditLog }) => {
  const UI = window.AdminUsers;
  return (
    <div>
      <UI.SectionHeader
        title="Audit log"
        subtitle="Registo de alterações · tabela colaboradores_audit"
      />
      <UI.AuditLogList entries={auditLog} />
      <div style={{
        marginTop: 12, padding: '8px 12px',
        fontSize: 10.5, color: 'var(--text-dim)',
        fontFamily: 'var(--font-mono)',
        textAlign: 'center',
      }}>
        Cada alteração regista: campo, valor antigo, valor novo, autor, timestamp.
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════════
// HELPERS
// ════════════════════════════════════════════════════════════════
const ModoDigiInline = ({ modo }) => {
  const D = window.AdminUsersData;
  const m = D?.MODOS_DIGI?.find(x => x.id === modo);
  if (!m) return <span>—</span>;
  return <strong style={{ color: m.color, fontFamily: 'var(--font-mono)' }}>{m.label.toLowerCase()}</strong>;
};
const fmtSavedAt = (d) => {
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 5) return 'agora mesmo';
  if (diff < 60) return `há ${Math.floor(diff)}s`;
  return `às ${d.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' })}`;
};

// Inject keyframes once
if (typeof document !== 'undefined' && !document.getElementById('au-drawer-keyframes')) {
  const s = document.createElement('style');
  s.id = 'au-drawer-keyframes';
  s.textContent = `
    @keyframes slideInRight { from { transform: translateX(20px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
    @keyframes fadeIn       { from { opacity: 0; } to { opacity: 1; } }
  `;
  document.head.appendChild(s);
}

window.AdminUserDrawer = AdminUserDrawer;
