(function() {
    if (window.CountryStateDonateInitialized) return;
    window.CountryStateDonateInitialized = true;

    let baseUrl = "";
    if (typeof DONATION_API_URL !== 'undefined') baseUrl = DONATION_API_URL;
    else if (typeof window.DONATION_API_URL !== 'undefined') baseUrl = window.DONATION_API_URL;
    else if (typeof window.HOME_URL !== 'undefined') baseUrl = window.HOME_URL;
    baseUrl = baseUrl ? baseUrl.replace(/\/$/, "") : "";

    const CONFIG = {
        remoteStaticAPI: baseUrl,
        select2Css: "https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css",
        select2Js: "https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js",
        jqueryJs: "https://code.jquery.com/jquery-3.6.0.min.js"
    };

    let globalCountriesData = {};
    
    const targetFieldIds = {
        countries: ['donation_billing_address_country', 'unlock_billing_address_country', 'einvoice_billing_address_country'],
        states: [
            { country: 'donation_billing_address_country', state: 'donation_billing_address_state' },
            { country: 'unlock_billing_address_country', state: 'unlock_billing_address_state' },
            { country: 'einvoice_billing_address_country', state: 'einvoice_billing_address_state' }
        ]
    };

    // --- 2. Correct Parent Logic ---
    function getDropdownParent(element) {
        if (element.id.indexOf('donation_') === 0) return jQuery('#donation-coffee-overlay');
        if (element.id.indexOf('unlock_') === 0) return jQuery('#unlock-paywall-overlay');
        if (element.id.indexOf('einvoice_') === 0) return jQuery('.einvoice-form-container');
        return jQuery('body');
    }

    // --- 3. Public Re-init Function ---
    window.refreshCountryStateSelect2 = function() {
        if (typeof jQuery === 'undefined' || typeof jQuery.fn.select2 === 'undefined') return;

        [...targetFieldIds.countries].forEach(id => {
            const el = document.getElementById(id);
            if (el) initSelect2(el);
        });
        
        targetFieldIds.states.forEach(pair => {
            const el = document.getElementById(pair.state);
            if (el) initSelect2(el);
        });
    };


    window.validateIdDocument = function(type, value) {
        if (!value) return { isValid: false, message: "Required" };

        let cleanValue = value.toString().replace(/[- ]/g, "").toUpperCase();

        let isValid = true;
        let message = "";

        switch (type) {
            case 'NRIC':
                if (!/^\d{12}$/.test(cleanValue)) {
                    isValid = false;
                    message = "NRIC 必须是12位数字";
                }
                break;

            case 'Passport':
                if (!/^[A-Z0-9]{6,20}$/.test(cleanValue)) {
                    isValid = false;
                    message = "护照号码格式无效";
                }
                break;

            case 'Company Registration':
            case 'Business Registration':
                if (!/^[A-Z0-9]{8,20}$/.test(cleanValue)) {
                    isValid = false;
                    message = "注册号码格式无效";
                }
                break;
                
            default:
                if (cleanValue.length < 4) {
                    isValid = false;
                    message = "无效输入";
                }
                break;
        }

        return { isValid, cleanValue, message };
    };


    const ENABLE_TIN_FORMAT_VALIDATION = true;
    const ENABLE_SST_FORMAT_VALIDATION = false;

    window.validateName = function(value) {
        const trimmed = value ? value.toString().trim() : '';

        if (!trimmed) {
            return { isValid: false, message: '请填写署名' };
        }

        const hasValidChar = /[a-zA-Z\u4e00-\u9fff\u3400-\u4dbf]/.test(trimmed);
        if (!hasValidChar) {
            return { isValid: false, message: '署名不可为纯数字或符号' };
        }

        return { isValid: true, cleanValue: trimmed };
    };

    window.validateEmail = function(value) {
        const trimmed = value ? value.toString().trim() : '';

        if (!trimmed) {
            return { isValid: false, message: '请填写电邮' };
        }

        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailPattern.test(trimmed)) {
            return { isValid: false, message: '请填写有效的电邮地址' };
        }

        return { isValid: true, cleanValue: trimmed };
    };

    window.validateTIN = function(value, idType) {
        
        const companyTypes = ['Company Registration', 'Business Registration'];
        const isCompany = companyTypes.includes(idType);

        let cleanValue = value ? value.toString().replace(/\s/g, "").toUpperCase() : "";

        // 1. Company types ALWAYS require TIN (business rule - always enforced)
        if (isCompany && !cleanValue) {
             return { isValid: false, message: "公司/商业注册必须填写税务识别号 (TIN)" };
        }

        if (!cleanValue) {
            return { isValid: true, cleanValue: "" };
        }

        if (!ENABLE_TIN_FORMAT_VALIDATION) {
            return { isValid: true, cleanValue: cleanValue };
        }
        
        let isValid = false;
        const individualPattern = /^SG\d{10}$/; 
        const companyPattern = /^C\d{10}$/;     
        const companyDigitsPattern = /^\d{12}$/; 

        if (individualPattern.test(cleanValue) || 
            companyPattern.test(cleanValue) || 
            companyDigitsPattern.test(cleanValue)) {
            isValid = true;
        }

        return { 
            isValid: isValid, 
            cleanValue: cleanValue, 
            message: isValid ? "" : "TIN 格式无效 (e.g. C1234567890)" 
        };
    };

    window.validateSST = function(value) {

        if (!value) return { isValid: true, cleanValue: "" };

        if (!ENABLE_SST_FORMAT_VALIDATION) {
            return { isValid: true, cleanValue: value || "" };
        }

        let cleanValue = value.toString().replace(/[\s-]/g, "").toUpperCase();
        let isValid = false;

        const sstPattern = /^[A-Z]\d{11}$/;
        const sstPatternAlt = /^[A-Z]\d{14}$/;

        if (sstPattern.test(cleanValue) || sstPatternAlt.test(cleanValue)) {
            isValid = true;
        }

        return { 
            isValid: isValid, 
            cleanValue: cleanValue, 
            message: isValid ? "" : "SST 格式无效 (e.g. W10-1808-32000455)" 
        };
    };


    window.toggleTinRequirement = function(prefix) {
        const idSelect = document.getElementById(prefix + '_billing_id_type');
        
        const tinLabel = document.querySelector(`label[for="${prefix}_billing_tin"]`);
        
        if (!idSelect || !tinLabel) return;

        const checkType = function() {
            const val = idSelect.value;
            const isCompany = (val === 'Company Registration' || val === 'Business Registration');
            let starSpan = tinLabel.querySelector('.required-asterisk-dynamic');
            if (isCompany) {
                if (!starSpan) {
                    starSpan = document.createElement('span');
                    starSpan.className = 'required-asterisk required-asterisk-dynamic';
                    starSpan.style.color = '#FF0505';
                    starSpan.style.fontSize = '12px';
                    starSpan.style.marginLeft = '2px';
                    starSpan.innerText = '*';
                    const englishSpan = tinLabel.querySelector('.english-label');
                    if(englishSpan) {
                         tinLabel.insertBefore(starSpan, englishSpan);
                    } else {
                         tinLabel.appendChild(starSpan);
                    }
                }
                starSpan.style.display = 'inline';
            } else {
                if (starSpan) starSpan.style.display = 'none';
            }
        };

        idSelect.addEventListener('change', checkType);
        
        checkType();
    };    


    function init() {
        if (typeof jQuery === 'undefined') {
            loadScript(CONFIG.jqueryJs, function() { loadSelect2AndStart(); });
        } else {
            loadSelect2AndStart();
        }
    }

    function loadSelect2AndStart() {
        if (typeof jQuery.fn.select2 === 'undefined') {
            loadStylesheet(CONFIG.select2Css);
            loadScript(CONFIG.select2Js, function() { startApp(); });
        } else {
            startApp();
        }
    }

    async function startApp() {

        const hasCountryFields = targetFieldIds.countries.some(id => document.getElementById(id));
        if (!hasCountryFields) return;

        try {
            const response = await fetch(`${CONFIG.remoteStaticAPI}/api/country`);
            if (!response.ok) throw new Error('Failed to fetch');
            const resp = await response.json();
            globalCountriesData = resp.data;

            targetFieldIds.countries.forEach(id => populateCountryDropdown(id, globalCountriesData));
            setupCountryChangeListeners();
        } catch (error) {
            console.error('CountryStateDonate Error:', error);
        }
    }

    function populateCountryDropdown(selectId, countriesData) {
        const selectElement = document.getElementById(selectId);
        if (!selectElement) return;

        selectElement.innerHTML = '<option value="" disabled selected>选择国家 Select Country</option>';
        Object.entries(countriesData).forEach(([code, country]) => {
            const option = document.createElement('option');
            option.value = code;
            option.textContent = country.name;
            selectElement.appendChild(option);
        });
        initSelect2(selectElement);
    }

    function setupCountryChangeListeners() {
        targetFieldIds.states.forEach(pair => {
            const countrySelect = document.getElementById(pair.country);
            if (countrySelect) {
                jQuery(countrySelect).off('change.stateLoader').on('change.stateLoader', function() {
                    loadStates(this.value, pair.state);
                });
            }
        });
    }

    async function loadStates(countryCode, stateSelectId) {
        const stateSelect = document.getElementById(stateSelectId);
        if (!stateSelect) return;
        
        if (!countryCode) { clearStateDropdown(stateSelect); return; }

        try {
            const response = await fetch(`${CONFIG.remoteStaticAPI}/api/country/${countryCode}/state`);
            const resp = await response.json();
            const statesData = resp.data || resp;

            if (!statesData || Object.keys(statesData).length === 0) {
                clearStateDropdown(stateSelect); return;
            }

            stateSelect.innerHTML = '<option value="" disabled selected>选择您的州属 Select State</option>';
            Object.entries(statesData).forEach(([code, name]) => {
                const opt = document.createElement('option');
                opt.value = code; opt.textContent = name;
                stateSelect.appendChild(opt);
            });
            initSelect2(stateSelect);
        } catch (error) {
            clearStateDropdown(stateSelect);
        }
    }

    function clearStateDropdown(stateSelect) {
        stateSelect.innerHTML = '<option value="" disabled selected>选择您的州属 Select State</option>';
        initSelect2(stateSelect);
    }

    function initSelect2(element) {
        if (typeof jQuery !== 'undefined' && jQuery.fn.select2) {
            if (jQuery(element).hasClass('select2-hidden-accessible')) {
                jQuery(element).select2('destroy');
            }
            jQuery(element).select2({
                width: '100%',
                dropdownParent: getDropdownParent(element)
            });
        }
    }

    function loadScript(url, callback) {
        const script = document.createElement('script');
        script.src = url; script.async = true; script.onload = callback; document.head.appendChild(script);
    }
    function loadStylesheet(url) {
        if (document.querySelector(`link[href="${url}"]`)) return;
        const link = document.createElement('link');
        link.rel = 'stylesheet'; link.href = url; document.head.appendChild(link);
    }

    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
    else init();
})();