// NavSidebar: estende a Sidebar do DS (256 / 76 px, logo 104 px, navy fixo nos dois temas) com grupos recolhíveis,
// contadores, "NOVO", alertas, cadeado por permissão, seletor de organização/ambiente e bloco do usuário.
function NavBadge({ it, collapsed }) {
  const locked = it.perm && !useAccess().can(it.perm);
  if (collapsed) return (it.alert && !locked) ? <span style={{ position: 'absolute', top: 7, right: 12, width: 8, height: 8, borderRadius: '50%', background: VX_TONE[it.alert] }} /> : null;
  if (locked) return <i className="ph ph-lock-simple" style={{ fontSize: 14, color: 'var(--text-subtle)', marginLeft: 'auto' }} />;
  return (
    <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
      {it.isNew && <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.1em', color: 'var(--text-accent)', border: '1px solid ' + vxMix('var(--status-info)', 40), borderRadius: 999, padding: '2px 6px' }}>NOVO</span>}
      {it.alert && <span style={{ width: 8, height: 8, borderRadius: '50%', background: VX_TONE[it.alert] }} />}
      {it.count != null && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: it.tone ? VX_TONE[it.tone] : 'var(--text-muted)', background: it.tone ? vxMix(VX_TONE[it.tone], 14) : 'var(--overlay-06)', borderRadius: 999, padding: '2px 8px' }}>{it.count}</span>}
    </span>
  );
}

function NavSidebar({ active, go, collapsed, onToggle, closed, toggleGroup, user, env, onUser, onOrg, onLogo, sheet }) {
  const { Avatar } = window.VRticeDesignSystem_d763eb;
  const { can, allows } = useAccess();
  const c = collapsed;
  const row = it => {
    const locked = it.perm && !can(it.perm);
    return (
      <a key={it.id} href="#" title={it.label + (locked ? ' · acesso restrito' : '')} className="vx-navitem" aria-current={active === it.id ? 'page' : undefined} style={{ justifyContent: c ? 'center' : 'flex-start', position: 'relative', opacity: locked ? 0.6 : 1 }} onClick={e => { e.preventDefault(); go(it.id); }}>
        <i className={'ph ' + it.icon} />{!c && <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</span>}<NavBadge it={it} collapsed={c} />
      </a>
    );
  };
  // Item aparece só quando permissão E escopo (interno/cliente) permitem; `deny: 'lock'` mostra o cadeado quando só a permissão falha.
  const visible = g => g.items.filter(it => allows(it) || (it.deny === 'lock' && can(it.perm) === false && allows({ ...it, perm: null })));
  return (
    <div data-theme="dark" style={{ position: 'relative', height: '100%', width: c ? 76 : (sheet ? 288 : 256), transition: 'width 0.22s ease', color: 'var(--text-primary)', flex: 'none' }}>
      <aside className="vx-sidebar" style={{ background: 'var(--bg-sidebar)', borderRight: '1px solid var(--border-subtle)', display: 'flex', flexDirection: 'column', height: '100%', boxSizing: 'border-box', overflowY: 'auto', overflowX: 'hidden' }}>
        <button type="button" className="vx-logobtn" onClick={onLogo} aria-label="Vértice OS" style={{ height: 104, flex: 'none', width: '100%', border: 'none', background: 'transparent', cursor: 'pointer', color: 'inherit', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: c ? 'center' : 'flex-start', padding: c ? '24px 0' : '24px 30px', boxSizing: 'border-box' }}>
          {c ? <img src="assets/vertice-symbol.svg" alt="Vértice" style={{ height: 40 }} /> : <img src="assets/vertice-logo.svg" alt="Vértice Operations & Solutions" style={{ width: '100%', maxHeight: 56, objectFit: 'contain', objectPosition: 'left center' }} />}
        </button>
        <div style={{ padding: '14px 14px 0' }}>
          <button type="button" onClick={onOrg} title="Organização e ambiente" aria-haspopup="menu" style={{ all: 'unset', boxSizing: 'border-box', width: '100%', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: c ? 'center' : 'flex-start', gap: 10, padding: c ? '8px 0' : '10px 12px', borderRadius: 10, background: 'var(--overlay-04)', border: '1px solid var(--border-default)' }}>
            <span style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--action-primary-tint)', color: 'var(--action-selected-icon)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}><i className="ph ph-buildings" style={{ fontSize: 16 }} /></span>
            {!c && <>
              <span style={{ display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0, flex: 1 }}>
                <span style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{env.org}</span>
                <span style={{ fontSize: 10, letterSpacing: '0.12em', color: VX_TONE[env.tone], textTransform: 'uppercase' }}>{env.label}</span>
              </span>
              <i className="ph ph-caret-up-down" style={{ fontSize: 14, color: 'var(--text-muted)' }} />
            </>}
          </button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: c ? 8 : 14, padding: '18px 14px' }}>
          {window.VX_NAV.groups.map(g => {
            const items = visible(g); if (!items.length) return null;
            const shut = !c && closed.includes(g.id) && !items.some(i => i.id === active);
            return (
              <nav key={g.id} aria-label={g.title} style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                {c ? <span style={{ height: 1, margin: '0 10px 8px', background: 'var(--border-subtle)' }} /> :
                  <button type="button" onClick={() => toggleGroup(g.id)} aria-expanded={!shut} style={{ all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 14px 6px', fontSize: 10, fontWeight: 600, letterSpacing: '0.18em', color: 'var(--text-subtle)' }}>{g.title}<i className={'ph ' + (shut ? 'ph-caret-right' : 'ph-caret-down')} style={{ fontSize: 11 }} /></button>}
                {!shut && items.map(row)}
              </nav>
            );
          })}
        </div>
        <a href="#perfil" onClick={e => { e.preventDefault(); onUser(); }} title="Meu perfil" style={{ marginTop: 'auto', padding: '18px ' + (c ? 0 : 24) + 'px', borderTop: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: c ? 'center' : 'flex-start', gap: 12, textDecoration: 'none', color: 'var(--text-primary)' }}>
          <Avatar name={user.name} src={user.photo} color={user.color} size={36} />
          {!c && <span style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}><span style={{ fontSize: 14, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name}</span><span style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--text-muted)', textTransform: 'uppercase' }}>{user.role}</span></span>}
        </a>
      </aside>
      {onToggle && <button type="button" onClick={onToggle} title={c ? 'Expandir menu' : 'Recolher menu'} aria-label={c ? 'Expandir menu' : 'Recolher menu'} style={{ position: 'absolute', top: '50%', right: -16, transform: 'translateY(-50%)', zIndex: 30, width: 16, height: 64, padding: 0, cursor: 'pointer', background: 'var(--surface-raised)', border: '1px solid rgba(96,165,250,0.35)', borderLeft: 'none', borderRadius: '0 10px 10px 0', color: 'var(--text-secondary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className={'ph ' + (c ? 'ph-caret-right' : 'ph-caret-left')} style={{ fontSize: 12 }} /></button>}
    </div>
  );
}
window.NavSidebar = NavSidebar;
