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

function resolveFileRendererEntry(): string {
  return path.join(app.getAppPath(), "dist", "renderer", "index.html");
}

function hasExplicitRendererUrl(): boolean {
  return Boolean(process.env.QJCLAW_RENDERER_URL?.trim() || process.env.VITE_DEV_SERVER_URL?.trim());
}

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 resolveFileRendererEntry();
}

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).catch((error: unknown) => {
      const fileRendererEntry = resolveFileRendererEntry();
      if (!app.isPackaged && !hasExplicitRendererUrl() && existsSync(fileRendererEntry)) {
        return window.loadURL(pathToFileURL(fileRendererEntry).toString());
      }
      throw error;
    });
  }

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