/**
 * Blaminhor Essentials Admin JavaScript
 *
 * @package BlaminhorEssentials
 */

(function($) {
    'use strict';

    // Main object
    const BlaminhorEssentials = {
        /**
         * Initialize
         */
        init: function() {
            this.bindModuleToggles();
            this.bindCategoryTabs();
            this.bindFeedbackForm();
            this.bindTabs();
            this.bindModals();
            this.bindDismissFeedback();
        },

        /**
         * Module toggle handlers
         */
        bindModuleToggles: function() {
            $(document).on('change', '.module-toggle-input', function() {
                const $toggle = $(this);
                const $module = $toggle.closest('.ap-module-card, .blaminhor-essentials-module');
                const moduleId = $toggle.data('module');
                const activate = $toggle.is(':checked');

                // Confirm deactivation
                if (!activate && !confirm(blaminhorEssentials.strings.confirmDeactivate)) {
                    $toggle.prop('checked', true);
                    return;
                }

                // Disable toggle during request
                $toggle.prop('disabled', true);

                // Update status text if it exists (legacy design)
                const $status = $module.find('.module-status');
                if ($status.length) {
                    $status.text(activate ? blaminhorEssentials.strings.activating : blaminhorEssentials.strings.deactivating);
                }

                $.ajax({
                    url: blaminhorEssentials.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'blaminhor_essentials_toggle_module',
                        nonce: blaminhorEssentials.nonce,
                        module: moduleId,
                        activate: activate
                    },
                    success: function(response) {
                        if (response.success) {
                            if ($status.length) {
                                $status.text(activate ? blaminhorEssentials.strings.active : blaminhorEssentials.strings.inactive);
                            }
                            $module.toggleClass('active', activate);

                            // Redirect to settings page on activation, reload on deactivation
                            if (activate && response.data.settings_url) {
                                window.location.href = response.data.settings_url;
                            } else {
                                window.location.reload();
                            }
                        } else {
                            $toggle.prop('checked', !activate);
                            if ($status.length) {
                                $status.text(!activate ? blaminhorEssentials.strings.active : blaminhorEssentials.strings.inactive);
                            }
                            alert(response.data.message || blaminhorEssentials.strings.error);
                        }
                    },
                    error: function() {
                        $toggle.prop('checked', !activate);
                        if ($status.length) {
                            $status.text(!activate ? blaminhorEssentials.strings.active : blaminhorEssentials.strings.inactive);
                        }
                        alert(blaminhorEssentials.strings.error);
                    },
                    complete: function() {
                        $toggle.prop('disabled', false);
                    }
                });
            });
        },

        /**
         * Category tabs handler
         */
        bindCategoryTabs: function() {
            // Tab click handler
            $(document).on('click', '.ap-category-tab', function() {
                const $tab = $(this);
                const categoryId = $tab.data('category');

                // Update active tab
                $('.ap-category-tab').removeClass('active');
                $tab.addClass('active');

                // Update active grid
                $('.ap-modules-grid').removeClass('active');
                $('.ap-modules-grid[data-category="' + categoryId + '"]').addClass('active');
            });
        },

        /**
         * Feedback form handler
         */
        bindFeedbackForm: function() {
            const $form = $('#blaminhor-essentials-feedback-form');
            const $typeSelect = $form.find('#feedback-type');
            const $textarea = $form.find('#feedback-message');

            // Update placeholder based on type selection
            $typeSelect.on('change', function() {
                const type = $(this).val();
                if (type === 'bug') {
                    $textarea.attr('placeholder', $textarea.data('placeholder-bug'));
                } else {
                    $textarea.attr('placeholder', $textarea.data('placeholder-default'));
                }
            });

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

                const $button = $form.find('button[type="submit"]');
                const originalText = $button.text();
                const fileInput = $form.find('#feedback-attachments')[0];

                // Validate file sizes (max 10MB each)
                if (fileInput && fileInput.files.length > 0) {
                    const maxSize = 10 * 1024 * 1024; // 10MB
                    for (let i = 0; i < fileInput.files.length; i++) {
                        if (fileInput.files[i].size > maxSize) {
                            alert(blaminhorEssentials.strings.fileTooLarge || 'One or more files exceed the maximum size of 10 MB.');
                            return;
                        }
                    }
                }

                $button.prop('disabled', true).text(blaminhorEssentials.strings.sending);

                // Use FormData to support file uploads
                const formData = new FormData();
                formData.append('action', 'blaminhor_essentials_send_feedback');
                formData.append('nonce', blaminhorEssentials.nonce);
                formData.append('type', $form.find('#feedback-type').val());
                formData.append('message', $form.find('#feedback-message').val());
                formData.append('email', $form.find('#feedback-email').val());

                // Add files
                if (fileInput && fileInput.files.length > 0) {
                    for (let i = 0; i < fileInput.files.length; i++) {
                        formData.append('attachments[]', fileInput.files[i]);
                    }
                }

                $.ajax({
                    url: blaminhorEssentials.ajaxUrl,
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message);
                            $form[0].reset();
                            // Reset placeholder to default after form reset
                            $textarea.attr('placeholder', $textarea.data('placeholder-default'));
                        } else {
                            alert(response.data.message || blaminhorEssentials.strings.error);
                        }
                    },
                    error: function() {
                        alert(blaminhorEssentials.strings.error);
                    },
                    complete: function() {
                        $button.prop('disabled', false).text(originalText);
                    }
                });
            });
        },

        /**
         * Tabs handler with URL hash support
         */
        bindTabs: function() {
            const self = this;

            // Activate a specific tab
            function activateTab(tab, $container) {
                if (!$container) {
                    $container = $('.blaminhor-essentials-tabs-wrapper');
                }
                $container.find('.blaminhor-essentials-tab').removeClass('active');
                $container.find('[data-tab="' + tab + '"]').addClass('active');
                $container.find('.blaminhor-essentials-tab-content').removeClass('active');
                $container.find('[data-tab-content="' + tab + '"]').addClass('active');
            }

            // Parse "#tab[:field]" into the target tab and an optional setting
            // name to highlight (used by audit recommendations to land the
            // user directly on the row they are supposed to toggle).
            function parseTabHash() {
                var raw = window.location.hash.replace('#', '');
                var sep = raw.indexOf(':');
                return sep === -1
                    ? { tab: raw, field: '' }
                    : { tab: raw.slice(0, sep), field: raw.slice(sep + 1) };
            }

            function highlightField(name) {
                if (!name) { return; }
                var $el = $('[name="' + name + '"]').first();
                if (!$el.length) { return; }
                var $row = $el.closest('tr');
                if (!$row.length) {
                    $row = $el.closest('.form-table > tbody > tr, .blaminhor-essentials-setting-row, p, div').first();
                }
                if (!$row.length) { return; }
                var node = $row[0];
                if (typeof node.scrollIntoView === 'function') {
                    node.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
                $row.addClass('blaminhor-essentials-highlight');
                setTimeout(function () { $row.removeClass('blaminhor-essentials-highlight'); }, 4000);
            }

            // Restore tab + optional field highlight from URL hash on page load.
            var initial = parseTabHash();
            if (initial.tab && $('[data-tab-content="' + initial.tab + '"]').length) {
                activateTab(initial.tab);
                if (initial.field) {
                    // Slight delay so the tab content is laid out before scrolling.
                    setTimeout(function () { highlightField(initial.field); }, 200);
                }
            }

            // Also react when the hash changes after page load — e.g. when a
            // recommendation card on the Audit tab links to "#page-cache" and
            // the user is already on the same admin page (no reload triggered).
            $(window).on('hashchange', function () {
                var changed = parseTabHash();
                if (changed.tab && $('[data-tab-content="' + changed.tab + '"]').length) {
                    activateTab(changed.tab);
                    if (changed.field) {
                        setTimeout(function () { highlightField(changed.field); }, 100);
                    }
                }
            });

            // Tab click handler
            $(document).on('click', '.blaminhor-essentials-tab', function(e) {
                e.preventDefault();

                const $tab = $(this);
                const target = $tab.data('tab');
                const $container = $tab.closest('.blaminhor-essentials-tabs-wrapper');

                activateTab(target, $container);

                // Update URL hash without scrolling
                if (history.replaceState) {
                    history.replaceState(null, null, '#' + target);
                }
            });

            // Preserve tab on form submit
            $(document).on('submit', '.blaminhor-essentials-tabs-wrapper form', function() {
                var $form = $(this);
                var $activeTab = $form.closest('.blaminhor-essentials-tabs-wrapper').find('.blaminhor-essentials-tab.active');
                var activeTab = $activeTab.data('tab');
                if (activeTab) {
                    var action = $form.attr('action') || window.location.pathname + window.location.search;
                    $form.attr('action', action.split('#')[0] + '#' + activeTab);
                    // Also set hidden input for server-side redirect.
                    var $hidden = $form.find('input[name="active_tab"]');
                    if ($hidden.length) {
                        $hidden.val(activeTab);
                    }
                }
            });

            // Expose activateTab for use by modules
            window.BlaminhorEssentialsActivateTab = activateTab;
        },

        /**
         * Modal handlers
         */
        bindModals: function() {
            // Open modal
            $(document).on('click', '[data-modal]', function(e) {
                e.preventDefault();
                const modalId = $(this).data('modal');
                $('#' + modalId).addClass('active');
            });

            // Close modal
            $(document).on('click', '.blaminhor-essentials-modal-overlay', function(e) {
                if ($(e.target).hasClass('blaminhor-essentials-modal-overlay')) {
                    $(this).removeClass('active');
                }
            });

            $(document).on('click', '[data-modal-close]', function(e) {
                e.preventDefault();
                $(this).closest('.blaminhor-essentials-modal-overlay').removeClass('active');
            });

            // Close on escape
            $(document).on('keyup', function(e) {
                if (e.key === 'Escape') {
                    $('.blaminhor-essentials-modal-overlay.active').removeClass('active');
                }
            });
        },

        /**
         * Dismiss feedback notice handler
         */
        bindDismissFeedback: function() {
            $(document).on('click', '.ap-dismiss-feedback', function(e) {
                e.preventDefault();

                const $notice = $(this).closest('.blaminhor-essentials-notice');

                $.ajax({
                    url: blaminhorEssentials.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'blaminhor_essentials_dismiss_feedback',
                        nonce: blaminhorEssentials.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $notice.fadeOut(300, function() {
                                $(this).remove();
                            });
                        }
                    }
                });
            });
        },

        /**
         * Escape HTML so user-controlled strings are safe inside DOM templates.
         */
        escHtml: function(str) {
            if (str === null || str === undefined || str === '') return '';
            const div = document.createElement('div');
            div.appendChild(document.createTextNode(String(str)));
            return div.innerHTML;
        },

        /**
         * Show notification.
         *
         * @param {string} message Text to display.
         * @param {string} type    'success' | 'error' | 'warning' | 'info'.
         * @param {Object} [opts]  Overrides:
         *   container {string|jQuery} target element, default '.blaminhor-essentials-wrap'
         *   position  {'prepend'|'append'|'before'|'after'} default 'prepend'
         *   style     {'plugin'|'wp'} default 'plugin' (WP = native admin notice)
         *   timeout   {number} ms before fade out, 0 disables, default 5000
         *   escape    {boolean} escape message, default true
         *   icon      {boolean} dashicon next to text (plugin style only), default false
         * @return {jQuery} the inserted notice element
         */
        showNotice: function(message, type, opts) {
            type = type || 'info';
            const settings = $.extend({
                container: '.blaminhor-essentials-wrap',
                position: 'prepend',
                style: 'plugin',
                timeout: 5000,
                escape: true,
                icon: false
            }, opts || {});

            const $container = settings.container && settings.container.jquery
                ? settings.container
                : $(settings.container);
            if (!$container.length) return $();

            const safe = settings.escape ? this.escHtml(message) : message;
            let $notice;

            if (settings.style === 'wp') {
                const wpClass = type === 'success' ? 'notice-success'
                              : type === 'error'   ? 'notice-error'
                              : type === 'warning' ? 'notice-warning'
                              :                      'notice-info';
                $notice = $('<div class="notice ' + wpClass + ' is-dismissible"><p></p></div>');
                $notice.find('p').html(safe);
            } else {
                let iconHtml = '';
                if (settings.icon) {
                    const dashicon = type === 'success' ? 'yes'
                                   : type === 'error'   ? 'warning'
                                   : type === 'warning' ? 'warning'
                                   :                      'info';
                    iconHtml = '<span class="dashicons dashicons-' + dashicon + '"></span> ';
                }
                $notice = $('<div class="blaminhor-essentials-notice ' + type + '"></div>');
                $notice.html(iconHtml + safe);
            }

            switch (settings.position) {
                case 'append':  $container.append($notice); break;
                case 'before':  $container.before($notice); break;
                case 'after':   $container.after($notice);  break;
                case 'prepend':
                default:        $container.prepend($notice);
            }

            if (settings.timeout > 0) {
                setTimeout(function() {
                    $notice.fadeOut(300, function() { $(this).remove(); });
                }, settings.timeout);
            }

            return $notice;
        },

        /**
         * Build a FormData payload for AJAX uploads.
         * Centralised so modules don't reinvent action/nonce wiring.
         *
         * @param {string} action  WP AJAX action.
         * @param {Object} data    Key/value pairs (FormData.append).
         * @param {string} [nonce] Defaults to the global plugin nonce.
         * @return {FormData}
         */
        buildFormData: function(action, data, nonce) {
            const fd = new FormData();
            fd.append('action', action);
            fd.append('nonce', nonce || (window.blaminhorEssentials && blaminhorEssentials.nonce) || '');
            if (data) {
                Object.keys(data).forEach(function(key) {
                    const value = data[key];
                    if (value === undefined || value === null) return;
                    if (value instanceof FileList) {
                        for (let i = 0; i < value.length; i++) fd.append(key, value[i]);
                    } else {
                        fd.append(key, value);
                    }
                });
            }
            return fd;
        }
    };

    // SMTP Module specific functionality
    const SMTPModule = {
        init: function() {
            this.bindProviderSelection();
            this.bindTestEmail();
            this.bindRelaySort();
            this.bindDeleteRelay();
        },

        /**
         * Provider selection
         */
        bindProviderSelection: function() {
            $(document).on('click', '.smtp-provider-card', function() {
                const $card = $(this);
                const provider = $card.data('provider');

                $('.smtp-provider-card').removeClass('selected');
                $card.addClass('selected');
                $('#smtp-provider').val(provider);

                // Auto-fill known provider settings
                SMTPModule.fillProviderDefaults(provider);
            });
        },

        /**
         * Fill provider defaults
         */
        fillProviderDefaults: function(provider) {
            const providers = {
                'brevo': { host: 'smtp-relay.brevo.com', port: 587, encryption: 'tls' },
                'sendgrid': { host: 'smtp.sendgrid.net', port: 587, encryption: 'tls' },
                'mailgun': { host: 'smtp.mailgun.org', port: 587, encryption: 'tls' },
                'amazon_ses': { host: 'email-smtp.us-east-1.amazonaws.com', port: 587, encryption: 'tls' },
                'postmark': { host: 'smtp.postmarkapp.com', port: 587, encryption: 'tls' },
                'sparkpost': { host: 'smtp.sparkpostmail.com', port: 587, encryption: 'tls' },
                'mailjet': { host: 'in-v3.mailjet.com', port: 587, encryption: 'tls' },
                'gmail': { host: 'smtp.gmail.com', port: 587, encryption: 'tls' },
                'outlook': { host: 'smtp.office365.com', port: 587, encryption: 'tls' },
                'zoho': { host: 'smtp.zoho.com', port: 587, encryption: 'tls' },
                'other': { host: '', port: 587, encryption: 'tls' }
            };

            if (providers[provider]) {
                $('#smtp-host').val(providers[provider].host);
                $('#smtp-port').val(providers[provider].port);
                $('#smtp-encryption').val(providers[provider].encryption);
            }
        },

        /**
         * Test email functionality
         */
        bindTestEmail: function() {
            $('#smtp-test-form').on('submit', function(e) {
                e.preventDefault();

                const $form = $(this);
                const $button = $form.find('button[type="submit"]');
                const $result = $('#smtp-test-result');
                const originalText = $button.text();

                $button.prop('disabled', true).text(blaminhorEssentials.strings.sending || 'Sending...');
                $result.removeClass('success error').html('');

                $.ajax({
                    url: blaminhorEssentials.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'blaminhor_essentials_smtp_test',
                        nonce: blaminhorEssentials.nonce,
                        email: $form.find('#test-email').val(),
                        relay_id: $form.find('#test-relay').val()
                    },
                    success: function(response) {
                        if (response.success) {
                            $result.addClass('success').html(response.data.message);
                        } else {
                            $result.addClass('error').html(response.data.message);
                        }
                    },
                    error: function() {
                        $result.addClass('error').html(blaminhorEssentials.strings.error);
                    },
                    complete: function() {
                        $button.prop('disabled', false).text(originalText);
                    }
                });
            });
        },

        /**
         * Sortable relays
         */
        bindRelaySort: function() {
            if ($.fn.sortable) {
                $('.smtp-relays-list').sortable({
                    handle: '.relay-handle',
                    update: function(event, ui) {
                        SMTPModule.saveRelayOrder();
                    }
                });
            }
        },

        /**
         * Save relay order
         */
        saveRelayOrder: function() {
            const order = [];
            $('.smtp-relay-item').each(function() {
                order.push($(this).data('relay-id'));
            });

            $.ajax({
                url: blaminhorEssentials.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'blaminhor_essentials_smtp_reorder',
                    nonce: blaminhorEssentials.nonce,
                    order: order
                }
            });
        },

        /**
         * Delete relay
         */
        bindDeleteRelay: function() {
            $(document).on('click', '.delete-relay', function(e) {
                e.preventDefault();

                if (!confirm(blaminhorEssentials.strings.confirmDeleteRelay || 'Are you sure you want to delete this relay?')) {
                    return;
                }

                const $item = $(this).closest('.smtp-relay-item');
                const relayId = $item.data('relay-id');

                $.ajax({
                    url: blaminhorEssentials.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'blaminhor_essentials_smtp_delete_relay',
                        nonce: blaminhorEssentials.nonce,
                        relay_id: relayId
                    },
                    success: function(response) {
                        if (response.success) {
                            $item.fadeOut(300, function() {
                                $(this).remove();
                            });
                        } else {
                            alert(response.data.message);
                        }
                    }
                });
            });
        }
    };

    // Duplicator Module specific functionality
    const DuplicatorModule = {
        init: function() {
            // Module-specific initialization
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        BlaminhorEssentials.init();

        // Initialize module-specific JS if on their pages
        if ($('.blaminhor-essentials-smtp-settings').length) {
            SMTPModule.init();
        }

        if ($('.blaminhor-essentials-duplicator-settings').length) {
            DuplicatorModule.init();
        }
    });

    // Expose to global
    window.BlaminhorEssentials = BlaminhorEssentials;
    window.BlaminhorEssentialsSMTP = SMTPModule;
    window.BlaminhorEssentialsDuplicator = DuplicatorModule;

})(jQuery);
