const NAV_GROUPS = [
  {
    label: "Main",
    items: [
      { id: "dashboard", label: "Dashboard", icon: <Icons.dashboard/> },
      { id: "projects", label: "Projects", icon: <Icons.project/> },
      { id: "workItems", label: "Tasks & Subtasks", icon: <Icons.check/> },
      { id: "schedule", label: "Work Programme", icon: <Icons.schedule/> },
      { id: "quality", label: "Quality Control", icon: <Icons.quality/> },
      { id: "mindMap", label: "Mind Map", icon: <Icons.mindMap/> }
    ]
  },
  {
    label: "Operations",
    items: [
      { id: "fieldTeams", label: "Field Teams", icon: <Icons.users/> },
      { id: "procurement", label: "Procurement", icon: <Icons.cart/> },
      { id: "finance", label: "Finance", icon: <Icons.finance/> }
    ]
  },
  {
    label: "System",
    items: [
      { id: "settings", label: "Settings", icon: <Icons.settings/> },
      { id: "login", label: "Role Login", icon: <Icons.users/> }
    ]
  }
];

const NAV = NAV_GROUPS.flatMap((group) => group.items);

const SIDEBAR_COLLAPSED_KEY = "constructpro.sidebarCollapsed";

function readSidebarCollapsed() {
  try {
    return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === "1";
  } catch {
    return false;
  }
}

function Sidebar({ current, onNav, collapsed, onToggleCollapsed }) {
  return (
    <aside
      id="app-sidebar"
      className={`app-sidebar hidden shrink-0 flex-col bg-inverse-surface text-inverse-on-surface md:flex ${collapsed ? "app-sidebar--collapsed" : ""}`}
      aria-expanded={!collapsed}
    >
      <div className="app-sidebar__header border-b border-white/10">
        <button onClick={() => onNav("dashboard")} className="app-sidebar__brand" title="ConstructPro">
          <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary-container text-on-primary">
            <Icons.project size={24} active/>
          </span>
          <span className="app-sidebar__brand-copy">
            <span className="block text-lg font-bold text-white">ConstructPro</span>
            <span className="block text-[10px] font-bold uppercase tracking-widest text-inverse-on-surface/70">Site Operations</span>
          </span>
        </button>
        <button
          type="button"
          className="app-sidebar__toggle"
          onClick={onToggleCollapsed}
          aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
          title={collapsed ? "Expand sidebar" : "Collapse sidebar"}
        >
          {collapsed ? <Icons.panelRight size={20}/> : <Icons.panelLeft size={20}/>}
        </button>
      </div>
      <nav className="flex-1 overflow-y-auto py-4">
        {NAV_GROUPS.map((group) => (
          <div key={group.label} className="app-sidebar__group mb-5">
            <div className="app-sidebar__group-label mb-2 px-4 text-[10px] font-bold uppercase tracking-widest text-inverse-on-surface/60">{group.label}</div>
            <div className="space-y-1 px-3">
              {group.items.map((item) => {
                const active = current === item.id;
                return (
                  <button
                    key={item.id}
                    onClick={() => onNav(item.id)}
                    className={`app-sidebar__nav-item flex w-full items-center gap-3 rounded-lg border-l-4 px-3 py-2.5 text-left text-sm font-semibold transition-colors ${active ? "border-primary bg-white/10 text-white" : "border-transparent text-inverse-on-surface/75 hover:bg-white/5 hover:text-white"}`}
                    aria-current={active ? "page" : undefined}
                    title={collapsed ? item.label : undefined}
                  >
                    <span className="app-sidebar__nav-icon">{React.cloneElement(item.icon, { active })}</span>
                    <span className="app-sidebar__nav-label">{item.label}</span>
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </nav>
      <div className="app-sidebar__footer border-t border-white/10 p-4">
        <div className="app-sidebar__profile flex items-center gap-3">
          <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-white/10 font-bold text-white" title="Jai Deshmukh">JD</div>
          <div className="app-sidebar__profile-copy min-w-0">
            <p className="truncate text-sm font-bold text-white">Jai Deshmukh</p>
            <p className="truncate text-xs text-inverse-on-surface/70">Project Manager</p>
          </div>
        </div>
      </div>
    </aside>
  );
}

function Header({ current, onNav, snapshot }) {
  const title = NAV.find((item) => item.id === current)?.label || "Dashboard";
  const project = snapshot.project;
  const activeAlerts = (snapshot.alerts || []).filter((alert) => ["active", "submitted", "escalated"].includes(alert.status)).length;
  const projectMeta = [project.code, project.name, project.location].filter(Boolean).join(" · ");

  return (
    <header className="m3-top-app-bar sticky top-0 z-40">
      <div className="m3-top-app-bar__row">
        <div className="m3-top-app-bar__text min-w-0 flex-1">
          <h1 className="m3-top-app-bar__title truncate">{title}</h1>
          <p className="m3-top-app-bar__subtitle truncate" title={projectMeta}>{projectMeta}</p>
        </div>
        <button
          type="button"
          onClick={() => onNav("fieldTeams")}
          className={`m3-icon-button m3-icon-button--tonal ${activeAlerts ? "m3-icon-button--badge" : ""}`}
          aria-label={`${activeAlerts} active alerts`}
          data-badge={activeAlerts || undefined}
        >
          <Icons.bell size={24}/>
        </button>
      </div>
    </header>
  );
}

const MOBILE_PRIMARY_NAV_ITEMS = [
  { id: "dashboard", label: "Home", icon: Icons.dashboard },
  // Mind Map is desktop-only on phones
  { id: "projects", label: "Project", icon: Icons.project },
  { id: "workItems", label: "Tasks", icon: Icons.check },
  { id: "fieldTeams", label: "Alerts", icon: Icons.bell }
];

const MOBILE_OVERFLOW_NAV_ITEMS = [
  { id: "schedule", label: "Work Programme", icon: Icons.schedule },
  { id: "quality", label: "Quality Control", icon: Icons.quality },
  { id: "procurement", label: "Procurement", icon: Icons.cart },
  { id: "finance", label: "Finance", icon: Icons.finance },
  { id: "settings", label: "Settings", icon: Icons.settings },
  { id: "login", label: "Role Login", icon: Icons.users }
];

function MobileNav({ current, onNav }) {
  const [showMore, setShowMore] = React.useState(false);
  const overflowActive = MOBILE_OVERFLOW_NAV_ITEMS.some((item) => item.id === current);
  const mobileNavItems = [
    ...MOBILE_PRIMARY_NAV_ITEMS,
    { id: "__more__", label: "More", icon: Icons.settings, isMore: true }
  ];

  React.useEffect(() => {
    if (showMore) setShowMore(false);
  }, [current]);

  return (
    <>
      <nav className="m3-navigation-bar mobile-web-nav" aria-label="Primary mobile navigation">
        {mobileNavItems.map((item) => {
          const active = item.isMore ? overflowActive : current === item.id;
          const handleClick = () => {
            if (item.isMore) {
              setShowMore(true);
              return;
            }
            onNav(item.id);
          };
          const Icon = item.icon;
          return (
            <button
              key={item.id}
              type="button"
              className={`m3-navigation-bar__destination ${active ? "is-active" : ""}`}
              onClick={handleClick}
              aria-current={active ? "page" : undefined}
            >
              <span className="m3-navigation-bar__indicator" aria-hidden="true"/>
              <span className="m3-navigation-bar__icon">
                <Icon size={24} active={active}/>
              </span>
              <span className="m3-navigation-bar__label">{item.label}</span>
            </button>
          );
        })}
      </nav>

      <MobileSheet
        open={showMore}
        onClose={() => setShowMore(false)}
        title="More"
        subtitle="Quick access to remaining admin sections"
      >
        <div className="space-y-2">
          {MOBILE_OVERFLOW_NAV_ITEMS.map((item) => {
            const active = current === item.id;
            const Icon = item.icon;
            return (
              <button
                key={item.id}
                type="button"
                onClick={() => {
                  onNav(item.id);
                  setShowMore(false);
                }}
                className={`w-full rounded-xl border px-3 py-3 text-left transition-colors ${active ? "border-primary bg-primary-fixed/40 text-primary" : "border-border-light bg-white text-text-primary hover:bg-gray-50"}`}
              >
                <span className="flex items-center gap-3">
                  <span><Icon size={20} active={active}/></span>
                  <span className="text-sm font-semibold">{item.label}</span>
                </span>
              </button>
            );
          })}
        </div>
      </MobileSheet>
    </>
  );
}

function Shell({ current, onNav, snapshot, children }) {
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(readSidebarCollapsed);

  const toggleSidebar = () => {
    setSidebarCollapsed((current) => {
      const next = !current;
      try {
        localStorage.setItem(SIDEBAR_COLLAPSED_KEY, next ? "1" : "0");
      } catch {
        // ignore storage failures
      }
      return next;
    });
  };

  return (
    <div className="flex h-screen overflow-hidden bg-background text-on-background">
      <Sidebar current={current} onNav={onNav} collapsed={sidebarCollapsed} onToggleCollapsed={toggleSidebar}/>
      <main data-app-scroll className="m3-mobile-scaffold min-w-0 flex-1 overflow-y-auto md:pb-0">
        <Header current={current} onNav={onNav} snapshot={snapshot}/>
        <div className="m3-mobile-content p-4 md:p-6 lg:p-8">
          {children}
        </div>
      </main>
      <MobileNav current={current} onNav={onNav}/>
    </div>
  );
}

Object.assign(window, { Shell });
