import "@/styles/index.scss";
import "splitpanes/dist/splitpanes.css";
// dayjs国际化文件
import "dayjs/locale/zh-cn";
import "dayjs/locale/zh-hk";
import "dayjs/locale/en";
import "dayjs/locale/ar";
import "dayjs/locale/id";


import type { App as TypeApp } from "vue";
import {
  RouterHistory,
  Router as TypeRouter,
} from "vue-router";
import { initDevAuth } from "./devAuth";
import { prepare, type PrepareContext } from "./prepare";
import { bootstrap } from "./bootstrap.js";


declare const window: Window & Record<string, any>;
let app: TypeApp | undefined = undefined;
let router: TypeRouter | undefined = undefined;
let history: RouterHistory | undefined = undefined;
const appName = import.meta.env.VITE_APP_NAME;

const preparePromise: Promise<PrepareContext> = prepare();

async function render(props: any = {}) {
  const { routerHistory } = props ?? {};
  const { appContext, appName: receiveAppName } = window.$wujie?.props ?? {};

  let base = 'child';

  let parentPath: string | undefined = (window as any).top._APP_OPTIONS_?.appContext as string;
  if (receiveAppName === 'user-workspace') {
    base = 'apps';
    parentPath = (window as any).top?.__XINPLAT_CONFIG__.PLAT_BASE_PATH as string;
    if (parentPath && !parentPath.endsWith('/')) {
      parentPath = `${parentPath}/`
    }
  }
  const baseURL =
    import.meta.env.DEV && window.__POWERED_BY_WUJIE__
      ? import.meta.env.VITE_APP_BASE_API
      : (appContext ??
        parentPath ??
        import.meta.env.VITE_APP_BASE_API ??
        "/");
  ({
    app,
    router,
    history,
  } = await bootstrap(
    baseURL,
    preparePromise,
    base,
    routerHistory,
  ));
  if (import.meta.env.DEV) {
    await initDevAuth(router);
  }
}
function mount() {
  console.log("%c%s", "color: blue;", `${appName} app mount`);
  render().catch((err) => {
    console.error(`[${appName}] mount failed`, err);
  });
}

function unmount() {
  console.log("%c%s", "color: blue;", `${appName} app unmount`);
  // -- 安全网：销毁可能残留的所有 ag-Grid 实例 --
  document.querySelectorAll('#sub-app .ag-root').forEach(el => {
    const gridEl: any = el.closest('[grid-id]');
    if (gridEl?.gridInstance) {
      try { gridEl.gridInstance.destroy(); } catch { }
    }
  });
  // 1. 销毁 Vue 应用（彻底释放响应式系统）
  if (app) {
    // 先停止所有 effect 作用域，确保 Dep、ReactiveEffect、ComputedRefImpl 可被 GC
    //@ts-ignore
    app._instance?.scope?.stop?.();
    app.unmount();
    app = undefined;
  }

  // 2. 销毁 router（清理路由守卫和 history 监听）
  if (router) {
    router.options?.history?.destroy?.();
    router = undefined;
  }

  // 3. 清理 OTel（停止 span 处理器和 fetch/XMLHttpRequest 插桩）
  if ((window as any).__OTEL_PROVIDER__) {
    (window as any).__OTEL_PROVIDER__.shutdown?.().catch?.()?.();
    delete (window as any).__OTEL_PROVIDER__;
  }

  // 4. 清理 Module Federation 缓存
  const mf = globalThis.__FEDERATION__?.__INSTANCES__?.[0];
  if (mf) {
    mf.moduleCache.clear();
    mf.snapshotHandler?.manifestCache?.clear?.();
    //@ts-ignore
    if (mf?.moduleCacheMap) mf.moduleCacheMap.clear();
  }

  // 5. 清理全局 Vue 相关状态
  window.__VUE_DEVTOOLS_PLUGINS__ = [];
  window.__VUE_INSTANCE_SETTERS__ = [];

  // 6. 清理 wujie 标记
  if (window.__POWERED_BY_WUJIE__) {
    //@ts-ignore
    delete window.__WUJIE_MOUNT;
    //@ts-ignore
    delete window.__WUJIE_UNMOUNT;
  }
}
if (window.__POWERED_BY_WUJIE__) {
  window.__WUJIE_MOUNT = mount;
  window.__WUJIE_UNMOUNT = unmount;
  //@ts-ignore
  window.__WUJIE.mount();
} else {
  render().catch(console.error);
}

console.log(
  `%c===================================================`,
  "color:green",
);
console.log(`%capp name: %c${appName}`, "color: blue", "color:red");
// console.log(`%cversion: %c${appVersion}`, "color: blue", "color:red");
console.log(
  `%cversion: %c${new URL(window.location.href).searchParams.get("ver") ?? ""}`,
  "color: blue",
  "color:red",
);
console.log(
  `%cbuild time: %c${process.env.BUILD_TIMESTAMP}`,
  "color: blue",
  "color:red",
);
console.log(
  `%c===================================================`,
  "color:green",
);
