/**
 * GGM Commerce Email Admin JavaScript
 */
(function($) {
    'use strict';

    var GGMC_Email_Admin = {
        currentEmailType: null,
        editor: null,

        init: function() {
            this.bindEvents();
        },

        bindEvents: function() {
            var self = this;

            // Toggle email enabled/disabled
            $(document).on('change', '.ggmc-email-toggle', function() {
                self.toggleEmail($(this));
            });

            // Open configure modal
            $(document).on('click', '.ggmc-configure-email', function() {
                var emailId = $(this).data('email-id');
                self.openConfigureModal(emailId);
            });

            // Close modal
            $(document).on('click', '.ggmc-modal-close', function() {
                self.closeModal();
            });

            // Close modal on backdrop click
            $(document).on('click', '.ggmc-modal', function(e) {
                if ($(e.target).hasClass('ggmc-modal')) {
                    self.closeModal();
                }
            });

            // Close modal on Escape key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape') {
                    self.closeModal();
                }
            });

            // Save template
            $(document).on('click', '#ggmc-save-template', function() {
                self.saveTemplate();
            });

            // Preview email
            $(document).on('click', '#ggmc-preview-email', function() {
                self.previewEmail();
            });

            // Send test email
            $(document).on('click', '#ggmc-send-test-email', function() {
                self.sendTestEmail();
            });

            // Reset template
            $(document).on('click', '#ggmc-reset-template', function() {
                if (confirm(ggmcEmailAdmin.strings.confirmReset)) {
                    self.resetTemplate();
                }
            });

            // Click to insert placeholder
            $(document).on('click', '.ggmc-placeholder-tag', function() {
                self.insertPlaceholder($(this).text());
            });
        },

        toggleEmail: function($toggle) {
            var emailId = $toggle.data('email-id');
            var enabled = $toggle.is(':checked');

            $.ajax({
                url: ggmcEmailAdmin.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'ggmc_toggle_email',
                    nonce: ggmcEmailAdmin.nonce,
                    email_type: emailId,
                    enabled: enabled
                },
                success: function(response) {
                    if (!response.success) {
                        // Revert toggle on error
                        $toggle.prop('checked', !enabled);
                    }
                },
                error: function() {
                    $toggle.prop('checked', !enabled);
                }
            });
        },

        openConfigureModal: function(emailId) {
            var self = this;
            self.currentEmailType = emailId;

            // Show loading state
            $('#ggmc-email-editor-modal').show();
            $('#ggmc-modal-title').text('Loading...');

            // Fetch template data
            $.ajax({
                url: ggmcEmailAdmin.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'ggmc_get_email_template',
                    nonce: ggmcEmailAdmin.nonce,
                    email_type: emailId
                },
                success: function(response) {
                    if (response.success) {
                        self.populateForm(response.data);
                    } else {
                        self.closeModal();
                        alert('Error loading template');
                    }
                },
                error: function() {
                    self.closeModal();
                    alert('Error loading template');
                }
            });
        },

        populateForm: function(data) {
            $('#ggmc-modal-title').text(data.title);
            $('#ggmc-email-type').val(data.email_type);
            $('#ggmc-email-subject').val(data.subject);
            $('#ggmc-email-heading').val(data.heading);
            $('#ggmc-additional-recipients').val(data.additional_recipients || '');

            // Set content in TinyMCE
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('ggmc-email-content')) {
                tinyMCE.get('ggmc-email-content').setContent(data.content || '');
            } else {
                $('#ggmc-email-content').val(data.content || '');
            }

            // Populate placeholders
            this.populatePlaceholders(data.placeholders);
        },

        populatePlaceholders: function(placeholders) {
            var $list = $('#ggmc-placeholders-list');
            $list.empty();

            if (placeholders) {
                $.each(placeholders, function(key, label) {
                    $list.append(
                        $('<span>')
                            .addClass('ggmc-placeholder-tag')
                            .text('{' + key + '}')
                            .attr('title', label)
                    );
                });
            }
        },

        insertPlaceholder: function(placeholder) {
            // Insert into TinyMCE if active
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('ggmc-email-content') && !tinyMCE.get('ggmc-email-content').isHidden()) {
                tinyMCE.get('ggmc-email-content').execCommand('mceInsertContent', false, placeholder);
            } else {
                // Insert into textarea
                var $textarea = $('#ggmc-email-content');
                var cursorPos = $textarea[0].selectionStart;
                var text = $textarea.val();
                $textarea.val(text.substring(0, cursorPos) + placeholder + text.substring(cursorPos));
            }
        },

        closeModal: function() {
            $('.ggmc-modal').hide();
            this.currentEmailType = null;
        },

        getFormData: function() {
            var content = '';

            // Get content from TinyMCE or textarea
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('ggmc-email-content') && !tinyMCE.get('ggmc-email-content').isHidden()) {
                content = tinyMCE.get('ggmc-email-content').getContent();
            } else {
                content = $('#ggmc-email-content').val();
            }

            return {
                email_type: this.currentEmailType,
                subject: $('#ggmc-email-subject').val(),
                heading: $('#ggmc-email-heading').val(),
                content: content,
                additional_recipients: $('#ggmc-additional-recipients').val()
            };
        },

        saveTemplate: function() {
            var self = this;
            var $button = $('#ggmc-save-template');
            var originalText = $button.html();

            $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> ' + ggmcEmailAdmin.strings.saving);

            var data = this.getFormData();
            data.action = 'ggmc_save_email_template';
            data.nonce = ggmcEmailAdmin.nonce;

            $.ajax({
                url: ggmcEmailAdmin.ajaxUrl,
                method: 'POST',
                data: data,
                success: function(response) {
                    if (response.success) {
                        $button.html('<span class="dashicons dashicons-yes"></span> ' + ggmcEmailAdmin.strings.saved);
                        setTimeout(function() {
                            $button.prop('disabled', false).html(originalText);
                        }, 2000);
                    } else {
                        alert(response.data.message || ggmcEmailAdmin.strings.error);
                        $button.prop('disabled', false).html(originalText);
                    }
                },
                error: function() {
                    alert(ggmcEmailAdmin.strings.error);
                    $button.prop('disabled', false).html(originalText);
                }
            });
        },

        previewEmail: function() {
            var self = this;
            var data = this.getFormData();

            if (!data.email_type) {
                alert('Error: No email type selected');
                return;
            }

            data.action = 'ggmc_preview_email';
            data.nonce = ggmcEmailAdmin.nonce;

            $.ajax({
                url: ggmcEmailAdmin.ajaxUrl,
                method: 'POST',
                data: data,
                success: function(response) {
                    if (response.success) {
                        self.showPreview(response.data.html);
                    } else {
                        alert(response.data && response.data.message ? response.data.message : 'Error generating preview');
                    }
                },
                error: function(xhr, status, error) {
                    alert('Error generating preview: ' + error);
                }
            });
        },

        showPreview: function(html) {
            var $modal = $('#ggmc-preview-modal');
            var $iframe = $('#ggmc-preview-frame');

            $modal.show();

            // Write HTML to iframe
            var iframeDoc = $iframe[0].contentDocument || $iframe[0].contentWindow.document;
            iframeDoc.open();
            iframeDoc.write(html);
            iframeDoc.close();
        },

        sendTestEmail: function() {
            var self = this;
            var $button = $('#ggmc-send-test-email');
            var originalText = $button.html();

            // Prompt for email address
            var recipient = prompt('Enter email address for test:', '');
            if (!recipient) return;

            $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> ' + ggmcEmailAdmin.strings.sending);

            var data = this.getFormData();
            data.action = 'ggmc_send_test_email';
            data.nonce = ggmcEmailAdmin.nonce;
            data.recipient = recipient;

            $.ajax({
                url: ggmcEmailAdmin.ajaxUrl,
                method: 'POST',
                data: data,
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message || ggmcEmailAdmin.strings.sent);
                    } else {
                        alert(response.data.message || ggmcEmailAdmin.strings.sendError);
                    }
                    $button.prop('disabled', false).html(originalText);
                },
                error: function() {
                    alert(ggmcEmailAdmin.strings.sendError);
                    $button.prop('disabled', false).html(originalText);
                }
            });
        },

        resetTemplate: function() {
            var self = this;
            var $button = $('#ggmc-reset-template');
            var originalText = $button.html();

            $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> ' + ggmcEmailAdmin.strings.resetting);

            $.ajax({
                url: ggmcEmailAdmin.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'ggmc_reset_email_template',
                    nonce: ggmcEmailAdmin.nonce,
                    email_type: this.currentEmailType
                },
                success: function(response) {
                    if (response.success) {
                        self.populateForm(response.data.template);
                        alert(ggmcEmailAdmin.strings.resetComplete);
                    } else {
                        alert(response.data.message || 'Error resetting template');
                    }
                    $button.prop('disabled', false).html(originalText);
                },
                error: function() {
                    alert('Error resetting template');
                    $button.prop('disabled', false).html(originalText);
                }
            });
        }
    };

    // Initialize
    $(document).ready(function() {
        GGMC_Email_Admin.init();
    });

    // Add spinning animation
    $('<style>.dashicons.spin { animation: ggmc-spin 1s linear infinite; } @keyframes ggmc-spin { 100% { transform: rotate(360deg); } }</style>').appendTo('head');

})(jQuery);
