// Sidebar — adapts to role (admin vs tenant)

function adminNav() {
  const pendingVerifs = INVOICES.filter(i => i.status === 'pending_verification').length;
  return [
    { id: 'a-overview', label: 'Overview', icon: <Icon.Home /> },
    { id: 'a-tenants', label: 'Tenants', icon: <Icon.Users />, badge: TENANTS.length },
    { id: 'a-devices', label: 'Devices', icon: <Icon.Cpu />, badge: DEVICES.length },
    { section: 'Billing' },
    { id: 'a-invoices', label: 'All Invoices', icon: <Icon.Receipt /> },
    { id: 'a-verifications', label: 'Pending Verifications', icon: <Icon.Check />, badge: pendingVerifs || null, alert: pendingVerifs > 0 },
    { section: 'Catalog' },
    { id: 'a-packages', label: 'Packages & Tariff', icon: <Icon.Package /> },
    { section: 'System' },
    { id: 'a-settings', label: 'Settings', icon: <Icon.Settings /> },
  ];
}

const TENANT_NAV = [
  { id: 't-dashboard', label: 'Dashboard', icon: <Icon.Home /> },
  { id: 't-analytics', label: 'Analytics', icon: <Icon.ChartLine /> },
  { section: 'Billing' },
  { id: 't-invoices', label: 'Invoices', icon: <Icon.Receipt /> },
  { id: 't-payments', label: 'Payment History', icon: <Icon.Wallet /> },
  { section: 'Account' },
  { id: 't-account', label: 'My Account', icon: <Icon.Settings /> },
];

const Sidebar = ({ role, route, onNav, tenant }) => {
  const items = role === 'admin' ? adminNav() : TENANT_NAV;
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="mark">
          <img src="assets/bleu-logo.png" alt="Bleu SmartDER" />
        </div>
        <div>
          <div className="name"><span>Bleu</span> SmartDER</div>
          <div className="sub">{role === 'admin' ? 'Operator Console' : tenant?.name || 'Tenant Portal'}</div>
        </div>
      </div>

      <div className="nav">
        {items.map((it, i) => {
          if (it.section) return <div key={i} className="nav-section">{it.section}</div>;
          const on = route?.startsWith(it.id);
          return (
            <div key={it.id} className="nav-item" data-on={on}
              onClick={() => onNav(it.id)}>
              <span style={{ color: on ? 'var(--navy-700)' : 'var(--ink-500)' }}>{it.icon}</span>
              <span>{it.label}</span>
              {it.badge != null && (
                <span className={"badge " + (it.alert ? '' : 'calm')}>{it.badge}</span>
              )}
            </div>
          );
        })}
      </div>

      <div className="nav-foot">
        <span><span className="status-dot" /> All systems normal</span>
        <span className="mono">v4.0</span>
      </div>
    </aside>
  );
};

window.Sidebar = Sidebar;
