/**
 * Prompt History functionality for ClearPost Simple AI Auto Post
 *
 * Handles click events for prompt history buttons and modal functionality
 */
jQuery(document).ready(function($) {
    
    // Add our event listener directly to document for prompt buttons
    document.addEventListener('click', function(e) {
        // Check if the clicked element or any of its parents have the class
        if (e.target.closest('.saiap-history-prompt')) {
            
            // Get the button
            var button = e.target.closest('.saiap-history-prompt');
            
            // Get data from button attributes
            var prompt = button.getAttribute('data-prompt');
            var model = button.getAttribute('data-model');
            
            // Fill form fields
            if (prompt) {
                var promptField = document.getElementById('saiap-prompt');
                if (promptField) {
                    promptField.value = prompt;
                }
            }
            
            // Determine provider based on model
            if (model) {
                var provider = 'openai';
                if (model.indexOf('claude') !== -1) {
                    provider = 'anthropic';
                } else if (model.indexOf('gemini') !== -1) {
                    provider = 'gemini';
                }
                
                // Set provider
                var providerField = document.getElementById('saiap-provider');
                if (providerField) {
                    providerField.value = provider;
                    
                    // Trigger change event
                    var event = new Event('change');
                    providerField.dispatchEvent(event);
                }
                
                // Set appropriate model field
                var modelField = null;
                if (provider === 'openai') {
                    modelField = document.getElementById('saiap-model');
                } else if (provider === 'anthropic') {
                    modelField = document.getElementById('saiap-anthropic-model');
                } else if (provider === 'gemini') {
                    modelField = document.getElementById('saiap-gemini-model');
                }
                
                if (modelField) {
                    modelField.value = model;
                }
            }
        }
    });
    
    /**
     * Handle "Load More" button
     */
    $('#saiap-load-more-prompts').on('click', function(e) {
        e.preventDefault();
        
        var button = $(this);
        var currentPage = parseInt(button.data('page'), 10);
        var nextPage = currentPage + 1;
        var nonce = button.data('nonce');
        
        // Disable button while loading
        button.prop('disabled', true);
        
        // Send AJAX request
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'saiap_get_all_prompts',
                nonce: nonce,
                page: nextPage,
                per_page: 5
            },
            success: function(response) {
                if (response.success && response.data.prompts && response.data.prompts.length > 0) {
                    // Append new prompts to the list
                    $.each(response.data.prompts, function(index, prompt) {
                        var postTitles = '';
                        if (prompt.post_titles) {
                            var titles = prompt.post_titles.split('||');
                            var trimmedTitles = titles.map(function(title) {
                                return title.split(' ').slice(0, 5).join(' ') + (title.split(' ').length > 5 ? '...' : '');
                            });
                            postTitles = '<span class="saiap-prompt-posts">' + trimmedTitles.join(', ') + '</span>';
                        }
                        
                        var timeAgo = '';
                        if (prompt.created_at) {
                            // Simple time ago calculation
                            var date = new Date(prompt.created_at);
                            var now = new Date();
                            var diffInSeconds = Math.floor((now - date) / 1000);
                            
                            if (diffInSeconds < 60) {
                                timeAgo = diffInSeconds + ' seconds ago';
                            } else if (diffInSeconds < 3600) {
                                timeAgo = Math.floor(diffInSeconds / 60) + ' minutes ago';
                            } else if (diffInSeconds < 86400) {
                                timeAgo = Math.floor(diffInSeconds / 3600) + ' hours ago';
                            } else {
                                timeAgo = Math.floor(diffInSeconds / 86400) + ' days ago';
                            }
                        }
                        
                        var promptText = prompt.prompt;
                        // Trim prompt text to 15 words
                        if (promptText.split(' ').length > 15) {
                            promptText = promptText.split(' ').slice(0, 15).join(' ') + '...';
                        }
                        
                        var promptHtml = '<button type="button" ' +
                            'class="secondary-button saiap-history-prompt" ' +
                            'data-prompt="' + (prompt.prompt || '').replace(/"/g, '&quot;') + '" ' +
                            'data-model="' + (prompt.model || '') + '" ' +
                            'data-system-prompt="' + (prompt.system_prompt || '').replace(/"/g, '&quot;') + '" ' +
                            'data-timestamp="' + (prompt.created_at || '') + '" ' +
                            'title="' + (prompt.prompt || '').replace(/"/g, '&quot;') + '">' +
                            promptText +
                            (postTitles ? postTitles : '') +
                            '<span class="saiap-prompt-timestamp">' + timeAgo + '</span>' +
                            '</button>';
                        
                        $('#saiap-prompt-list').append(promptHtml);
                    });
                    
                    // Update page number
                    button.data('page', nextPage);
                    
                    // Hide button if no more prompts
                    if (!response.data.has_more) {
                        button.hide();
                    }
                } else {
                    // No more prompts, hide button
                    button.hide();
                }
            },
            error: function(xhr, status, error) {
                console.error('Error loading more prompts:', status, error);
            },
            complete: function() {
                button.prop('disabled', false);
            }
        });
    });
});
