/**
 * Wisewand Plugin Admin JavaScript
 */

(function($) {
    'use strict';

    const WisewandAdmin = {
        init: function() {
            this.bindEvents();
            this.initTooltips();
            this.initFormValidation();
        },

        bindEvents: function() {
            // Test connection button
            $(document).on('click', '#test-connection', this.testConnection);

            // Generate HMAC secret
            $(document).on('click', '#generate-secret', this.generateSecret);

            // Pull article form
            $(document).on('submit', '#wisewand-pull-form', this.pullArticle);

            // Export logs
            $(document).on('click', '#export-logs', this.exportLogs);

            // Purge logs
            $(document).on('click', '#purge-logs', this.purgeLogs);

            // SEO mode change
            $(document).on('change', '#seo_mode', this.toggleMetaMapping);

            // Real-time validation
            $(document).on('input', 'input[name="ip_whitelist"]', this.validateIPWhitelist);
            $(document).on('input', 'input[name^="seo_meta_mapping"]', this.validateMetaKey);

            // Auto-save drafts for long forms
            $(document).on('input change', '.wisewand-form-section input, .wisewand-form-section select, .wisewand-form-section textarea',
                this.debounce(this.autoSave, 2000));
        },

        testConnection: function(e) {
            e.preventDefault();

            const $button = $(this);
            const originalText = $button.text();

            $button.prop('disabled', true)
                   .html('<span class="wisewand-spinner"></span>' + wisewandAdmin.strings.testConnection);

            $.ajax({
                url: wisewandAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wisewand_test_connection',
                    nonce: wisewandAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        WisewandAdmin.showMessage(wisewandAdmin.strings.connectionSuccess, 'success');
                        console.log('Connection test result:', response.data);
                    } else {
                        WisewandAdmin.showMessage(wisewandAdmin.strings.connectionFailed + ' ' + response.data.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    WisewandAdmin.showMessage(wisewandAdmin.strings.connectionFailed + ' ' + error, 'error');
                },
                complete: function() {
                    $button.prop('disabled', false).text(originalText);
                }
            });
        },

        generateSecret: function(e) {
            e.preventDefault();

            const $button = $(this);
            const $input = $('input[name="hmac_secret"]');

            // Generate a secure random secret
            const secret = WisewandAdmin.generateRandomString(64);

            $input.val(secret);
            WisewandAdmin.showMessage(wisewandAdmin.strings.secretGenerated, 'success');

            // Highlight the input briefly
            $input.addClass('highlight');
            setTimeout(() => $input.removeClass('highlight'), 2000);
        },

        pullArticle: function(e) {
            e.preventDefault();

            const $form = $(this);
            const $button = $form.find('button[type="submit"]');
            const $status = $('#wisewand-pull-status');
            const articleId = $form.find('input[name="article_id"]').val();
            const outputIndex = $form.find('select[name="output_index"]').val() || 0;

            if (!articleId.trim()) {
                WisewandAdmin.showMessage('Article ID is required', 'error');
                return;
            }

            $button.prop('disabled', true);
            $status.removeClass('success error').addClass('pending').show()
                   .html('<span class="wisewand-spinner"></span>' + wisewandAdmin.strings.pullingArticle);

            $.ajax({
                url: wisewandAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wisewand_pull_article',
                    nonce: wisewandAdmin.nonce,
                    article_id: articleId,
                    output_index: outputIndex
                },
                success: function(response) {
                    if (response.success) {
                        $status.removeClass('pending error').addClass('success')
                               .html(wisewandAdmin.strings.pullSuccess);

                        if (response.data.post_id) {
                            const editUrl = '/wp-admin/post.php?post=' + response.data.post_id + '&action=edit';
                            $status.append(' <a href="' + editUrl + '" target="_blank">View Post</a>');
                        }

                        // Reset form
                        $form[0].reset();
                    } else {
                        $status.removeClass('pending success').addClass('error')
                               .html(wisewandAdmin.strings.pullFailed + ' ' + (response.data?.message || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    $status.removeClass('pending success').addClass('error')
                           .html(wisewandAdmin.strings.pullFailed + ' ' + error);
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        },

        exportLogs: function(e) {
            e.preventDefault();

            const format = $(this).data('format') || 'json';
            const limit = $('#log_export_limit').val() || 1000;

            // Create a temporary form for file download
            const $form = $('<form>', {
                method: 'POST',
                action: wisewandAdmin.ajaxUrl
            }).append(
                $('<input>', { name: 'action', value: 'wisewand_export_logs', type: 'hidden' }),
                $('<input>', { name: 'nonce', value: wisewandAdmin.nonce, type: 'hidden' }),
                $('<input>', { name: 'format', value: format, type: 'hidden' }),
                $('<input>', { name: 'limit', value: limit, type: 'hidden' })
            );

            $form.appendTo('body').submit().remove();
        },

        purgeLogs: function(e) {
            e.preventDefault();

            if (!confirm(wisewandAdmin.strings.confirmPurge)) {
                return;
            }

            const $button = $(this);
            const originalText = $button.text();

            $button.prop('disabled', true).text('Purging...');

            $.ajax({
                url: wisewandAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wisewand_purge_logs',
                    nonce: wisewandAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        WisewandAdmin.showMessage('Logs purged successfully', 'success');
                        // Reload logs table if present
                        if ($('#wisewand-logs-table').length) {
                            location.reload();
                        }
                    } else {
                        WisewandAdmin.showMessage('Failed to purge logs: ' + response.data.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    WisewandAdmin.showMessage('Failed to purge logs: ' + error, 'error');
                },
                complete: function() {
                    $button.prop('disabled', false).text(originalText);
                }
            });
        },

        toggleMetaMapping: function() {
            const mode = $(this).val();
            const $section = $('#meta_mapping_section');

            if (mode === 'meta_mapping') {
                $section.slideDown();
            } else {
                $section.slideUp();
            }
        },

        validateIPWhitelist: function() {
            const $input = $(this);
            const value = $input.val();
            const lines = value.split('\n').filter(line => line.trim() !== '');

            let hasErrors = false;
            const errors = [];

            lines.forEach((line, index) => {
                const ip = line.trim();
                if (!WisewandAdmin.isValidIPOrCIDR(ip)) {
                    hasErrors = true;
                    errors.push('Line ' + (index + 1) + ': Invalid IP or CIDR notation');
                }
            });

            WisewandAdmin.updateFieldValidation($input, !hasErrors, errors.join('\n'));
        },

        validateMetaKey: function() {
            const $input = $(this);
            const value = $input.val().trim();

            if (value === '') {
                WisewandAdmin.updateFieldValidation($input, true);
                return;
            }

            const isValid = /^[a-zA-Z0-9_-]+$/.test(value);
            const message = isValid ? '' : 'Meta key should only contain letters, numbers, underscores, and hyphens';

            WisewandAdmin.updateFieldValidation($input, isValid, message);
        },

        isValidIPOrCIDR: function(ip) {
            // IPv4 address
            const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
            // IPv4 CIDR
            const cidrRegex = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/;

            if (ipv4Regex.test(ip)) {
                // Validate each octet
                const octets = ip.split('.');
                return octets.every(octet => {
                    const num = parseInt(octet, 10);
                    return num >= 0 && num <= 255;
                });
            }

            if (cidrRegex.test(ip)) {
                const [ipPart, cidr] = ip.split('/');
                const cidrNum = parseInt(cidr, 10);

                if (cidrNum < 0 || cidrNum > 32) {
                    return false;
                }

                // Validate IP part
                const octets = ipPart.split('.');
                return octets.every(octet => {
                    const num = parseInt(octet, 10);
                    return num >= 0 && num <= 255;
                });
            }

            return false;
        },

        updateFieldValidation: function($field, isValid, message = '') {
            $field.removeClass('valid invalid');

            // Remove existing validation message
            $field.siblings('.validation-message').remove();

            if (isValid) {
                $field.addClass('valid');
            } else {
                $field.addClass('invalid');
                if (message) {
                    $field.after('<div class="validation-message error">' + message + '</div>');
                }
            }
        },

        generateRandomString: function(length) {
            const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';

            // Use crypto.getRandomValues if available for better security
            if (window.crypto && window.crypto.getRandomValues) {
                const array = new Uint8Array(length);
                window.crypto.getRandomValues(array);

                for (let i = 0; i < length; i++) {
                    result += charset[array[i] % charset.length];
                }
            } else {
                // Fallback to Math.random
                for (let i = 0; i < length; i++) {
                    result += charset[Math.floor(Math.random() * charset.length)];
                }
            }

            return result;
        },

        showMessage: function(message, type = 'info') {
            // Remove existing messages
            $('.wisewand-message').remove();

            const $message = $('<div class="wisewand-message ' + type + '">' + message + '</div>');

            // Insert after the first h1 or at the top of the wrap
            const $insertAfter = $('.wisewand-admin h1').first();
            if ($insertAfter.length) {
                $insertAfter.after($message);
            } else {
                $('.wisewand-admin').prepend($message);
            }

            // Auto-hide success messages after 5 seconds
            if (type === 'success') {
                setTimeout(() => $message.fadeOut(), 5000);
            }
        },

        autoSave: function() {
            // Simple auto-save functionality for form data
            const formData = {};
            $('.wisewand-form-section input, .wisewand-form-section select, .wisewand-form-section textarea').each(function() {
                const $field = $(this);
                const name = $field.attr('name');
                if (name) {
                    formData[name] = $field.val();
                }
            });

            localStorage.setItem('wisewand_form_draft', JSON.stringify(formData));
            console.log('Form data auto-saved');
        },

        loadAutoSave: function() {
            const savedData = localStorage.getItem('wisewand_form_draft');
            if (savedData) {
                try {
                    const formData = JSON.parse(savedData);
                    Object.keys(formData).forEach(name => {
                        const $field = $('input[name="' + name + '"], select[name="' + name + '"], textarea[name="' + name + '"]');
                        if ($field.length && $field.val() === '') {
                            $field.val(formData[name]);
                        }
                    });
                } catch (e) {
                    console.error('Failed to load auto-saved form data:', e);
                }
            }
        },

        initTooltips: function() {
            // Initialize tooltips for help text
            $('.wisewand-tooltip').each(function() {
                const $trigger = $(this);
                const content = $trigger.data('tooltip');

                $trigger.on('mouseenter', function() {
                    const $tooltip = $('<div class="wisewand-tooltip-content">' + content + '</div>');
                    $('body').append($tooltip);

                    const offset = $trigger.offset();
                    $tooltip.css({
                        position: 'absolute',
                        top: offset.top - $tooltip.outerHeight() - 5,
                        left: offset.left + ($trigger.outerWidth() / 2) - ($tooltip.outerWidth() / 2),
                        zIndex: 999999
                    }).fadeIn(200);
                }).on('mouseleave', function() {
                    $('.wisewand-tooltip-content').fadeOut(200, function() {
                        $(this).remove();
                    });
                });
            });
        },

        initFormValidation: function() {
            // Add real-time form validation
            $('form').on('submit', function(e) {
                const $form = $(this);
                let hasErrors = false;

                // Check for invalid fields
                $form.find('.invalid').each(function() {
                    hasErrors = true;
                    $(this).focus();
                    return false; // Break the loop
                });

                if (hasErrors) {
                    e.preventDefault();
                    WisewandAdmin.showMessage('Please correct the errors below before submitting.', 'error');
                }
            });
        },

        debounce: function(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func.apply(this, args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
    };

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

    // Handle page visibility change to save form data
    $(document).on('visibilitychange', function() {
        if (document.hidden) {
            WisewandAdmin.autoSave();
        }
    });

    // Handle before unload to save form data
    $(window).on('beforeunload', function() {
        WisewandAdmin.autoSave();
    });

    // Export for global access
    window.WisewandAdmin = WisewandAdmin;

})(jQuery);