const settings = window.settings || {};
const assetNonce = window.__ADMIN_ASSET_NONCE__ || String(Date.now());
const securePath = String(settings.secure_path || "admin").replace(/^\/+/, "");
const adminBase = `/api/v2/${securePath}`;

window.ADMIN_APP_CONFIG = {
  title: settings.title || "XBoard Admin",
  version: settings.version || "1.0.0",
  securePath,
  baseUrl: settings.base_url || window.location.origin,
  api: {
    adminBase,
    adminConfig: `${adminBase}/config/fetch`,
    dashboardSummary: `${adminBase}/dashboard/summary`,
    systemStatus: `${adminBase}/system/getSystemStatus`,
    serverNodes: `${adminBase}/server/manage/getNodes`,
    serverGroups: `${adminBase}/server/group/fetch`,
    serverRoutes: `${adminBase}/server/route/fetch`,
    plans: `${adminBase}/plan/fetch`,
    orders: `${adminBase}/order/fetch`,
    coupons: `${adminBase}/coupon/fetch`,
    users: `${adminBase}/user/fetch`,
    tickets: `${adminBase}/ticket/fetch`,
    realnameBase: `${adminBase}/realname`,
    onlineDevices: `${adminBase}/user-online-devices/users`,
    ipv6Base: `${adminBase}/user-add-ipv6-subscription`,
  },
};

document.documentElement.dataset.adminExecutionMode = "main-app";

function showBootError(error) {
  console.error("Failed to boot admin app", error);
  const root = document.getElementById("admin-app");
  if (root) {
    root.innerHTML =
      `<div style="padding:24px;font-family:system-ui,sans-serif;color:#b91c1c;">Admin app failed to load.<br>${String(
        error && error.message ? error.message : error || "Unknown error",
      )}</div>`;
  }
}

window.addEventListener("error", (event) => {
  if (!event || !event.error) {
    return;
  }
  showBootError(event.error);
});

const script = document.createElement("script");
script.src = `/admin-assets/app.js?v=${encodeURIComponent(assetNonce)}`;
script.defer = true;
script.onerror = () => showBootError(new Error("Failed to load /admin-assets/app.js"));
document.body.appendChild(script);
