import { IonicVue } from "@ionic/vue";
import { createPinia } from "pinia";
import { useRegisterSW } from "virtual:pwa-register/vue";
import { createApp } from "vue";
import uiComponents from "@/ui";
import App from "./App.vue";
import { authClient } from "./auth";
import { i18n } from "./locales";
import { setupMocks } from "./mocks";
import { router } from "./router";

/* Core CSS required for Ionic components to work properly */
import "@ionic/vue/css/core.css";
/* Basic CSS for apps built with Ionic */
import "@ionic/vue/css/normalize.css";
import "@ionic/vue/css/structure.css";

import "@ionic/vue/css/typography.css";
/* Optional CSS utils that can be commented out */
import "@ionic/vue/css/padding.css";
import "@ionic/vue/css/float-elements.css";
import "@ionic/vue/css/text-alignment.css";
import "@ionic/vue/css/text-transformation.css";
import "@ionic/vue/css/flex-utils.css";

/**
 * Ionic Dark Mode
 * -----------------------------------------------------
 * For more info, please see:
 * https://ionicframework.com/docs/theming/dark-mode
 */

import "@ionic/vue/css/display.css";
// import "@ionic/vue/css/palettes/dark.system.css";

// import "@ionic/vue/css/palettes/dark.always.css";
import "@ionic/vue/css/palettes/dark.class.css";
/* Theme variables */
import "./theme/index.css";
import "./theme/variables.css";
import "./theme/ionic.css";

useTheme();

// 注册 PWA Service Worker（使用 Vue 3 Composition API）
const { offlineReady, needRefresh, updateServiceWorker } = useRegisterSW({
  onRegistered(registration) {
    console.log("[PWA] Service Worker registered:", registration);
  },
  onRegisterError(error) {
    console.error("[PWA] Service Worker registration failed:", error);
  },
  immediate: true,
});

// 监听 PWA 状态
watch(offlineReady, (ready) => {
  if (ready) {
    console.log("[PWA] App ready to work offline.");
  }
});

watch(needRefresh, (refresh) => {
  if (refresh) {
    console.log("[PWA] New content available, please refresh.");
  }
});

function initTradingView() {
  const { VITE_TRADINGVIEW_LIBRARY_URL } = useEnv();
  const promise1 = new Promise((resolve) => {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = `${VITE_TRADINGVIEW_LIBRARY_URL}/charting_library/charting_library.standalone.js`;
    script.async = true;
    document.body.appendChild(script);
    script.onload = () => resolve(true);
  });
  const promise2 = new Promise((resolve) => {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = `${VITE_TRADINGVIEW_LIBRARY_URL}/datafeeds/udf/bundle.js`;
    script.async = true;
    document.body.appendChild(script);
    script.onload = () => resolve(true);
  });
  return Promise.all([promise1, promise2]);
}

function initApp() {
  initTradingView().then(() => {
    authClient.getSession().then((session) => {
      const pinia = createPinia();
      const userStore = useUserStore(pinia);
      userStore.setToken(session.data?.session.token || "");

      const app = createApp(App)
        .use(IonicVue, {
          backButtonText: "返回",
          mode: "ios",
          statusTap: true,
          swipeBackEnabled: true,
        // rippleEffect: true,
        // animated: false,
        })
        .use(uiComponents)
        .use(pinia)
        .use(router)
        .use(i18n);

      router.isReady().then(() => {
        app.mount("#app");
      });
    });
  });
}

setupMocks().then(() => {
  initApp();
});
