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

const changedHandlers = [];

ipcRenderer.on('settings', (e, method, setting, newValue) => {
    if (method === 'changed') {
        for (const handler of changedHandlers) {
            try {
                handler(setting, newValue);
            } catch (err) {
                console.error('Error in settings changed handler:', err);
            }
        }
    }
});

contextBridge.exposeInMainWorld('api', {
    settings: {
        has(setting) {
            return ipcRenderer.invoke('settings', 'has', setting);
        },
        set(setting, value) {
            return ipcRenderer.invoke('settings', 'set', setting, value);
        },
        unset(setting) {
            return ipcRenderer.invoke('settings', 'unset', setting);
        },
        get(setting) {
            return ipcRenderer.invoke('settings', 'get', setting);
        },
        changed(callback) {
            if (typeof callback === 'function') {
                changedHandlers.push(callback);
            } else {
                console.warn('api.settings.changed: callback is not a function');
            }
        }
    },
    trayService: {
        showEnvelope() {
            return ipcRenderer.invoke('trayService', 'showEnvelope');
        },
        hideEnvelope() {
            return ipcRenderer.invoke('trayService', 'hideEnvelope');
        }
    },
    keytar: {
        getPassword(service, login) {
            return ipcRenderer.invoke('keytar', 'getPassword', service, login);
        },
        setPassword(service, login, password) {
            return ipcRenderer.invoke('keytar', 'setPassword', service, login, password);
        },
        deletePassword(service, login) {
            return ipcRenderer.invoke('keytar', 'deletePassword', service, login);
        }
    },
    app: {
        quit() {
            ipcRenderer.send('app-quit');
        }
    }
});

window.addEventListener('wheel', (event) => {
    if (event.ctrlKey) {
        ipcRenderer.send(event.deltaY > 0 ? 'increaseZoom' : 'decreaseZoom');
    }
});

window.addEventListener('keydown', (event) => {
    if (event.ctrlKey) {
        if (event.key === '+' || event.key === '=') {
            ipcRenderer.send('increaseZoom');
        } else if (event.key === '-') {
            ipcRenderer.send('decreaseZoom');
        }
    }
});
