const PAGE_REGISTRY_URL = "/pages.config.js?v=20260803-2";

function loadRuntimeScripts(sources) {
  return Promise.all(sources.map((src) => new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = src;
    script.async = false;
    script.addEventListener("load", resolve, { once: true });
    script.addEventListener("error", () => reject(new Error(`无法加载运行脚本：${src}`)), { once: true });
    document.body.append(script);
  })));
}

async function loadPageFragment(fragment) {
  const response = await fetch(fragment.url, { credentials: "same-origin" });
  if (!response.ok) {
    throw new Error(`无法加载页面片段：${fragment.url}（HTTP ${response.status}）`);
  }
  return response.text();
}

async function bootstrap() {
  await import(PAGE_REGISTRY_URL);
  const registry = window.XiaobaiPages;
  const mount = document.querySelector(".app-main");
  if (!registry || !mount) throw new Error("页面注册表或挂载点不存在");

  const fragments = await Promise.all(registry.fragments.map(loadPageFragment));
  fragments.forEach((markup) => mount.insertAdjacentHTML("beforeend", markup));
  await loadRuntimeScripts(registry.runtimeScripts);
  document.body.dataset.runtimeReady = "true";
}

bootstrap().catch((error) => {
  document.body.dataset.bootstrapError = "true";
  const status = document.querySelector("#statusText");
  if (status) status.textContent = error?.message || "页面初始化失败";
  setTimeout(() => { throw error; });
});
