const { app: electronApp, BrowserWindow } = require('electron');
electronApp.commandLine.appendSwitch('enable-experimental-web-platform-features');
const path = require('path');
const http = require('http');
const next = require('next');

let mainWindow;
let server;

// Pure Node.js port finder to avoid port conflicts
function findFreePort(startPort, callback) {
  const net = require('net');
  const server = net.createServer();
  server.listen(startPort, () => {
    server.once('close', () => {
      callback(startPort);
    });
    server.close();
  });
  server.on('error', () => {
    findFreePort(startPort + 1, callback);
  });
}

function createWindow(port) {
  mainWindow = new BrowserWindow({
    width: 1280,
    height: 720,
    title: 'Cat Tv',
    backgroundColor: '#141414',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
    },
    autoHideMenuBar: true,
    icon: path.join(__dirname, 'public', 'logo.png'),
  });

  mainWindow.loadURL(`http://localhost:${port}`);

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

electronApp.on('ready', () => {
  findFreePort(3000, async (port) => {
    console.log(`[Electron]: Starting custom Next.js server on port ${port}...`);

    try {
      // Start Next.js programmatically inside the Electron process (no spawn needed!)
      const dev = false;
      const nextApp = next({ dev, dir: __dirname });
      const handle = nextApp.getRequestHandler();

      await nextApp.prepare();

      server = http.createServer((req, res) => {
        handle(req, res);
      });

      server.listen(port, () => {
        console.log(`[Electron]: Custom Next.js server running on port ${port}`);
        createWindow(port);
      });

      server.on('error', (err) => {
        console.error('[Electron]: Server error:', err);
      });

    } catch (err) {
      console.error('[Electron]: Failed to start Next.js server programmatically:', err);
      // Fallback: try opening window anyway
      createWindow(port);
    }
  });
});

electronApp.on('window-all-closed', () => {
  console.log('[Electron]: Window closed. Shutting down custom server...');
  if (server) {
    server.close();
  }
  if (process.platform !== 'darwin') {
    electronApp.quit();
  }
});
