// Shell.jsx — sidebar + topbar + layout (v2: reorganized for AppSheet-style structure)
const NAV = [
  { group: 'Workspace', items: [
    { id: 'dashboard', label: 'Dashboard', icon: 'Home' },
  ]},
  { group: 'Operations', items: [
    { id: 'bookings', label: 'Current Bookings', icon: 'Briefcase', badge: 7 },
    { id: 'allbookings', label: 'All Bookings', icon: 'List' },
    { id: 'notes', label: 'Daily Notes', icon: 'FileText' },
    { id: 'mobile', label: 'My Job (Mobile)', icon: 'Phone' },
    { id: 'completion', label: 'Job Completion', icon: 'PenTool' },
    { id: 'rm', label: 'Repair & Maintenance', icon: 'Wrench' },
  ]},
  { group: 'Comms & Insights', items: [
    { id: 'notifications', label: 'Notifications', icon: 'Bell', badge: 3 },
    { id: 'analytics', label: 'Analytics', icon: 'BarChart' },
    { id: 'export', label: 'AutoCount Export', icon: 'Download' },
  ]},
  { group: 'Master Data', items: [
    { id: 'pricelist', label: 'Customer', icon: 'Users' },
    { id: 'masterdata', label: 'Machinery', icon: 'Truck' },
    { id: 'employees', label: 'Employees', icon: 'HardHat' },
    { id: 'tools', label: 'Tools & Equipment', icon: 'Tool' },
    { id: 'rmitems', label: 'Repair & Maintenance Items', icon: 'Layers' },
    { id: 'stocks', label: 'Stocks', icon: 'Package' },
    { id: 'suppliers', label: 'Supplier', icon: 'Factory' },
  ]},
  { group: 'Administration', items: [
    { id: 'users', label: 'User Management', icon: 'Users' },
    { id: 'permissions', label: 'Role Permissions', icon: 'Shield' },
    { id: 'settings', label: 'Settings', icon: 'Settings' },
  ]},
];

function Sidebar({ page, setPage, user, open, setOpen, role }) {
  const filteredNav = NAV.map(g => ({
    ...g,
    items: g.items.filter(i => canView(role, i.id))
  })).filter(g => g.items.length > 0);
  return (
    <>
      <div className={"scrim " + (open ? "scrim--open" : "")} onClick={() => setOpen(false)} />
      <aside className={"sidebar " + (open ? "sidebar--open" : "")}>
        <div className="sidebar__brand">
          <img src="assets/powlee-logo.png" alt="Pow Lee" className="sidebar__brand-logo"/>
          <div className="sidebar__brand-name">
            POW LEE CRANE &amp; ENGINEERING SDN. BHD.
          </div>
        </div>

        {filteredNav.map(group => (
          <div key={group.group} className="sidebar__group">
            <div className="sidebar__group-label">{group.group}</div>
            {group.items.map(item => {
              const Ico = window[item.icon];
              return (
                <button key={item.id}
                  className={"nav-item " + (page === item.id ? "nav-item--active" : "")}
                  onClick={() => { setPage(item.id); setOpen(false); }}>
                  {Ico ? <Ico size={18}/> : null}
                  <span>{item.label}</span>
                  {item.badge ? <span className="nav-item__badge">{item.badge}</span> : null}
                </button>
              );
            })}
          </div>
        ))}

        <div className="sidebar__footer">
          <div className="sidebar__avatar">{user.initials}</div>
          <div className="sidebar__user">
            <div className="sidebar__user-name">{user.name}</div>
            <div className="sidebar__user-role">{user.role}</div>
          </div>
          <button className="nav-item" style={{width: 36, padding: 8, justifyContent: 'center'}} onClick={() => window.dispatchEvent(new CustomEvent('logout'))} title="Sign out">
            <LogOut size={16}/>
          </button>
        </div>
      </aside>
    </>
  );
}

function Topbar({ title, sub, onMenu }) {
  return (
    <header className="topbar">
      <button className="menu-btn" onClick={onMenu}><Menu size={22}/></button>
      <div>
        <div className="topbar__title">{title}</div>
        {sub ? <div className="topbar__sub">{sub}</div> : null}
      </div>
      <div className="topbar__search">
        <Search size={16} className="topbar__search-icon"/>
        <input placeholder="Search bookings, customers, machines..."/>
      </div>
      <div className="topbar__actions">
        <button className="topbar__icon-btn" title="Notifications"><Bell size={20}/><span className="dot"/></button>
        <button className="topbar__icon-btn" title="Settings"><Settings size={20}/></button>
      </div>
    </header>
  );
}

function Toast({ msg, onDone, kind = 'success' }) {
  React.useEffect(() => {
    const t = setTimeout(onDone, 2400);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className={"toast " + (kind === 'success' ? 'toast--success' : '')}>
      <Check size={18}/>
      <span>{msg}</span>
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, Toast });
