/**
 * Shadow Spot - Preload Script
 * Exposes secure API to renderer process
 */

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('shadowspot', {
    // Locations (dynamic, user-imported)
    getLocations: () => ipcRenderer.invoke('get-locations'),
    addLocation: (vlessUrl) => ipcRenderer.invoke('add-location', vlessUrl),
    removeLocation: (locationId) => ipcRenderer.invoke('remove-location', locationId),
    decodeQr: (filePath) => ipcRenderer.invoke('decode-qr', filePath),

    // Locations changed event
    onLocationsChanged: (callback) => {
        ipcRenderer.on('locations-changed', (event, data) => callback(data));
    },

    // Connection
    connect: (locationId) => ipcRenderer.invoke('connect', locationId),
    disconnect: () => ipcRenderer.invoke('disconnect'),
    getStatus: () => ipcRenderer.invoke('get-status'),

    // Window controls
    minimize: () => ipcRenderer.send('window-minimize'),
    close: () => ipcRenderer.send('window-close'),

    // Event listeners
    onTrafficUpdate: (callback) => {
        ipcRenderer.on('traffic-update', (event, data) => callback(data));
    },
    onLogUpdate: (callback) => {
        ipcRenderer.on('log-update', (event, data) => callback(data));
    },
    onStatusUpdate: (callback) => {
        ipcRenderer.on('status-update', (event, data) => callback(data));
    },

    // Tray status toggle → renderer performs connect/disconnect
    onTrayToggle: (callback) => {
        ipcRenderer.on('tray-toggle-connection', () => callback());
    },

    // Modal events
    onShowModal: (callback) => {
        ipcRenderer.on('show-modal', (event, data) => callback(data));
    },

    // Modal responses
    modalResponse: (response) => ipcRenderer.send('modal-response', response),
    requestElevation: () => ipcRenderer.send('request-elevation'),

    // Ping
    ping: (host) => ipcRenderer.invoke('ping', host),
    getCurrentServer: () => ipcRenderer.invoke('get-current-server')
});
