/* eslint-disable no-undef */
// Remove CommonJS requires and use ES module imports
import path from "path";
import { loadConfig } from "../config.js";
import log4js from "log4js";
import { fileURLToPath } from "url";
import { startWaiting, stopWaiting } from "../spinner.js";
// Load configuration
const config = loadConfig();

const logger = log4js.getLogger("Electron");
logger.level = config.logLevel;

export async function createElectronWindow() {
  // Only import Electron if we're in an Electron environment
  let app, BrowserWindow;
  try {
    const electron = (await import("electron")).default;
    app = electron.app;
    BrowserWindow = electron.BrowserWindow;
    logger.trace("Imported electron");
  } catch (error) {
    logger.warn(
      "Electron not available, skipping window creation. Error:",
      error,
    );
    return;
  }

  // Only proceed if we have app
  if (!app) {
    logger.warn("Electron app not available, skipping window creation");
    return;
  }

  // __dirname workaround for ES modules
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);

  // Determine if we are running from the build directory or src
  const isRunningFromBuild =
    __dirname.includes(path.sep + "build") || __dirname.includes("app.asar");

  return new Promise((resolve) => {
    function createWindow() {
      logger.debug("Creating browser window...");

      // Resolve paths correctly based on environment
      const preloadPath =
        process.env.NODE_ENV === "development"
          ? path.join(__dirname, "preload.js")
          : isRunningFromBuild
            ? path.join(__dirname, "preload.js")
            : path.join(__dirname, "..", "build", "electron", "preload.js");

      const win = new BrowserWindow({
        width: 900,
        height: 600,
        resizable: true,
        frame: false,
        titleBarStyle: "hiddenInset",
        trafficLightPosition: { x: 14, y: 12 },
        webPreferences: {
          nodeIntegration: true,
          contextIsolation: true,
          preload: preloadPath,
        },
      });

      // Make the window globally accessible for IPC
      global.mainWindow = win;

      logger.info("Preload Script", preloadPath);
      if (process.env.NODE_ENV === "development") {
        startWaiting("Loading development url...", logger);
        win.loadURL("http://localhost:5287"); // Vite dev server
      } else {
        // In production, the built files will be in the build/electron directory
        const htmlPath = isRunningFromBuild
          ? path.join(__dirname, "index.html")
          : path.join(__dirname, "..", "build", "electron", "index.html");

        startWaiting("Loading production file...", logger);
        logger.info("Loading production file:", htmlPath);
        win.loadFile(htmlPath);
      }

      // Resolve the promise when the window is ready
      win.webContents.on("did-finish-load", async () => {
        await stopWaiting();
        resolve(win);
      });
    }

    app.whenReady().then(() => {
      createWindow();

      app.on("activate", function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
      });
    });

    app.on("window-all-closed", function () {
      if (process.platform !== "darwin") app.quit();
    });
  });
}
