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

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

export function getInboxWindow(): BrowserWindowType | null {
  return inboxWindow;
}

export function createInboxWindow(opts: { visible?: boolean } = {}): BrowserWindowType {
  const visible = opts.visible ?? true;
  if (inboxWindow && !inboxWindow.isDestroyed()) {
    if (visible) {
      inboxWindow.show();
      inboxWindow.focus();
    }
    return inboxWindow;
  }

  inboxWindow = new BrowserWindow({
    width: 900,
    height: 720,
    show: false,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false
    }
  });

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

  inboxWindow.on('close', (e) => {
    if (!app.isQuitting) {
      e.preventDefault();
      inboxWindow?.hide();
    }
  });

  inboxWindow.once('ready-to-show', () => {
    if (visible) {
      inboxWindow?.show();
      return;
    }
    // macOS hidden autostart: regular NSWindow 를 NSApp 에 register 해야 dock running
    // indicator (점) 가 표출된다. panel type 의 quickCapture 만 있으면 NSPanel 미인지 →
    // dock 점이 안 보여 "앱이 안 떠 있는 것처럼" 보이는 버그. showInactive 로 focus 점유
    // 없이 짧게 표출 후 즉시 hide — 사용자 화면 깜빡임 최소화.
    if (process.platform === 'darwin') {
      inboxWindow?.showInactive();
      inboxWindow?.hide();
    }
  });
  return inboxWindow;
}
