jQuery(document).ready(function($) {
    
    // Toggle suggestion form
    window.pcToggleSuggestionForm = function() {
        const form = document.getElementById('pc-suggestion-form');
        if (form.style.display === 'none') {
            form.style.display = 'block';
            form.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        } else {
            form.style.display = 'none';
        }
    };
    
    // Change sort method
    window.pcChangeSort = function(sort) {
        const url = new URL(window.location.href);
        url.searchParams.set('sort', sort);
        window.location.href = url.toString();
    };
    
    // Handle suggestion submission
    $('#pc-new-suggestion-form').on('submit', function(e) {
        e.preventDefault();
        
        const form = $(this);
        const submitBtn = form.find('button[type="submit"]');
        const title = $('#pc-suggestion-title').val().trim();
        const content = $('#pc-suggestion-content').val().trim();
        
        // Basic validation
        if (!title || !content) {
            alert(pcCommunitySuggestions.i18n.fill_all_fields);
            return;
        }
        
        if (title.length > 255) {
            alert(pcCommunitySuggestions.i18n.title_too_long);
            return;
        }
        
        submitBtn.prop('disabled', true).addClass('pc-loading');
        
        $.ajax({
            url: pcCommunitySuggestions.ajax_url,
            type: 'POST',
            data: {
                action: 'pc_submit_suggestion',
                title: title,
                content: content,
                nonce: pcCommunitySuggestions.nonce
            },
            success: function(response) {
                console.log('AJAX Response:', response);
                if (response.success) {
                    // Clear form and show success message
                    form[0].reset();
                    pcToggleSuggestionForm();
                    
                    // Show success message
                    pcShowMessage(response.data.message, 'success');
                    
                    // Reload page to show new suggestion
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    pcShowMessage(response.data.message, 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                console.error('Response Text:', xhr.responseText);
                console.error('Status Code:', xhr.status);
                if (xhr.responseText) {
                    pcShowMessage('Error: ' + xhr.responseText.substring(0, 200) + '...', 'error');
                } else {
                    pcShowMessage(pcCommunitySuggestions.i18n.ajax_error + ' (Status: ' + xhr.status + ')', 'error');
                }
            },
            complete: function() {
                submitBtn.prop('disabled', false).removeClass('pc-loading');
            }
        });
    });
    
    // Handle voting
    window.pcVoteSuggestion = function(suggestionId) {
        if (!pcCommunitySuggestions.is_user_logged_in) {
            alert(pcCommunitySuggestions.i18n.login_to_vote);
            return;
        }
        
        const voteBtn = $(`.pc-vote-button[onclick*="${suggestionId}"]`);
        if (voteBtn.prop('disabled')) {
            return;
        }
        
        voteBtn.prop('disabled', true).addClass('pc-loading');
        
        $.ajax({
            url: pcCommunitySuggestions.ajax_url,
            type: 'POST',
            data: {
                action: 'pc_vote_suggestion',
                suggestion_id: suggestionId,
                nonce: pcCommunitySuggestions.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Update UI
                    const voteCount = voteBtn.find('.pc-vote-count');
                    const currentVotes = parseInt(voteCount.text());
                    voteCount.text(currentVotes + 1);
                    
                    voteBtn.addClass('pc-voted');
                    voteBtn.find('.pc-vote-arrow').css('color', '#2a6b2a');
                    
                    pcShowMessage(response.data.message, 'success');
                } else {
                    pcShowMessage(response.data.message, 'error');
                }
            },
            error: function() {
                pcShowMessage(pcCommunitySuggestions.i18n.ajax_error, 'error');
            },
            complete: function() {
                voteBtn.removeClass('pc-loading');
            }
        });
    };
    
    // Show message function
    function pcShowMessage(message, type = 'info') {
        // Remove existing messages
        $('.pc-message').remove();
        
        const messageClass = `pc-message pc-message-${type}`;
        const messageHtml = `
            <div class="${messageClass}">
                <p>${message}</p>
                <button class="pc-message-close" onclick="$(this).parent().fadeOut(300, function() { $(this).remove(); })">
                    &times;
                </button>
            </div>
        `;
        
        $('.pc-suggestions-header').after(messageHtml);
        
        // Auto-hide after 5 seconds
        setTimeout(() => {
            $('.pc-message').fadeOut(300, function() {
                $(this).remove();
            });
        }, 5000);
    }
    
    // Add message styles dynamically
    $('<style>')
        .text(`
            .pc-message {
                padding: 15px 20px;
                margin: 20px 0;
                border-radius: 6px;
                border-left: 4px solid;
                position: relative;
                animation: pc-slide-in 0.3s ease-out;
            }
            
            .pc-message-success {
                background: #edfaef;
                border-color: #00a32a;
                color: #2a6b2a;
            }
            
            .pc-message-error {
                background: #fcf0f1;
                border-color: #d63638;
                color: #b32d2e;
            }
            
            .pc-message-info {
                background: #f0f6ff;
                border-color: #2271b1;
                color: #135e96;
            }
            
            .pc-message-close {
                position: absolute;
                top: 10px;
                right: 10px;
                background: none;
                border: none;
                font-size: 18px;
                cursor: pointer;
                padding: 0;
                width: 20px;
                height: 20px;
                line-height: 1;
            }
            
            @keyframes pc-slide-in {
                from {
                    opacity: 0;
                    transform: translateY(-10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
        `)
        .appendTo('head');
    
    // Add loading class styles
    $('<style>')
        .text(`
            .pc-loading {
                opacity: 0.7;
                pointer-events: none;
                position: relative;
            }
            
            .pc-loading::after {
                content: '';
                display: inline-block;
                width: 16px;
                height: 16px;
                border: 2px solid #f3f3f3;
                border-top: 2px solid #2271b1;
                border-radius: 50%;
                animation: pc-spin 1s linear infinite;
                margin-left: 8px;
                vertical-align: middle;
            }
            
            @keyframes pc-spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `)
        .appendTo('head');
    

    
    // Handle enter key in form
    $('#pc-suggestion-title, #pc-suggestion-content').on('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            $('#pc-new-suggestion-form').submit();
        }
    });
    
    // Auto-resize textarea
    $('#pc-suggestion-content').on('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    }).trigger('input');
    
    // Focus on title field when form opens
    $(document).on('click', '#pc-suggestion-form', function(e) {
        if (e.target === this) {
            $('#pc-suggestion-title').focus();
        }
    });
});