import "../css/admin.css";
import { createApp, h, type DefineComponent } from "vue";
import { createInertiaApp } from "@inertiajs/vue3";
import AdminLayout from "./Layouts/AdminLayout.vue";
import BadgeCell from "./components/ui/BadgeCell.vue";
import PermissionsInput from "./components/fields/PermissionsInput.vue";
import { registry } from "./registry";
import { loadModules } from "./loadModules";

type PageComponent = DefineComponent & { layout?: unknown };

// Register built-in cell components
registry.registerComponent("BadgeCell", BadgeCell);
registry.registerComponent("PermissionsInput", PermissionsInput);

// Load all external module packages before booting Inertia, so their
// components (widgets, field types, pages) are available on first render.
loadModules()
  .catch((e: unknown) => console.error("[Builder] Module loading failed:", e))
  .finally(() => {
    createInertiaApp({
      title: (title) => (title ? `${title} – Builder` : "Builder"),

      resolve: async (name: string): Promise<DefineComponent> => {
        // Check module registry for dynamically registered page components first
        const modulePage = registry.resolvePage(name);
        if (modulePage) {
          const page = modulePage as PageComponent;
          page.layout ??= AdminLayout;
          return page as DefineComponent;
        }

        // Fall back to built-in core pages
        // @ts-ignore
        const pages = import.meta.glob<{ default: PageComponent }>(
          "./Pages/**/*.vue",
        );
        const path = `./Pages/${name}.vue`;

        if (path in pages) {
          const module = await pages[path]();
          module.default.layout ??= AdminLayout;
          return module.default as DefineComponent;
        }

        throw new Error(`[Builder] Page component "${name}" not found.`);
      },

      setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
          .use(plugin)
          .mount(el);
      },

      progress: {
        color: "#6366f1",
      },
    });
  });
