import { createPinia } from "pinia";
import { App as VueApp, ComponentPublicInstance, createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import axios from "axios";
import VueAxios from "vue-axios";
import Notifications from "notiwind";
import "./assets/styles/tailwind.css";
import { FontAwesomeIcon } from "./libs/fontawesome";
import Camera from "simple-vue-camera";
import { logger } from "./utils/logger";

// const platform = process.env.VITE_PLATFORM;
// const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";

// Global Error Handler
function setupGlobalErrorHandler(app: VueApp) {
  app.config.errorHandler = (
    err: unknown,
    instance: ComponentPublicInstance | null,
    info: string,
  ) => {
    logger.error("[App Error] Global Error Handler:", {
      error: err,
      info,
      component: instance?.$options.name || "unknown",
    });
    alert(
      (err instanceof Error ? err.message : "Something bad happened") +
        " - Try reloading or restarting the app.",
    );
  };
}

// Function to initialize the app
export function initializeApp() {
  const app = createApp(App);
  app.component("FontAwesome", FontAwesomeIcon).component("camera", Camera);
  const pinia = createPinia();
  app.use(pinia);
  app.use(VueAxios, axios);
  app.use(router);
  app.use(Notifications);
  setupGlobalErrorHandler(app);
  return app;
}
