/* Shared shell: Sidebar, Topbar, Digi AI chat drawer, Command palette (⌘K) */

// Sub-navegação por departamento. Se existir, o item expande (accordion).
// DEV (build · modificar) — construir e alterar a plataforma
const DEV_SUBNAV = [
  { id: 'inicio', label: 'Início', kbd: '1' },
  { id: 'architecture', label: 'Architecture', kbd: '2' },
  { id: 'prompts', label: 'Prompts', kbd: '3' },
  { id: 'kb', label: 'Knowledge Base', badge: 21, kbd: '4' },
  { id: 'agents', label: 'Sub-agentes', badge: 7, kbd: '5' },
  { id: 'skills', label: 'Skills', badge: '7+21', kbd: '6' },
  { id: 'tools', label: 'Tools', badge: '3+2', kbd: '7' },
  { id: 'routing', label: 'Routing', kbd: '8' },
  { id: 'conversations', label: 'Replay', kbd: '9' },
  { id: 'costs', label: 'Costs', kbd: 'C' },
  { id: 'deploy', label: 'Deploy', kbd: 'D' },
  { id: 'integracoes', label: 'Integrações', badge: 16, kbd: 'I' },
  { id: 'roadmap', label: 'Roadmap', badge: 'P1', kbd: 'R' },
];

// ADMIN (governance · gestão) — modo privilegiado, gating por lista nominal
const ADMIN_SUBNAV = [
  { id: 'inicio', label: 'Início', kbd: '1' },
  { id: 'utilizadores', label: 'Utilizadores', badge: 193, kbd: '2' },
  { id: 'empresas', label: 'Empresas', badge: 10, kbd: '3' },
  { id: 'audit', label: 'Audit log', kbd: '4' },
  { id: 'integracoes', label: 'Integrações', badge: 3, kbd: '5' },
];

// SISTEMA (run · observar) — operar e monitorizar
const SISTEMA_SUBNAV = [
  { id: 'inbox', label: 'Inbox · Live', badge: '6 prod', kbd: '1' },
  { id: 'overview', label: 'Overview', kbd: '2' },
  { id: 'kpis', label: 'KPIs', badge: 'NEW', kbd: '3' },
  { id: 'costs', label: 'Costs', kbd: '4' },
  { id: 'integrations', label: 'Integrations', kbd: '5' },
  { id: 'alerts', label: 'Alerts', badge: 2, kbd: 'A' },
];

const MARKETING_SUBNAV = [
  { id: 'performance', label: 'Performance 2025', kbd: '1' },
  { id: 'plano', label: 'Plano Comunicação 2026', badge: 109, kbd: '2' },
  { id: 'estrategia', label: 'Estratégia', kbd: '3' },
  { id: 'agentes', label: 'Sub-agentes', badge: 6, kbd: '4' },
];

const FINANCE_SUBNAV = [
  { id: 'cobrancas',     label: 'Cobranças',      badge: 9,   kbd: '1' },
  { id: 'tesouraria',    label: 'Tesouraria',     muted: true, kbd: '2' },
  { id: 'contabilidade', label: 'Contabilidade',  muted: true, kbd: '3' },
  { id: 'controlling',   label: 'Controlling',    muted: true, kbd: '4' },
];

const COMERCIAL_SUBNAV = [
  { id: 'dashboard', label: 'Dashboard', kbd: '1' },
  { id: 'digi', label: 'Chat', kbd: '2', ai: true },
  { id: 'clientes', label: 'Clientes', kbd: '3' },
  { id: 'carteira', label: 'Carteira', kbd: '4' },
  { id: 'prospeccao', label: 'Prospecção', kbd: '5' },
  { id: 'simulador', label: 'Simulador', kbd: '6' },
  { id: 'bp', label: 'Business Plan', kbd: '7' },
];

const NAV = [
  { section: 'Plataforma' },
  { id: 'dev', label: 'DEV', subtitle: 'build · modificar', icon: 'dev', iconColor: 'var(--ai-500)', target: 'dev', subKey: 'dev', sub: DEV_SUBNAV, subStorage: 'digi-dev-sub', subDefault: 'inicio' },
  { id: 'sistema', label: 'SISTEMA', subtitle: 'run · observar', icon: 'pulse', iconColor: 'var(--warning, #f59e0b)', target: 'sistema', subKey: 'sistema', sub: SISTEMA_SUBNAV, subStorage: 'digi-sistema-sub', subDefault: 'kpis' },
  { section: 'Gestão' },
  { id: 'board', label: 'Board', icon: 'board' },
  { section: 'Departamentos' },
  { id: 'comercial', label: 'Comercial', icon: 'sales', target: 'comercial', badge: 3, subKey: 'comercial', sub: COMERCIAL_SUBNAV, subStorage: 'digi-comercial-sub', subDefault: 'dashboard' },
  { id: 'sat', label: 'SAT', icon: 'sat', target: 'sat', badge: 1 },
  { id: 'operacoes', label: 'Operações', icon: 'ops' },
  { id: 'marketing', label: 'Marketing', icon: 'marketing', target: 'marketing', subKey: 'marketing', sub: MARKETING_SUBNAV, subStorage: 'digi-marketing-sub', subDefault: 'plano' },
  { id: 'financeiro', label: 'Financeiro', icon: 'finance', target: 'financeiro', badge: 9, subKey: 'financeiro', sub: FINANCE_SUBNAV, subStorage: 'digi-financeiro-sub', subDefault: 'cobrancas' },
  { id: 'rh', label: 'Recursos Humanos', icon: 'hr' },
  { id: 'bi', label: 'BI', icon: 'bi' },
  { section: 'Admin', requiresAdminMode: true },
  { id: 'admin', label: 'ADMIN', subtitle: 'governance · gestão', icon: 'user', iconColor: 'oklch(0.58 0.16 30)', target: 'admin', subKey: 'admin', sub: ADMIN_SUBNAV, subStorage: 'digi-admin-sub', subDefault: 'inicio', requiresAdminMode: true },
];

// Shared sub-nav state across Sidebar and screens. Source of truth: localStorage per storage-key.
const useSubNav = (storageKey, fallback) => {
  const [val, setVal] = React.useState(() => {
    if (!storageKey) return fallback;
    try { return localStorage.getItem(storageKey) || fallback; } catch { return fallback; }
  });
  React.useEffect(() => {
    if (!storageKey) return;
    try { localStorage.setItem(storageKey, val); } catch {}
    window.dispatchEvent(new CustomEvent('digi-subnav', { detail: { storageKey, val } }));
  }, [val, storageKey]);
  React.useEffect(() => {
    if (!storageKey) return;
    const onSync = (e) => {
      if (e.detail && e.detail.storageKey === storageKey && e.detail.val !== val) setVal(e.detail.val);
    };
    window.addEventListener('digi-subnav', onSync);
    return () => window.removeEventListener('digi-subnav', onSync);
  }, [storageKey, val]);
  return [val, setVal];
};
window.useSubNav = useSubNav;

// Indented accordion sub-list. Each row has: vertical rail, label, badge, kbd.
const SubNavList = ({ items, storageKey, fallback, isParentActive, onNavigateParent }) => {
  const [subActive, setSubActive] = useSubNav(storageKey, fallback);
  return (
    <div style={{
      position: 'relative',
      marginLeft: 19, paddingLeft: 10,
      marginTop: 2, marginBottom: 6,
      borderLeft: '1px solid var(--border)',
    }}>
      {items.map(s => {
        const active = isParentActive && s.id === subActive;
        return (
          <button key={s.id}
            onClick={() => {
              if (!isParentActive) onNavigateParent();
              setSubActive(s.id);
            }}
            style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 8,
              padding: '5px 8px', marginBottom: 1,
              borderRadius: 5,
              background: active ? 'var(--bg-hover)' : 'transparent',
              color: active ? 'var(--text)' : (s.muted ? 'var(--text-dim)' : 'var(--text-muted)'),
              fontSize: 12, fontWeight: active ? 500 : 400,
              fontStyle: s.muted && !active ? 'italic' : 'normal',
              position: 'relative',
            }}
            onMouseEnter={e => { if (!active) e.currentTarget.style.color = 'var(--text)'; }}
            onMouseLeave={e => { if (!active) e.currentTarget.style.color = 'var(--text-muted)'; }}
          >
            {active && (
              <span style={{ position: 'absolute', left: -11, top: 6, bottom: 6, width: 2, background: 'var(--ai-500)', borderRadius: 1 }} />
            )}
            <span style={{ flex: 1, textAlign: 'left', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.label}</span>
            {s.badge && <span style={{ padding: '0 5px', fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--accent-500)', background: 'rgba(0,163,255,0.14)', borderRadius: 3 }}>{s.badge}</span>}
            {s.kbd && <kbd style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-dim)', padding: '1px 4px', border: '1px solid var(--border)', borderRadius: 3, background: 'var(--bg-sunken)' }}>{s.kbd}</kbd>}
          </button>
        );
      })}
    </div>
  );
};

const Sidebar = ({ active, onNavigate, variation, allowedScreens, userRole, userEmail }) => {
  // Se allowedScreens for null → tudo. Senão, só itens cujo target está na lista
  // (ou items section/sem target são mantidos se houver algum item visível à volta).
  // requiresRole filtra também por role do utilizador.
  // requiresAdminMode consulta AdminUsersData.canAccessAdminMode (lista nominal de 5 emails).
  const adminGate = window.AdminUsersData?.canAccessAdminMode;
  const filterNav = (items) => {
    const allowed = allowedScreens ? new Set(allowedScreens) : null;
    const roleOk = (it) => !it.requiresRole || (userRole && it.requiresRole.includes(userRole));
    const adminOk = (it) => !it.requiresAdminMode || (adminGate && adminGate({ email_profissional: userEmail }));
    const passes = (it) => roleOk(it) && adminOk(it);
    // Primeiro passo: determina items cujo target é permitido
    const visibleByTarget = items.map(it => {
      if (it.section) return false;
      if (!passes(it)) return false;
      if (!it.target) return false;
      return allowed ? allowed.has(it.target) : true;
    });
    // Segundo passo: mantém sections que tenham pelo menos 1 item visível à sua frente
    return items.filter((it, i) => {
      if (it.section) {
        if (!passes(it)) return false;
        for (let j = i + 1; j < items.length; j++) {
          if (items[j].section) return false;
          if (visibleByTarget[j]) return true;
        }
        return false;
      }
      return visibleByTarget[i];
    });
  };
  const visibleNav = filterNav(NAV);

  const [compact, setCompact] = React.useState(() => {
    try { return localStorage.getItem('sidebar-compact') === '1'; } catch { return false; }
  });
  // Which accordion section is open. Only ONE at a time. null = none open.
  const [openSub, setOpenSub] = React.useState(() => {
    try { return localStorage.getItem('sidebar-open-sub') || null; } catch { return null; }
  });
  // Auto-open on mount/when switching to a dept-with-sub; close when switching to dept without sub.
  const prevActiveRef = React.useRef(null);
  React.useEffect(() => {
    const item = NAV.find(n => n.target === active && n.sub);
    const prev = prevActiveRef.current;
    if (prev !== active) {
      if (item) setOpenSub(item.subKey);
      else if (prev !== null) setOpenSub(null);
    }
    prevActiveRef.current = active;
  }, [active]);
  React.useEffect(() => {
    try { localStorage.setItem('sidebar-open-sub', openSub || ''); } catch {}
  }, [openSub]);
  const toggle = () => {
    setCompact(v => {
      const next = !v;
      try { localStorage.setItem('sidebar-compact', next ? '1' : '0'); } catch {}
      return next;
    });
  };

  // ⌘/ keyboard shortcut to toggle sidebar
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === '/') {
        e.preventDefault();
        toggle();
      }
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);
  return (
    <aside style={{
      width: compact ? 72 : 'var(--sidebar-w)',
      background: 'var(--bg-elev)',
      borderRight: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column',
      height: '100vh', position: 'sticky', top: 0, flexShrink: 0,
      transition: 'width 0.22s cubic-bezier(0.4, 0, 0.2, 1)',
    }}>
      <div style={{ padding: compact ? '14px 12px' : '14px 18px', borderBottom: '1px solid var(--border)', height: 'var(--topbar-h)', display: 'flex', alignItems: 'center', justifyContent: compact ? 'center' : 'space-between', minWidth: 0, gap: 8 }}>
        <DigiMark size={compact ? 32 : 36} showLabel={!compact} aiDot={false} />
      </div>

      {/* Company switcher */}
      {!compact ? (
        <div style={{ padding: '12px 12px 8px' }}>
          <button style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 10px', borderRadius: 'var(--r-3)',
            border: '1px solid var(--border)', background: 'var(--surface-muted)',
            fontSize: 12,
          }}>
            <div style={{ width: 22, height: 22, borderRadius: 4, background: 'var(--brand-900)', color: '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 11 }}>DP</div>
            <div style={{ flex: 1, textAlign: 'left', lineHeight: 1.2 }}>
              <div style={{ fontWeight: 600 }}>Digidelta PT</div>
              <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>6 empresas · 193 colab.</div>
            </div>
            <Icon name="chevron" size={14} />
          </button>
        </div>
      ) : (
        <div style={{ padding: '10px 0 4px', display: 'flex', justifyContent: 'center' }}>
          <button title="Digidelta PT · 6 empresas" style={{
            width: 36, height: 36, borderRadius: 6,
            background: 'var(--brand-900)', color: '#fff',
            display: 'grid', placeItems: 'center',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 11,
            border: '1px solid var(--border)',
          }}>DP</button>
        </div>
      )}

      <nav style={{ flex: 1, padding: '4px 8px', overflowY: 'auto', overflowX: 'hidden' }} className="scrollbar">
        {visibleNav.map((item, idx) => {
          if (item.section) {
            if (compact) {
              return idx === 0 ? null : (
                <div key={`s-${idx}`} style={{ height: 1, background: 'var(--border)', margin: '10px 8px' }} />
              );
            }
            return (
              <div key={`s-${idx}`} style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.1em', padding: idx === 0 ? '8px 10px 6px' : '16px 10px 6px', textTransform: 'uppercase' }}>{item.section}</div>
            );
          }
          const isActive = item.id === active;
          const hasSub = !!item.sub;
          // Only one sub-menu expanded at a time.
          const isExpanded = hasSub && !compact && openSub === item.subKey;
          const [subActive] = hasSub ? useSubNav(item.subStorage, item.subDefault) : [null];
          return (
            <React.Fragment key={item.id}>
            <button
              onClick={() => {
                if (hasSub && !compact) {
                  if (openSub === item.subKey) {
                    setOpenSub(null);
                  } else {
                    setOpenSub(item.subKey);
                    if (!isActive && item.target) onNavigate(item.target);
                  }
                } else if (item.target) {
                  if (!hasSub) setOpenSub(null);
                  onNavigate(item.target);
                }
              }}
              disabled={!item.target}
              title={compact ? item.label : ''}
              style={{
                width: '100%', display: 'flex', alignItems: 'center',
                gap: 12, padding: compact ? '10px' : (item.subtitle ? '7px 10px 6px' : '8px 10px'),
                borderRadius: 'var(--r-3)', marginBottom: 2,
                justifyContent: compact ? 'center' : 'flex-start',
                background: isActive ? 'var(--brand-900)' : 'transparent',
                color: isActive ? '#fff' : (item.target ? 'var(--text)' : 'var(--text-dim)'),
                fontSize: 13, fontWeight: isActive ? 500 : 400,
                opacity: item.target ? 1 : 0.6,
                cursor: item.target ? 'pointer' : 'default',
                position: 'relative',
              }}
              onMouseEnter={e => { if (!isActive && item.target) e.currentTarget.style.background = 'var(--bg-hover)'; }}
              onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
            >
              <Icon name={item.icon} size={18} style={{ color: item.iconColor && !isActive ? item.iconColor : undefined, flexShrink: 0 }} />
              {!compact && (
                <span style={{ flex: 1, textAlign: 'left', display: 'flex', flexDirection: 'column', lineHeight: 1.15, minWidth: 0 }}>
                  <span style={{ fontFamily: item.subtitle ? 'var(--font-display)' : undefined, fontWeight: item.subtitle ? 600 : (isActive ? 500 : 400), letterSpacing: item.subtitle ? '0.04em' : undefined }}>{item.label}</span>
                  {item.subtitle && <span style={{ fontSize: 10, fontStyle: 'italic', color: isActive ? 'rgba(255,255,255,0.65)' : 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.02em', marginTop: 1 }}>{item.subtitle}</span>}
                </span>
              )}
              {!compact && item.badge && <span className="badge badge-danger" style={{ padding: '1px 6px', fontSize: 10 }}>{item.badge}</span>}
              {!compact && hasSub && (
                <Icon name="chevron" size={12} style={{ transform: isExpanded ? 'rotate(180deg)' : 'none', transition: 'transform 0.18s', opacity: 0.7 }} />
              )}

              {compact && item.badge && <span style={{ position: 'absolute', top: 4, right: 6, minWidth: 14, height: 14, padding: '0 4px', borderRadius: 7, background: 'var(--danger)', color: '#fff', fontSize: 9, fontWeight: 600, display: 'inline-grid', placeItems: 'center', border: '2px solid var(--bg-elev)' }}>{item.badge}</span>}
            </button>
            {hasSub && isExpanded && (
              <SubNavList
                items={item.sub}
                storageKey={item.subStorage}
                fallback={item.subDefault}
                isParentActive={isActive}
                onNavigateParent={() => { if (!isActive && item.target) onNavigate(item.target); }}
              />
            )}
            </React.Fragment>
          );
        })}
      </nav>

      {/* Digi AI ambient status + collapse toggle */}
      <div style={{ padding: 12, borderTop: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div className="ai-surface" style={{ padding: compact ? 10 : 12, borderRadius: 'var(--r-3)', display: 'flex', alignItems: 'center', gap: 10, justifyContent: compact ? 'center' : 'flex-start' }}>
          <div style={{ position: 'relative', flexShrink: 0 }}>
            <div style={{ width: 24, height: 24, borderRadius: 6, background: 'var(--ai-500)', display: 'grid', placeItems: 'center' }}>
              <Icon name="sparkle" size={14} style={{ color: '#fff' }} />
            </div>
            <div className="ai-dot" style={{ position: 'absolute', top: -2, right: -2, animation: 'ai-shimmer 2s ease-in-out infinite' }} />
          </div>
          {!compact && (
            <div style={{ lineHeight: 1.2, flex: 1 }}>
              <div className="font-display" style={{ fontWeight: 600, fontSize: 12, letterSpacing: '0.02em' }}>Digi AI</div>
              <div style={{ fontSize: 10, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>online · 101.453 chunks</div>
            </div>
          )}
        </div>
        <button
          onClick={toggle}
          title={compact ? 'Expandir menu' : 'Colapsar menu'}
          style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: compact ? '6px' : '6px 10px',
            borderRadius: 'var(--r-2)',
            border: '1px solid var(--border)',
            background: 'transparent',
            color: 'var(--text-muted)',
            fontSize: 11, fontFamily: 'var(--font-mono)',
            justifyContent: compact ? 'center' : 'space-between',
            transition: 'all 0.15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)'; e.currentTarget.style.color = 'var(--text)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-muted)'; }}
        >
          {!compact && <span style={{ letterSpacing: '0.06em' }}>Colapsar</span>}
          <Icon name={compact ? 'chevronRight' : 'menu'} size={14} style={{ transform: compact ? 'none' : 'rotate(0deg)' }} />
          {!compact && <kbd style={{ fontFamily: 'var(--font-mono)', fontSize: 9, padding: '1px 4px', border: '1px solid var(--border)', borderRadius: 3, background: 'var(--bg-sunken)' }}>⌘/</kbd>}
        </button>
      </div>
    </aside>
  );
};

const Topbar = ({ title, subtitle, brand, onOpenChat, onOpenCmd, onToggleTheme, theme, right, livePill, user, onSwitchUser, onOpenDrawer, onNavigate }) => {
  return (
    <header style={{
      height: 'var(--topbar-h)', flexShrink: 0,
      borderBottom: '1px solid var(--border)',
      background: 'var(--bg-elev)',
      display: 'flex', alignItems: 'center',
      padding: '0 20px', gap: 16,
      position: 'sticky', top: 0, zIndex: 50,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
          <h1 className="font-display" style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em' }}>{title}</h1>
          {subtitle && <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{subtitle}</span>}
        </div>
      </div>

      {brand && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 10px', border: '1px solid var(--border)', borderRadius: 999, fontSize: 12 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: brand.color }} />
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.04em' }}>{brand.name}</span>
          <Icon name="chevron" size={12} style={{ color: 'var(--text-dim)' }} />
        </div>
      )}

      <button onClick={onOpenCmd} style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '6px 12px 6px 10px',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-3)',
        background: 'var(--surface-muted)',
        color: 'var(--text-muted)',
        fontSize: 12,
        minWidth: 260,
      }}>
        <Icon name="search" size={14} />
        <span style={{ flex: 1, textAlign: 'left' }}>Pesquisar ou pedir à Digi AI…</span>
        <kbd style={{ fontFamily: 'var(--font-mono)', fontSize: 10, padding: '2px 6px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg-elev)' }}>⌘K</kbd>
      </button>

      {right}

      {livePill && (
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '4px 10px 4px 8px',
          borderRadius: 999,
          background: 'color-mix(in oklch, var(--success) 14%, transparent)',
          border: '1px solid color-mix(in oklch, var(--success) 34%, transparent)',
          fontSize: 11, fontFamily: 'var(--font-mono)',
          color: 'var(--success)',
          whiteSpace: 'nowrap',
        }} title="Sessões activas em produção · 24h">
          <span style={{
            width: 7, height: 7, borderRadius: '50%',
            background: 'var(--success)',
            boxShadow: '0 0 0 3px color-mix(in oklch, var(--success) 24%, transparent)',
            animation: 'ai-shimmer 2s ease-in-out infinite',
          }} />
          <span style={{ fontWeight: 600 }}>{livePill.live} ao vivo</span>
          <span style={{ opacity: 0.6 }}>·</span>
          <span style={{ opacity: 0.85 }}>{livePill.total} sessões 24h</span>
        </div>
      )}

      <button className="btn btn-sm btn-ghost" onClick={onToggleTheme} title="Alternar tema">
        <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={16} />
      </button>

      <button className="btn btn-sm btn-ghost" style={{ position: 'relative' }} title="Notificações">
        <Icon name="bell" size={16} />
        <span style={{ position: 'absolute', top: 4, right: 4, width: 7, height: 7, borderRadius: '50%', background: 'var(--danger)' }} />
      </button>

      <button onClick={onOpenChat} className="btn btn-sm btn-ai" style={{ padding: '6px 12px' }}>
        <Icon name="sparkle" size={14} />
        Digi AI
      </button>

      <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingLeft: 8, borderLeft: '1px solid var(--border)' }}>
        <UserMenu user={user} onSwitchUser={onSwitchUser} onOpenDrawer={onOpenDrawer} onNavigate={onNavigate} />
      </div>
    </header>
  );
};

window.Sidebar = Sidebar;
window.Topbar = Topbar;
