/**
 * Certificate Admin JavaScript
 * 
 * Handles certificate admin functionality including preview generation.
 */

(function($) {
    'use strict';
    
    // Initialize color pickers
    function initColorPickers() {
        if ($.fn.wpColorPicker) {
            $('.hvac-color-picker').wpColorPicker({
                change: function() {
                    // Trigger settings change on color picker change
                    $(this).trigger('change');
                }
            });
        }
    }
    
    // Generate certificate preview
    function generatePreview() {
        var previewContainer = $('.hvac-certificate-preview');
        var loadingIndicator = $('<div class="hvac-preview-loading">Generating preview...</div>');
        
        // Show loading indicator
        previewContainer.html(loadingIndicator);
        
        // Collect all settings
        var settings = {};
        $('.hvac-certificate-settings input, .hvac-certificate-settings select, .hvac-certificate-settings textarea').each(function() {
            var input = $(this);
            var name = input.attr('name');
            
            if (name && name.startsWith('hvac_certificate_')) {
                var key = name.replace('hvac_certificate_', '');
                settings[key] = input.val();
            }
        });
        
        // Send AJAX request
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'hvac_preview_certificate',
                nonce: hvacCertificateData.previewNonce,
                settings: settings
            },
            success: function(response) {
                if (response.success) {
                    // Create preview image
                    var previewImg = $('<img>', {
                        src: response.data.preview_url,
                        alt: 'Certificate Preview',
                        class: 'hvac-certificate-preview-img'
                    });
                    
                    // Display preview
                    previewContainer.html(previewImg);
                } else {
                    // Show error
                    previewContainer.html('<div class="hvac-preview-error">Error: ' + response.data.message + '</div>');
                }
            },
            error: function() {
                // Show connection error
                previewContainer.html('<div class="hvac-preview-error">Error: Could not connect to the server</div>');
            }
        });
    }
    
    // Handle file uploads
    function initFileUploads() {
        // Background image upload
        $('#hvac_upload_background_btn').on('click', function(e) {
            e.preventDefault();
            
            var button = $(this);
            var field = $('#hvac_certificate_custom_background');
            
            var frame = wp.media({
                title: 'Select Certificate Background',
                button: {
                    text: 'Use this image'
                },
                multiple: false
            });
            
            frame.on('select', function() {
                var attachment = frame.state().get('selection').first().toJSON();
                field.val(attachment.url);
                
                // Show preview
                if ($('#background_preview').length) {
                    $('#background_preview').attr('src', attachment.url);
                } else {
                    $('<img>', {
                        id: 'background_preview',
                        src: attachment.url,
                        class: 'hvac-image-preview',
                        style: 'max-width: 200px; margin-top: 10px;'
                    }).insertAfter(field);
                }
                
                // Trigger change to update preview
                field.trigger('change');
            });
            
            frame.open();
        });
        
        // Logo image upload
        $('#hvac_upload_logo_btn').on('click', function(e) {
            e.preventDefault();
            
            var button = $(this);
            var field = $('#hvac_certificate_custom_logo');
            
            var frame = wp.media({
                title: 'Select Certificate Logo',
                button: {
                    text: 'Use this image'
                },
                multiple: false
            });
            
            frame.on('select', function() {
                var attachment = frame.state().get('selection').first().toJSON();
                field.val(attachment.url);
                
                // Show preview
                if ($('#logo_preview').length) {
                    $('#logo_preview').attr('src', attachment.url);
                } else {
                    $('<img>', {
                        id: 'logo_preview',
                        src: attachment.url,
                        class: 'hvac-image-preview',
                        style: 'max-width: 100px; margin-top: 10px;'
                    }).insertAfter(field);
                }
                
                // Trigger change to update preview
                field.trigger('change');
            });
            
            frame.open();
        });
    }
    
    // Insert placeholder
    function initPlaceholders() {
        $('.hvac-placeholder-insert').on('click', function(e) {
            e.preventDefault();
            
            var placeholder = $(this).data('placeholder');
            var targetField = $('#hvac_certificate_completion_text');
            
            // Insert at cursor position
            var field = targetField[0];
            var startPos = field.selectionStart;
            var endPos = field.selectionEnd;
            var text = field.value;
            
            field.value = text.substring(0, startPos) + placeholder + text.substring(endPos);
            
            // Set cursor position after placeholder
            field.selectionStart = startPos + placeholder.length;
            field.selectionEnd = startPos + placeholder.length;
            
            // Focus the field
            field.focus();
            
            // Trigger change to update preview
            targetField.trigger('change');
        });
    }
    
    // Init on document ready
    $(document).ready(function() {
        // Initialize color pickers
        initColorPickers();
        
        // Initialize file uploads
        initFileUploads();
        
        // Initialize placeholder inserts
        initPlaceholders();
        
        // Generate preview on settings change (debounced)
        var previewTimeout;
        $('.hvac-certificate-settings input, .hvac-certificate-settings select, .hvac-certificate-settings textarea').on('change', function() {
            clearTimeout(previewTimeout);
            previewTimeout = setTimeout(generatePreview, 800);
        });
        
        // Generate initial preview
        generatePreview();
        
        // Handle preview button click
        $('#hvac_generate_preview_btn').on('click', function(e) {
            e.preventDefault();
            generatePreview();
        });
    });
    
})(jQuery);