"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateAdminSidebar = generateAdminSidebar;
const Generator = __importStar(require("@postxl/generator"));
const utils_1 = require("../utils");
/**
 * Generator function that generates the shared Admin sidebar component
 */
function generateAdminSidebar({ context }) {
    const imports = Generator.ImportGenerator
        //
        .from(Generator.toBackendModuleLocation('@ui/admin/AdminSidebar'))
        .addImport({
        from: Generator.toPackageName('react'),
        items: [Generator.toFunctionName('ComponentProps')],
    })
        .addImport({
        from: Generator.toPackageName('lucide-react'),
        items: [Generator.toFunctionName('ChevronRight'), Generator.toFunctionName('Home')],
    });
    const { schemas: sortedSchemas, modelsBySchema } = (0, utils_1.groupAndSortModelsBySchema)(context);
    // Generate schema keys for collapse state (lowercase for valid JS identifiers)
    const schemaKeys = sortedSchemas.map((schema) => schema.toLowerCase());
    // Generate the CollapseState type properties
    const collapseStateTypeProps = [...schemaKeys, 'advanced'].map((key) => `  ${key}: boolean`).join('\n');
    // Generate the defaultCollapseState properties
    const defaultCollapseStateProps = [...schemaKeys, 'advanced'].map((key) => `  ${key}: true,`).join('\n');
    // Generate the schema sections
    const schemaSections = sortedSchemas
        .map((schema) => {
        const models = modelsBySchema.get(schema);
        const modelLinks = models
            .map((model) => `
            <SidebarMenuSubItem key="${model.name}">
              <SidebarMenuSubButton asChild>
                <Link
                  to="${model.route}"
                  className="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors"
                >
                  ${model.userFriendlyName}
                </Link>
              </SidebarMenuSubButton>
            </SidebarMenuSubItem>
          `)
            .join('');
        const schemaKey = schema.toLowerCase();
        return `
        <Collapse open={collapseState.${schemaKey}} onOpenChange={setOpen('${schemaKey}')} className="group/collapsible-${schemaKey}" key="${schemaKey}">
          <SidebarGroup>
            <SidebarGroupLabel asChild>
              <CollapseTrigger asChild>
                <SidebarMenuButton>
                  ${schema}
                  <ChevronRight className="ml-auto transition-transform group-data-[state=open]/collapsible-${schemaKey}:rotate-90" />
                </SidebarMenuButton>
              </CollapseTrigger>
            </SidebarGroupLabel>

            <CollapseContent>
              <SidebarGroupContent>
                <SidebarMenuSub>
                    ${modelLinks}
                </SidebarMenuSub>
              </SidebarGroupContent>
            </CollapseContent>
          </SidebarGroup>
        </Collapse>`;
    })
        .join('');
    return `
import { Link } from '@tanstack/react-router'
import useSessionStorageState from 'use-session-storage-state'
import {
  Collapse,
  CollapseContent,
  CollapseTrigger,
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
} from '@postxl/ui-components'
${imports.generate()}

const STORAGE_KEY = 'admin-sidebar-collapse-state'

type CollapseState = {
${collapseStateTypeProps}
}

const defaultCollapseState: CollapseState = {
${defaultCollapseStateProps}
}

export function AdminSidebar({ ...props }: ComponentProps<typeof Sidebar>) {
  const [collapseState, setCollapseState] = useSessionStorageState<CollapseState>(STORAGE_KEY, {
    defaultValue: defaultCollapseState,
  })

  const setOpen = (key: keyof CollapseState) => (open: boolean) => {
    setCollapseState((prev) => ({ ...prev, [key]: open }))
  }
  
  return (
    <Sidebar className="h-svh border-r" {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton asChild>
              <Link to="/admin" className="hover:text-sidebar-primary transition-colors">
                <Home size={16} className="mr-2" />
                <span className="text-lg font-bold">Admin</span>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>

      <SidebarContent>
        ${schemaSections}
        
        {import.meta.env.VITE_PUBLIC_ALLOW_ADMIN === 'true' && (
          <Collapse open={collapseState.advanced} onOpenChange={setOpen('advanced')} className="group/collapsible-advanced">
            <SidebarGroup>
              <SidebarGroupLabel asChild>
                <CollapseTrigger asChild>
                  <SidebarMenuButton>
                    Advanced
                    <ChevronRight className="ml-auto transition-transform group-data-[state=open]/collapsible-advanced:rotate-90" />
                  </SidebarMenuButton>
                </CollapseTrigger>
              </SidebarGroupLabel>

              <CollapseContent>
                <SidebarGroupContent>
                  <SidebarMenuSub>
                    <SidebarMenuSubItem key="DataManagement">
                      <SidebarMenuSubButton asChild>
                        <Link
                          to="/admin/data-management"
                          className="block px-4 py-2 hover:bg-sidebar-accent rounded transition-colors"
                        >
                          Data Management
                        </Link>
                      </SidebarMenuSubButton>
                    </SidebarMenuSubItem>
                  </SidebarMenuSub>
                </SidebarGroupContent>
              </CollapseContent>
            </SidebarGroup>
          </Collapse>
        )}
      </SidebarContent>
    </Sidebar>
  )
}
`;
}
//# sourceMappingURL=admin-sidebar.generator.js.map