const { app, BrowserWindow, screen } = require('electron');
const path = require('path');
const { registerAll } = require('./ipc');
const { readConfig, updateConfig } = require('./config');

app.setName('Photo Renamer');

let mainWindow;

function createWindow() {
  const windowState = getSavedWindowState();
  mainWindow = new BrowserWindow({
    x: windowState.bounds?.x,
    y: windowState.bounds?.y,
    width: windowState.bounds?.width || 1200,
    height: windowState.bounds?.height || 820,
    minWidth: 900,
    minHeight: 600,
    titleBarStyle: 'hiddenInset',
    backgroundColor: '#0f0f17',
    icon: path.join(__dirname, '../../assets/icon.icns'),
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      contextIsolation: true,
      nodeIntegration: false,
    },
    show: false,
  });

  mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
    if (windowState.isFullScreen) mainWindow.setFullScreen(true);
  });

  mainWindow.on('close', saveWindowState);

  mainWindow.on('enter-full-screen', () => {
    mainWindow.webContents.send('fullscreen-change', true);
  });
  mainWindow.on('leave-full-screen', () => {
    mainWindow.webContents.send('fullscreen-change', false);
  });
}

function getSavedWindowState() {
  const cfg = readConfig();
  const state = cfg.windowState || {};
  const bounds = isUsableBounds(state.bounds) ? state.bounds : null;
  return {
    bounds,
    isFullScreen: state.isFullScreen === true,
  };
}

function isUsableBounds(bounds) {
  if (!bounds) return false;
  const values = [bounds.x, bounds.y, bounds.width, bounds.height];
  if (!values.every(Number.isFinite)) return false;
  if (bounds.width < 900 || bounds.height < 600) return false;
  return screen.getAllDisplays().some(display => rectanglesOverlap(bounds, display.workArea));
}

function rectanglesOverlap(a, b) {
  return a.x < b.x + b.width &&
         a.x + a.width > b.x &&
         a.y < b.y + b.height &&
         a.y + a.height > b.y;
}

function saveWindowState() {
  if (!mainWindow) return;
  const isFullScreen = mainWindow.isFullScreen();
  const bounds = isFullScreen ? mainWindow.getNormalBounds() : mainWindow.getBounds();
  updateConfig(cfg => {
    cfg.windowState = { isFullScreen, bounds };
  });
}

app.whenReady().then(() => {
  createWindow();
  registerAll(mainWindow);
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
