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(): BrowserWindowType {
  if (inboxWindow && !inboxWindow.isDestroyed()) {
    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', () => inboxWindow?.show());
  return inboxWindow;
}
