/* ============================================================
   MaintenanceOS — Enhanced App Shell
   Role-based navigation with admin functionality
   ============================================================ */

// Enhanced navigation with role-based access
function getNavigationForUser(userId = "u1") {
  const { hasPermission } = window.ADMIN_HELPERS;

  const baseNav = [
    { group: "Main", items: [
      { id: "dashboard", label: "Dashboard", icon: "dashboard" },
      { id: "work-orders", label: "Work Orders", icon: "wrench", badge: 11,
        permission: "workorders.view" },
      { id: "requests", label: "Requests", icon: "inbox", badge: 6,
        permission: "requests.view" },
    ]},
    { group: "Facilities", items: [
      { id: "facilities", label: "Facilities", icon: "building",
        permission: "facilities.view" },
      { id: "assets", label: "Assets", icon: "box",
        permission: "assets.view" },
      { id: "pm", label: "PM Schedules", icon: "calendarClock",
        permission: "pm.view" },
    ]},
    { group: "Operations", items: [
      { id: "documents", label: "Documents", icon: "folder",
        permission: "documents.view" },
      { id: "checklists", label: "Checklists", icon: "clipboard",
        permission: "checklists.view" },
      { id: "analytics", label: "Analytics", icon: "chart",
        permission: "reports.view" },
    ]},
  ];

  // Add admin section for users with admin permissions
  if (hasPermission(userId, "users.view") || hasPermission(userId, "settings.manage")) {
    baseNav.push({
      group: "Administration",
      items: [
        { id: "admin", label: "Admin Dashboard", icon: "shield",
          permission: "users.view" },
        { id: "settings", label: "Settings", icon: "settings",
          permission: "settings.manage" },
      ]
    });
  }

  // Filter navigation items based on user permissions
  return baseNav.map(group => ({
    ...group,
    items: group.items.filter(item =>
      !item.permission || hasPermission(userId, item.permission)
    )
  })).filter(group => group.items.length > 0);
}

// Enhanced Topbar with user management
function EnhancedTopbar({ route, search, setSearch, onToggleSidebar, theme, setTheme }) {
  const [userMenu, setUserMenu] = useState(false);
  const [notifications, setNotifications] = useState(false);

  // Get current user (in real app, this would come from auth context)
  const currentUser = window.ADMIN_DATA.USERS.find(u => u.id === "u1");
  const userRole = window.ADMIN_DATA.USER_ROLES[currentUser?.role];

  const notificationCount = window.ADMIN_DATA.SYSTEM_NOTIFICATIONS.filter(n => !n.read).length;

  return (
    <header className="topbar">
      <div className="topbar-left">
        <button onClick={onToggleSidebar} className="btn-icon sidebar-toggle">
          <Icon name="menu" size={20} />
        </button>

        <div className="breadcrumb">
          <span>{route.screen === "admin" ? "Admin Dashboard" : navItem(route.screen)?.label || route.screen}</span>
        </div>
      </div>

      <div className="topbar-center">
        <div className="search-box">
          <Icon name="search" size={16} />
          <input
            type="text"
            placeholder="Search work orders, assets, or facilities..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
      </div>

      <div className="topbar-right">
        {/* Notifications */}
        <div className="notification-container">
          <button
            className={`btn-icon ${notifications ? "active" : ""}`}
            onClick={() => setNotifications(!notifications)}
          >
            <Icon name="bell" size={18} />
            {notificationCount > 0 && (
              <span className="notification-badge">{notificationCount}</span>
            )}
          </button>

          {notifications && (
            <NotificationDropdown
              notifications={window.ADMIN_DATA.SYSTEM_NOTIFICATIONS}
              onClose={() => setNotifications(false)}
            />
          )}
        </div>

        {/* Theme Toggle */}
        <button
          onClick={() => setTheme(theme === "light" ? "dark" : "light")}
          className="btn-icon"
        >
          <Icon name={theme === "light" ? "moon" : "sun"} size={18} />
        </button>

        {/* User Menu */}
        <div className="user-menu-container">
          <button
            onClick={() => setUserMenu(!userMenu)}
            className="user-menu-trigger"
            style={{
              display: "flex", alignItems: "center", gap: 12,
              padding: "6px 12px", borderRadius: "var(--radius-md)",
              background: userMenu ? "var(--surface-2)" : "transparent",
              cursor: "pointer", border: "none"
            }}
          >
            <div className="avatar" style={{
              width: 32, height: 32, borderRadius: 8,
              background: userRole?.color + "40",
              color: userRole?.color,
              display: "flex", alignItems: "center", justifyContent: "center",
              fontWeight: 600, fontSize: 12
            }}>
              {currentUser?.initials}
            </div>
            <div style={{ textAlign: "left", display: "var(--mobile-hide)" }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{currentUser?.name}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{userRole?.name}</div>
            </div>
            <Icon name="chevronDown" size={16} />
          </button>

          {userMenu && (
            <UserDropdown
              user={currentUser}
              onClose={() => setUserMenu(false)}
            />
          )}
        </div>
      </div>
    </header>
  );
}

// Enhanced Sidebar with role-based navigation
function EnhancedSidebar({ route, go, collapsed, setCollapsed, userId = "u1" }) {
  const navigation = getNavigationForUser(userId);

  return (
    <aside className="sidebar" style={{
      width: collapsed ? "var(--sidebar-w-collapsed)" : "var(--sidebar-w)",
      background: "var(--sidebar-bg)", borderRight: "1px solid var(--border)",
      display: "flex", flexDirection: "column", flex: "0 0 auto",
      transition: "width .22s cubic-bezier(.4,0,.2,1)", height: "100%", position: "relative", zIndex: 20,
    }}>
      <div style={{ height: "var(--topbar-h)", display: "flex", alignItems: "center", padding: collapsed ? "0" : "0 18px", justifyContent: collapsed ? "center" : "flex-start", borderBottom: "1px solid var(--border)" }}>
        <Logo collapsed={collapsed} />
      </div>

      <nav style={{ flex: 1, overflowY: "auto", padding: collapsed ? "12px 12px" : "14px 14px", display: "flex", flexDirection: "column", gap: collapsed ? 4 : 2 }}>
        {navigation.map((g, gi) => (
          <div key={g.group} style={{ marginTop: gi ? 14 : 0 }}>
            {!collapsed && <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".09em", textTransform: "uppercase", color: "var(--text-faint)", padding: "0 12px 7px" }}>{g.group}</div>}
            {collapsed && gi > 0 && <div style={{ height: 1, background: "var(--border)", margin: "4px 8px 8px" }} />}
            <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
              {g.items.map((it) => <NavLink key={it.id} item={it} active={route.screen === it.id} collapsed={collapsed} onClick={() => go(it.id)} />)}
            </div>
          </div>
        ))}
      </nav>

      {/* Sidebar Footer */}
      <div style={{ padding: collapsed ? "12px" : "14px", borderTop: "1px solid var(--border)" }}>
        <button
          onClick={() => setCollapsed(!collapsed)}
          className="btn-icon"
          style={{ width: "100%" }}
        >
          <Icon name={collapsed ? "chevronRight" : "chevronLeft"} size={16} />
        </button>
      </div>
    </aside>
  );
}

// Notification Dropdown Component
function NotificationDropdown({ notifications, onClose }) {
  return (
    <div className="dropdown" style={{
      position: "absolute", right: 0, top: "100%", marginTop: 8,
      width: 320, maxHeight: 400, overflowY: "auto",
      background: "var(--bg)", border: "1px solid var(--border)",
      borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)", zIndex: 50
    }}>
      <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h3 style={{ margin: 0 }}>Notifications</h3>
          <button onClick={onClose} className="btn-icon btn-sm">
            <Icon name="x" size={16} />
          </button>
        </div>
      </div>
      <div style={{ padding: "8px 0" }}>
        {notifications.slice(0, 5).map(notif => (
          <div key={notif.id} style={{
            padding: "12px 20px", display: "flex", gap: 12,
            background: notif.read ? "transparent" : "var(--surface-1)",
            borderLeft: notif.read ? "none" : "3px solid var(--accent)"
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8,
              display: "flex", alignItems: "center", justifyContent: "center",
              background: notif.type === "warning" ? "var(--orange-100)" :
                         notif.type === "success" ? "var(--green-100)" : "var(--blue-100)"
            }}>
              <Icon name={notif.type === "warning" ? "alertTriangle" :
                          notif.type === "success" ? "checkCircle" : "info"}
                    size={16}
                    color={notif.type === "warning" ? "var(--orange-600)" :
                           notif.type === "success" ? "var(--green-600)" : "var(--blue-600)"} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>{notif.title}</div>
              <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 4 }}>{notif.message}</div>
              <div style={{ fontSize: 12, color: "var(--text-faint)" }}>
                {new Date(notif.timestamp).toLocaleString()}
              </div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding: "12px 20px", borderTop: "1px solid var(--border)" }}>
        <button className="btn btn-sm" style={{ width: "100%" }}>View All Notifications</button>
      </div>
    </div>
  );
}

// User Dropdown Component
function UserDropdown({ user, onClose }) {
  const role = window.ADMIN_DATA.USER_ROLES[user?.role];

  return (
    <div className="dropdown" style={{
      position: "absolute", right: 0, top: "100%", marginTop: 8,
      width: 240, background: "var(--bg)", border: "1px solid var(--border)",
      borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)", zIndex: 50
    }}>
      <div style={{ padding: 16, borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
          <div className="avatar" style={{
            width: 40, height: 40, borderRadius: 10,
            background: role?.color + "40", color: role?.color,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontWeight: 600, fontSize: 14
          }}>
            {user?.initials}
          </div>
          <div>
            <div style={{ fontWeight: 600 }}>{user?.name}</div>
            <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{user?.email}</div>
          </div>
        </div>
        <span className="badge" style={{
          background: role?.color + "20",
          color: role?.color,
          fontWeight: 600, fontSize: 12
        }}>
          {role?.name}
        </span>
      </div>

      <div style={{ padding: "8px 0" }}>
        <button className="dropdown-item">
          <Icon name="user" size={16} />
          Profile Settings
        </button>
        <button className="dropdown-item">
          <Icon name="settings" size={16} />
          Preferences
        </button>
        <button className="dropdown-item">
          <Icon name="help" size={16} />
          Help & Support
        </button>
        <hr style={{ margin: "8px 16px", border: "none", height: 1, background: "var(--border)" }} />
        <button className="dropdown-item">
          <Icon name="logOut" size={16} />
          Sign Out
        </button>
      </div>
    </div>
  );
}

// Reuse existing Logo and NavLink components
function Logo({ collapsed, mono }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
      <span style={{
        width: 34, height: 34, borderRadius: 10, flex: "0 0 auto",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        background: "linear-gradient(150deg, var(--accent), var(--accent-strong))",
        color: "var(--accent-fg)", fontWeight: 800, fontSize: 18, letterSpacing: "-.03em",
        boxShadow: "var(--shadow-sm)",
      }}>M</span>
      {!collapsed && (
        <span style={{ fontWeight: 750, fontSize: 17, letterSpacing: "-.025em", color: mono ? "var(--sidebar-active-text)" : "var(--text)", whiteSpace: "nowrap" }}>
          Maintenance<span style={{ color: "var(--accent-strong)" }}>OS</span>
        </span>
      )}
    </div>
  );
}

function NavLink({ item, active, collapsed, onClick }) {
  const [h, setH] = useState(false);
  return (
    <div style={{ position: "relative" }}>
      <button
        onClick={onClick}
        onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{
          width: "100%", display: "flex", alignItems: "center", gap: 12,
          padding: collapsed ? "0" : "0 12px", height: 42,
          justifyContent: collapsed ? "center" : "flex-start",
          borderRadius: "var(--radius-sm)", cursor: "pointer", position: "relative",
          fontSize: 14, fontWeight: active ? 650 : 500, textAlign: "left",
          color: active ? "var(--sidebar-active-text)" : (h ? "var(--text)" : "var(--sidebar-text)"),
          background: active ? "var(--sidebar-active-bg)" : (h ? "color-mix(in oklch, var(--text) 6%, transparent)" : "transparent"),
          border: "1px solid transparent", transition: "background-color .15s ease, color .15s ease",
        }}>
        {active && !collapsed && <span style={{ position: "absolute", left: 0, top: 9, bottom: 9, width: 3, borderRadius: 99, background: "var(--accent)" }} />}
        <Icon name={item.icon} size={19} stroke={active ? 2.2 : 2} />
        {!collapsed && <span style={{ flex: 1, whiteSpace: "nowrap" }}>{item.label}</span>}
        {!collapsed && item.badge != null && (
          <span className="tnum" style={{ fontSize: 11.5, fontWeight: 700, color: active ? "var(--accent-fg)" : "var(--text-muted)", background: active ? "var(--accent)" : "var(--surface-3)", borderRadius: 99, padding: "1px 7px", minWidth: 20, textAlign: "center" }}>{item.badge}</span>
        )}
        {collapsed && item.badge != null && (
          <span style={{ position: "absolute", top: 6, right: 12, width: 7, height: 7, borderRadius: 99, background: "var(--accent)" }} />
        )}
      </button>
      {collapsed && h && (
        <span style={{ position: "absolute", left: "calc(100% + 12px)", top: "50%", transform: "translateY(-50%)", zIndex: 50,
          background: "var(--text)", color: "var(--bg)", fontSize: 12.5, fontWeight: 600, padding: "5px 10px",
          borderRadius: 7, whiteSpace: "nowrap", pointerEvents: "none", boxShadow: "var(--shadow-md)" }}>
          {item.label}{item.badge != null ? ` · ${item.badge}` : ""}
        </span>
      )}
    </div>
  );
}

// Export enhanced components
window.EnhancedShell = {
  Sidebar: EnhancedSidebar,
  Topbar: EnhancedTopbar,
  getNavigationForUser,
  navItem: (id) => {
    const allNav = getNavigationForUser().flatMap(g => g.items);
    return allNav.find(i => i.id === id) || { label: id };
  }
};