// Content script — injects scripts into the page context
// and relays messages between page ↔ background service worker

(function () {
    'use strict';

    /** Safe wrapper: returns true if extension context is still valid */
    function isContextValid() {
        try {
            return !!(chrome && chrome.runtime && chrome.runtime.id);
        } catch (e) {
            return false;
        }
    }

    // Inject the captcha solver first, then the page-level interceptor
    try {
        const solverScript = document.createElement('script');
        solverScript.src = chrome.runtime.getURL('captchaSolver.js');
        solverScript.onload = function () {
            const script = document.createElement('script');
            script.src = chrome.runtime.getURL('inject.js');
            script.onload = function () { this.remove(); };
            (document.head || document.documentElement).appendChild(script);
            this.remove();
        };
        (document.head || document.documentElement).appendChild(solverScript);

        if (window.location.hostname.includes('banglarbhumi.gov.in')) {
            const hiddenScript = document.createElement('script');
            hiddenScript.src = chrome.runtime.getURL('banglarbhumi_hidden_captcha.js');
            hiddenScript.onload = function () { this.remove(); };
            (document.head || document.documentElement).appendChild(hiddenScript);
        }

        if (window.location.hostname.includes('eshram.gov.in') || window.location.hostname.includes('eshram')) {
            const eshramScript = document.createElement('script');
            eshramScript.src = chrome.runtime.getURL('eshram_interceptor.js');
            eshramScript.onload = function () { this.remove(); };
            (document.head || document.documentElement).appendChild(eshramScript);
        }
    } catch (e) { }

    // Listen for messages from injected page scripts
    window.addEventListener('message', function (event) {
        if (event.source !== window) return;
        if (!event.data || !event.data.type) return;
        if (!isContextValid()) return;

        // Relay voter data to background
        if (event.data.type === '__ECI_VOTER_DATA__') {
            try {
                chrome.runtime.sendMessage({
                    action: 'STORE_VOTER_DATA',
                    payload: event.data.payload,
                    timestamp: event.data.timestamp
                });
            } catch (e) { }
        }

        // Relay captcha solve request to background (bypasses CORS)
        if (event.data.type === '__SOLVE_CAPTCHA_REQUEST__') {
            try {
                chrome.runtime.sendMessage(
                    { action: 'SOLVE_CAPTCHA', captcha: event.data.captcha, solverType: event.data.solverType, hostname: event.data.hostname || '' },
                    (response) => {
                        try {
                            window.postMessage({
                                type: '__SOLVE_CAPTCHA_RESPONSE__',
                                requestId: event.data.requestId,
                                result: response || { success: false, text: '', confidence: 0, error: 'No response' }
                            }, '*');
                        } catch (e) { }
                    }
                );
            } catch (e) { }
        }

        // Relay fetch request for cross-origin images to background
        if (event.data.type === '__FETCH_IMAGE_REQUEST__') {
            try {
                chrome.runtime.sendMessage(
                    { action: 'FETCH_IMAGE_BASE64', url: event.data.url },
                    (response) => {
                        try {
                            window.postMessage({
                                type: '__FETCH_IMAGE_RESPONSE__',
                                requestId: event.data.requestId,
                                result: response || { success: false, error: 'No response' }
                            }, '*');
                        } catch (e) { }
                    }
                );
            } catch (e) { }
        }

        // Relay settings request from page script to background
        if (event.data.type === '__GET_SOLVER_SETTINGS__') {
            try {
                chrome.storage.sync.get(['solverSettings'], (result) => {
                    try {
                        window.postMessage({
                            type: '__SOLVER_SETTINGS_RESPONSE__',
                            requestId: event.data.requestId,
                            settings: (result && result.solverSettings) || null
                        }, '*');
                    } catch (e) { }
                });
            } catch (e) { }
        }

        // Relay solver config request from page script to background
        if (event.data.type === '__GET_SOLVER_CONFIG__') {
            try {
                chrome.runtime.sendMessage(
                    { action: 'GET_SOLVER_CONFIG' },
                    (response) => {
                        try {
                            window.postMessage({
                                type: '__SOLVER_CONFIG_RESPONSE__',
                                requestId: event.data.requestId,
                                config: (response && response.config) || null
                            }, '*');
                        } catch (e) { }
                    }
                );
            } catch (e) { }
        }
    });

    // Listen for manual trigger from popup
    try {
        chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
            try {
                if (message.action === 'TRIGGER_CAPTCHA_SOLVE') {
                    window.postMessage({ type: '__TRIGGER_CAPTCHA_SOLVE__' }, '*');
                    sendResponse({ success: true });
                }
            } catch (e) { }
        });
    } catch (e) { }

    // Listen for manual trigger in page context (forwarded from above)
    window.addEventListener('message', function (event) {
        if (event.source !== window) return;
        if (event.data && event.data.type === '__TRIGGER_CAPTCHA_SOLVE__') {
            if (typeof window.__captchaSolverForceRun === 'function') {
                window.__captchaSolverForceRun();
            }
        }
    });
})();
