const { app, BrowserWindow, ipcMain, session, Menu, Tray, nativeImage } = require('electron');
const path = require('path');
const Store = require('electron-store');
const log = require('electron-log');
const { autoUpdater } = require('electron-updater');
const crypto = require('crypto');

// Generate or retrieve encryption key
function getEncryptionKey() {
  const keyStore = new Store({ name: 'streamflow-key' });
  let key = keyStore.get('encryptionKey');
  if (!key) {
    key = crypto.randomBytes(32).toString('hex');
    keyStore.set('encryptionKey', key);
  }
  return key;
}

// Initialize secure store for credentials
const store = new Store({
  encryptionKey: getEncryptionKey(),
  name: 'streamflow-config'
});

// Initialize offline store for cached content
const offlineStore = new Store({
  name: 'streamflow-offline',
  clearInvalidConfig: true
});

let mainWindow;
let connectionWindow;
let tray = null;
let pipWindow = null;

// Configure logging
log.transports.file.level = 'info';
log.transports.console.level = 'debug';

// Configure auto-updater
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
autoUpdater.autoDownload = false; // Ask user before downloading

function createTray() {
  // Try multiple icon paths for dev and production
  let iconPath = path.join(__dirname, '../../build/icon.png');
  if (!require('fs').existsSync(iconPath)) {
    iconPath = path.join(process.resourcesPath, 'build/icon.png');
  }
  if (!require('fs').existsSync(iconPath)) {
    iconPath = path.join(__dirname, '../../../build/icon.png');
  }
  
  const trayIcon = nativeImage.createFromPath(iconPath);
  if (trayIcon.isEmpty()) {
    log.error('Tray icon not found at:', iconPath);
    return;
  }
  
  tray = new Tray(trayIcon.resize({ width: 22, height: 22 }));
  
  const contextMenu = Menu.buildFromTemplate([
    {
      label: 'Show StreamFlow',
      click: () => {
        if (mainWindow) {
          mainWindow.show();
          mainWindow.focus();
        } else if (connectionWindow) {
          connectionWindow.show();
          connectionWindow.focus();
        }
      }
    },
    { type: 'separator' },
    {
      label: 'Picture-in-Picture',
      click: () => {
        if (mainWindow) {
          createPipWindow();
        }
      }
    },
    { type: 'separator' },
    {
      label: 'Check for Updates',
      click: () => {
        checkForUpdates(true);
      }
    },
    { type: 'separator' },
    {
      label: 'Quit',
      click: () => {
        app.isQuitting = true;
        app.quit();
      }
    }
  ]);
  
  tray.setToolTip('StreamFlow IPTV');
  tray.setContextMenu(contextMenu);
  
  tray.on('click', () => {
    if (mainWindow) {
      if (mainWindow.isVisible()) {
        mainWindow.hide();
      } else {
        mainWindow.show();
        mainWindow.focus();
      }
    }
  });
}

function createConnectionWindow() {
  // Find icon path (works in dev and production)
  const fs = require('fs');
  let iconPath = path.join(__dirname, '../../build/icon.png');
  if (!fs.existsSync(iconPath)) {
    iconPath = path.join(process.resourcesPath, 'build/icon.png');
  }
  if (!fs.existsSync(iconPath)) {
    iconPath = path.join(__dirname, '../../../build/icon.png');
  }
  
  connectionWindow = new BrowserWindow({
    width: 500,
    height: 650,
    resizable: false,
    frame: true,
    title: 'StreamFlow - Server Connection',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: true,
      preload: path.join(__dirname, '../preload/preload.js')
    },
    icon: iconPath
  });
  
  if (process.platform === 'linux' && fs.existsSync(iconPath)) {
    connectionWindow.setIcon(iconPath);
  }

  // Load connection window HTML with error handling
  const htmlPath = path.join(__dirname, '../renderer/connection.html');
  log.info('Loading connection window from:', htmlPath);
  
  connectionWindow.loadFile(htmlPath).catch(err => {
    log.error('Failed to load connection window:', err);
    // Show error in window
    connectionWindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(`
      <html>
        <head><title>Error</title></head>
        <body style="font-family:sans-serif;padding:40px;text-align:center">
          <h1>Failed to Load</h1>
          <p>Could not load connection window.</p>
          <p style="color:#999;font-size:12px">${htmlPath}</p>
          <button onclick="location.reload()" style="margin-top:20px;padding:10px 20px;background:#6366f1;color:white;border:none;border-radius:4px;cursor:pointer">Retry</button>
        </body>
      </html>
    `));
  });
  
  // Log when page finishes loading
  connectionWindow.webContents.on('did-finish-load', () => {
    log.info('Connection window loaded successfully');
  });
  
  connectionWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    log.error('Connection window failed to load:', errorCode, errorDescription);
  });
  
  // Remove menu bar
  connectionWindow.setMenuBarVisibility(false);

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

function createPipWindow() {
  if (pipWindow) {
    pipWindow.focus();
    return;
  }

  // Find icon path (works in dev and production)
  const fs = require('fs');
  let iconPath = path.join(__dirname, '../../build/icon.png');
  if (!fs.existsSync(iconPath)) {
    iconPath = path.join(process.resourcesPath, 'build/icon.png');
  }
  if (!fs.existsSync(iconPath)) {
    iconPath = path.join(__dirname, '../../../build/icon.png');
  }
  
  pipWindow = new BrowserWindow({
    width: 480,
    height: 270,
    alwaysOnTop: true,
    frame: false,
    resizable: true,
    title: 'StreamFlow - PiP',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: true,
      preload: path.join(__dirname, '../preload/preload.js'),
      partition: 'persist:streamflow'
    },
    icon: iconPath
  });
  
  if (process.platform === 'linux' && fs.existsSync(iconPath)) {
    pipWindow.setIcon(iconPath);
  }

  const serverUrl = store.get('serverUrl');
  pipWindow.loadURL(serverUrl);

  // Make it stay on top
  pipWindow.setAlwaysOnTop(true, 'floating');
  pipWindow.setVisibleOnAllWorkspaces(true);
  pipWindow.setSkipTaskbar(true);

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

  log.info('Picture-in-Picture window created');
}

function createMainWindow(serverUrl) {
  // Find icon path (works in dev and production)
  const fs = require('fs');
  let iconPath = path.join(__dirname, '../../build/icon.png');
  if (!fs.existsSync(iconPath)) {
    iconPath = path.join(process.resourcesPath, 'build/icon.png');
  }
  if (!fs.existsSync(iconPath)) {
    iconPath = path.join(__dirname, '../../../build/icon.png');
  }
  
  mainWindow = new BrowserWindow({
    width: 1280,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    title: 'StreamFlow',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: true,
      preload: path.join(__dirname, '../preload/preload.js'),
      webviewTag: false,
      // Enable media features and allow mixed content for video streams
      allowDisplayingInsecureContent: true,
      allowRunningInsecureContent: true,
      // Enable web storage for session persistence
      partition: 'persist:streamflow'
    },
    icon: iconPath,
    show: false, // Don't show until ready
    // Enable maximize button
    maximizable: true
  });
  
  // Set the window class name to match desktop file
  if (process.platform === 'linux' && fs.existsSync(iconPath)) {
    mainWindow.setIcon(iconPath);
  }
  
  // Show window when ready to prevent flash
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
    
    // Open DevTools only if explicitly requested
    if (process.argv.includes('--devtools')) {
      mainWindow.webContents.openDevTools();
    }
  });
  
  // Log console messages for debugging
  mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
    if (message.includes('video') || message.includes('media') || message.includes('stream') || message.includes('error')) {
      log.info(`Console [${level}]:`, message);
    }
  });

  // Get the session for persistent storage
  const ses = session.fromPartition('persist:streamflow');
  
  // Set up content security policy with relaxed media settings for video playback
  ses.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          "default-src 'self' *; " +
          "script-src 'self' 'unsafe-inline' 'unsafe-eval' *; " +
          "style-src 'self' 'unsafe-inline' *; " +
          "img-src 'self' data: https: http: blob: *; " +
          "media-src 'self' https: http: blob: data: mediastream: * ; " +
          "connect-src 'self' " + serverUrl + " https: http: ws: wss: blob: *; " +
          "font-src 'self' data: https: *; " +
          "object-src 'none'; " +
          "base-uri 'self'; " +
          "worker-src 'self' blob: *; " +
          "child-src 'self' blob: *; " +
          "frame-src 'self' blob: *;"
        ]
      }
    });
  });
  
  // Enable media codecs and hardware acceleration
  app.commandLine.appendSwitch('enable-features', 'PlatformHEVCDecoderSupport,PlatformVP9Decoder,VaapiVideoDecoder');
  app.commandLine.appendSwitch('enable-gpu-rasterization');
  app.commandLine.appendSwitch('enable-zero-copy');
  app.commandLine.appendSwitch('ignore-gpu-blocklist');

  // Load the web app from the configured server
  mainWindow.loadURL(serverUrl).catch(err => {
    log.error('Failed to load URL:', err);
  });
  
  // Handle page load failures
  mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
    log.error('Page failed to load:', errorCode, errorDescription, validatedURL);
    if (errorCode !== -3) { // -3 is ERR_ABORTED, which is normal for redirects
      // Show error to user
      mainWindow.webContents.executeJavaScript(`
        document.body.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100vh;font-family:sans-serif;background:#1a1a1a;color:#fff"><div style="text-align:center"><h1>Connection Error</h1><p>Failed to connect to server: ${errorDescription}</p><p style="color:#888">${validatedURL}</p><button onclick="location.reload()" style="margin-top:20px;padding:10px 20px;background:#6366f1;color:white;border:none;border-radius:4px;cursor:pointer">Retry</button></div></div>';
      `);
    }
  });
  
  // Session persistence happens automatically via partition: 'persist:streamflow'
  // The web app will maintain the login session across app restarts

  // Create application menu
  const template = [
    {
      label: 'File',
      submenu: [
        {
          label: 'Change Server',
          click: () => {
            mainWindow.close();
            createConnectionWindow();
          }
        },
        { type: 'separator' },
        {
          label: 'Minimize to Tray',
          accelerator: 'CmdOrCtrl+H',
          click: () => {
            mainWindow.hide();
          }
        },
        { type: 'separator' },
        {
          label: 'Quit',
          accelerator: 'CmdOrCtrl+Q',
          click: () => {
            app.isQuitting = true;
            app.quit();
          }
        }
      ]
    },
    {
      label: 'View',
      submenu: [
        { role: 'reload' },
        { role: 'forceReload' },
        { type: 'separator' },
        { role: 'resetZoom' },
        { role: 'zoomIn' },
        { role: 'zoomOut' },
        { type: 'separator' },
        { role: 'togglefullscreen' },
        { type: 'separator' },
        {
          label: 'Picture-in-Picture',
          accelerator: 'CmdOrCtrl+P',
          click: () => {
            createPipWindow();
          }
        }
      ]
    },
    {
      label: 'Playback',
      submenu: [
        {
          label: 'Toggle Offline Mode',
          type: 'checkbox',
          checked: store.get('offlineMode', false),
          click: (item) => {
            toggleOfflineMode(item.checked);
          }
        },
        { type: 'separator' },
        {
          label: 'Cast to Device',
          click: () => {
            discoverChromecastDevices();
          }
        }
      ]
    },
    {
      label: 'Window',
      submenu: [
        { role: 'minimize' },
        { role: 'close' }
      ]
    },
    {
      label: 'Help',
      submenu: [
        {
          label: 'Check for Updates',
          click: () => {
            checkForUpdates(true);
          }
        },
        { type: 'separator' },
        {
          label: 'About StreamFlow',
          click: () => {
            const { dialog } = require('electron');
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: 'About StreamFlow',
              message: 'StreamFlow Desktop',
              detail: `Version: ${app.getVersion()}\nElectron: ${process.versions.electron}\nChrome: ${process.versions.chrome}\nNode: ${process.versions.node}`,
              buttons: ['OK']
            });
          }
        }
      ]
    }
  ];

  if (process.env.NODE_ENV === 'development' || process.argv.includes('--dev')) {
    template[1].submenu.push(
      { type: 'separator' },
      { role: 'toggleDevTools' }
    );
  }

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

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

  // Handle window close button (minimize to tray instead)
  mainWindow.on('close', (event) => {
    if (!app.isQuitting) {
      event.preventDefault();
      mainWindow.hide();
      
      if (process.platform === 'linux') {
        const { Notification } = require('electron');
        if (Notification.isSupported()) {
          const fs = require('fs');
          let iconPath = path.join(__dirname, '../../build/icon.png');
          if (!fs.existsSync(iconPath)) {
            iconPath = path.join(process.resourcesPath, 'build/icon.png');
          }
          new Notification({
            title: 'StreamFlow',
            body: 'App minimized to system tray',
            icon: iconPath
          }).show();
        }
      }
    }
    return false;
  });

  // Handle external links
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    // Allow same-origin navigations
    if (url.startsWith(serverUrl)) {
      return { action: 'allow' };
    }
    // Block external links for security
    log.warn('Blocked external navigation to:', url);
    return { action: 'deny' };
  });
}

// Track if update check is in progress to prevent duplicates
let isCheckingForUpdates = false;
let isManualCheck = false;

// Auto-update functionality
function checkForUpdates(manual = false) {
  if (isCheckingForUpdates) {
    log.info('Update check already in progress');
    return;
  }
  
  isCheckingForUpdates = true;
  isManualCheck = manual;
  log.info(`Checking for updates... (manual: ${manual})`);
  
  autoUpdater.checkForUpdates().catch(err => {
    isCheckingForUpdates = false;
    log.error('Update check failed:', err);
    
    if (manual) {
      const { dialog } = require('electron');
      dialog.showMessageBox(mainWindow || connectionWindow, {
        type: 'error',
        title: 'Update Check Failed',
        message: 'Unable to check for updates',
        detail: 'Please check your internet connection and try again later.\n\n' + err.message,
        buttons: ['OK']
      });
    }
  });
}

autoUpdater.on('update-available', (info) => {
  isCheckingForUpdates = false;
  log.info('Update available:', info);
  const { dialog } = require('electron');
  
  // Only show dialog once
  dialog.showMessageBox(mainWindow || connectionWindow, {
    type: 'info',
    title: 'Update Available',
    message: `Version ${info.version} is available!`,
    detail: `Current version: ${app.getVersion()}\nNew version: ${info.version}\n\nWould you like to download it now?`,
    buttons: ['Download', 'Later'],
    defaultId: 0,
    cancelId: 1
  }).then(result => {
    if (result.response === 0) {
      autoUpdater.downloadUpdate();
    }
  });
});

autoUpdater.on('update-not-available', (info) => {
  isCheckingForUpdates = false;
  log.info('Update not available:', info);
  
  // Show message only for manual checks
  if (isManualCheck) {
    const { dialog } = require('electron');
    dialog.showMessageBox(mainWindow || connectionWindow, {
      type: 'info',
      title: 'No Updates Available',
      message: 'You are running the latest version!',
      detail: `Current version: ${app.getVersion()}`,
      buttons: ['OK']
    });
  }
  
  isManualCheck = false;
});

autoUpdater.on('download-progress', (progress) => {
  const percent = Math.round(progress.percent);
  log.info(`Download progress: ${percent}%`);
  
  if (mainWindow) {
    mainWindow.setProgressBar(progress.percent / 100);
    mainWindow.webContents.send('update-progress', percent);
  }
});

autoUpdater.on('update-downloaded', (info) => {
  log.info('Update downloaded:', info);
  const { dialog } = require('electron');
  
  if (mainWindow) {
    mainWindow.setProgressBar(-1); // Remove progress bar
  }
  
  dialog.showMessageBox(mainWindow || connectionWindow, {
    type: 'info',
    title: 'Update Ready',
    message: 'Update downloaded successfully!',
    detail: 'The application will restart to install the update.',
    buttons: ['Restart Now', 'Later'],
    defaultId: 0,
    cancelId: 1
  }).then(result => {
    if (result.response === 0) {
      setImmediate(() => autoUpdater.quitAndInstall());
    }
  });
});

// Offline mode functionality
function toggleOfflineMode(enabled) {
  store.set('offlineMode', enabled);
  log.info(`Offline mode: ${enabled ? 'enabled' : 'disabled'}`);
  
  if (mainWindow) {
    mainWindow.webContents.send('offline-mode-changed', enabled);
  }
  
  const { Notification } = require('electron');
  if (Notification.isSupported()) {
    const fs = require('fs');
    let iconPath = path.join(__dirname, '../../build/icon.png');
    if (!fs.existsSync(iconPath)) {
      iconPath = path.join(process.resourcesPath, 'build/icon.png');
    }
    new Notification({
      title: 'StreamFlow',
      body: `Offline mode ${enabled ? 'enabled' : 'disabled'}`,
      icon: iconPath
    }).show();
  }
}

// Chromecast discovery
function discoverChromecastDevices() {
  log.info('Searching for Chromecast devices...');
  
  try {
    const Client = require('chromecast-api');
    const client = new Client();
    
    const { dialog } = require('electron');
    let devices = [];
    
    client.on('device', device => {
      log.info('Found Chromecast device:', device.friendlyName);
      devices.push(device);
    });
    
    // Wait 5 seconds for discovery
    setTimeout(() => {
      if (devices.length === 0) {
        dialog.showMessageBox(mainWindow, {
          type: 'info',
          title: 'No Devices Found',
          message: 'No Chromecast devices found on your network.',
          detail: 'Make sure your Chromecast is on the same network and powered on.',
          buttons: ['OK']
        });
      } else {
        const deviceNames = devices.map((d, i) => `${i + 1}. ${d.friendlyName}`).join('\n');
        dialog.showMessageBox(mainWindow, {
          type: 'info',
          title: 'Chromecast Devices',
          message: `Found ${devices.length} device(s):`,
          detail: deviceNames,
          buttons: ['OK']
        });
        
        // Send devices to renderer for selection
        if (mainWindow) {
          mainWindow.webContents.send('chromecast-devices', devices.map(d => ({
            name: d.friendlyName,
            host: d.host
          })));
        }
      }
    }, 5000);
  } catch (error) {
    log.error('Chromecast discovery error:', error);
    const { dialog } = require('electron');
    dialog.showErrorBox('Cast Error', 'Failed to search for Chromecast devices.');
  }
}

// Cache management for offline mode
function cacheContent(key, data) {
  try {
    offlineStore.set(`cache.${key}`, {
      data: data,
      timestamp: Date.now()
    });
    log.info(`Cached content: ${key}`);
  } catch (error) {
    log.error('Cache error:', error);
  }
}

function getCachedContent(key, maxAge = 24 * 60 * 60 * 1000) { // 24 hours default
  try {
    const cached = offlineStore.get(`cache.${key}`);
    if (!cached) return null;
    
    const age = Date.now() - cached.timestamp;
    if (age > maxAge) {
      offlineStore.delete(`cache.${key}`);
      return null;
    }
    
    return cached.data;
  } catch (error) {
    log.error('Cache retrieval error:', error);
    return null;
  }
}

function clearCache() {
  try {
    offlineStore.delete('cache');
    log.info('Cache cleared');
  } catch (error) {
    log.error('Cache clear error:', error);
  }
}

// IPC Handlers
ipcMain.handle('get-server-config', async () => {
  const serverUrl = store.get('serverUrl');
  const rememberCredentials = store.get('rememberCredentials', false);
  const username = rememberCredentials ? store.get('username') : null;
  
  return {
    serverUrl,
    rememberCredentials,
    username
  };
});

ipcMain.handle('save-server-config', async (event, config) => {
  try {
    const { serverUrl, username, password, rememberCredentials } = config;
    
    // Validate server URL
    if (!serverUrl || (!serverUrl.startsWith('http://') && !serverUrl.startsWith('https://'))) {
      throw new Error('Invalid server URL. Must start with http:// or https://');
    }

    // Save configuration
    store.set('serverUrl', serverUrl.replace(/\/$/, '')); // Remove trailing slash
    store.set('rememberCredentials', rememberCredentials);
    
    if (rememberCredentials) {
      store.set('username', username);
      store.set('password', password); // Encrypted by electron-store
    } else {
      store.delete('username');
      store.delete('password');
    }

    log.info('Server configuration saved');
    return { success: true };
  } catch (error) {
    log.error('Error saving server config:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('test-connection', async (event, serverUrl) => {
  try {
    const axios = require('axios');
    
    // Normalize URL
    const normalizedUrl = serverUrl.replace(/\/$/, '');
    
    // Test connection to server
    const response = await axios.get(`${normalizedUrl}/api/health`, {
      timeout: 10000,
      validateStatus: (status) => status < 500
    });

    if (response.status === 200 || response.status === 404) {
      // 404 is acceptable if /api/health doesn't exist but server is reachable
      return { success: true, message: 'Connection successful' };
    }

    return { success: false, message: 'Server is not responding correctly' };
  } catch (error) {
    log.error('Connection test failed:', error);
    return { 
      success: false, 
      message: error.code === 'ECONNREFUSED' 
        ? 'Connection refused. Please check the server URL and ensure the server is running.'
        : `Connection failed: ${error.message}`
    };
  }
});

ipcMain.handle('connect-to-server', async (event) => {
  const serverUrl = store.get('serverUrl');
  
  if (!serverUrl) {
    return { success: false, error: 'No server URL configured' };
  }

  // Close connection window and open main window
  if (connectionWindow) {
    connectionWindow.close();
  }

  createMainWindow(serverUrl);
  return { success: true };
});

ipcMain.handle('get-stored-credentials', async () => {
  const rememberCredentials = store.get('rememberCredentials', false);
  
  if (!rememberCredentials) {
    return { username: '', password: '' };
  }

  return {
    username: store.get('username', ''),
    password: store.get('password', '')
  };
});

ipcMain.handle('clear-credentials', async () => {
  store.delete('username');
  store.delete('password');
  store.set('rememberCredentials', false);
  log.info('Credentials cleared');
  return { success: true };
});

// Offline mode IPC handlers
ipcMain.handle('cache-content', async (event, key, data) => {
  cacheContent(key, data);
  return { success: true };
});

ipcMain.handle('get-cached-content', async (event, key, maxAge) => {
  const data = getCachedContent(key, maxAge);
  return { success: true, data };
});

ipcMain.handle('clear-cache', async () => {
  clearCache();
  return { success: true };
});

ipcMain.handle('get-offline-mode', async () => {
  return { enabled: store.get('offlineMode', false) };
});

// Picture-in-Picture IPC handlers
ipcMain.handle('open-pip', async () => {
  createPipWindow();
  return { success: true };
});

ipcMain.handle('close-pip', async () => {
  if (pipWindow) {
    pipWindow.close();
  }
  return { success: true };
});

// Chromecast IPC handlers
ipcMain.handle('discover-chromecast', async () => {
  discoverChromecastDevices();
  return { success: true };
});

ipcMain.handle('cast-to-device', async (event, deviceInfo, mediaUrl) => {
  try {
    const Client = require('chromecast-api');
    const client = new Client();
    
    return new Promise((resolve) => {
      client.on('device', device => {
        if (device.friendlyName === deviceInfo.name || device.host === deviceInfo.host) {
          device.play(mediaUrl, 0, () => {
            log.info(`Casting to ${device.friendlyName}`);
            resolve({ success: true, message: `Casting to ${device.friendlyName}` });
          });
        }
      });
      
      setTimeout(() => {
        resolve({ success: false, error: 'Device not found' });
      }, 5000);
    });
  } catch (error) {
    log.error('Cast error:', error);
    return { success: false, error: error.message };
  }
});

// Update IPC handlers
ipcMain.handle('check-for-updates', async () => {
  checkForUpdates(true);
  return { success: true };
});

// App lifecycle
app.whenReady().then(() => {
  // Create system tray
  createTray();
  
  // Check if server is already configured
  const serverUrl = store.get('serverUrl');
  
  if (serverUrl) {
    // If server is configured, go directly to main window
    createMainWindow(serverUrl);
  } else {
    // Otherwise, show connection setup
    createConnectionWindow();
  }

  // Check for updates on startup (silently)
  setTimeout(() => {
    checkForUpdates(false);
  }, 5000);

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      if (store.get('serverUrl')) {
        createMainWindow(store.get('serverUrl'));
      } else {
        createConnectionWindow();
      }
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    // Don't quit if tray is enabled
    if (!tray) {
      app.quit();
    }
  }
});

app.on('before-quit', () => {
  app.isQuitting = true;
});

// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
  log.error('Uncaught exception:', error);
});

process.on('unhandledRejection', (error) => {
  log.error('Unhandled rejection:', error);
});
