/*
|--------------------------------------------------------------------------
| Comments Frontend JavaScript - jQuery + Bootstrap 5
|--------------------------------------------------------------------------
*/

(function($) {
    'use strict';

    let currentPage = 1;
    let totalPages = 1;
    let isLoading = false;

    // ========================================
    // Initialize
    // ========================================
    $(document).ready(function() {
        loadComments();
        initForm();
    });

    // ========================================
    // Load Comments
    // ========================================
    function loadComments(page = 1, append = false) {
        if (isLoading) return;
        isLoading = true;

        const $container = $('#commentsList');
        const $loading = $('#commentsLoading');
        const $loadMore = $('#loadMoreWrapper');

        if (!append) {
            $container.html($loading.show());
        }

        $.ajax({
            url: COMMENTS_FRONTEND_CONFIG.routes.index,
            method: 'GET',
            data: { page: page },
            success: function(response) {
                if (response.success) {
                    currentPage = response.pagination.current_page;
                    totalPages = response.pagination.last_page;

                    // Update stats
                    updateStats(response.stats);

                    // Render comments
                    if (!append) {
                        $container.empty();
                    }
                    $loading.hide();

                    if (response.comments.length > 0) {
                        response.comments.forEach(function(comment) {
                            $container.append(renderComment(comment));
                        });
                    } else if (!append) {
                        $container.html(renderNoComments());
                    }

                    // Show/hide load more
                    if (currentPage < totalPages) {
                        $loadMore.show();
                    } else {
                        $loadMore.hide();
                    }
                }
            },
            error: function() {
                $loading.hide();
                $container.html('<div class="text-danger text-center py-4">' + COMMENTS_FRONTEND_CONFIG.translations.error + '</div>');
            },
            complete: function() {
                isLoading = false;
            }
        });
    }

    // ========================================
    // Update Stats
    // ========================================
    function updateStats(stats) {
        $('#commentStats').html(stats.total + ' ' + COMMENTS_FRONTEND_CONFIG.translations.reviews);

        if (COMMENTS_FRONTEND_CONFIG.showRating && stats.average_rating) {
            $('#ratingSummary').show();
            $('#avgRating').text(parseFloat(stats.average_rating).toFixed(1));
            $('#totalRatings').text(stats.total + ' ' + COMMENTS_FRONTEND_CONFIG.translations.reviews);

            // Render stars
            let starsHtml = '';
            const avgRating = Math.round(stats.average_rating);
            for (let i = 1; i <= 5; i++) {
                starsHtml += '<i class="fas fa-star ' + (i <= avgRating ? '' : 'empty') + '"></i>';
            }
            $('#avgRatingStars').html(starsHtml);

            // Render rating bars
            let barsHtml = '';
            const distribution = stats.rating_distribution;
            const maxCount = Math.max(...Object.values(distribution), 1);

            for (let i = 5; i >= 1; i--) {
                const count = distribution[i] || 0;
                const percentage = (count / maxCount) * 100;
                barsHtml += `
                    <div class="rating-bar-row">
                        <span class="rating-bar-label">${i} stars</span>
                        <div class="rating-bar-track">
                            <div class="rating-bar-fill" style="width: ${percentage}%"></div>
                        </div>
                        <span class="rating-bar-count">${count}</span>
                    </div>
                `;
            }
            $('#ratingBars').html(barsHtml);
        }
    }

    // ========================================
    // Render Comment
    // ========================================
    function renderComment(comment, isReply = false) {
        let starsHtml = '';
        if (comment.rating && !isReply) {
            for (let i = 1; i <= 5; i++) {
                starsHtml += '<i class="fas fa-star ' + (i <= comment.rating ? '' : 'empty') + '"></i>';
            }
        }

        let repliesHtml = '';
        if (comment.replies && comment.replies.length > 0) {
            repliesHtml = '<div class="comment-replies">';
            comment.replies.forEach(function(reply) {
                repliesHtml += renderComment(reply, true);
            });
            repliesHtml += '</div>';
        }

        return `
            <div class="comment" data-id="${comment.id}">
                <div class="comment-avatar">
                    <span class="avatar-initials">${comment.author_initials}</span>
                </div>
                <div class="comment-body">
                    <div class="comment-header">
                        <span class="comment-author">${escapeHtml(comment.author_name)}</span>
                        <span class="comment-date">${comment.created_at_human}</span>
                    </div>
                    ${starsHtml ? '<div class="comment-rating">' + starsHtml + '</div>' : ''}
                    <div class="comment-content">${comment.content}</div>
                    <div class="comment-actions">
                        <button type="button" class="btn-reply" onclick="replyTo(${comment.id}, '${escapeHtml(comment.author_name)}')">
                            <i class="fas fa-reply"></i> ${COMMENTS_FRONTEND_CONFIG.translations.reply}
                        </button>
                    </div>
                    ${repliesHtml}
                </div>
            </div>
        `;
    }

    // ========================================
    // Render No Comments
    // ========================================
    function renderNoComments() {
        return `
            <div class="no-comments">
                <i class="far fa-comments"></i>
                <p>${COMMENTS_FRONTEND_CONFIG.translations.no_comments}</p>
            </div>
        `;
    }

    // ========================================
    // Initialize Form
    // ========================================
    function initForm() {
        $('#commentForm').on('submit', function(e) {
            e.preventDefault();
            submitComment();
        });

        $('#loadMoreBtn').on('click', function() {
            loadComments(currentPage + 1, true);
        });
    }

    // ========================================
    // Submit Comment
    // ========================================
    function submitComment() {
        const $form = $('#commentForm');
        const $btn = $form.find('.btn-submit');
        const originalText = $btn.html();

        $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> ...');

        $.ajax({
            url: COMMENTS_FRONTEND_CONFIG.routes.store,
            method: 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    // Reset form
                    $form[0].reset();
                    cancelReply();

                    // Show success message
                    showAlert('success', response.message);

                    // If approved, add comment to list
                    if (response.is_approved && response.comment) {
                        const $newComment = $(renderComment(response.comment));
                        
                        // If reply, append to parent
                        if (response.comment.parent_id) {
                            const $parent = $(`.comment[data-id="${response.comment.parent_id}"]`);
                            let $replies = $parent.find('.comment-replies').first();
                            if ($replies.length === 0) {
                                $replies = $('<div class="comment-replies"></div>');
                                $parent.find('.comment-body').first().append($replies);
                            }
                            $replies.append($newComment);
                        } else {
                            // Prepend to list
                            const $noComments = $('#commentsList .no-comments');
                            if ($noComments.length) {
                                $noComments.remove();
                            }
                            $('#commentsList').prepend($newComment);
                        }
                    }
                } else {
                    showAlert('danger', response.message);
                }
            },
            error: function(xhr) {
                let message = COMMENTS_FRONTEND_CONFIG.translations.error;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }
                showAlert('danger', message);
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalText);
            }
        });
    }

    // ========================================
    // Reply To
    // ========================================
    window.replyTo = function(commentId, authorName) {
        $('#parentId').val(commentId);
        $('#replyToName').text(authorName);
        $('#replyIndicator').show();
        
        // Hide rating for replies
        $('#ratingInputGroup').hide();
        
        // Scroll to form
        $('html, body').animate({
            scrollTop: $('#commentFormWrapper').offset().top - 100
        }, 300);
        
        $('#commentContent').focus();
    };

    window.cancelReply = function() {
        $('#parentId').val('');
        $('#replyIndicator').hide();
        $('#ratingInputGroup').show();
    };

    // ========================================
    // Show Alert
    // ========================================
    function showAlert(type, message) {
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        const $alert = $(alertHtml);
        $('#commentFormWrapper').prepend($alert);
        
        setTimeout(function() {
            $alert.alert('close');
        }, 5000);
    }

    // ========================================
    // Escape HTML
    // ========================================
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

})(jQuery);
