import { registry } from "./registry";

type ModuleManifest = {
  modules: Array<{ key: string; label: string | null; entry: string }>;
};

type ModuleExport = {
  register?: (
    registry: typeof import("./registry").registry,
    ctx: { key: string },
  ) => void;
};

export async function loadModules(): Promise<void> {
  let manifest: ModuleManifest;

  const prefix =
    (
      document.querySelector(
        'meta[name="builder-prefix"]',
      ) as HTMLMetaElement | null
    )?.content ?? "admin";

  try {
    const res = await fetch(`/${prefix}/modules/manifest.json`, {
      headers: { Accept: "application/json" },
    });

    if (!res.ok) {
      // No modules registered — that's fine
      return;
    }

    manifest = (await res.json()) as ModuleManifest;
  } catch {
    // Network error or no modules endpoint — continue without modules
    return;
  }

  for (const mod of manifest.modules) {
    try {
      // Modules are loaded via import maps; Vue and @builder/ui are shared
      const m = (await import(/* @vite-ignore */ mod.entry)) as ModuleExport;
      m.register?.(registry, { key: mod.key });
    } catch (e: unknown) {
      console.error(`[Builder] Failed loading module "${mod.key}":`, e);
    }
  }
}
