const { app, BrowserWindow, dialog } = require('electron');
const path = require('path');

let serverInstance = null;
let win = null;

// In dev, main.js lives in electron/ and src/ is the parent's sibling.
// In the packaged app, main.js and src/ sit together at the asar root.
// app.isPackaged + app.getAppPath() picks the right one (this is the bug that
// made the .deb show a black screen — the server never started).
function getServerModule() {
  const appPath = app.getAppPath();
  return app.isPackaged
    ? require(path.join(appPath, 'src', 'server.js'))
    : require(path.join(appPath, '..', 'src', 'server.js'));
}
function getConfigManager() {
  const appPath = app.getAppPath();
  return app.isPackaged
    ? require(path.join(appPath, 'src', 'config-manager.js'))
    : require(path.join(appPath, '..', 'src', 'config-manager.js'));
}

function startServer() {
  const configManager = getConfigManager();
  const PORT = process.env.PORT || configManager.getPort();
  // Loopback by default (the world lives on your machine). Set
  // OLLIE_COSMOS_HOST=0.0.0.0 (or `host` in state.json) to host a world friends
  // on your LAN can join by IP — same knob whether launched as the app or `npm start`.
  const HOST = configManager.getHost();
  return new Promise((resolve) => {
    try {
      const serverModule = getServerModule();
      if (serverModule && typeof serverModule.listen === 'function') {
        serverInstance = serverModule.listen(PORT, HOST, () => resolve(PORT));
        serverInstance.on('error', (err) => {
          if (err.code === 'EADDRINUSE') {
            // Another instance already serves this port — just use it.
            resolve(PORT);
          } else {
            if (app.isPackaged) dialog.showErrorBox('Ollie Cosmos', `Server error: ${err.message}`);
            resolve(PORT);
          }
        });
      } else {
        resolve(PORT);
      }
    } catch (error) {
      console.error('[world] failed to start server:', error);
      if (app.isPackaged) {
        dialog.showErrorBox('Ollie Cosmos', `Failed to start the internal server:\n${error.message}\n\nPath: ${app.getAppPath()}`);
      }
      resolve(PORT);
    }
  });
}

function createWindow(port) {
  win = new BrowserWindow({
    width: 1280,
    height: 800,
    backgroundColor: '#0d1117',
    title: 'Cosmos',
    icon: path.join(__dirname, 'icons', 'icon.png'),
    webPreferences: { contextIsolation: true },
  });
  // Window chrome shows the short name "Cosmos" (not "Ollie Cosmos"), and the
  // page's <title> must not override it — matches the rest of the suite.
  win.on('page-title-updated', (e) => e.preventDefault());
  win.loadURL(`http://localhost:${port}/`);
  win.on('closed', () => { win = null; });
}

app.whenReady().then(async () => {
  const port = await startServer();
  createWindow(port);
  app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(port); });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});
app.on('quit', () => { try { serverInstance && serverInstance.close(); } catch (_) {} });
