/**
 * eShram Captcha Interceptor
 * -------------------------------------------------
 * Runs in the actual page context (injected via content.js).
 * Intercepts XMLHttpRequest and fetch to capture the `generateCode` response.
 * Extracts the captchaValue and pushes it to content.js to be solved.
 */

(function () {
    const isEshram = window.location.hostname.includes('eshram.gov.in') || window.location.hostname.includes('eshram');
    if (!isEshram) return;

    // ── Helper to process captured JSON response ──
    function processEshramResponse(responseText) {
        try {
            const data = JSON.parse(responseText);
            if (data && data.data && data.data.captchaValue) {
                const rawCaptchaValue = data.data.captchaValue;
                
                // Send it to the content script > background script solver pipeline
                // The background script API mapping for 'eshram' expects the whole base64 payload
                const requestId = "__eshram_" + Date.now() + "_" + Math.random();
                const startTime = performance.now();
                
                // We're acting as the page context. Post message to content script
                window.postMessage({
                    type: "__SOLVE_CAPTCHA_REQUEST__",
                    captcha: rawCaptchaValue, // Passing the raw ODM3... string
                    solverType: 'eshram',
                    hostname: window.location.hostname,
                    requestId: requestId,
                }, "*");

                // Listen for the response just once
                const listener = function(event) {
                    if (event.source !== window || !event.data || event.data.type !== "__SOLVE_CAPTCHA_RESPONSE__") return;
                    if (event.data.requestId === requestId) {
                        window.removeEventListener("message", listener);
                        const result = event.data.result;
                        const elapsed = Math.round(performance.now() - startTime);
                        if (result && result.success && result.text) {
                            fillInput(result.text);
                            showToast(`✅ Solved eShram Captcha: ${result.text}  in ${elapsed}ms`, "success");
                        } else {
                            showToast(`❌ Failed: ${result?.error || 'unknown data'}`, "error");
                        }
                    }
                };
                window.addEventListener("message", listener);
            }
        } catch (err) {
            // Not JSON or parse error, ignore
        }
    }

    /** Fill the captcha input securely */
    function fillInput(text) {
        // Find standard captcha inputs typically used
        const inputEl = document.querySelector('input#inputCaptcha, input[name="captcha"], input[aria-label="Enter Captcha"], input#captcha, input[placeholder*="Captcha"], input[placeholder*="captcha"]');
        if (!inputEl) {
            return false;
        }
        
        try {
            // Attempt React/Vue native setter bypass if standard value assignment fails to trigger bind
            const nativeSetter = Object.getOwnPropertyDescriptor(
                window.HTMLInputElement.prototype, "value"
            ).set;
            if (nativeSetter) {
                nativeSetter.call(inputEl, text);
            } else {
                inputEl.value = text;
            }
        } catch(e) {
             inputEl.value = text;
        }
        
        inputEl.dispatchEvent(new Event("input", { bubbles: true }));
        inputEl.dispatchEvent(new Event("change", { bubbles: true }));
        return true;
    }

    // Reuse Toast from captchaSolver if not present, but since they run in different scopes (injected vs content),
    // we define a mini-toast here.
    function showToast(message, type = "success") {
        let container = document.getElementById("__eshram-toast-container");
        if (!container) {
            container = document.createElement("div");
            container.id = "__eshram-toast-container";
            container.style.cssText = `
                position: fixed; top: 16px; right: 16px; z-index: 999999;
                display: flex; flex-direction: column; gap: 8px;
                pointer-events: none; font-family: 'Segoe UI', sans-serif;
            `;
            document.body.appendChild(container);
        }

        const toast = document.createElement("div");
        const bg = type === "success" ? "#0d9" : type === "error" ? "#f44" : "#fa0";
        toast.style.cssText = `
            background: ${bg}; color: #fff; padding: 10px 18px;
            border-radius: 8px; font-size: 14px; font-weight: 600;
            box-shadow: 0 4px 16px rgba(0,0,0,.25);
            opacity: 0; transform: translateX(60px);
            transition: opacity .3s, transform .3s;
            pointer-events: auto;
        `;
        toast.textContent = message;
        container.appendChild(toast);

        requestAnimationFrame(() => {
            toast.style.opacity = "1";
            toast.style.transform = "translateX(0)";
        });

        setTimeout(() => {
            toast.style.opacity = "0";
            toast.style.transform = "translateX(60px)";
            setTimeout(() => toast.remove(), 400);
        }, 4000);
    }
    
    // ── Intercept XMLHttpRequest ──
    const originalXHRSend = XMLHttpRequest.prototype.send;
    const originalXHROpen = XMLHttpRequest.prototype.open;

    XMLHttpRequest.prototype.open = function(method, url) {
        this._url = url;
        return originalXHROpen.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function() {
        if (this._url && this._url.includes('generateCode')) {
            this.addEventListener('load', function() {
                if (this.status >= 200 && this.status < 300) {
                    processEshramResponse(this.responseText);
                }
            });
        }
        return originalXHRSend.apply(this, arguments);
    };

    // ── Intercept Fetch ──
    const originalFetch = window.fetch;
    window.fetch = async function(...args) {
        const fetchRef = originalFetch;
        const response = await fetchRef.apply(this, args);
        
        const url = (typeof args[0] === 'string') ? args[0] : (args[0] && args[0].url) ? args[0].url : '';
        
        if (url && url.includes('generateCode')) {
            // Clone the response so we can read the JSON without consuming the original stream
            const clone = response.clone();
            clone.text().then(text => {
                processEshramResponse(text);
            }).catch(e => {}); // Silent catch
        }

        return response;
    };

})();
