(function($){
    $(document).ready(function(){
        // Only run on settings page where selects exist
        if ($('#wpgv_checkbox_allowed_templates').length === 0 && $('#wpgv_checkbox_allowed_products').length === 0) {
            return;
        }

        // Toggle checkbox settings visibility
        $('#is_product_page_gift_checkbox').on('change', function() {
            if ($(this).val() == '1') {
                $('.wpgv-checkbox-settings').fadeIn();
            } else {
                $('.wpgv-checkbox-settings').fadeOut();
            }
        });

        // Initialize Select2 for multi-select if available
        if (typeof $.fn.select2 !== 'undefined') {
            $('.wpgv-select2').select2({
                placeholder: 'Select options...',
                allowClear: true
            });
        }

        // Load templates based on orientation filter
        function loadTemplates(orientation, selectedTemplates) {
            $.ajax({
                url: wpgv_setting_backend.ajaxurl,
                type: 'POST',
                data: {
                    action: 'wpgv_get_checkbox_templates',
                    orientation: orientation || 'all',
                    nonce: wpgv_setting_backend.nonce
                },
                success: function(response) {
                    if (response.success) {
                        var $select = $('#wpgv_checkbox_allowed_templates');
                        $select.empty();

                        // Add 'All' option
                        var allSelected = selectedTemplates && (selectedTemplates.indexOf('all') !== -1 || selectedTemplates.length === 0);
                        $select.append(new Option('All templates', 'all', allSelected, allSelected));

                        $.each(response.data, function(index, template) {
                            var selected = selectedTemplates && selectedTemplates.indexOf(template.id) !== -1;
                            $select.append(new Option(template.title + ' (ID: ' + template.id + ')', template.id, selected, selected));
                        });

                        $select.trigger('change');
                        enforceAllExclusivity($select);
                    }
                }
            });
        }

        // Load products list
        function loadProducts(selectedProducts) {
            $.ajax({
                url: wpgv_setting_backend.ajaxurl,
                type: 'POST',
                data: {
                    action: 'wpgv_get_checkbox_products',
                    nonce: wpgv_setting_backend.nonce
                },
                success: function(response) {
                    if (response.success) {
                        var $select = $('#wpgv_checkbox_allowed_products');
                        $select.empty();

                        // Add 'All' option
                        var allSelected = selectedProducts && (selectedProducts.indexOf('all') !== -1 || selectedProducts.length === 0);
                        $select.append(new Option('All products (except product data gift voucher)', 'all', allSelected, allSelected));

                        $.each(response.data, function(index, product) {
                            var selected = selectedProducts && selectedProducts.indexOf(product.id) !== -1;
                            $select.append(new Option(product.title + ' (ID: ' + product.id + ')', product.id, selected, selected));
                        });

                        $select.trigger('change');
                        enforceAllExclusivity($select);
                    }
                }
            });
        }

        // Initial load with saved values from localized data
        var savedTemplates = wpgv_setting_backend.saved_templates || [];
        var savedProducts = wpgv_setting_backend.saved_products || [];
        var currentOrientation = $('#wpgv_checkbox_template_orientation').val();

        loadTemplates(currentOrientation, savedTemplates);
        loadProducts(savedProducts);

        // Reload templates when orientation changes
        $('#wpgv_checkbox_template_orientation').on('change', function() {
            var selectedTemplates = $('#wpgv_checkbox_allowed_templates').val() || [];
            loadTemplates($(this).val(), selectedTemplates);
        });

        // Ensure mutual exclusivity between 'all' and other options for select2
        function enforceAllExclusivity($select) {
            // Only operate on select2-enhanced selects
            if (!$select || $select.length === 0) return;

            // When value changes, if 'all' selected -> deselect others; if other selected -> deselect 'all'
            $select.off('change.enforceAll').on('change.enforceAll', function(e) {
                var val = $(this).val() || [];
                // Normalize to array of strings
                var values = Array.isArray(val) ? val.map(String) : [String(val)];

                if (values.indexOf('all') !== -1 && values.length > 1) {
                    // keep only 'all'
                    $(this).val(['all']).trigger('change.select2');
                } else if (values.indexOf('all') === -1 && values.length === 0) {
                    // nothing selected - keep as is
                } else if (values.indexOf('all') === -1 && values.length >= 1) {
                    // ensure 'all' not selected
                    var opts = $(this).find('option[value="all"]');
                    if (opts.length) {
                        opts.prop('selected', false);
                        // update select2 UI
                        $(this).trigger('change.select2');
                    }
                }
            });

            // Immediately enforce on current value too
            var initial = $select.val() || [];
            if (Array.isArray(initial) && initial.length > 1 && initial.indexOf('all') !== -1) {
                $select.val(['all']).trigger('change.select2');
            }
        }

        // Attach exclusivity enforcement to our selects
        enforceAllExclusivity($('#wpgv_checkbox_allowed_templates'));
        enforceAllExclusivity($('#wpgv_checkbox_allowed_products'));
    });
})(jQuery);
