/**
 * desktop/src/window.ts — creates the single BrowserWindow that hosts the
 * unchanged web frontend, loaded from the embedded localhost server.
 *
 * Hardening (DESKTOP_PLAN §8 / TECH_DOC §7): contextIsolation on, nodeIntegration
 * off, sandbox on, preload restricted to a minimal contextBridge. Because the
 * only page ever loaded is the trusted embedded http://127.0.0.1:<port> origin,
 * we deny every new-window request and block navigation to any foreign origin —
 * a defence-in-depth guard against a hijacked page trying to escape localhost.
 */
import { BrowserWindow } from 'electron'

const WINDOW_WIDTH = 1100
const WINDOW_HEIGHT = 720
const BACKGROUND_COLOR = '#0e0f13'

/** Parse the origin of a URL, returning null for anything malformed. */
function originOf(url: string): string | null {
  try {
    return new URL(url).origin
  } catch {
    return null
  }
}

export function createMainWindow(url: string, preloadPath: string): BrowserWindow {
  const win = new BrowserWindow({
    width: WINDOW_WIDTH,
    height: WINDOW_HEIGHT,
    backgroundColor: BACKGROUND_COLOR,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true,
      preload: preloadPath,
    },
  })

  const allowedOrigin = originOf(url)

  // Never spawn child windows; the frontend has no legitimate reason to.
  win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))

  // Block navigation away from the embedded localhost origin.
  win.webContents.on('will-navigate', (event, targetUrl) => {
    if (allowedOrigin === null) return
    if (originOf(targetUrl) !== allowedOrigin) {
      event.preventDefault()
    }
  })

  void win.loadURL(url)
  return win
}
