// banglarbhumi_hidden_captcha.js
// Solves some Banglarbhumi captchas without calling the API by copying from hidden fields

(function () {
    const isBanglarbhumi = window.location.hostname.includes('banglarbhumi.gov.in');
    if (!isBanglarbhumi) return;

    console.log('[BanglarBhumi] Hidden Captcha Solver initialized');

    function copyCaptcha(sourceId, targetId) {
        const source = document.getElementById(sourceId);
        const target = document.getElementById(targetId);
        if (source && target) {
            let value = source.value;
            if (value) {
                if (sourceId === 'txtCaptcha') value = value.replace(/\s+/g, '');
                if (target.value !== value) {
                    target.value = value;
                    target.dispatchEvent(new Event('input', { bubbles: true }));
                    target.dispatchEvent(new Event('change', { bubbles: true }));
                }
            }
        }
    }

    function updateCaptchaText(inputSelector, captchaSelector) {
        const inputElement = document.querySelector(inputSelector);
        const captchaElement = document.querySelector(captchaSelector);
        if (inputElement && captchaElement && captchaElement.value) {
            const val = captchaElement.value.replace(/\s+/g, "");
            if (inputElement.value !== val) {
                inputElement.value = val;
                inputElement.dispatchEvent(new Event('input', { bubbles: true }));
                inputElement.dispatchEvent(new Event('change', { bubbles: true }));
            }
        }
    }

    setInterval(() => {
        try {
            const captchaPairs = [
                ['captchaText', 'drawText1'],
                ['captchaText', 'drawText'],
                ['captchaText', 'txtDrawText'],
                ['captchaText1', 'drawText11'],
                ['captchaText2', 'drawText111'],
                ['captchaText3', 'drawText1111'],
                ['captchaText4', 'drawText11111'],
                ['txtCaptcha', 'txtInput'],
                ['captaText', 'dText'],
                ['regCaptcha', 'regInputCaptcha']
            ];

            captchaPairs.forEach(([source, target]) => {
                copyCaptcha(source, target);
            });

            updateCaptchaText("#txtDrawText", "#captchaText");
            updateCaptchaText("#drawText1", "#captchaText");
            updateCaptchaText("#drawText2", "#captchaText");
            updateCaptchaText("#drawText11", "#captchaText1");
            updateCaptchaText("#drawText111", "#captchaText2");
            updateCaptchaText("#drawText1111", "#captchaText3");
            updateCaptchaText("#drawText11111", "#captchaText4");
            updateCaptchaText("#txtInput", "#txtCaptcha");
            updateCaptchaText("#regCaptcha", "#regInputCaptcha");
        } catch (e) {
            // suppress errors
        }
    }, 1000);
})();
