document.addEventListener('DOMContentLoaded', function() {
    // Auto filter when the filter is changed
    var filter = document.getElementById('min_rating');
    if (filter) {
        filter.addEventListener('change', ratingFilter);
        filter.dispatchEvent(new Event('change', { cancelable: true }));
    }
    var migrateWPCommentBtn = document.getElementById('migrate-wp-comment');
    if (migrateWPCommentBtn) {
        migrateWPCommentBtn.addEventListener('click', migrateWPComment);
    }
});
/**
 * Handles the rating filter functionality.
 * 
 * @param {Event} e - The event object.
 */
function ratingFilter(e) {
    e.preventDefault();
    
    var minRating = this.value;
    
    var xhr = new XMLHttpRequest();
    xhr.open('POST', erbwp_ajax.url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            if (response.success) {
                let posts = `
                <table class="table table-bordered display" id="erbwp-table">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Average Rating</th>
                            <th>Detail</th>
                        </tr>
                    </thead>
                    <tbody>
                `;

                response.data.forEach(post => {
                    let ratingsHTML = '';
                    ratingsHTML = ratingsHTML.length > 0 ? ratingsHTML : 'No ratings';
                    posts += `
                    <tr id="post-${post.id}">
                        <td><strong><a href="${post.link}" target="_blank">${post.title}</a></strong></td>
                        <td>${post.average_rating}</td>
                        <td>
                            <button type="button" class="btn btn-primary" data-toggle="modal" id="modal-${post.id}" onclick='showModal("${escapeHTML(post.title)}", ${JSON.stringify(post.ratings)})'>
                                View Detail
                            </button>
                            
                        </td>
                    </tr>
                    `;
                    
                });

                posts += `
                    </tbody>
                </table>
                `;
                jQuery('#post-ratings-container').html(posts);
                jQuery("#erbwp-table").DataTable({
                    "columnDefs": [
                        { "orderable": false, "targets": 2 },
                    ],
                    layout: {
                        top2Start: 'buttons',
                        top2End: null,
                        topStart: 'pageLength',
                        topEnd: 'search',
                        bottomStart: null,
                        bottomEnd: null,
                        bottom2Start: 'info',
                        bottom2End: 'paging'
                    },
                });
            }
        }
    };
    
    xhr.send('action=erbwp_filter_posts&min_rating=' + minRating + '&nonce=' + erbwp_ajax.nonce);
}

document.getElementById('premium-features-question-mark')?.addEventListener('click', function() {
    jQuery('#premiumFeatureModal').modal('show');
});

function showModal(postTitle, ratings) {
    let modalHTML = `
    <div class="modal" tabindex="-1" id="detailModal">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Detailed Ratings for "${postTitle}"</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <canvas id="ratingChart" max-width="400" max-height="400"></canvas>
            </div>
            </div>
        </div>
    </div>
    `;
    jQuery('body').append(modalHTML);
    jQuery('#detailModal').modal('show');
    jQuery('#detailModal').on('hidden.bs.modal', function () {
        jQuery(this).remove();
    });

    // Prepare the data for the chart
    const labels = [];
    const data = [];

    for (let rating in ratings) {
        if (ratings.hasOwnProperty(rating)) {
            labels.push(`${rating} star${rating != 1 ? 's' : ''}`);
            data.push(ratings[rating]);
        }
    }

    // Configuration for the Chart.js chart
    const config = {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Number of Votes',
                    data: data,
                    backgroundColor: [
                        'rgba(0, 128, 0, 0.8)'
                    ],
                    borderColor: [
                        'rgba(0, 128, 0, 1)'
                    ],
                    borderWidth: 1,
                    barThickness: 20,
                }
            ]
        },
        options: {
            indexAxis: 'y',
            scales: {
                x: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1,
                        callback: function(value) {
                            if (Number.isInteger(value)) {
                                return value;
                            }
                        }
                    },
                    grid: {
                        display: false
                    }
                },
                y: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    };

    // Render the chart
    const ctx = document.getElementById('ratingChart').getContext('2d');
    const ratingChart = new Chart(ctx, config);
}

function escapeHTML(str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}

function migrateWPComment(e) {
    e.preventDefault();
    jQuery('#overlay').fadeIn();
    let xhr = new XMLHttpRequest();
    xhr.open('POST', erbwp_ajax.url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            jQuery('#overlay').fadeOut();
            let response = JSON.parse(xhr.responseText);
            if (response.success) {
                alert(response.data);
            }
        }
        else if(xhr.readyState === 4 && (xhr.status < 200 || xhr.status > 400)) {
            jQuery('#overlay').fadeOut();
            alert('Error occurred while migrating WP comments.');
        }
    };
    xhr.send('action=erbwp_migrate_wp_comment&nonce=' + erbwp_ajax.nonce);
}
