// Left sidebar navigation
function Sidebar({ view, setView, counts, currentUser, users, setCurrentUserId, isLeadership, isAdmin, role, accessMatrix, onReset }) {
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const allow = (id) => window.canAccessView ? window.canAccessView(accessMatrix, role, id) : true;

  const allItems = [
  { id: 'overview', label: 'Overview', icon: 'dashboard' },
  { id: 'contacts', label: 'Contacts', icon: 'mail' },
  { id: 'calendar', label: 'Calendar', icon: 'calendar' },
  { id: 'pipeline', label: 'Pipeline', icon: 'pipeline', badge: counts.active },
  { id: 'deals', label: 'All Deals', icon: 'table', badge: counts.total },
  { id: 'aging', label: 'Aging & Stuck', icon: 'clock', badge: counts.stuck, badgeAlert: true },
  { id: 'showrooms', label: window.T ? window.T('locations') : 'Showrooms', icon: 'home', leadershipOnly: true },
  { id: 'reps', label: 'Sales ' + (window.T ? window.T('reps') : 'Reps'), icon: 'users' },
  { id: 'reports', label: 'Reports', icon: 'trend' },
  { id: 'company_kpis', label: 'Company KPIs', icon: 'target' },
  { id: 'forecast', label: 'Forecast', icon: 'target' }];

  const newFeatureItems = [
  { id: 'ai_hub', label: 'AI Intelligence', icon: 'spark' },
  { id: 'comms', label: 'Comms Hub', icon: 'mail' },
  { id: 'quotes', label: 'Quote Builder', icon: 'trend' },
  { id: 'analytics_plus', label: 'Analytics+', icon: 'dashboard' },
  { id: 'customer_portal', label: 'Customer Portal', icon: 'users' },
  { id: 'mobile_app', label: 'Mobile Field App', icon: 'home' }];

  const adminItems = [
  { id: 'admin', label: 'Team & Access', icon: 'sliders', adminOnly: true },
  { id: 'audit_log', label: 'Audit Log', icon: 'lock', adminOnly: true },
  { id: 'compliance', label: 'Compliance', icon: 'check', adminOnly: true },
  { id: 'manage_showrooms', label: 'Manage ' + (window.T ? window.T('locations') : 'Showrooms'), icon: 'home', adminOnly: true },
  { id: 'workspace', label: 'Workspace & Industry', icon: 'sliders', adminOnly: true },
  { id: 'targets', label: 'Sales Targets', icon: 'target', adminOnly: true },
  { id: 'kpi_admin', label: 'KPI Targets', icon: 'target', adminOnly: true },
  { id: 'automations', label: 'Automations', icon: 'spark', adminOnly: true },
  { id: 'settings', label: 'Settings', icon: 'sliders', adminOnly: true },
  { id: 'import', label: 'Data Import', icon: 'download', superAdminOnly: true },
  { id: 'roi', label: 'ROI Calculator', icon: 'trend', adminOnly: true }];

  const items = allItems.filter((it) => allow(it.id));
  const visibleAdmin = adminItems.filter((it) => allow(it.id));
  const visibleNewFeatures = newFeatureItems.filter((it) => allow(it.id));
  const showSuperAdmin = currentUser && currentUser.superAdmin;

  const leadership = users.filter((u) => u.role === 'leadership');
  const reps = users.filter((u) => u.role === 'sales_designer');

  return (
    <aside className="sidebar">
      <div className="brand">
        {(() => {
          const liveLogoUrl = window.STAGEVO_AUTHED && window.SALES_DATA && window.SALES_DATA.org && window.SALES_DATA.org.logo_url;
          const demoLogo = !window.STAGEVO_AUTHED && window.KUB_LOGO;
          if (liveLogoUrl || demoLogo) {
            return (
              <React.Fragment>
                <img
                  src={liveLogoUrl || demoLogo || 'assets/logo.png'}
                  alt="Logo"
                  className="brand-logo"
                  onError={(e) => {e.target.style.display='none';e.target.nextSibling.style.display='flex';}}
                />
                <div className="brand-mark" style={{ display:'none' }}>S</div>
              </React.Fragment>
            );
          }
          return (
            <div style={{ display:'flex', alignItems:'center', gap:10, padding:'4px 0' }}>
              <div style={{ width:34, height:34, borderRadius:9, background:'linear-gradient(135deg,#57C79E,#1F6E5A)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:16, fontWeight:800, color:'white', flexShrink:0, letterSpacing:'-0.03em' }}>S</div>
              <div>
                <div style={{ fontSize:15, fontWeight:800, color:'var(--sidebar-ink)', letterSpacing:'-0.03em', lineHeight:1.1 }}>Stagevo</div>
                <div style={{ fontSize:10, color:'var(--sidebar-dim)', letterSpacing:'0.08em', textTransform:'uppercase', marginTop:1 }}>Sales OS</div>
              </div>
            </div>
          );
        })()}
      </div>
      <div className="powered-by">
        <span className="pb-mark"></span>
         <strong></strong>
      </div>

      <div className="nav-section">
        <div className="nav-label">Analyse</div>
        {items.map((it) =>
        <div
          key={it.id}
          className={`nav-item ${view === it.id ? 'active' : ''}`}
          data-nav-id={it.id}
          onClick={() => setView(it.id)}>
          
            <span className="nav-icon"><Icon name={it.icon} size={15} /></span>
            {it.label}
            {it.badge != null &&
          <span className="nav-badge" style={it.badgeAlert && it.badge > 0 ? { background: 'var(--lost)', color: 'white' } : null}>
                {it.badge}
              </span>
          }
          </div>
        )}
      </div>

      {visibleNewFeatures.length > 0 && (
      <div className="nav-section" style={{ marginTop: 16 }}>
        <div className="nav-label" style={{ display:'flex', alignItems:'center', gap:5 }}>
          <span style={{ color:'#7C3AED', fontSize:10 }}>✦</span> New Features
        </div>
        {visibleNewFeatures.map((it) =>
          <div
            key={it.id}
            className={`nav-item ${view === it.id ? 'active' : ''}`}
            data-nav-id={it.id}
            onClick={() => setView(it.id)}>
            <span className="nav-icon"><Icon name={it.icon} size={15} /></span>
            {it.label}
            <span style={{ marginLeft:'auto', fontSize:9, fontWeight:700, background:'#7C3AED', color:'white', borderRadius:99, padding:'1px 6px', letterSpacing:'0.04em' }}>NEW</span>
          </div>
        )}
      </div>
      )}

      {visibleAdmin.length > 0 &&
      <div className="nav-section" style={{ marginTop: 16 }}>
          <div className="nav-label">Admin</div>
          {visibleAdmin.map((it) =>
        <div
          key={it.id}
          className={`nav-item ${view === it.id ? 'active' : ''}`}
          data-nav-id={it.id}
          onClick={() => setView(it.id)}>
          
              <span className="nav-icon"><Icon name={it.icon} size={15} /></span>
              {it.label}
            </div>
        )}
          <div className="nav-item" onClick={() => alert('In real version: re-syncs from the linked Google Sheet')}>
            <span className="nav-icon"><Icon name="download" size={15} /></span>
            Sync sheet
          </div>
        </div>
      }

      <div className="nav-section" style={{ marginTop: 10 }}>
        <div
          className={`nav-item ${view === 'profile' ? 'active' : ''}`}
          onClick={() => setView('profile')}>
          <span className="nav-icon"><Icon name="sliders" size={15}/></span>
          My Settings
        </div>
        <div
          className={`nav-item ${view === 'help' ? 'active' : ''}`}
          onClick={() => setView('help')}>
          <span className="nav-icon"><Icon name="help" size={15} /></span>
          Help &amp; Guide
        </div>
      </div>

      {showSuperAdmin && (
        <div className="nav-section" style={{ marginTop: 8 }}>
          <div className="nav-label" style={{ color:'#F87171' }}>⚡ Super Admin</div>
          <div
            className={`nav-item ${view === 'super_admin' ? 'active' : ''}`}
            onClick={() => setView('super_admin')}
            style={{ color: view === 'super_admin' ? 'var(--sidebar-ink)' : '#F87171' }}>
            <span className="nav-icon"><Icon name="sliders" size={15} /></span>
            Platform Admin
          </div>
        </div>
      )}

      <div className="sidebar-footer" onClick={() => setPickerOpen((o) => !o)} style={{ cursor: 'pointer', position: 'relative' }}>
        <span className="avatar" style={currentUser.avatarColor ? { background: currentUser.avatarColor } : null}>
          {currentUser.name.split(' ').map((s) => s[0]).slice(0, 2).join('')}
        </span>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ color: 'var(--sidebar-ink)', fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5 }}>
            {currentUser.name}
            <Icon name="chevron-down" size={11} style={{ opacity: 0.6, marginLeft: 'auto', color: 'var(--sidebar-dim)' }} />
          </div>
          <div style={{ color: 'var(--sidebar-dim)', fontSize: 11, display: 'flex', alignItems: 'center', gap: 5 }}>
            {currentUser.title}
            <span className={`role-pill ${currentUser.role}`}>
              {currentUser.role === 'admin' ? 'Admin' :
              currentUser.role === 'leadership' ? 'Lead' :
              currentUser.role === 'manager' ? 'Mgr' :
              'Designer'}
            </span>
          </div>
        </div>

        {pickerOpen &&
        <div className="user-picker" onClick={(e) => e.stopPropagation()}>
          {!window.STAGEVO_AUTHED && [
          { key: 'admin', label: 'Admin', pillLabel: 'Admin', pillClass: 'admin' },
          { key: 'leadership', label: 'Leadership', pillLabel: 'Lead', pillClass: 'leadership' },
          { key: 'manager', label: 'Showroom Manager', pillLabel: 'Mgr', pillClass: 'manager' },
          { key: 'sales_designer', label: 'Sales Designer', pillLabel: 'Designer', pillClass: 'sales_designer' }].
          map((group) => {
            const roleUsers = users.filter((u) => u.role === group.key);
            if (roleUsers.length === 0) return null;
            return (
              <div className="up-section" key={group.key}>
                <div className="up-label">View as · {group.label}</div>
                {roleUsers.map((u) =>
                <div
                  key={u.id}
                  className={`up-item ${u.id === currentUser.id ? 'on' : ''}`}
                  onClick={() => {setCurrentUserId(u.id);setPickerOpen(false);}}>
                  
                    <span className="avatar sm" style={u.avatarColor ? { background: u.avatarColor } : null}>
                      {u.name.split(' ').map((s) => s[0]).slice(0, 2).join('')}
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="up-name">{u.name}</div>
                      <div className="up-sub">
                        {group.key === 'sales_designer' ?
                      `${(u.works || []).length} showroom${(u.works || []).length !== 1 ? 's' : ''}` :
                      group.key === 'manager' ?
                      `Manages ${(u.manages || []).length} showroom${(u.manages || []).length !== 1 ? 's' : ''}` :
                      u.title || ''}
                      </div>
                    </div>
                    <span className={`role-pill ${group.pillClass}`}>{group.pillLabel}</span>
                  </div>
                )}
              </div>);

          })}
            <div className="up-foot" style={{ flexDirection: 'column', alignItems: 'stretch', gap: 6 }}>
              {window.STAGEVO_AUTHED ? (
                <React.Fragment>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    <Icon name="lock" size={11} /> Signed in as {currentUser.email || currentUser.name}
                  </div>
                  <button
                    onClick={(e) => { e.stopPropagation(); if (window.StagevoSignOut) window.StagevoSignOut(); }}
                    style={{
                      fontSize: 12, fontWeight: 500, padding: '6px 8px', borderRadius: 6,
                      background: 'var(--surface-2)', color: 'var(--lost)',
                      border: '1px solid var(--border)', cursor: 'pointer',
                      textAlign: 'left', display: 'flex', alignItems: 'center', gap: 6
                    }}>
                    <Icon name="arrow-right" size={12} />
                    Sign out
                  </button>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                    <Icon name="alert" size={11} />
                    Demo only — shows how access is locked per role
                  </div>
                  {window.STAGEVO_BACKEND === 'live' ? (
                <button
                  onClick={(e) => { e.stopPropagation(); if (window.StagevoSignOut) window.StagevoSignOut(); }}
                  style={{
                    fontSize: 12, fontWeight: 500, padding: '6px 8px', borderRadius: 6,
                    background: 'var(--surface-2)', color: 'var(--accent-ink)',
                    border: '1px solid var(--border)', cursor: 'pointer',
                    textAlign: 'left', display: 'flex', alignItems: 'center', gap: 6
                  }}>
                      <Icon name="lock" size={12} />
                      Back to sign in
                    </button>
                  ) : (isLeadership && onReset &&
                <button
                  onClick={(e) => {e.stopPropagation();onReset();setPickerOpen(false);}}
                  style={{
                    fontSize: 11, padding: '4px 8px', borderRadius: 6,
                    background: 'var(--surface-2)', color: 'var(--ink-2)',
                    border: '1px solid var(--border)', cursor: 'pointer',
                    textAlign: 'left', display: 'flex', alignItems: 'center', gap: 5
                  }}>
                  
                      <Icon name="download" size={11} />
                      Reset to imported sheet data
                    </button>
                  )}
                </React.Fragment>
              )}
            </div>
          </div>
        }
      </div>
    </aside>);

}

window.Sidebar = Sidebar;