/**
 * GGM Commerce Bulk Actions JavaScript
 *
 * Handles bulk selection and actions for products, categories, tags, attributes, and variations
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

(function($) {
    'use strict';

    // Bulk Actions Handler
    const GGMCBulkActions = {
        /**
         * Initialize bulk actions
         */
        init: function() {
            this.bindProductsEvents();
            this.bindCategoriesEvents();
            this.bindTagsEvents();
            this.bindAttributesEvents();
            this.bindVariationsEvents();
        },

        /**
         * Bind events for Products bulk actions
         */
        bindProductsEvents: function() {
            const $form = $('#ggmc-products-bulk-form');
            if (!$form.length) return;

            // Select all checkbox
            $('#cb-select-all-1').on('change', function() {
                const isChecked = $(this).prop('checked');
                $form.find('.ggmc-bulk-checkbox').prop('checked', isChecked);
                GGMCBulkActions.updateSelectedCount('products');
            });

            // Individual checkbox
            $form.on('change', '.ggmc-bulk-checkbox', function() {
                GGMCBulkActions.updateSelectAllState('products');
                GGMCBulkActions.updateSelectedCount('products');
            });

            // Apply bulk action button
            $('#ggmc-apply-bulk-action').on('click', function() {
                GGMCBulkActions.applyProductsBulkAction();
            });
        },

        /**
         * Bind events for Categories bulk actions
         */
        bindCategoriesEvents: function() {
            const $form = $('#ggmc-categories-bulk-form');
            if (!$form.length) return;

            // Select all checkbox
            $('#cb-select-all-categories').on('change', function() {
                const isChecked = $(this).prop('checked');
                $form.find('.ggmc-bulk-checkbox').prop('checked', isChecked);
                GGMCBulkActions.updateSelectedCount('categories');
            });

            // Individual checkbox
            $form.on('change', '.ggmc-bulk-checkbox', function() {
                GGMCBulkActions.updateSelectAllState('categories');
                GGMCBulkActions.updateSelectedCount('categories');
            });

            // Apply bulk action button
            $('#ggmc-apply-categories-bulk-action').on('click', function() {
                GGMCBulkActions.applyCategoriesBulkAction();
            });
        },

        /**
         * Bind events for Tags bulk actions
         */
        bindTagsEvents: function() {
            const $form = $('#ggmc-tags-bulk-form');
            if (!$form.length) return;

            // Select all checkbox
            $('#cb-select-all-tags').on('change', function() {
                const isChecked = $(this).prop('checked');
                $form.find('.ggmc-bulk-checkbox').prop('checked', isChecked);
                GGMCBulkActions.updateSelectedCount('tags');
            });

            // Individual checkbox
            $form.on('change', '.ggmc-bulk-checkbox', function() {
                GGMCBulkActions.updateSelectAllState('tags');
                GGMCBulkActions.updateSelectedCount('tags');
            });

            // Apply bulk action button
            $('#ggmc-apply-tags-bulk-action').on('click', function() {
                GGMCBulkActions.applyTagsBulkAction();
            });
        },

        /**
         * Bind events for Attributes bulk actions
         */
        bindAttributesEvents: function() {
            // Attribute Groups
            const $groupsForm = $('#ggmc-attribute-groups-bulk-form');
            if ($groupsForm.length) {
                $('#cb-select-all-attr-groups').on('change', function() {
                    const isChecked = $(this).prop('checked');
                    $groupsForm.find('.ggmc-bulk-checkbox').prop('checked', isChecked);
                    GGMCBulkActions.updateSelectedCount('attr-groups');
                });

                $groupsForm.on('change', '.ggmc-bulk-checkbox', function() {
                    GGMCBulkActions.updateSelectAllState('attr-groups');
                    GGMCBulkActions.updateSelectedCount('attr-groups');
                });

                $('#ggmc-apply-attr-groups-bulk-action').on('click', function() {
                    GGMCBulkActions.applyAttributesBulkAction('group');
                });
            }

            // Individual Attributes
            const $attrsForm = $('#ggmc-attributes-bulk-form');
            if ($attrsForm.length) {
                $('#cb-select-all-attrs').on('change', function() {
                    const isChecked = $(this).prop('checked');
                    $attrsForm.find('.ggmc-bulk-checkbox').prop('checked', isChecked);
                    GGMCBulkActions.updateSelectedCount('attrs');
                });

                $attrsForm.on('change', '.ggmc-bulk-checkbox', function() {
                    GGMCBulkActions.updateSelectAllState('attrs');
                    GGMCBulkActions.updateSelectedCount('attrs');
                });

                $('#ggmc-apply-attrs-bulk-action').on('click', function() {
                    GGMCBulkActions.applyAttributesBulkAction('attribute');
                });
            }
        },

        /**
         * Bind events for Variations (variation attributes) bulk actions
         */
        bindVariationsEvents: function() {
            const $form = $('#ggmc-variations-bulk-form');
            if (!$form.length) return;

            // Select all checkbox
            $('#cb-select-all-variations').on('change', function() {
                const isChecked = $(this).prop('checked');
                $form.find('.ggmc-bulk-checkbox').prop('checked', isChecked);
                GGMCBulkActions.updateSelectedCount('variations');
            });

            // Individual checkbox
            $form.on('change', '.ggmc-bulk-checkbox', function() {
                GGMCBulkActions.updateSelectAllState('variations');
                GGMCBulkActions.updateSelectedCount('variations');
            });

            // Apply bulk action button
            $('#ggmc-apply-variations-bulk-action').on('click', function() {
                GGMCBulkActions.applyVariationsBulkAction();
            });

            // Individual delete buttons (not part of bulk form to avoid nested forms)
            $(document).on('click', '.ggmc-delete-variation-attr', function() {
                const id = $(this).data('id');
                const name = $(this).data('name');

                if (confirm('Delete variation "' + name + '"?')) {
                    $('#ggmc-variation-attr-delete-id').val(id);
                    $('#ggmc-variation-attr-delete-form').submit();
                }
            });
        },

        /**
         * Update select all checkbox state based on individual checkboxes
         */
        updateSelectAllState: function(type) {
            let $form, $selectAll;

            switch(type) {
                case 'products':
                    $form = $('#ggmc-products-bulk-form');
                    $selectAll = $('#cb-select-all-1');
                    break;
                case 'categories':
                    $form = $('#ggmc-categories-bulk-form');
                    $selectAll = $('#cb-select-all-categories');
                    break;
                case 'tags':
                    $form = $('#ggmc-tags-bulk-form');
                    $selectAll = $('#cb-select-all-tags');
                    break;
                case 'attr-groups':
                    $form = $('#ggmc-attribute-groups-bulk-form');
                    $selectAll = $('#cb-select-all-attr-groups');
                    break;
                case 'attrs':
                    $form = $('#ggmc-attributes-bulk-form');
                    $selectAll = $('#cb-select-all-attrs');
                    break;
                case 'variations':
                    $form = $('#ggmc-variations-bulk-form');
                    $selectAll = $('#cb-select-all-variations');
                    break;
                default:
                    return;
            }

            const $checkboxes = $form.find('.ggmc-bulk-checkbox');
            const totalCount = $checkboxes.length;
            const checkedCount = $checkboxes.filter(':checked').length;

            if (checkedCount === 0) {
                $selectAll.prop('checked', false).prop('indeterminate', false);
            } else if (checkedCount === totalCount) {
                $selectAll.prop('checked', true).prop('indeterminate', false);
            } else {
                $selectAll.prop('checked', false).prop('indeterminate', true);
            }
        },

        /**
         * Update selected count display
         */
        updateSelectedCount: function(type) {
            let $form, $countDisplay;

            switch(type) {
                case 'products':
                    $form = $('#ggmc-products-bulk-form');
                    $countDisplay = $('#ggmc-bulk-selected-count');
                    break;
                case 'categories':
                    $form = $('#ggmc-categories-bulk-form');
                    $countDisplay = $('#ggmc-categories-selected-count');
                    break;
                case 'tags':
                    $form = $('#ggmc-tags-bulk-form');
                    $countDisplay = $('#ggmc-tags-selected-count');
                    break;
                case 'attr-groups':
                    $form = $('#ggmc-attribute-groups-bulk-form');
                    $countDisplay = $('#ggmc-attr-groups-selected-count');
                    break;
                case 'attrs':
                    $form = $('#ggmc-attributes-bulk-form');
                    $countDisplay = $('#ggmc-attrs-selected-count');
                    break;
                case 'variations':
                    $form = $('#ggmc-variations-bulk-form');
                    $countDisplay = $('#ggmc-variations-selected-count');
                    break;
                default:
                    return;
            }

            const checkedCount = $form.find('.ggmc-bulk-checkbox:checked').length;

            if (checkedCount > 0) {
                $countDisplay.text(checkedCount + ' selected');
            } else {
                $countDisplay.text('');
            }
        },

        /**
         * Apply bulk action to products
         */
        applyProductsBulkAction: function() {
            const $form = $('#ggmc-products-bulk-form');
            const action = $form.find('#bulk-action-selector-top').val();
            const selectedIds = $form.find('.ggmc-bulk-checkbox:checked').map(function() {
                return $(this).val();
            }).get();

            if (!action) {
                alert('Please select an action.');
                return;
            }

            if (selectedIds.length === 0) {
                alert('Please select at least one product.');
                return;
            }

            // Confirmation for destructive actions
            if (action === 'delete_permanently') {
                if (!confirm('Are you sure you want to permanently delete ' + selectedIds.length + ' product(s)? This cannot be undone.')) {
                    return;
                }
            } else if (action === 'move_to_trash') {
                if (!confirm('Move ' + selectedIds.length + ' product(s) to trash?')) {
                    return;
                }
            }

            // Get nonce from form
            const nonce = $form.find('input[name="ggmc_bulk_nonce"]').val();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ggmc_bulk_products_action',
                    nonce: nonce,
                    bulk_action: action,
                    product_ids: selectedIds
                },
                beforeSend: function() {
                    $('#ggmc-apply-bulk-action').prop('disabled', true).text('Processing...');
                },
                success: function(response) {
                    if (response.success) {
                        // Show success message and reload
                        alert(response.data.message);
                        location.reload();
                    } else {
                        alert(response.data.message || 'An error occurred.');
                    }
                },
                error: function() {
                    alert('An error occurred while processing your request.');
                },
                complete: function() {
                    $('#ggmc-apply-bulk-action').prop('disabled', false).text('Apply');
                }
            });
        },

        /**
         * Apply bulk action to categories
         */
        applyCategoriesBulkAction: function() {
            const $form = $('#ggmc-categories-bulk-form');
            const action = $form.find('#bulk-action-selector-categories').val();
            const selectedIds = $form.find('.ggmc-bulk-checkbox:checked').map(function() {
                return $(this).val();
            }).get();

            if (!action) {
                alert('Please select an action.');
                return;
            }

            if (selectedIds.length === 0) {
                alert('Please select at least one category.');
                return;
            }

            // Confirmation for delete
            if (action === 'delete') {
                if (!confirm('Are you sure you want to delete ' + selectedIds.length + ' category(ies)? Products will be unassigned from these categories.')) {
                    return;
                }
            }

            const nonce = $form.find('input[name="ggmc_categories_bulk_nonce"]').val();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ggmc_bulk_categories_action',
                    nonce: nonce,
                    bulk_action: action,
                    category_ids: selectedIds
                },
                beforeSend: function() {
                    $('#ggmc-apply-categories-bulk-action').prop('disabled', true).text('Processing...');
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        location.reload();
                    } else {
                        alert(response.data.message || 'An error occurred.');
                    }
                },
                error: function() {
                    alert('An error occurred while processing your request.');
                },
                complete: function() {
                    $('#ggmc-apply-categories-bulk-action').prop('disabled', false).text('Apply');
                }
            });
        },

        /**
         * Apply bulk action to tags
         */
        applyTagsBulkAction: function() {
            const $form = $('#ggmc-tags-bulk-form');
            const action = $form.find('#bulk-action-selector-tags').val();
            const selectedIds = $form.find('.ggmc-bulk-checkbox:checked').map(function() {
                return $(this).val();
            }).get();

            if (!action) {
                alert('Please select an action.');
                return;
            }

            if (selectedIds.length === 0) {
                alert('Please select at least one tag.');
                return;
            }

            // Confirmation for delete
            if (action === 'delete') {
                if (!confirm('Are you sure you want to delete ' + selectedIds.length + ' tag(s)? Products will be untagged.')) {
                    return;
                }
            }

            const nonce = $form.find('input[name="ggmc_tags_bulk_nonce"]').val();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ggmc_bulk_tags_action',
                    nonce: nonce,
                    bulk_action: action,
                    tag_ids: selectedIds
                },
                beforeSend: function() {
                    $('#ggmc-apply-tags-bulk-action').prop('disabled', true).text('Processing...');
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        location.reload();
                    } else {
                        alert(response.data.message || 'An error occurred.');
                    }
                },
                error: function() {
                    alert('An error occurred while processing your request.');
                },
                complete: function() {
                    $('#ggmc-apply-tags-bulk-action').prop('disabled', false).text('Apply');
                }
            });
        },

        /**
         * Apply bulk action to attributes
         */
        applyAttributesBulkAction: function(attributeType) {
            let $form, action, selectedIds, nonce, $button;

            if (attributeType === 'group') {
                $form = $('#ggmc-attribute-groups-bulk-form');
                action = $form.find('#bulk-action-selector-attr-groups').val();
                nonce = $form.find('input[name="ggmc_attr_groups_bulk_nonce"]').val();
                $button = $('#ggmc-apply-attr-groups-bulk-action');
            } else {
                $form = $('#ggmc-attributes-bulk-form');
                action = $form.find('#bulk-action-selector-attrs').val();
                nonce = $form.find('input[name="ggmc_attrs_bulk_nonce"]').val();
                $button = $('#ggmc-apply-attrs-bulk-action');
            }

            selectedIds = $form.find('.ggmc-bulk-checkbox:checked').map(function() {
                return $(this).val();
            }).get();

            if (!action) {
                alert('Please select an action.');
                return;
            }

            if (selectedIds.length === 0) {
                alert('Please select at least one ' + (attributeType === 'group' ? 'attribute group' : 'attribute') + '.');
                return;
            }

            // Confirmation for delete
            if (action === 'delete') {
                const itemType = attributeType === 'group' ? 'attribute group(s)' : 'attribute(s)';
                if (!confirm('Are you sure you want to delete ' + selectedIds.length + ' ' + itemType + '? This will remove associated product data.')) {
                    return;
                }
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ggmc_bulk_attributes_action',
                    nonce: nonce,
                    bulk_action: action,
                    attribute_ids: selectedIds,
                    attribute_type: attributeType
                },
                beforeSend: function() {
                    $button.prop('disabled', true).text('Processing...');
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        location.reload();
                    } else {
                        alert(response.data.message || 'An error occurred.');
                    }
                },
                error: function() {
                    alert('An error occurred while processing your request.');
                },
                complete: function() {
                    $button.prop('disabled', false).text('Apply');
                }
            });
        },

        /**
         * Apply bulk action to variations (variation attributes)
         */
        applyVariationsBulkAction: function() {
            const $form = $('#ggmc-variations-bulk-form');
            const action = $form.find('#bulk-action-selector-variations').val();
            const selectedIds = $form.find('.ggmc-bulk-checkbox:checked').map(function() {
                return $(this).val();
            }).get();

            if (!action) {
                alert('Please select an action.');
                return;
            }

            if (selectedIds.length === 0) {
                alert('Please select at least one variation.');
                return;
            }

            // Confirmation for delete
            if (action === 'delete') {
                if (!confirm('Are you sure you want to delete ' + selectedIds.length + ' variation(s)? This may affect products using these variations.')) {
                    return;
                }
            }

            const nonce = $form.find('input[name="ggmc_variations_bulk_nonce"]').val();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ggmc_bulk_variations_action',
                    nonce: nonce,
                    bulk_action: action,
                    variation_ids: selectedIds
                },
                beforeSend: function() {
                    $('#ggmc-apply-variations-bulk-action').prop('disabled', true).text('Processing...');
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        location.reload();
                    } else {
                        alert(response.data.message || 'An error occurred.');
                    }
                },
                error: function() {
                    alert('An error occurred while processing your request.');
                },
                complete: function() {
                    $('#ggmc-apply-variations-bulk-action').prop('disabled', false).text('Apply');
                }
            });
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        GGMCBulkActions.init();
    });

})(jQuery);

/**
 * GGM Commerce Import/Export Handler
 */
(function($) {
    'use strict';

    const GGMCImportExport = {
        /**
         * Initialize import/export handlers
         */
        init: function() {
            this.bindExportEvents();
            this.bindTemplateEvents();
            this.bindImportEvents();
        },

        /**
         * Bind export button events
         */
        bindExportEvents: function() {
            $(document).on('click', '.ggmc-export-btn[data-type]', function(e) {
                e.preventDefault();
                const $btn = $(this);
                const type = $btn.data('type');
                const nonce = $btn.data('nonce');
                if (!type || !nonce) return;

                $btn.prop('disabled', true).text('Exporting...');

                // Determine the AJAX action based on type
                let action = 'ggmc_export_' + type;

                $.ajax({
                    url: ajaxurl,
                    method: 'POST',
                    data: {
                        action: action,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Trigger download
                            window.location.href = response.data.download_url;
                            alert('Exported ' + response.data.count + ' ' + type + ' successfully.');
                        } else {
                            alert(response.data.message || 'Export failed.');
                        }
                    },
                    error: function() {
                        alert('An error occurred during export.');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-download" style="margin-top: 4px;"></span> Export CSV');
                    }
                });
            });
        },

        /**
         * Bind template download button events
         */
        bindTemplateEvents: function() {
            $(document).on('click', '.ggmc-template-btn', function(e) {
                e.preventDefault();
                const $btn = $(this);
                const type = $btn.data('type');
                const nonce = $btn.data('nonce');

                $btn.prop('disabled', true);

                $.ajax({
                    url: ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'ggmc_download_taxonomy_template',
                        type: type,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            window.location.href = response.data.download_url;
                        } else {
                            alert(response.data.message || 'Template download failed.');
                        }
                    },
                    error: function() {
                        alert('An error occurred while downloading template.');
                    },
                    complete: function() {
                        $btn.prop('disabled', false);
                    }
                });
            });
        },

        /**
         * Bind import form events
         */
        bindImportEvents: function() {
            // Categories import
            $('#ggmc-import-categories-form').on('submit', function(e) {
                e.preventDefault();
                GGMCImportExport.startImport($(this), 'categories', 'ggmc_import_taxonomy_init', 'ggmc_import_taxonomy_batch');
            });

            // Tags import
            $('#ggmc-import-tags-form').on('submit', function(e) {
                e.preventDefault();
                GGMCImportExport.startImport($(this), 'tags', 'ggmc_import_taxonomy_init', 'ggmc_import_taxonomy_batch');
            });

            // Attributes import
            $('#ggmc-import-attributes-form').on('submit', function(e) {
                e.preventDefault();
                GGMCImportExport.startImport($(this), 'attributes', 'ggmc_import_attributes_init', 'ggmc_import_attributes_batch');
            });

            // Attribute Groups import
            $('#ggmc-import-attribute-groups-form').on('submit', function(e) {
                e.preventDefault();
                GGMCImportExport.startImport($(this), 'groups', 'ggmc_import_attributes_init', 'ggmc_import_attributes_batch');
            });

            // Variation Types import
            $('#ggmc-import-variation-types-form').on('submit', function(e) {
                e.preventDefault();
                GGMCImportExport.startImport($(this), 'variation_types', 'ggmc_import_variation_types_init', 'ggmc_import_variation_types_batch');
            });
        },

        /**
         * Start an import process
         */
        startImport: function($form, type, initAction, batchAction) {
            const $section = $form.closest('.ggmc-import-section');
            const $progress = $section.find('.ggmc-import-progress');
            const $progressFill = $progress.find('.ggmc-progress-fill');
            const $progressText = $progress.find('.ggmc-progress-text');
            const $result = $section.find('.ggmc-import-result');
            const $btn = $form.find('.ggmc-import-btn');
            const nonce = $btn.data('nonce');

            // Get file
            const file = $form.find('input[type="file"]')[0].files[0];
            if (!file) {
                alert('Please select a file to import.');
                return;
            }

            // Prepare form data
            const formData = new FormData();
            formData.append('action', initAction);
            formData.append('nonce', nonce);
            formData.append('type', type);
            formData.append('file', file);
            formData.append('duplicate_handling', $form.find('[name="duplicate_handling"]').val());

            // Optional flags
            if ($form.find('[name="download_images"]').is(':checked')) {
                formData.append('download_images', '1');
            }
            if ($form.find('[name="create_groups"]').is(':checked')) {
                formData.append('create_groups', '1');
            }

            // Show progress
            $btn.prop('disabled', true).text('Initializing...');
            $progress.show();
            $result.hide();
            $progressFill.css('width', '0%');
            $progressText.text('Initializing import...');

            // Initialize import
            $.ajax({
                url: ajaxurl,
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $progressText.text('Processing 0 of ' + response.data.total_rows + '...');
                        GGMCImportExport.processBatch($section, type, batchAction, nonce);
                    } else {
                        GGMCImportExport.showResult($section, 'error', response.data.message || 'Import initialization failed.');
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import');
                    }
                },
                error: function() {
                    GGMCImportExport.showResult($section, 'error', 'An error occurred during import initialization.');
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import');
                }
            });
        },

        /**
         * Process a batch of import rows
         */
        processBatch: function($section, type, batchAction, nonce) {
            const $progress = $section.find('.ggmc-import-progress');
            const $progressFill = $progress.find('.ggmc-progress-fill');
            const $progressText = $progress.find('.ggmc-progress-text');
            const $btn = $section.find('.ggmc-import-btn');

            $.ajax({
                url: ajaxurl,
                method: 'POST',
                data: {
                    action: batchAction,
                    nonce: nonce,
                    type: type
                },
                success: function(response) {
                    if (response.success) {
                        const data = response.data;

                        // Update progress
                        $progressFill.css('width', data.progress + '%');
                        $progressText.text('Processing ' + data.processed_rows + ' of ' + data.total_rows + '...');

                        if (data.status === 'complete') {
                            // Import complete
                            GGMCImportExport.showImportComplete($section, data);
                            $btn.prop('disabled', false).html('<span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import');

                            // Reload page after delay
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        } else {
                            // Continue processing
                            GGMCImportExport.processBatch($section, type, batchAction, nonce);
                        }
                    } else {
                        GGMCImportExport.showResult($section, 'error', response.data.message || 'Batch processing failed.');
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import');
                    }
                },
                error: function() {
                    GGMCImportExport.showResult($section, 'error', 'An error occurred during batch processing.');
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import');
                }
            });
        },

        /**
         * Show import complete summary
         */
        showImportComplete: function($section, data) {
            let message = '<strong>Import Complete!</strong><br>';
            message += 'Created: ' + data.created + '<br>';
            message += 'Updated: ' + data.updated + '<br>';
            message += 'Skipped: ' + data.skipped + '<br>';

            if (data.errors && data.errors.length > 0) {
                message += '<br><strong>Errors (' + data.errors.length + '):</strong><br>';
                data.errors.slice(0, 5).forEach(function(err) {
                    message += '- Row ' + err.row + ': ' + err.message + '<br>';
                });
                if (data.errors.length > 5) {
                    message += '... and ' + (data.errors.length - 5) + ' more errors<br>';
                }
            }

            if (data.warnings && data.warnings.length > 0) {
                message += '<br><strong>Warnings (' + data.warnings.length + '):</strong><br>';
                data.warnings.slice(0, 5).forEach(function(warn) {
                    message += '- ' + warn.message + '<br>';
                });
                if (data.warnings.length > 5) {
                    message += '... and ' + (data.warnings.length - 5) + ' more warnings<br>';
                }
            }

            message += '<br><em>Reloading page...</em>';

            const hasErrors = data.errors && data.errors.length > 0;
            GGMCImportExport.showResult($section, hasErrors ? 'warning' : 'success', message);
        },

        /**
         * Show result message
         */
        showResult: function($section, type, message) {
            const $result = $section.find('.ggmc-import-result');
            const bgColor = type === 'success' ? '#d4edda' : (type === 'warning' ? '#fff3cd' : '#f8d7da');
            const borderColor = type === 'success' ? '#c3e6cb' : (type === 'warning' ? '#ffc107' : '#f5c6cb');

            $result
                .css({
                    'background': bgColor,
                    'border': '1px solid ' + borderColor
                })
                .html(message)
                .show();
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        GGMCImportExport.init();
    });

})(jQuery);
