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

import "./dayjs";
/* 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";

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

import "@ionic/vue/css/flex-utils.css";
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";
import "@/theme/index.css";

// 注册 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.");
  }
});

if (import.meta.env.DEV) {
  const vConsole = new VConsole();
  globalThis.vConsole = vConsole;
  console.log("VConsole is enabled in development mode.");
}

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(pinia)
    .use(router)
    .use(i18n);

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