import electron from 'electron';
import type { BrowserWindow as BrowserWindowType } from 'electron';
const { BrowserWindow, screen } = electron;
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

let win: BrowserWindowType | null = null;
const __dirname = fileURLToPath(new URL('.', import.meta.url));

export function getQuickCaptureWindow(): BrowserWindowType | null { return win; }

export function createQuickCaptureWindow(): BrowserWindowType {
  if (win && !win.isDestroyed()) return win;
  const primary = screen.getPrimaryDisplay();
  const W = 640, H = 280;
  const x = Math.round((primary.workArea.width - W) / 2 + primary.workArea.x);
  const y = Math.round((primary.workArea.height - H) / 3 + primary.workArea.y);

  win = new BrowserWindow({
    width: W, height: H, x, y,
    frame: false, show: false, alwaysOnTop: true,
    skipTaskbar: true, resizable: false,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      contextIsolation: true, nodeIntegration: false, sandbox: false
    }
  });

  if (process.env.ELECTRON_RENDERER_URL) {
    win.loadURL(`${process.env.ELECTRON_RENDERER_URL}/quickcapture/index.html`);
  } else {
    win.loadFile(join(__dirname, '../renderer/quickcapture/index.html'));
  }

  win.on('blur', () => { if (win?.isVisible()) win.hide(); });
  return win;
}

export function showQuickCapture(): void {
  const w = createQuickCaptureWindow();
  w.show(); w.focus();
}
