/**
 * Legal Pages Generator - JavaScript
 * Handles AJAX requests and UI interactions
 */

(function ($) {
    'use strict';

    $(document).ready(function () {
        const form = $('#aiautotool-legal-pages-form');
        const submitBtn = $('#generate-legal-pages-btn');
        const progress = $('#legal-pages-progress');
        const progressFill = progress.find('.progress-fill');
        const progressText = progress.find('.progress-text');
        const result = $('#legal-pages-result');

        // Form submission
        form.on('submit', function (e) {
            e.preventDefault();

            // Validate required fields
            const email = $('#legal_pages_email').val();
            if (!email || !isValidEmail(email)) {
                showError(aiautotoolLegalPages.strings.validationError);
                return;
            }

            // Disable submit button
            submitBtn.prop('disabled', true);

            // Show progress
            result.hide();
            progress.show();
            updateProgress(0, aiautotoolLegalPages.strings.generating);

            // Prepare form data
            const formData = {
                action: 'aiautotool_generate_legal_pages',
                nonce: aiautotoolLegalPages.nonce,
                prompt: $('#legal_pages_prompt').val(),
                email: email,
                phone: $('#legal_pages_phone').val(),
                address: $('#legal_pages_address').val()
            };

            // Simulate progress for better UX
            let progressValue = 0;
            const progressInterval = setInterval(function () {
                if (progressValue < 90) {
                    progressValue += 5;
                    updateProgress(progressValue, aiautotoolLegalPages.strings.generating);
                }
            }, 500);

            // Make AJAX request
            $.ajax({
                url: aiautotoolLegalPages.ajaxUrl,
                type: 'POST',
                data: formData,
                success: function (response) {
                    clearInterval(progressInterval);
                    updateProgress(100, 'Complete!');

                    setTimeout(function () {
                        progress.hide();

                        if (response.success) {
                            showSuccess(response.data);
                        } else {
                            showError(response.data.message || aiautotoolLegalPages.strings.error);
                        }

                        submitBtn.prop('disabled', false);
                    }, 500);
                },
                error: function (xhr, status, error) {
                    clearInterval(progressInterval);
                    progress.hide();
                    showError(aiautotoolLegalPages.strings.error + ' ' + error);
                    submitBtn.prop('disabled', false);
                }
            });
        });

        /**
         * Update progress bar
         */
        function updateProgress(percent, text) {
            progressFill.css('width', percent + '%');
            progressText.text(text);
        }

        /**
         * Show success message
         */
        function showSuccess(data) {
            let html = '<div class="notice notice-success is-dismissible">';
            html += '<p><strong>' + aiautotoolLegalPages.strings.success + '</strong></p>';

            if (data.pages) {
                html += '<p>The following pages have been created as drafts:</p>';
                html += '<ul class="legal-pages-results-list">';

                for (let key in data.pages) {
                    const page = data.pages[key];
                    if (page.success) {
                        html += '<li>';
                        html += '<i class="fa-solid fa-check-circle" style="color: #46b450;"></i> ';
                        html += '<strong>' + page.title + '</strong> - ';
                        html += '<a href="' + page.edit_url + '" target="_blank">Edit Page</a>';
                        html += '</li>';
                    }
                }

                html += '</ul>';
                html += '<p><em>Please review each page before publishing. Consider having them reviewed by a legal professional.</em></p>';
            }

            html += '</div>';
            result.html(html).show();

            // Scroll to result
            $('html, body').animate({
                scrollTop: result.offset().top - 100
            }, 500);
        }

        /**
         * Show error message
         */
        function showError(message) {
            const html = '<div class="notice notice-error is-dismissible">' +
                '<p><strong>Error:</strong> ' + message + '</p>' +
                '</div>';
            result.html(html).show();

            // Scroll to result
            $('html, body').animate({
                scrollTop: result.offset().top - 100
            }, 500);
        }

        /**
         * Validate email
         */
        function isValidEmail(email) {
            const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return re.test(email);
        }

        // Handle dismiss on dynamic notices
        $(document).on('click', '.notice.is-dismissible .notice-dismiss', function (e) {
            $(this).closest('.notice').fadeOut();
        });
    });

})(jQuery);
