// Browser API polyfill for cross-browser compatibility
(function() {
    'use strict';
    
    // If browser is not defined but chrome is, create a simple polyfill
    // Options page runs in regular web context, so window is available
    if (typeof browser === 'undefined' && typeof chrome !== 'undefined') {
        window.browser = chrome;
    }
})();

(function(browser) {
    // DOM elements
    const behaviorRadios = document.querySelectorAll('input[name="linkBehavior"]');
    const domainRadios = document.querySelectorAll('input[name="domainMatching"]');
    const modifierKeysGroup = document.getElementById('modifierKeysGroup');
    const modifierCheckboxes = {
        cmd: document.getElementById('modifierCmd'),
        shift: document.getElementById('modifierShift'),
        alt: document.getElementById('modifierAlt'),
        ctrl: document.getElementById('modifierCtrl')
    };
    const respectTargetBlankCheckbox = document.getElementById('respectTargetBlank');
    const statusDiv = document.getElementById('status');

    // Default settings
    const defaultSettings = {
        linkBehavior: 'disabled', // 'disabled', 'automatic', 'modifier'
        domainMatching: 'base', // 'exact', 'base', 'subdomain'
        modifierKeys: {
            cmd: false,
            shift: false,
            alt: false,
            ctrl: false
        },
        respectTargetBlank: true
    };

    // Show status message
    function showStatus(message, isError = false) {
        statusDiv.textContent = message;
        statusDiv.className = `status ${isError ? 'error' : 'success'}`;
        statusDiv.style.display = 'block';
        
        // Hide status after 3 seconds
        setTimeout(() => {
            statusDiv.style.display = 'none';
        }, 3000);
    }

    // Show browser information
    function showBrowserInfo() {
        browser.runtime.sendMessage({ action: "getBrowserInfo" }).then((response) => {
            if (response) {
                const browserInfo = document.querySelector('.footer p:first-child');
                if (browserInfo) {
                    let infoText = `OpenIn Extension v4.3`;
                    if (response.browser) {
                        infoText += ` (${response.browser})`;
                    }
                    if (response.hasNativeMessaging) {
                        infoText += ' - Safari native messaging enabled';
                    } else {
                        infoText += ' - Using URL scheme fallback';
                    }
                    browserInfo.textContent = infoText;
                }
            }
        }).catch((error) => {
            console.log('Could not get browser info:', error);
        });
    }

    // Update modifier keys group visibility
    function updateModifierKeysVisibility() {
        const modifierSelected = document.querySelector('input[name="linkBehavior"]:checked')?.value === 'modifier';
        if (modifierSelected) {
            modifierKeysGroup.classList.remove('disabled');
        } else {
            modifierKeysGroup.classList.add('disabled');
        }
    }

    // Validate modifier keys selection
    function validateModifierKeys() {
        const behaviorValue = document.querySelector('input[name="linkBehavior"]:checked')?.value;
        if (behaviorValue === 'modifier') {
            const anyModifierSelected = Object.values(modifierCheckboxes).some(checkbox => checkbox.checked);
            if (!anyModifierSelected) {
                showStatus('Please select at least one modifier key when using modifier key behavior', true);
                return false;
            }
        }
        return true;
    }

    // Load saved settings
    function loadSettings() {
        const getSettings = browser.storage.sync.get(Object.keys(defaultSettings));
        
        // Handle both promise-based (Firefox) and callback-based (Chrome) APIs
        if (getSettings && typeof getSettings.then === 'function') {
            // Promise-based API (Firefox)
            getSettings.then((result) => {
                applySettings(result);
            }).catch((error) => {
                console.error('Error loading settings:', error);
                showStatus('Error loading settings', true);
            });
        } else {
            // Callback-based API (Chrome)
            browser.storage.sync.get(Object.keys(defaultSettings), (result) => {
                if (browser.runtime.lastError) {
                    console.error('Error loading settings:', browser.runtime.lastError);
                    showStatus('Error loading settings', true);
                } else {
                    applySettings(result);
                }
            });
        }
    }
    
    // Apply loaded settings to UI
    function applySettings(result) {
        const settings = { ...defaultSettings, ...result };
        
        // Set behavior radio
        const behaviorRadio = document.querySelector(`input[name="linkBehavior"][value="${settings.linkBehavior}"]`);
        if (behaviorRadio) {
            behaviorRadio.checked = true;
        }
        
        // Set domain matching radio
        const domainRadio = document.querySelector(`input[name="domainMatching"][value="${settings.domainMatching}"]`);
        if (domainRadio) {
            domainRadio.checked = true;
        }
        
        // Set modifier keys
        Object.keys(modifierCheckboxes).forEach(key => {
            if (modifierCheckboxes[key] && settings.modifierKeys && settings.modifierKeys[key]) {
                modifierCheckboxes[key].checked = true;
            }
        });
        
        // Set additional options
        if (respectTargetBlankCheckbox) {
            respectTargetBlankCheckbox.checked = settings.respectTargetBlank;
        }

        
        // Update UI state
        updateModifierKeysVisibility();
    }

    // Save settings
    function saveSettings() {
        if (!validateModifierKeys()) {
            return;
        }

        const settings = {
            linkBehavior: document.querySelector('input[name="linkBehavior"]:checked')?.value || defaultSettings.linkBehavior,
            domainMatching: document.querySelector('input[name="domainMatching"]:checked')?.value || defaultSettings.domainMatching,
            modifierKeys: {
                cmd: modifierCheckboxes.cmd?.checked || false,
                shift: modifierCheckboxes.shift?.checked || false,
                alt: modifierCheckboxes.alt?.checked || false,
                ctrl: modifierCheckboxes.ctrl?.checked || false
            },
            respectTargetBlank: respectTargetBlankCheckbox?.checked ?? defaultSettings.respectTargetBlank
        };

        const setSettings = browser.storage.sync.set(settings);
        
        // Handle both promise-based (Firefox) and callback-based (Chrome) APIs
        if (setSettings && typeof setSettings.then === 'function') {
            // Promise-based API (Firefox)
            setSettings.then(() => {
                showStatus('Settings saved successfully!');
                notifyContentScripts(settings);
            }).catch((error) => {
                console.error('Error saving settings:', error);
                showStatus('Error saving settings', true);
            });
        } else {
            // Callback-based API (Chrome)
            browser.storage.sync.set(settings, () => {
                if (browser.runtime.lastError) {
                    console.error('Error saving settings:', browser.runtime.lastError);
                    showStatus('Error saving settings', true);
                } else {
                    showStatus('Settings saved successfully!');
                    notifyContentScripts(settings);
                }
            });
        }
    }
    
    // Notify content scripts about settings changes
    function notifyContentScripts(settings) {
        const queryTabs = browser.tabs.query({});
        
        if (queryTabs && typeof queryTabs.then === 'function') {
            // Promise-based API (Firefox)
            queryTabs.then((tabs) => {
                tabs.forEach((tab) => {
                    browser.tabs.sendMessage(tab.id, {
                        action: 'settingsChanged',
                        settings: settings
                    }).catch(() => {
                        // Ignore errors for tabs that don't have content scripts
                    });
                });
            }).catch(() => {
                // Ignore query errors
            });
        } else {
            // Callback-based API (Chrome)
            browser.tabs.query({}, (tabs) => {
                if (!browser.runtime.lastError && tabs) {
                    tabs.forEach((tab) => {
                        browser.tabs.sendMessage(tab.id, {
                            action: 'settingsChanged',
                            settings: settings
                        }, () => {
                            // Ignore errors for tabs that don't have content scripts
                        });
                    });
                }
            });
        }
    }

    // Initialize
    document.addEventListener('DOMContentLoaded', () => {
        loadSettings();
        showBrowserInfo();
        
        // Add event listeners for behavior radio buttons
        behaviorRadios.forEach(radio => {
            radio.addEventListener('change', () => {
                updateModifierKeysVisibility();
                saveSettings();
            });
        });
        
        // Add event listeners for domain matching radio buttons
        domainRadios.forEach(radio => {
            radio.addEventListener('change', saveSettings);
        });
        
        // Add event listeners for modifier key checkboxes
        Object.values(modifierCheckboxes).forEach(checkbox => {
            if (checkbox) {
                checkbox.addEventListener('change', saveSettings);
            }
        });
        
        // Add event listeners for additional options
        if (respectTargetBlankCheckbox) {
            respectTargetBlankCheckbox.addEventListener('change', saveSettings);
        }
    });

})(typeof browser !== 'undefined' ? browser : chrome);