import { createApp } from 'vue';
import App from './App.vue';
import './styles/home.css';

const root = document.querySelector('#app');
let vueApp = null;
let legacyLoading = null;

window.__EIS_VUE_SHELL__ = true;

function currentRoute() {
  return location.hash.slice(1) || 'home';
}

function isVueRoute(route) {
  return route === 'home';
}

function showLegacyBoot() {
  root.innerHTML = `
    <div class="hz-loading" role="status" aria-live="polite">
      <span class="hz-loading__seal" aria-hidden="true">衡</span>
      <strong>正在进入业务中心</strong>
      <small>请稍候</small>
    </div>`;
}

function loadLegacy() {
  if (legacyLoading) return legacyLoading;
  if (vueApp) {
    vueApp.unmount();
    vueApp = null;
  }
  showLegacyBoot();
  legacyLoading = import(/* @vite-ignore */ '/js/app.js?v=20260723-vue').catch(error => {
    console.error('Legacy application failed to load', error);
    root.innerHTML = '<main class="hz-failure"><span>服务提示</span><h1>业务中心暂时无法加载</h1><p>请刷新页面后重试。</p><button type="button" onclick="location.reload()">刷新页面</button></main>';
    throw error;
  });
  return legacyLoading;
}

function mountVue() {
  if (vueApp) return;
  root.innerHTML = '';
  vueApp = createApp(App);
  vueApp.mount(root);
}

function renderEntry() {
  if (isVueRoute(currentRoute())) mountVue();
  else loadLegacy();
}

window.addEventListener('hashchange', () => {
  const route = currentRoute();
  if (isVueRoute(route) && legacyLoading) {
    location.reload();
    return;
  }
  if (!isVueRoute(route) && !legacyLoading) loadLegacy();
});

renderEntry();
