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);

  // v0.3.10 — macOS fullscreen Space 위에 quick capture 띄우기.
  // 기본 BrowserWindow 는 첫 생성된 Space (홈 데스크탑) 에만 표시되므로
  // 사용자가 다른 앱 fullscreen 중일 때 macOS 가 강제 Space 전환 → 사용자 경험 깨짐.
  // 'panel' 타입 + 'screen-saver' level + visibleOnFullScreen 조합으로 현재 Space 위에 overlay.
  const isMac = process.platform === 'darwin';
  win = new BrowserWindow({
    width: W, height: H, x, y,
    frame: false, show: false, alwaysOnTop: true,
    skipTaskbar: true, resizable: false,
    ...(isMac ? { type: 'panel' as const } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      contextIsolation: true, nodeIntegration: false, sandbox: false
    }
  });

  if (isMac) {
    // 'screen-saver' level — fullscreen app 위에 띄울 수 있는 가장 높은 level.
    // visibleOnFullScreen: true — 현재 fullscreen Space 에 함께 표시 (Space 전환 안 함).
    win.setAlwaysOnTop(true, 'screen-saver');
    win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
  }

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