import { app, BrowserWindow, shell } from 'electron';
import path from 'path';

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
    app.quit();
}

let mainWindow: BrowserWindow | null = null;

const createWindow = () => {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 1280,
        height: 800,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: false,
            contextIsolation: true,
        },
        title: 'Veza',
        backgroundColor: '#000000',
        show: false, // Don't show until ready-to-show
    });

    // Load the app.
    // In development, load the local Vite server.
    // In production, load the built files from apps/web/dist.
    // We assume apps/web dist folder is copied to dist/web or similar during build,
    // OR we point relatively to it if convenient.

    const isDev = !app.isPackaged; // or process.env.NODE_ENV === 'development'

    if (isDev) {
        const WEB_URL = process.env.VITE_DEV_SERVER_URL || 'http://localhost:5173';
        console.log(`[Veza Desktop] Loading URL: ${WEB_URL}`);
        mainWindow.loadURL(WEB_URL).catch(e => {
            console.error('Failed to load local dev server. Is apps/web running?');
            console.error(e);
        });
        mainWindow.webContents.openDevTools();
    } else {
        // In production, we expect the web app to be bundled.
        // This path needs to be adjusted based on where electron-builder puts files.
        // Usually we might copy apps/web/dist into veza-desktop/dist/renderer
        // For now let's assume standard behavior or relative path for this "wrapper" setup.
        // A robust way:
        // mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));

        // However, since we are just wrapping, let's try to load the file.
        // Note: 'dist/main/main.js' is where this file will be compiled to.
        // So __dirname will be .../veza-desktop/dist/main
        // So we need to go up.

        // Let's assume the builder configuration copies the web build.
        // For now, let's define the strategy:
        // We will look for index.html in relative path ../renderer/index.html (a standard convention)
        mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));
    }

    mainWindow.once('ready-to-show', () => {
        mainWindow?.show();
    });

    // Open external links in default browser
    mainWindow.webContents.setWindowOpenHandler(({ url }) => {
        if (url.startsWith('http')) {
            shell.openExternal(url);
            return { action: 'deny' };
        }
        return { action: 'allow' };
    });
};

app.on('ready', createWindow);

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

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