const { app, BrowserWindow, Menu, ipcMain, shell, dialog, nativeImage } = require('electron');
const path = require('path');
const fs = require('fs');

// Keep a global reference of the window object
let mainWindow;
let isDev = process.argv.includes('--dev');

// Windows 11 specific configurations
const windowsConfig = {
  icon: path.join(__dirname, '../assets/icon.ico'),
  show: false,
  autoHideMenuBar: true,
  frame: true,
  titleBarStyle: 'default',
  minWidth: 800,
  minHeight: 600,
  // DPI and scaling optimizations
  backgroundColor: '#667eea',
  hasShadow: true,
  thickFrame: true,
  webPreferences: {
    nodeIntegration: false,
    contextIsolation: true,
    enableRemoteModule: false,
    preload: path.join(__dirname, 'preload.js'),
    // Enable zoom and scaling
    zoomFactor: 1.0,
    // Better rendering
    experimentalFeatures: true,
    // Enable smooth scrolling
    smoothScroll: true
  }
};

function createWindow() {
  // Get primary display for DPI scaling
  const { screen } = require('electron');
  const primaryDisplay = screen.getPrimaryDisplay();
  const scaleFactor = primaryDisplay.scaleFactor;
  
  // Calculate window size based on DPI
  const baseWidth = 1200;
  const baseHeight = 800;
  const scaledWidth = Math.floor(baseWidth * scaleFactor);
  const scaledHeight = Math.floor(baseHeight * scaleFactor);
  
  // Create the browser window with Windows 11 styling
  mainWindow = new BrowserWindow({
    ...windowsConfig,
    width: scaledWidth,
    height: scaledHeight,
    // DPI awareness
    deviceScaleFactor: scaleFactor,
    webPreferences: {
      ...windowsConfig.webPreferences,
      // Enable features for Windows 11
      experimentalFeatures: true,
      spellcheck: true,
      // DPI scaling
      zoomFactor: 1.0 / scaleFactor
    }
  });

  // Load the app
  if (isDev) {
    // Load from dev server on port 12005 in development
    mainWindow.loadURL('http://localhost:12005');
  } else {
    // Load from local file in production
    mainWindow.loadFile('src/index.html');
  }

  // Show window when ready to prevent visual flash
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
    
    // Focus the window on show
    if (isDev) {
      mainWindow.webContents.openDevTools();
    }
  });

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

  // Set Windows 11 specific handlers
  setupWindowsHandlers();
}

function setupWindowsHandlers() {
  // Handle Windows notifications
  mainWindow.webContents.on('did-finish-load', () => {
    // Inject Windows 11 specific styles
    mainWindow.webContents.insertCSS(`
      @media (prefers-color-scheme: dark) {
        :root {
          --surface: #1e1e1e;
          --surface-variant: #2d2d2d;
          --on-surface: #ffffff;
          --on-surface-variant: #cccccc;
        }
      }
      
      /* Windows 11 specific styling */
      .titlebar {
        -webkit-app-region: drag;
        height: 32px;
        background: transparent;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 10000;
      }
      
      .titlebar button {
        -webkit-app-region: no-drag;
      }
      
      /* Windows 11 Mica effect (if supported) */
      @supports (backdrop-filter: blur(20px)) {
        .app-header {
          backdrop-filter: blur(20px) saturate(180%);
          background: rgba(255, 255, 255, 0.7);
        }
        
        @media (prefers-color-scheme: dark) {
          .app-header {
            background: rgba(30, 30, 30, 0.7);
          }
        }
      }
    `);
  });

  // Handle external links
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url);
    return { action: 'deny' };
  });
}

// Create application menu for Windows
function createMenu() {
  const template = [
    {
      label: 'File',
      submenu: [
        {
          label: 'Export Data',
          accelerator: 'CmdOrCtrl+E',
          click: () => {
            mainWindow.webContents.send('export-data');
          }
        },
        {
          label: 'Import Data',
          accelerator: 'CmdOrCtrl+I',
          click: () => {
            mainWindow.webContents.send('import-data');
          }
        },
        { type: 'separator' },
        {
          label: 'Exit',
          accelerator: process.platform === 'win32' ? 'Alt+F4' : 'CmdOrCtrl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        { role: 'undo', label: 'Undo' },
        { role: 'redo', label: 'Redo' },
        { type: 'separator' },
        { role: 'cut', label: 'Cut' },
        { role: 'copy', label: 'Copy' },
        { role: 'paste', label: 'Paste' }
      ]
    },
    {
      label: 'View',
      submenu: [
        { role: 'reload', label: 'Reload' },
        { role: 'forceReload', label: 'Force Reload' },
        { role: 'toggleDevTools', label: 'Toggle Developer Tools' },
        { type: 'separator' },
        { role: 'resetZoom', label: 'Actual Size' },
        { role: 'zoomIn', label: 'Zoom In' },
        { role: 'zoomOut', label: 'Zoom Out' },
        { type: 'separator' },
        { role: 'togglefullscreen', label: 'Toggle Fullscreen' }
      ]
    },
    {
      label: 'Window',
      submenu: [
        { role: 'minimize', label: 'Minimize' },
        { role: 'close', label: 'Close' }
      ]
    },
    {
      label: 'Help',
      submenu: [
        {
          label: 'About MindShift',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: 'About MindShift',
              message: 'MindShift CBT Therapy',
              detail: 'Version 1.0.0\n\nYour personal CBT therapy companion for mood management and mental wellness.\n\n© 2024 MindShift Team',
              buttons: ['OK']
            });
          }
        }
      ]
    }
  ];

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

// App event handlers
app.whenReady().then(() => {
  createWindow();
  createMenu();
  
  // Handle Windows 11 taskbar integration
  if (process.platform === 'win32') {
    app.setUserTasks([
      {
        program: process.execPath,
        arguments: '--quick-relax',
        title: 'Quick Relax',
        description: 'Start a quick relaxation exercise',
        iconPath: process.execPath,
        iconIndex: 0
      },
      {
        program: process.execPath,
        arguments: '--mood-check',
        title: 'Mood Check',
        description: 'Check your current mood',
        iconPath: process.execPath,
        iconIndex: 0
      }
    ]);
  }

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

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

// Handle Windows 11 notifications
ipcMain.handle('show-notification', (event, title, body) => {
  const { Notification } = require('electron');
  
  if (Notification.isSupported()) {
    const notification = new Notification({
      title: title,
      body: body,
      icon: path.join(__dirname, '../assets/icon.ico'),
      silent: false
    });
    
    notification.show();
    return true;
  }
  
  return false;
});

// Handle file operations
ipcMain.handle('save-file', async (event, data, filename) => {
  try {
    const result = await dialog.showSaveDialog(mainWindow, {
      defaultPath: filename,
      filters: [
        { name: 'JSON Files', extensions: ['json'] },
        { name: 'CSV Files', extensions: ['csv'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    });

    if (!result.canceled) {
      fs.writeFileSync(result.filePath, data);
      return { success: true, path: result.filePath };
    }
    
    return { success: false, cancelled: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

ipcMain.handle('open-file', async (event) => {
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ['openFile'],
      filters: [
        { name: 'JSON Files', extensions: ['json'] },
        { name: 'CSV Files', extensions: ['csv'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    });

    if (!result.canceled && result.filePaths.length > 0) {
      const data = fs.readFileSync(result.filePaths[0], 'utf8');
      return { success: true, data: data, path: result.filePaths[0] };
    }
    
    return { success: false, cancelled: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// Handle protocol for deep linking
app.setAsDefaultProtocolClient('mindshift');

// Handle Windows 11 system theme changes
if (process.platform === 'win32') {
  const { systemPreferences } = require('electron');
  
  systemPreferences.on('color-changed', () => {
    // Notify renderer about theme change
    if (mainWindow) {
      mainWindow.webContents.send('theme-changed', systemPreferences.isDarkMode());
    }
  });
}