(function($) {
    'use strict';

    $(document).ready(function() {
        var $createBtn = $('#ezhp-create-pages-btn');
        var $spinner = $('#ezhp-automation-spinner');
        var $results = $('#ezhp-automation-results');
        var $messages = $('#ezhp-automation-messages');

        /**
         * Update row styling based on checkbox state
         */
        function updateRowStyling() {
            $('#ezhp-automation-grid tr').each(function() {
                var $row = $(this);
                var $checkbox = $row.find('.ezhp-create-checkbox');
                var $badge = $row.find('.ezhp-page-exists-badge');
                
                if (!$checkbox.is(':checked')) {
                    $row.css('opacity', '0.6');
                } else {
                    $row.css('opacity', '1');
                }
            });
        }

        // Apply initial row styling
        updateRowStyling();

        // Update styling when checkbox changes
        $(document).on('change', '.ezhp-create-checkbox', function() {
            updateRowStyling();
        });


        // Select all uncreated pages
        $('#ezhp-select-all-new').on('click', function(e) {
            e.preventDefault();
            $('#ezhp-automation-grid tr').each(function() {
                var $row = $(this);
                var $checkbox = $row.find('.ezhp-create-checkbox');
                var $badge = $row.find('.ezhp-page-exists-badge');
                
                // Only check if page doesn't exist
                if ($badge.length === 0) {
                    $checkbox.prop('checked', true);
                }
            });
            updateRowStyling();
            return false;
        });

        // Deselect all
        $('#ezhp-deselect-all').on('click', function(e) {
            e.preventDefault();
            $('#ezhp-automation-grid .ezhp-create-checkbox').prop('checked', false);
            updateRowStyling();
            return false;
        });

        // Select all (including existing)
        $('#ezhp-select-all').on('click', function(e) {
            e.preventDefault();
            $('#ezhp-automation-grid .ezhp-create-checkbox').prop('checked', true);
            updateRowStyling();
            return false;
        });

        /**
         * Validate the form before submission
         */
        function validateForm() {
            var isValid = true;
            var errors = [];

            // Clear previous error highlights
            $('.ezhp-slug-input').css('border-color', '');

            // Check each checked row for required slug
            $('#ezhp-automation-grid tr').each(function() {
                var $row = $(this);
                var $checkbox = $row.find('.ezhp-create-checkbox');
                var $slugInput = $row.find('.ezhp-slug-input');
                var $titleInput = $row.find('.ezhp-title-input');

                if ($checkbox.is(':checked')) {
                    var slug = $.trim($slugInput.val());
                    var title = $.trim($titleInput.val());

                    if (slug === '') {
                        isValid = false;
                        $slugInput.css('border-color', '#d63638');
                        errors.push(ezhpAutomation.strings.slugRequired.replace('%s', title || '(untitled)'));
                    }

                    if (title === '') {
                        isValid = false;
                        $titleInput.css('border-color', '#d63638');
                        errors.push(ezhpAutomation.strings.titleRequired.replace('%s', slug || '(no slug)'));
                    }
                }
            });

            if (!isValid) {
                showMessage('error', errors.join('<br>'));
            }

            return isValid;
        }

        /**
         * Collect form data for submission
         */
        function collectFormData() {
            var pages = [];

            $('#ezhp-automation-grid tr').each(function() {
                var $row = $(this);
                var index = $row.data('index');

                pages.push({
                    create: $row.find('.ezhp-create-checkbox').is(':checked') ? '1' : '',
                    title: $row.find('.ezhp-title-input').val(),
                    slug: $row.find('.ezhp-slug-input').val(),
                    block: $row.find('input[name="ezhp_pages[' + index + '][block]"]').val(),
                    sign: $row.find('input[name="ezhp_pages[' + index + '][sign]"]').val()
                });
            });

            return pages;
        }

        /**
         * Get selected language
         */
        function getSelectedLanguage() {
            return $('#ezhp-language-select').val() || 'en';
        }

        /**
         * Show a message in the messages area
         */
        function showMessage(type, message) {
            var className = type === 'error' ? 'notice-error' : 'notice-success';
            $messages.html(
                '<div class="notice ' + className + ' is-dismissible"><p>' + message + '</p></div>'
            );
        }

        /**
         * Display results after page creation
         */
        /**
         * Display results in modal after page creation
         */
        function displayResults(data) {
    var $modal = $('#ezhp-automation-modal');
    var $summary = $('#ezhp-modal-summary');
    var $tbody = $('#ezhp-modal-results-body');
    var $successMessage = $('#ezhp-modal-success-message');

    // Display success message if present
    if (data.successMessage) {
        if ($successMessage.length === 0) {
            // Create the element if it doesn't exist
            $summary.before('<div id="ezhp-modal-success-message" class="ezhp-success-message"></div>');
            $successMessage = $('#ezhp-modal-success-message');
        }
        $successMessage.html(data.successMessage).show();
    }

    // Build summary
    var summaryHtml = '<strong>' + ezhpAutomation.strings.created + ':</strong> ' + data.summary.created;
            if (data.summary.errors > 0) {
                summaryHtml += ' &nbsp;|&nbsp; <strong>' + ezhpAutomation.strings.errors + ':</strong> ' + data.summary.errors;
            }

            $summary.html(summaryHtml);
            
            // Set summary style based on results
            $summary.removeClass('has-errors all-success');
            if (data.summary.errors > 0) {
                $summary.addClass('has-errors');
            } else if (data.summary.created > 0) {
                $summary.addClass('all-success');
            }

            // Build table rows
            var rowsHtml = '';
            $.each(data.results, function(i, result) {
                var statusClass = result.status === 'created' ? 'status-created' : 'status-error';
                var statusText = result.status === 'created' 
                    ? ezhpAutomation.strings.statusCreated 
                    : ezhpAutomation.strings.statusError;

                rowsHtml += '<tr>';
                rowsHtml += '<td>' + escapeHtml(result.title) + '</td>';
                rowsHtml += '<td>' + (result.slug ? escapeHtml(result.slug) : '—') + '</td>';
                rowsHtml += '<td class="' + statusClass + '">' + statusText;
                
                if (result.status === 'error') {
                    rowsHtml += '<br><small>' + escapeHtml(result.message) + '</small>';
                }
                
                rowsHtml += '</td>';
                rowsHtml += '<td>';

                if (result.status === 'created') {
                    rowsHtml += '<a href="' + escapeHtml(result.url) + '" target="_blank">' + ezhpAutomation.strings.view + '</a>';
                    rowsHtml += ' | ';
                    rowsHtml += '<a href="' + escapeHtml(result.edit) + '" target="_blank">' + ezhpAutomation.strings.edit + '</a>';
                }

                rowsHtml += '</td>';
                rowsHtml += '</tr>';
            });

            $tbody.html(rowsHtml);

            // Show modal
            $modal.fadeIn(200);
            $('body').css('overflow', 'hidden');
        }

        /**
         * Close modal
         */
        function closeModal() {
            $('#ezhp-automation-modal').fadeOut(200);
            $('body').css('overflow', '');
        }

        // Modal close events
        $(document).on('click', '.ezhp-modal-close, .ezhp-modal-overlay', function() {
            closeModal();
        });

        // Close modal on Escape key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('#ezhp-automation-modal').is(':visible')) {
                closeModal();
            }
        });

        /**
         * Escape HTML to prevent XSS
         */
        function escapeHtml(text) {
            if (!text) return '';
            var div = document.createElement('div');
            div.appendChild(document.createTextNode(text));
            return div.innerHTML;
        }

        /**
         * Handle Create Pages button click
         */
        $createBtn.on('click', function() {
            // Clear previous results
            $results.html('');
            $messages.html('');

            // Validate form
            if (!validateForm()) {
                return;
            }

            // Confirm action
            if (!confirm(ezhpAutomation.strings.confirmCreate)) {
                return;
            }

            // Disable button and show spinner
            $createBtn.prop('disabled', true);
            $spinner.addClass('is-active');

            // Collect data and send AJAX request
            var pages = collectFormData();

            $.ajax({
                url: ezhpAutomation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'ezhp_create_pages',
                    nonce: ezhpAutomation.nonce,
                    pages: pages,
                    language: getSelectedLanguage()
                },
                success: function(response) {
                    if (response.success) {
                        showMessage('success', ezhpAutomation.strings.pagesCreated.replace('%d', response.data.summary.created));
                        displayResults(response.data);
                    } else {
                        showMessage('error', response.data.message || ezhpAutomation.strings.unknownError);
                    }
                },
                error: function(xhr, status, error) {
                    showMessage('error', ezhpAutomation.strings.ajaxError + ': ' + error);
                },
                complete: function() {
                    $createBtn.prop('disabled', false);
                    $spinner.removeClass('is-active');
                }
            });
        });

        /**
         * Auto-generate slug from title
         */
        $('.ezhp-title-input').on('blur', function() {
            var $row = $(this).closest('tr');
            var $slugInput = $row.find('.ezhp-slug-input');
            
            // Only auto-generate if slug is empty
            if ($slugInput.val() === '') {
                var title = $(this).val();
                var slug = title.toLowerCase()
                    .replace(/[^a-z0-9\s-]/g, '')
                    .replace(/\s+/g, '-')
                    .replace(/-+/g, '-')
                    .replace(/^-|-$/g, '');
                $slugInput.val(slug);
            }
        });

        /**
         * Clear error highlighting on input
         */
        $('.ezhp-slug-input, .ezhp-title-input').on('input', function() {
            $(this).css('border-color', '');
        });

        /**
         * Handle language change - reload page with new language parameter
         */
        $('#ezhp-language-select').on('change', function() {
            var selectedLang = $(this).val();
            var currentUrl = window.location.href;
            
            // Remove existing lang parameter if present
            var baseUrl = currentUrl.split('?')[0];
            var params = new URLSearchParams(window.location.search);
            
            // Set the new language
            params.set('lang', selectedLang);
            
            // Keep the user on the automation tab
            localStorage.setItem('ezhp-active-tab', '#ezhp-tab-automation');
            
            // Reload with new language
            window.location.href = baseUrl + '?' + params.toString();
        });
    });
})(jQuery);
/**
 * Cache clearing functionality for Utilities tab
 */
(function($) {
    'use strict';

    $(document).ready(function() {
        var $clearBtn = $('#ezhp-clear-cache-btn');
        var $spinner = $('#ezhp-cache-spinner');
        var $results = $('#ezhp-cache-results');

        if (!$clearBtn.length) {
            return;
        }

        $clearBtn.on('click', function() {
            var nonce = $('#ezhp_cache_nonce').val();

            $clearBtn.prop('disabled', true);
            $spinner.addClass('is-active');
            $results.html('');

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ezhp_clear_cache',
                    nonce: nonce
                },
                success: function(response) {
                    $spinner.removeClass('is-active');
                    $clearBtn.prop('disabled', false);

                    if (response.success) {
                        $results.html(
                            '<div class="notice notice-success inline"><p>' +
                            response.data.message +
                            '</p></div>'
                        );
                    } else {
                        $results.html(
                            '<div class="notice notice-error inline"><p>' +
                            response.data.message +
                            '</p></div>'
                        );
                    }
                },
                error: function() {
                    $spinner.removeClass('is-active');
                    $clearBtn.prop('disabled', false);
                    $results.html(
                        '<div class="notice notice-error inline"><p>' +
                        'An error occurred. Please try again.' +
                        '</p></div>'
                    );
                }
            });
        });
    });
})(jQuery);