/**
 * HVAC Communication Templates JavaScript
 * 
 * Handles the frontend functionality for email template management
 * 
 * @version 1.0.0
 */

(function($) {
    'use strict';

    // Template Manager Object
    const HVACTemplates = {
        
        // Configuration
        config: {
            ajaxUrl: hvacTemplates.ajaxUrl,
            nonce: hvacTemplates.nonce,
            placeholders: hvacTemplates.placeholders,
            categories: hvacTemplates.categories,
            strings: hvacTemplates.strings
        },

        // Current state
        currentTemplateId: null,
        isEditing: false,
        templates: [],

        // Initialize
        init: function() {
            this.bindEvents();
            this.loadTemplates();
            this.setupPlaceholderHelper();
        },

        // Bind event handlers
        bindEvents: function() {
            const self = this;

            // Toggle template manager
            $(document).on('click', '.hvac-template-toggle', function(e) {
                e.preventDefault();
                self.toggleTemplateManager();
            });

            // Category filter change
            $(document).on('change', '.hvac-template-category-filter', function() {
                self.filterTemplatesByCategory($(this).val());
            });

            // Template actions
            $(document).on('click', '.hvac-btn-load', function(e) {
                e.preventDefault();
                const templateId = $('.hvac-template-dropdown').val();
                if (templateId) {
                    self.loadTemplate(templateId);
                }
            });

            $(document).on('click', '.hvac-btn-edit', function(e) {
                e.preventDefault();
                const templateId = $('.hvac-template-dropdown').val();
                if (templateId) {
                    self.editTemplate(templateId);
                }
            });

            $(document).on('click', '.hvac-btn-delete', function(e) {
                e.preventDefault();
                const templateId = $('.hvac-template-dropdown').val();
                if (templateId && confirm(self.config.strings.confirmDelete)) {
                    self.deleteTemplate(templateId);
                }
            });

            $(document).on('click', '.hvac-btn-save', function(e) {
                e.preventDefault();
                self.saveTemplate();
            });

            // Form actions
            $(document).on('click', '.hvac-template-form-save', function(e) {
                e.preventDefault();
                self.saveTemplate();
            });

            $(document).on('click', '.hvac-template-form-cancel', function(e) {
                e.preventDefault();
                self.cancelTemplateForm();
            });

            // Placeholder insertion
            $(document).on('click', '.hvac-placeholder-item', function(e) {
                e.preventDefault();
                const placeholder = $(this).find('.hvac-placeholder-code').text();
                self.insertPlaceholder(placeholder);
            });

            // Auto-save prevention
            $(document).on('beforeunload', function() {
                if (self.isEditing && self.hasUnsavedChanges()) {
                    return 'You have unsaved changes. Are you sure you want to leave?';
                }
            });
        },

        // Toggle template manager visibility
        toggleTemplateManager: function() {
            const $manager = $('.hvac-template-manager');
            const $toggle = $('.hvac-template-toggle');
            
            if ($manager.is(':visible')) {
                $manager.slideUp();
                $toggle.removeClass('active').text('📝 Use Template');
            } else {
                $manager.slideDown();
                $toggle.addClass('active').text('📝 Hide Templates');
            }
        },

        // Load user templates
        loadTemplates: function(category = '') {
            const self = this;
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'hvac_get_templates',
                    nonce: this.config.nonce,
                    category: category
                },
                success: function(response) {
                    if (response.success) {
                        self.templates = response.data.templates;
                        self.populateTemplateDropdown();
                    } else {
                        self.showMessage(response.data.message, 'error');
                    }
                },
                error: function() {
                    self.showMessage(self.config.strings.error, 'error');
                }
            });
        },

        // Filter templates by category
        filterTemplatesByCategory: function(category) {
            this.loadTemplates(category);
        },

        // Populate template dropdown
        populateTemplateDropdown: function() {
            const $dropdown = $('.hvac-template-dropdown');
            $dropdown.empty();
            
            if (this.templates.length === 0) {
                $dropdown.append('<option value="">' + 'No templates found' + '</option>');
                $('.hvac-template-actions-buttons button').prop('disabled', true);
                return;
            }

            $dropdown.append('<option value="">' + 'Select a template...' + '</option>');
            
            this.templates.forEach(function(template) {
                $dropdown.append(
                    '<option value="' + template.id + '">' + 
                    template.title + 
                    (template.category ? ' (' + template.category + ')' : '') +
                    '</option>'
                );
            });

            $('.hvac-template-actions-buttons button').prop('disabled', false);
        },

        // Load template content into email form
        loadTemplate: function(templateId) {
            const self = this;
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'hvac_load_template',
                    nonce: this.config.nonce,
                    template_id: templateId
                },
                beforeSend: function() {
                    $('.hvac-btn-load').addClass('hvac-loading');
                },
                success: function(response) {
                    if (response.success) {
                        const template = response.data;
                        
                        // Populate email form fields
                        $('#email_subject').val(template.title);
                        
                        // Handle different content areas (WordPress editor or textarea)
                        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('email_message')) {
                            tinyMCE.get('email_message').setContent(template.content);
                        } else {
                            $('#email_message').val(template.content);
                        }
                        
                        self.showMessage('Template loaded successfully', 'success');
                        
                        // Optionally hide template manager after loading
                        // self.toggleTemplateManager();
                        
                    } else {
                        self.showMessage(response.data.message, 'error');
                    }
                },
                complete: function() {
                    $('.hvac-btn-load').removeClass('hvac-loading');
                }
            });
        },

        // Edit template
        editTemplate: function(templateId) {
            const self = this;
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'hvac_load_template',
                    nonce: this.config.nonce,
                    template_id: templateId
                },
                beforeSend: function() {
                    $('.hvac-btn-edit').addClass('hvac-loading');
                },
                success: function(response) {
                    if (response.success) {
                        const template = response.data;
                        self.currentTemplateId = template.id;
                        self.isEditing = true;
                        
                        // Populate template form
                        $('#hvac_template_title').val(template.title);
                        $('#hvac_template_content').val(template.content);
                        $('#hvac_template_category').val(template.category);
                        $('#hvac_template_description').val(template.description);
                        
                        // Show template form
                        $('.hvac-template-form').addClass('active');
                        
                        self.showMessage('Template loaded for editing', 'success');
                        
                    } else {
                        self.showMessage(response.data.message, 'error');
                    }
                },
                complete: function() {
                    $('.hvac-btn-edit').removeClass('hvac-loading');
                }
            });
        },

        // Delete template
        deleteTemplate: function(templateId) {
            const self = this;
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'hvac_delete_template',
                    nonce: this.config.nonce,
                    template_id: templateId
                },
                beforeSend: function() {
                    $('.hvac-btn-delete').addClass('hvac-loading');
                },
                success: function(response) {
                    if (response.success) {
                        self.showMessage(response.data.message, 'success');
                        self.loadTemplates(); // Refresh template list
                    } else {
                        self.showMessage(response.data.message, 'error');
                    }
                },
                complete: function() {
                    $('.hvac-btn-delete').removeClass('hvac-loading');
                }
            });
        },

        // Save template
        saveTemplate: function() {
            const self = this;
            
            const templateData = {
                action: 'hvac_save_template',
                nonce: this.config.nonce,
                template_id: this.currentTemplateId || 0,
                title: $('#hvac_template_title').val(),
                content: $('#hvac_template_content').val(),
                category: $('#hvac_template_category').val(),
                description: $('#hvac_template_description').val()
            };

            // Validation
            if (!templateData.title || !templateData.content) {
                this.showMessage('Template title and content are required', 'error');
                return;
            }

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: templateData,
                beforeSend: function() {
                    $('.hvac-template-form-save').addClass('hvac-loading');
                },
                success: function(response) {
                    if (response.success) {
                        self.showMessage(response.data.message, 'success');
                        self.cancelTemplateForm();
                        self.loadTemplates(); // Refresh template list
                    } else {
                        self.showMessage(response.data.message, 'error');
                    }
                },
                complete: function() {
                    $('.hvac-template-form-save').removeClass('hvac-loading');
                }
            });
        },

        // Cancel template form
        cancelTemplateForm: function() {
            this.currentTemplateId = null;
            this.isEditing = false;
            
            // Clear form
            $('#hvac_template_title').val('');
            $('#hvac_template_content').val('');
            $('#hvac_template_category').val('');
            $('#hvac_template_description').val('');
            
            // Hide form
            $('.hvac-template-form').removeClass('active');
        },

        // Setup placeholder helper
        setupPlaceholderHelper: function() {
            const $helper = $('.hvac-placeholder-helper');
            if ($helper.length === 0) return;

            const $grid = $helper.find('.hvac-placeholder-grid');
            
            Object.keys(this.config.placeholders).forEach(function(placeholder) {
                const description = HVACTemplates.config.placeholders[placeholder];
                
                const $item = $('<div class="hvac-placeholder-item">' +
                    '<span class="hvac-placeholder-code">' + placeholder + '</span>' +
                    '<span class="hvac-placeholder-desc">' + description + '</span>' +
                    '</div>');
                
                $grid.append($item);
            });
        },

        // Insert placeholder into content
        insertPlaceholder: function(placeholder) {
            // Try to insert into WordPress editor first
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('email_message')) {
                const editor = tinyMCE.get('email_message');
                editor.insertContent(placeholder);
                return;
            }
            
            // Try template content textarea
            if ($('#hvac_template_content').length) {
                const $textarea = $('#hvac_template_content');
                const cursorPos = $textarea[0].selectionStart;
                const textBefore = $textarea.val().substring(0, cursorPos);
                const textAfter = $textarea.val().substring(cursorPos);
                
                $textarea.val(textBefore + placeholder + textAfter);
                $textarea[0].setSelectionRange(cursorPos + placeholder.length, cursorPos + placeholder.length);
                $textarea.focus();
                return;
            }
            
            // Fallback to email message textarea
            if ($('#email_message').length) {
                const $textarea = $('#email_message');
                const cursorPos = $textarea[0].selectionStart;
                const textBefore = $textarea.val().substring(0, cursorPos);
                const textAfter = $textarea.val().substring(cursorPos);
                
                $textarea.val(textBefore + placeholder + textAfter);
                $textarea[0].setSelectionRange(cursorPos + placeholder.length, cursorPos + placeholder.length);
                $textarea.focus();
            }
        },

        // Check for unsaved changes
        hasUnsavedChanges: function() {
            if (!this.isEditing) return false;
            
            return $('#hvac_template_title').val() !== '' ||
                   $('#hvac_template_content').val() !== '' ||
                   $('#hvac_template_category').val() !== '' ||
                   $('#hvac_template_description').val() !== '';
        },

        // Show messages
        showMessage: function(message, type) {
            const $container = $('.hvac-template-manager');
            
            // Remove existing messages
            $container.find('.hvac-template-message').remove();
            
            // Add new message
            const $message = $('<div class="hvac-template-message ' + type + '">' + message + '</div>');
            $container.prepend($message);
            
            // Auto-hide success messages
            if (type === 'success') {
                setTimeout(function() {
                    $message.fadeOut(function() {
                        $message.remove();
                    });
                }, 3000);
            }
        },

        // Create new template (helper method)
        createNewTemplate: function() {
            this.currentTemplateId = null;
            this.isEditing = true;
            
            // Clear and show form
            this.cancelTemplateForm();
            $('.hvac-template-form').addClass('active');
            
            // Focus on title field
            $('#hvac_template_title').focus();
        },

        // Utility: Get current email content
        getCurrentEmailContent: function() {
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('email_message')) {
                return tinyMCE.get('email_message').getContent();
            }
            return $('#email_message').val() || '';
        },

        // Utility: Get current email subject
        getCurrentEmailSubject: function() {
            return $('#email_subject').val() || '';
        },

        // Save current email as template
        saveCurrentEmailAsTemplate: function() {
            const content = this.getCurrentEmailContent();
            const subject = this.getCurrentEmailSubject();
            
            if (!content && !subject) {
                this.showMessage('No email content to save as template', 'error');
                return;
            }
            
            // Pre-fill form with current email content
            $('#hvac_template_title').val(subject || 'New Template');
            $('#hvac_template_content').val(content);
            
            this.createNewTemplate();
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        // Only initialize if template manager is present
        if ($('.hvac-template-manager').length || $('.hvac-template-toggle').length) {
            HVACTemplates.init();
        }
    });

    // Expose to global scope for external usage
    window.HVACTemplates = HVACTemplates;

})(jQuery);