const { app, BrowserWindow, Menu, ipcMain, shell } = require("electron");
const fs = require("node:fs");
const path = require("node:path");

const SETTINGS_FILE = "team-workspace.json";
let mainWindow = null;

function settingsPath() {
  return path.join(app.getPath("userData"), SETTINGS_FILE);
}

function normalizeWorkspaceUrl(value) {
  const raw = String(value || "").trim();
  if (!raw) throw new Error("Enter the team workspace address.");
  let parsed;
  try {
    parsed = new URL(raw);
  } catch {
    throw new Error("Enter a complete http:// or https:// address.");
  }
  if (!parsed.hostname || !["http:", "https:"].includes(parsed.protocol)) {
    throw new Error("The team workspace must use http:// or https://.");
  }
  parsed.hash = "";
  return parsed.toString();
}

function loadWorkspaceUrl() {
  try {
    const saved = JSON.parse(fs.readFileSync(settingsPath(), "utf8"));
    return normalizeWorkspaceUrl(saved.workspaceUrl);
  } catch {
    return "";
  }
}

function saveWorkspaceUrl(workspaceUrl) {
  const target = settingsPath();
  fs.mkdirSync(path.dirname(target), { recursive: true });
  const temp = `${target}.tmp`;
  fs.writeFileSync(temp, `${JSON.stringify({ workspaceUrl }, null, 2)}\n`, { mode: 0o600 });
  fs.renameSync(temp, target);
}

function clearWorkspaceUrl() {
  fs.rmSync(settingsPath(), { force: true });
}

function loadSetup() {
  if (!mainWindow || mainWindow.isDestroyed()) return;
  mainWindow.setTitle("Easy Penpot Team");
  mainWindow.loadFile(path.join(__dirname, "renderer", "setup.html"));
}

function loadWorkspace(workspaceUrl) {
  if (!mainWindow || mainWindow.isDestroyed()) return;
  mainWindow.loadURL(workspaceUrl).catch(() => loadSetup());
}

function isExternalHttpUrl(value) {
  try {
    return ["http:", "https:", "mailto:"].includes(new URL(value).protocol);
  } catch {
    return false;
  }
}

function buildMenu() {
  const template = [
    {
      label: "Easy Penpot Team",
      submenu: [
        { label: "Workspace settings", accelerator: "CommandOrControl+,", click: loadSetup },
        { type: "separator" },
        { role: "reload" },
        { role: "quit" }
      ]
    },
    {
      label: "Edit",
      submenu: [{ role: "undo" }, { role: "redo" }, { type: "separator" }, { role: "cut" }, { role: "copy" }, { role: "paste" }, { role: "selectAll" }]
    },
    {
      label: "Window",
      submenu: [{ role: "minimize" }, { role: "zoom" }, { role: "close" }]
    }
  ];
  Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1280,
    height: 820,
    minWidth: 860,
    minHeight: 620,
    show: false,
    backgroundColor: "#151517",
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true,
      preload: path.join(__dirname, "preload.cjs")
    }
  });

  mainWindow.once("ready-to-show", () => mainWindow.show());
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    if (isExternalHttpUrl(url)) shell.openExternal(url);
    return { action: "deny" };
  });
  mainWindow.webContents.on("will-navigate", (event, url) => {
    if (url.startsWith("file:")) event.preventDefault();
  });
  mainWindow.on("closed", () => {
    mainWindow = null;
  });

  const workspaceUrl = loadWorkspaceUrl();
  if (workspaceUrl) loadWorkspace(workspaceUrl);
  else loadSetup();
}

ipcMain.handle("teamWorkspace:get", () => ({ workspaceUrl: loadWorkspaceUrl(), version: app.getVersion() }));
ipcMain.handle("teamWorkspace:save", (_event, value) => {
  const workspaceUrl = normalizeWorkspaceUrl(value);
  saveWorkspaceUrl(workspaceUrl);
  loadWorkspace(workspaceUrl);
  return { workspaceUrl };
});
ipcMain.handle("teamWorkspace:clear", () => {
  clearWorkspaceUrl();
  return { workspaceUrl: "" };
});

app.whenReady().then(() => {
  buildMenu();
  createWindow();
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

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