jQuery(function($){

    console.log(window);
    // helper: element -> vue component
    function getVueByFieldId(fieldId) {
        // Prefer registry if present
        if (window.wpcftoSelectRegistry && window.wpcftoSelectRegistry[fieldId]) {
            return window.wpcftoSelectRegistry[fieldId];
        }
        // fallback: find by id and read __vue__
        var el = document.getElementById(fieldId);
        return el && el.__vue__ ? el.__vue__ : null;
    }
    
    function convertLabelValueArray(arr) {
        const result = {};
        $.each(arr || [], function(_, obj) {
        if (obj && obj.value != null) result[obj.value] = obj.label || obj.value;
        });
        return result;
    }

    let defaultCurrencyDetected = false;
    let multicurrencyActive = Boolean(formipay_admin_setting.multicurrency);
    let all_currencies_array = formipay_admin_setting.all_currencies;
    let global_currencies_array = formipay_admin_setting.global_selected_currencies;
    let all_currencies_obj = formipay_admin_setting.all_currencies;                   // {value:label}
    let global_currencies_obj = formipay_admin_setting.global_selected_currencies; 
    let saved_default_currency = formipay_admin_setting.default_currency;
    // let defaultCurrencyVM = null;
    // Default Currency Options
    console.log(formipay_admin_setting);

    function set_default_currency_options(fieldId, currenciesObj, multicurrenciesArray) {
        const vm = getVueByFieldId(fieldId);
        if (!vm || typeof vm.updateCurrencyScope !== 'function') {
            console.error('wpcfto_select Vue instance not found or API missing for', fieldId);
            return;
        }
        // vm accepts both shapes and an optional saved default
        vm.updateCurrencyScope(currenciesObj, multicurrenciesArray || [], saved_default_currency);
    }
      
    // bootstrap once field exists in DOM
    const FIELD_ID = 'General-default_currency'; // your actual field_id
    const detectTimer = setInterval(() => {
        const vm = getVueByFieldId(FIELD_ID);
        if (vm) {
            const base = multicurrencyActive ? global_currencies_obj : all_currencies_obj;
            set_default_currency_options(FIELD_ID, base, []); // initial
            clearInterval(detectTimer);
        }
    }, 250);
      
    // reacting to multicurrency toggle
    $(document).on('change', '[name=enable_multicurrency]', function() {
        if ($(this).is(':checked')) {
            set_default_currency_options(FIELD_ID, global_currencies_obj, collectRepeaterSelectedCurrencies());
        } else {
            set_default_currency_options(FIELD_ID, all_currencies_obj, []);
        }
    });
      
    // gather repeater currencies into [{value,label}]
    function collectRepeaterSelectedCurrencies() {
        var items = [];
        var repeaterItems = $('.multicurrencies.repeater').find('.wpcfto-repeater-single');
        $.each(repeaterItems, function(_, obj) {
            var label = $(obj).find('.wpcfto_group_title').text();
            var value = $(obj).find('[field_native_name_inner=currency]').find('input').val();
            if (value) items.push({ label: label || value, value: value });
        });
        return items;
    }
    
    $(document).on('change', '[field_native_name_inner=currency] input', function() {
        set_default_currency_options(FIELD_ID, global_currencies_obj, collectRepeaterSelectedCurrencies());
    });
      
    $(document).on('repeater-item-removed repeater-item-added', function(event, repeater) {
        if (repeater && repeater.field_name == 'multicurrencies') {
            set_default_currency_options(FIELD_ID, global_currencies_obj, collectRepeaterSelectedCurrencies());
        }
    });

    // Paypal
    $(document).on('click', '.show-instruction', function(){
        $('.global-paypal-instruction').slideToggle();
        $(this).text(function(i, text){
            return text === 'Show Instruction' ? 'Hide Instruction' : 'Show Instruction';
        });
    });

    $(document).on('click', '.formipay-connect-paypal', function(e) {
        e.preventDefault();
        
        $.ajax({
            url: formipay_admin_setting.ajax_url,
            type: 'POST',
            data: {
                action: 'formipay_oneclick_connect',
                nonce: formipay_admin_setting.nonce
            },
            beforeSend: function() {
                $('#connect-status').html('<div class="notice notice-info"><p>Initiating PayPal connection...</p></div>');
            },
            success: function(response) {
                if (response.success) {
                    // Open PayPal auth in popup
                    const popup = window.open(
                        response.data.auth_url, 
                        'paypal_oauth',
                        'width=600,height=700,scrollbars=yes'
                    );
                    
                    // Listen for message from popup
                    window.addEventListener('message', function(event) {
                        if (event.data.type === 'formipay-paypal-connect') {
                            if (event.data.success) {
                                $('#connect-status').html(`
                                    <div class="notice notice-success">
                                        <p>${event.data.message}</p>
                                        <p>Webhook ID: ${event.data.webhook_id}</p>
                                    </div>
                                `);
                            } else {
                                $('#connect-status').html(`
                                    <div class="notice notice-error">
                                        <p>${event.data.message}</p>
                                    </div>
                                `);
                            }
                        }
                    });
                } else {
                    $('#connect-status').html(`
                        <div class="notice notice-error">
                            <p>Connection failed: ${response.data}</p>
                        </div>
                    `);
                }
            },
            error: function() {
                $('#connect-status').html(`
                    <div class="notice notice-error">
                        <p>Connection failed: Server error</p>
                    </div>
                `);
            }
        });
    });    
    
});