/**
 * @file Electron Main Entry Point
 * @author Matthew Raymer
 *
 * This file initializes the TimeSafari application for the Electron desktop platform.
 * It provides the main entry point for the Electron renderer process and handles
 * platform-specific initialization and configuration.
 *
 * Electron-Specific Features:
 * - Desktop platform service initialization
 * - Electron-specific error handling
 * - Desktop UI optimizations
 * - Native desktop integrations
 *
 * Integration Points:
 * - Electron main process communication
 * - Desktop file system access
 * - Native OS integration
 * - Platform-specific services
 *
 * Type Safety:
 * - Uses ElectronPlatformService for desktop-specific functionality
 * - Ensures type safety across Electron renderer and main processes
 * - Maintains compatibility with Capacitor-Electron plugins
 *
 * @example
 * // Electron renderer process initialization
 * // Automatically detects Electron environment
 * // Provides desktop-optimized user experience
 */

import { initializeApp } from "./main.common";
import { handleApiError } from "./services/api";
import { logger } from "./utils/logger";

// **CRITICAL**: Disable any existing service workers that might intercept API calls
// Service workers from web sessions can persist and cause issues in Electron
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
navigator.serviceWorker
  ?.getRegistrations()
  .then(function (registrations) {
    for (const registration of registrations) {
      logger.debug(
        "[Electron] Unregistering service worker:",
        registration.scope,
      );
      registration.unregister();
    }
    if (registrations.length > 0) {
      logger.log(
        "[Electron] Cleaned up",
        registrations.length,
        "service worker registrations",
      );
    }
  })
  .catch((error) => {
    logger.debug("[Electron] Service worker cleanup failed:", error);
  });

logger.log("[Electron] Starting initialization");
logger.log("[Electron] Platform:", process.env.VITE_PLATFORM);

// Verify we're running in the correct platform environment
if (process.env.VITE_PLATFORM !== "electron") {
  logger.warn(
    "[Electron] Platform mismatch - expected 'electron', got:",
    process.env.VITE_PLATFORM,
  );
}

const app = initializeApp();

// Initialize API error handling for unhandled promise rejections
window.addEventListener("unhandledrejection", (event) => {
  if (event.reason?.response) {
    handleApiError(event.reason, event.reason.config?.url || "unknown");
  }
});

// Electron-specific initialization
if (typeof window !== "undefined" && typeof window.require === "function") {
  // We're in an Electron renderer process
  logger.log("[Electron] Detected Electron renderer process");

  // **CRITICAL FIX**: Disable any existing service worker that might be intercepting API calls
  try {
    if (navigator.serviceWorker?.getRegistrations) {
      navigator.serviceWorker
        .getRegistrations()
        .then(function (registrations) {
          for (const registration of registrations) {
            logger.log(
              "[Electron] Unregistering service worker:",
              registration.scope,
            );
            registration.unregister();
          }
        })
        .catch((error) => {
          logger.log("[Electron] Failed to unregister service workers:", error);
        });
    }
  } catch (error) {
    logger.log("[Electron] Service worker cleanup not available:", error);
  }

  // Add any Electron-specific initialization here
  // For example, IPC communication setup, desktop-specific features, etc.
}

logger.log("[Electron] Mounting app");
app.mount("#app");
logger.log("[Electron] App mounted");

// Add Electron-specific cleanup on beforeunload
window.addEventListener("beforeunload", () => {
  logger.log("[Electron] App unloading");
});
