/* 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";
// 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);

  return new Promise((resolve) => {
    function createWindow() {
      logger.debug("Creating browser window...");
      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:
            process.env.NODE_ENV === "development"
              ? path.join(__dirname, "preload.js")
              : path.join(__dirname, "..", "build", "electron", "preload.js"),
        },
      });

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

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

      // Resolve the promise when the window is ready
      win.webContents.on("did-finish-load", () => {
        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();
    });
  });
}
