// App shell: navbar, role switcher, avatar menu.
const { useState: useStateShell, useEffect: useEffectShell, useRef: useRefShell } = React;

function NavBar({ user, currentRoute, onNav, onOpenUsers, onOpenConnections, onLogout, onSwitchUser }) {
  const role = window.AppData.ROLES[user.role];
  const [menuOpen, setMenuOpen] = useStateShell(false);
  const menuRef = useRefShell(null);

  useEffectShell(() => {
    function onDoc(e) {
      if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false);
    }
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const navItems = [];
  navItems.push({ id: 'tasks', label: 'Tasks', icon: 'Inbox' });
  navItems.push({ id: 'teams', label: 'Teams', icon: 'Teams' });
  navItems.push({ id: 'events', label: 'Events', icon: 'Calendar' });
  navItems.push({ id: 'forms', label: 'Forms', icon: 'FileText' });
  navItems.push({ id: 'budget', label: 'Budget', icon: 'Budget' });
  navItems.push({ id: 'starter-pack', label: 'Starter pack', icon: 'ShieldCheck' });

  const baseRoute = currentRoute.startsWith('team:') ? 'teams' : currentRoute;

  return (
    <header className="navbar">
      <div className="wordmark">
        <span className="wordmark-dot" />
        RecSports Hub
      </div>

      <nav className="nav-links">
        {navItems.map(n => {
          const Ic = window.I[n.icon];
          return (
            <button
              key={n.id}
              className={`nav-link ${baseRoute === n.id || (n.id === 'teams' && currentRoute.startsWith('team:')) ? 'active' : ''}`}
              onClick={() => onNav(n.id)}
            >
              <Ic size={14} />
              {n.label}
            </button>
          );
        })}
      </nav>

      <div className="nav-right" ref={menuRef}>
        <span className={`role-badge ${role.color}`}>{role.label}</span>
        <button className="avatar" onClick={() => setMenuOpen(o => !o)} title={user.name}>
          {user.initials}
        </button>
        {menuOpen && (
          <div className="avatar-menu">
            <div className="avatar-menu-header">{user.name}</div>
            <div style={{ padding: '0 10px 6px', fontSize: 11, color: 'var(--text-3)' }}>{user.email}</div>
            <div className="avatar-menu-divider" />
            {user.role === 'super_admin' && (
              <button className="avatar-menu-item" onClick={() => { setMenuOpen(false); onOpenUsers(); }}>
                <window.I.Users size={14} />
                User management
              </button>
            )}
            {user.id === 'u1' && (
              <button className="avatar-menu-item" onClick={() => { setMenuOpen(false); onOpenConnections && onOpenConnections(); }}>
                <window.I.RefreshCw size={14} />
                Form connections
                <span className="badge gold" style={{ marginLeft: 'auto', fontSize: 9 }}>OWNER</span>
              </button>
            )}
            <button className="avatar-menu-item muted">
              <window.I.Settings size={14} />
              Settings
            </button>
            <div className="avatar-menu-divider" />
            <button className="avatar-menu-item muted" onClick={() => { setMenuOpen(false); onLogout(); }}>
              <window.I.Logout size={14} />
              Sign out
            </button>
          </div>
        )}
      </div>
    </header>
  );
}

function RoleSwitcher({ currentRole, currentUserId, onChange }) {
  const opts = [
    { id: 'u1', role: 'super_admin', who: 'Justin Reilly' },
    { id: 'u3', role: 'staff_admin', who: 'Val · courts' },
    { id: 'u4', role: 'staff_admin', who: 'Stoney · fields' },
    { id: 'u5', role: 'cs_president', who: 'Maya Brooks' },
    { id: 'u6', role: 'cs_helper', who: 'Eli Watson' },
  ];
  return (
    <div className="role-switcher">
      <div className="role-switcher-head">
        <span>View as</span>
        <span className="demo-pill">Demo</span>
      </div>
      {opts.map(o => {
        const role = window.AppData.ROLES[o.role];
        const isActive = currentUserId === o.id;
        return (
          <button
            key={o.id}
            className={`role-option ${isActive ? 'active' : ''}`}
            onClick={() => onChange(o.id)}
          >
            <span className="role-option-marker" />
            <span className="role-option-name">{role.label}</span>
            <span className="role-option-who">{o.who}</span>
          </button>
        );
      })}
    </div>
  );
}

window.NavBar = NavBar;
window.RoleSwitcher = RoleSwitcher;
