/* global React, Ic, CloudGate */
const { useState, useEffect, useMemo, useRef } = React;

// ---------- Sidebar ----------
function Sidebar({ route, setRoute, collapsed, user }) {
  // The whole Admin section is SystemAdmin-only.  TenantAdmin and lower
  // roles never see the system-wide configuration pages.
  const isSysAdmin = user?.role === 'SystemAdmin';
  // CustomerAdmin / Operator / Viewer / API are scoped to a single Company,
  // so the menu entry reads "Company" (singular).  SystemAdmin and
  // TenantAdmin manage many — they keep the plural.
  const isMultiCompany = isSysAdmin || user?.role === 'TenantAdmin';
  const companyLabel = isMultiCompany ? 'Companies' : 'Company';
  // Page-visibility overrides only apply to company-scoped roles
  // (CustomerAdmin / Operator / Viewer / API).  SystemAdmin and TenantAdmin
  // always see every page, so they get no filter (`hidden` stays null).
  const hidden = (!isMultiCompany && user?.companyId)
    ? CloudGate.hiddenPagesForCompany(user.companyId)
    : null;
  const items = [
    { section: 'Workspace' },
    { id: 'dashboard',        label: 'Dashboard',        icon: Ic.dashboard },
    // Inventory & Stocking targets are regular pages now; per-company
    // visibility is managed under Tenant → Company Pages (the `hidden` filter
    // below), not by deployment mode.
    { id: 'inventory',        label: 'Inventory',        icon: Ic.layers },
    { id: 'locations-admin',  label: 'Locations',        icon: Ic.pin },
    { id: 'companies',        label: companyLabel,       icon: Ic.users },
    { id: 'users',            label: 'Users',            icon: Ic.user },
    { id: 'stocking-targets', label: 'Stocking targets', icon: Ic.layers },
    { id: 'asset-types',      label: 'Asset types',      icon: Ic.tag },
    { id: 'assets',           label: 'Assets',           icon: Ic.rfid },
    { section: 'Devices' },
    { id: 'readers-admin',    label: 'Readers',          icon: Ic.radio },
    // ── Tenant (SystemAdmin + TenantAdmin) ────────────────────────────
    // Per-company configuration that a Tenant administrator manages for
    // their own customers; the System administrator sees it for everyone.
    ...(isMultiCompany ? [
      { section: 'Tenant' },
      { id: 'company-pages',  label: 'Company Pages',  icon: Ic.eye   },
    ] : []),
    // ── Admin (SystemAdmin only) ──────────────────────────────────────
    ...(isSysAdmin ? [
      { section: 'Admin' },
      { id: 'location-types', label: 'Location types', icon: Ic.tag   },
      { id: 'tenants',        label: 'Tenants',        icon: Ic.users },
      { id: 'lookups',        label: 'Lookups',        icon: Ic.list  },
      { id: 'custom-fields',  label: 'Custom fields',  icon: Ic.edit  },
      { id: 'hub-clients',    label: 'Hub clients',    icon: Ic.radio },
    ] : []),
  ].filter(Boolean)
   // Drop any page hidden for this company's users.  Section labels (no id)
   // always pass here; the orphaned-label trim below removes empty sections.
   .filter(it => it.section || !hidden || !hidden.has(it.id));
  // Trim section labels left with no items under them (e.g. hiding the only
  // Devices page would otherwise leave a dangling "Devices" header).
  const navItems = items.filter((it, i) =>
    !it.section || (items[i + 1] && !items[i + 1].section));
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <div className="brand-tile">RFID</div>
        <div className="brand-text">
          <span className="brand-text-1">CloudGate</span>
          <span className="brand-text-2">Inventory</span>
          {CloudGate.isAdmin() && (
            <span className="brand-version" style={{fontSize:10, color:'var(--text-faint)', fontFamily:'var(--mono)', letterSpacing:'0.02em', marginTop:2}}>
              v{CloudGate.version}
            </span>
          )}
        </div>
      </div>
      <nav className="sidebar-nav">
        {navItems.map((it, i) => it.section
          ? <div key={i} className={"nav-section-label" + (i === 0 ? " first-section" : "")}>{it.section}</div>
          : (
            <div key={it.id}
                 className={"nav-item" + (route === it.id ? " active" : "")}
                 onClick={() => setRoute(it.id)}
                 title={collapsed ? it.label : ''}>
              {it.icon ? <it.icon className="icon"/> : <span className="icon"/>}
              <span className="label">{it.label}</span>
              {it.badge && <span className="badge">{it.badge}</span>}
            </div>
          )
        )}
      </nav>
      <div className="sidebar-footer">
        <div className="avatar">{user.initials}</div>
        <div className="user-meta">
          <span className="name">{user.name}</span>
          <span className="role">{user.roleLabel}</span>
        </div>
      </div>
    </aside>
  );
}

// ---------- Topbar ----------
// The scope picker behaviour depends on the user's role:
//
//   SystemAdmin → dropdown with "All" + every Tenant (as a group) + every
//                 Company (as a group).  Picking a tenant narrows the view
//                 to that tenant's companies; picking a company narrows it
//                 to that one company.
//   TenantAdmin → dropdown with "All <my tenant>" + every Company under
//                 their tenant.  No tenant entries — they can't switch
//                 tenants, only drill into one of their customers.
//   lower roles → no pill at all.  Their server snapshot already contains
//                 just their own Company so a switcher would be redundant.
//
// `activeScope` is one of { kind:'all'|'tenant'|'company', id:number|null }.
// We encode it as a single string in the <select> value:
//   "all"          → kind:'all',     id:null
//   "tenant:<id>"  → kind:'tenant',  id:<id>
//   "company:<id>" → kind:'company', id:<id>
function Topbar({ route, onToggle, onLogout,
                  showScopePicker, activeScope, scopeLabel, scopeAllLabel,
                  scopeOptions, onSwitchScope }) {
  const titles = {
    dashboard: 'Dashboard',
    inventory: 'Inventory',
    'locations-admin': 'Locations',
    assets: 'Assets',
    readers: 'Readers',
    'readers-admin': 'Readers',
    configuration: 'Configuration',
    companies: 'Companies',
    users: 'Users',
    'location-types': 'Location types',
    lookups: 'Lookups',
    'custom-fields': 'Custom fields',
    'asset-types': 'Asset types',
    'stocking-targets': 'Stocking targets',
    tenants: 'Tenants',
    'company-pages': 'Company Pages',
  };
  // Match the sidebar: lower roles see a singular "Company" breadcrumb.
  {
    const r = window.__currentUser?.role;
    if (r && r !== 'SystemAdmin' && r !== 'TenantAdmin') titles.companies = 'Company';
  }
  const code = (scopeLabel || '').split(/\s+/).map(w => w[0]).join('').slice(0,2).toUpperCase() || '—';
  const selectValue =
    activeScope?.kind === 'tenant'  ? 'tenant:'  + activeScope.id :
    activeScope?.kind === 'company' ? 'company:' + activeScope.id :
                                      'all';
  const onChange = (e) => {
    const v = e.target.value;
    if (v === 'all') return onSwitchScope({ kind:'all', id:null });
    const [kind, idStr] = v.split(':');
    onSwitchScope({ kind, id: parseInt(idStr, 10) });
  };
  return (
    <header className="topbar">
      <button className="topbar-toggle" onClick={onToggle} title="Toggle sidebar"><Ic.menu width="18" height="18"/></button>
      <div className="crumbs">
        <span>CloudGate</span>
        <span className="sep">/</span>
        <span className="current">{titles[route] || route}</span>
      </div>
      <div className="topbar-spacer"/>
      {showScopePicker && scopeOptions && (
        <div className="scope-pill" title="Active scope — pick a tenant or company">
          <span className="scope-dot">{code}</span>
          <span className="scope-label">Scope</span>
          <select value={selectValue} onChange={onChange}
                  style={{background:'transparent', border:'none', color:'inherit', font:'inherit', fontWeight:600, cursor:'pointer', outline:'none', minWidth:140}}>
            <option value="all">{scopeAllLabel}</option>
            {scopeOptions.tenants?.length > 0 && (
              <optgroup label="Tenants">
                {scopeOptions.tenants.map(t =>
                  <option key={'t'+t.Id} value={'tenant:'+t.Id}>{t.TenantName}</option>)}
              </optgroup>
            )}
            {scopeOptions.companies?.length > 0 && (
              <optgroup label="Companies">
                {scopeOptions.companies.map(c =>
                  <option key={'c'+c.Id} value={'company:'+c.Id}>{c.Name}</option>)}
              </optgroup>
            )}
          </select>
        </div>
      )}
      <button className="icon-btn" title="Notifications"><Ic.bell width="16" height="16"/><span className="dot"/></button>
      <button className="icon-btn" title="Sign out" onClick={onLogout}><Ic.logout width="16" height="16"/></button>
    </header>
  );
}

window.Sidebar = Sidebar;
window.Topbar = Topbar;
