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

const BOLT_URL = 'https://bolt.zeusllc.org';

function createWindow() {
  const win = new BrowserWindow({
    width: 1280,
    height: 820,
    minWidth: 800,
    minHeight: 600,
    title: 'Bolt — Business Optimizer',
    icon: path.join(__dirname, 'icon.ico'),
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      // allow session cookies so login persists between launches
      partition: 'persist:bolt',
    },
    backgroundColor: '#0f0e0c',
    show: false,
  });

  // Show once ready to avoid white flash
  win.once('ready-to-show', () => win.show());

  // Open external links (mailto, external websites) in the OS browser
  win.webContents.setWindowOpenHandler(({ url }) => {
    if (!url.startsWith(BOLT_URL)) {
      shell.openExternal(url);
      return { action: 'deny' };
    }
    return { action: 'allow' };
  });

  win.loadURL(BOLT_URL);

  // Basic offline / error page
  win.webContents.on('did-fail-load', (_event, _errorCode, errorDesc) => {
    win.webContents.loadURL(`data:text/html;charset=utf-8,
      <html style="font-family:sans-serif;background:#0f0e0c;color:#f0ede4;display:flex;align-items:center;justify-content:center;height:100vh;margin:0">
        <div style="text-align:center">
          <div style="font-size:48px;margin-bottom:16px">&#9889;</div>
          <h2 style="color:#d4a574;margin-bottom:8px">Could not connect to Bolt</h2>
          <p style="color:#888">${errorDesc}</p>
          <p style="color:#666;font-size:13px">Make sure you are connected to the internet.</p>
          <button onclick="window.location.href='${BOLT_URL}'"
            style="margin-top:20px;background:#d4a574;color:#0f0e0c;border:none;padding:10px 24px;border-radius:6px;font-size:14px;font-weight:700;cursor:pointer">
            Try Again
          </button>
        </div>
      </html>
    `);
  });
}

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

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