import { BrowserWindow, Menu, app } from "electron";
import path from "node:path";
import { pathToFileURL } from "node:url";

export function resolveRendererEntry(): string {
  if (!app.isPackaged) {
    return process.env.QJCLAW_RENDERER_URL ?? process.env.VITE_DEV_SERVER_URL ?? "http://127.0.0.1:5173";
  }

  return path.join(app.getAppPath(), "dist", "renderer", "index.html");
}

function buildApplicationMenu(): Menu {
  const appName = app.getName();
  return Menu.buildFromTemplate([
    {
      label: appName,
      submenu: [
        { role: "about", label: `About ${appName}` },
        { type: "separator" },
        { role: "quit", label: `Quit ${appName}`, accelerator: "Cmd+Q" }
      ]
    },
    {
      label: "Edit",
      submenu: [
        { role: "copy", accelerator: "Cmd+C" },
        { role: "paste", accelerator: "Cmd+V" },
        { role: "selectAll", accelerator: "Cmd+A" }
      ]
    },
    {
      label: "Window",
      submenu: [
        { role: "minimize", accelerator: "Cmd+M" },
        { role: "close", accelerator: "Cmd+W" }
      ]
    }
  ]);
}

export function createMainWindow(smokeEnabled = false): BrowserWindow {
  Menu.setApplicationMenu(buildApplicationMenu());
  const preloadPath = path.join(__dirname, "..", "preload", "index.js");
  return new BrowserWindow({
    width: 1400,
    height: 920,
    minWidth: 960,
    minHeight: 640,
    backgroundColor: "#f4f8ff",
    autoHideMenuBar: true,
    webPreferences: {
      additionalArguments: smokeEnabled ? ["--qjc-smoke"] : [],
      contextIsolation: true,
      sandbox: false,
      nodeIntegration: false,
      preload: preloadPath
    }
  });
}

export function loadMainWindowRenderer(window: BrowserWindow): Promise<void> {
  const rendererEntry = resolveRendererEntry();
  if (rendererEntry.startsWith("http://") || rendererEntry.startsWith("https://")) {
    return window.loadURL(rendererEntry);
  }

  return window.loadURL(pathToFileURL(rendererEntry).toString());
}
