/**
 * Analytics Page JavaScript
 *
 * @package ReplyIt_Chat_Widget
 */

(function($) {
    'use strict';

    let messagesChart = null;

    // Load analytics data
    function loadAnalytics() {
        $('#replyit-analytics-loading').show();
        $('#replyit-analytics-content').hide();
        $('#replyit-analytics-error').hide();

        const url = `${replyitAnalyticsConfig.apiUrl}/api/widgets/${replyitAnalyticsConfig.widgetId}/analytics?days=${replyitAnalyticsConfig.period}`;

        $.ajax({
            url: url,
            method: 'GET',
            headers: {
                'X-Widget-Secret': replyitAnalyticsConfig.apiSecret
            },
            success: function(response) {
                if (response.result) {
                    displayAnalytics(response.result);
                } else {
                    showError(response.message || 'Failed to load analytics');
                }
            },
            error: function(xhr) {
                let errorMsg = 'Failed to load analytics';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMsg = xhr.responseJSON.message;
                }
                showError(errorMsg);
            }
        });
    }

    // Display analytics data
    function displayAnalytics(data) {
        // Update summary stats
        $('#stat-total-conversations').text(data.summary.total_conversations || 0);
        $('#stat-total-messages').text(data.summary.total_messages || 0);
        $('#stat-inbound-messages').text(data.summary.inbound_messages || 0);
        $('#stat-outbound-messages').text(data.summary.outbound_messages || 0);

        // Render chart
        renderChart(data.daily_stats);

        // Render recent conversations
        renderConversations(data.recent_conversations);

        $('#replyit-analytics-loading').hide();
        $('#replyit-analytics-content').show();
    }

    // Render chart using Chart.js
    function renderChart(dailyStats) {
        const ctx = document.getElementById('replyit-messages-chart');
        if (!ctx) return;

        // Destroy existing chart
        if (messagesChart) {
            messagesChart.destroy();
        }

        // Prepare data
        const labels = dailyStats.map(stat => stat.date);
        const inboundData = dailyStats.map(stat => stat.inbound);
        const outboundData = dailyStats.map(stat => stat.outbound);

        messagesChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Inbound Messages',
                        data: inboundData,
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: 'Outbound Messages',
                        data: outboundData,
                        borderColor: '#8b5cf6',
                        backgroundColor: 'rgba(139, 92, 246, 0.1)',
                        tension: 0.4,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0
                        }
                    }
                }
            }
        });
    }

    // Render recent conversations table
    function renderConversations(conversations) {
        const tbody = $('#replyit-conversations-table');
        tbody.empty();

        if (!conversations || conversations.length === 0) {
            tbody.append(`
                <tr>
                    <td colspan="4" style="text-align: center;">No conversations yet</td>
                </tr>
            `);
            return;
        }

        conversations.forEach(conversation => {
            const lastMessage = conversation.last_message || '-';
            const truncatedMessage = lastMessage.length > 50 ? lastMessage.substring(0, 50) + '...' : lastMessage;
            const messageCount = conversation.message_count || 0;
            const lastActivity = conversation.last_message_time ? new Date(conversation.last_message_time).toLocaleString() : '-';

            tbody.append(`
                <tr>
                    <td><code>${escapeHtml(conversation.session_id)}</code></td>
                    <td>${escapeHtml(truncatedMessage)}</td>
                    <td>${messageCount}</td>
                    <td>${lastActivity}</td>
                </tr>
            `);
        });
    }

    // Show error message
    function showError(message) {
        $('#replyit-analytics-loading').hide();
        $('#replyit-analytics-error-message').text(message);
        $('#replyit-analytics-error').show();
    }

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

    // Initialize
    $(document).ready(function() {
        // Chart.js is now enqueued via WordPress
        loadAnalytics();

        // Refresh button
        $('#replyit-refresh-analytics').on('click', function() {
            loadAnalytics();
        });
    });

})(jQuery);
