import { AdminShell, type DbMenuItem } from "@gsc/web-kit/chrome";
import sidebarMenuJson from "@/config/sidebar-menu.json";
import { getAuthenticatedUser, requireAuth } from "@/auth";
import { brand } from "@/config/brand";
import ActiveGrantsWidget from "@/components/pam/ActiveGrantsWidget";

type LegacySidebarItem = {
  id: number;
  icon?: string;
  name: string;
  url: string;
  key: string;
  submenulvl1?: { name: string; url: string; key: string; icon?: string }[];
};

// Map the legacy JSON-driven sidebar onto the kit's DbMenuItem shape.
// (When gscMy gets its own admin.menu_items rows we can drop the JSON
// and load from DB the same way gscAdmin does.)
function toDbMenuItem(item: LegacySidebarItem, order: number): DbMenuItem {
  return {
    id: String(item.id),
    key: item.key,
    translationKey: item.key,
    url: item.url,
    icon: item.icon ?? null,
    sortOrder: order,
    isActive: true,
    isSystemRequired: false,
    children:
      item.submenulvl1?.map((c, i) => ({
        id: `${item.id}.${i + 1}`,
        key: c.key,
        translationKey: c.key,
        url: c.url,
        icon: c.icon ?? null,
        sortOrder: i,
        isActive: true,
        isSystemRequired: false,
      })) ?? [],
  };
}

const sidebar = (sidebarMenuJson as LegacySidebarItem[]).map(toDbMenuItem);

export default async function MyGroupLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  await requireAuth();
  const user = await getAuthenticatedUser();

  return (
    <AdminShell
      menus={{ sidebar, topbar: [], subbar: [] }}
      apps={[]}
      user={{
        displayName: user?.displayName || user?.email || "",
        email: user?.email ?? "",
      }}
      brand={brand}
      features={{
        chat: false,
        activityPanel: false,
      }}
      slots={{
        navbarExtras: <ActiveGrantsWidget />,
      }}
    >
      {children}
    </AdminShell>
  );
}
