import path from "node:path";
import { fileURLToPath } from "node:url";
import { app, BrowserWindow, shell } from "electron";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const defaultGodotRoot = "/Users/jason/Projects/anime-fighter-pro";
let serverHandle = null;
let mainWindow = null;
let quitting = false;
let startServerFn = null;

function isLocalUrl(url) {
  return Boolean(serverHandle) && url.startsWith(`http://127.0.0.1:${serverHandle.port}`);
}

async function stopServer() {
  if (!serverHandle?.server) {
    return;
  }
  const activeServer = serverHandle.server;
  serverHandle = null;
  await new Promise((resolve) => activeServer.close(resolve));
}

async function ensureServer() {
  if (!startServerFn) {
    ({ startServer: startServerFn } = await import("../src/server.js"));
  }
  if (!serverHandle) {
    serverHandle = await startServerFn({ port: 0 });
  }
}

async function createMainWindow() {
  process.env.SSB_ADMIN_DATA_ROOT = path.join(app.getPath("userData"), "runtime");
  process.env.SSB_GODOT_ROOT = process.env.SSB_GODOT_ROOT || defaultGodotRoot;

  await ensureServer();

  mainWindow = new BrowserWindow({
    width: 1500,
    height: 980,
    minWidth: 1180,
    minHeight: 760,
    title: "Anime Fighter Pro Organizer",
    backgroundColor: "#eef2f7",
    autoHideMenuBar: true,
    show: false,
    webPreferences: {
      contextIsolation: true,
      sandbox: true,
    },
  });

  mainWindow.on("ready-to-show", () => {
    mainWindow?.show();
  });

  mainWindow.on("closed", () => {
    mainWindow = null;
  });

  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    if (isLocalUrl(url)) {
      return { action: "allow" };
    }
    shell.openExternal(url);
    return { action: "deny" };
  });

  mainWindow.webContents.on("will-navigate", (event, url) => {
    if (!isLocalUrl(url)) {
      event.preventDefault();
      shell.openExternal(url);
    }
  });

  await mainWindow.loadURL(`http://127.0.0.1:${serverHandle.port}/admin`);
}

const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
  app.quit();
} else {
  app.on("second-instance", () => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) {
        mainWindow.restore();
      }
      mainWindow.focus();
    }
  });

  app.whenReady().then(async () => {
    await createMainWindow();

    app.on("activate", async () => {
      if (!BrowserWindow.getAllWindows().length) {
        await createMainWindow();
      }
    });
  });

  app.on("before-quit", async (event) => {
    if (quitting) {
      return;
    }
    event.preventDefault();
    quitting = true;
    await stopServer();
    app.quit();
  });

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