/**
 * OpenAI integration for Tech Repair Service
 */
(function($) {
    'use strict';
    
    // Initialize when document is ready
    $(document).ready(function() {
        // Only run on issue edit page
        if ($('#tech_repair_issue_details').length === 0) {
            return;
        }
        
        // Add generate button to editor
        addGenerateButton();
        
        // Handle generate button click
        $(document).on('click', '#tech_repair_generate_description', function(e) {
            e.preventDefault();
            generateDescription();
        });
    });
    
    /**
     * Add generate button to editor
     */
    function addGenerateButton() {
        // Create button HTML
        var buttonHtml = '<div id="tech-repair-openai-container" class="tech-repair-openai-container">' +
            '<button type="button" id="tech_repair_generate_description" class="button button-secondary">' +
            '<span class="dashicons dashicons-admin-site"></span> ' +
            techRepairOpenAI.generateButtonText +
            '</button>' +
            '<span class="spinner"></span>' +
            '</div>';
        
        // Add button before editor
        $('#wp-content-editor-tools .wp-editor-tabs').after(buttonHtml);
        
        // Add status container
        $('#tech-repair-openai-container').after('<div id="tech-repair-openai-status" class="tech-repair-openai-status"></div>');
    }
    
    /**
     * Generate description using OpenAI
     */
    function generateDescription() {
        // Get issue title
        var title = $('#title').val();
        
        // Get issue type
        var type = '';
        $('#tech_repair_issue_typechecklist input:checked').each(function() {
            type = $(this).parent().text().trim();
            return false; // Get only first selected type
        });
        
        // Get selected device (optional)
        var device = '';
        $('#tech_repair_issue_devices input:checked').each(function() {
            device = $(this).parent().text().trim();
            return false; // Get only first selected device
        });
        
        // Validate inputs
        if (!title) {
            showStatus('error', techRepairOpenAI.errorTitleRequired);
            return;
        }
        
        if (!type) {
            showStatus('error', techRepairOpenAI.errorTypeRequired);
            return;
        }
        
        // Show loading state
        $('#tech-repair-openai-container .spinner').addClass('is-active');
        $('#tech_repair_generate_description').prop('disabled', true);
        showStatus('info', techRepairOpenAI.generatingText);
        
        // Make AJAX request
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'tech_repair_generate_description',
                nonce: techRepairOpenAI.nonce,
                title: title,
                type: type,
                device: device
            },
            success: function(response) {
                // Hide loading state
                $('#tech-repair-openai-container .spinner').removeClass('is-active');
                $('#tech_repair_generate_description').prop('disabled', false);
                
                if (response.success) {
                    // Insert generated description into editor
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                        tinyMCE.get('content').setContent(response.data.description);
                    } else {
                        $('#content').val(response.data.description);
                    }
                    
                    showStatus('success', techRepairOpenAI.successText);
                } else {
                    showStatus('error', response.data.message);
                }
            },
            error: function() {
                // Hide loading state
                $('#tech-repair-openai-container .spinner').removeClass('is-active');
                $('#tech_repair_generate_description').prop('disabled', false);
                
                showStatus('error', techRepairOpenAI.errorText);
            }
        });
    }
    
    /**
     * Show status message
     * 
     * @param {string} type Message type (success, error, info)
     * @param {string} message Message text
     */
    function showStatus(type, message) {
        var statusClass = 'notice ';
        
        switch (type) {
            case 'success':
                statusClass += 'notice-success';
                break;
            case 'error':
                statusClass += 'notice-error';
                break;
            default:
                statusClass += 'notice-info';
        }
        
        $('#tech-repair-openai-status').html('<div class="' + statusClass + '"><p>' + message + '</p></div>');
        
        // Auto-hide success and info messages after 5 seconds
        if (type === 'success' || type === 'info') {
            setTimeout(function() {
                $('#tech-repair-openai-status').empty();
            }, 5000);
        }
    }
    
})(jQuery);
