/**
 * AI Event Tracking — Frontend Logic
 */

let autoRefreshInterval = null;
let eventChart = null;
let channelChart = null;
let allEvents = [];

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    initEventListeners();
    loadEvents();
    loadStats();
    initCharts();
});

function initEventListeners() {
    // Event type filter
    const filterChips = document.getElementById('filterChips');
    filterChips.addEventListener('click', (e) => {
        if (e.target.classList.contains('filter-chip')) {
            filterChips.querySelectorAll('.filter-chip').forEach(chip => chip.classList.remove('active'));
            e.target.classList.add('active');
            loadEvents(e.target.dataset.type);
        }
    });

    // Search input
    document.getElementById('searchInput').addEventListener('input', debounce(searchEvents, 300));

    // Custom event type toggle
    document.getElementById('testEventType').addEventListener('change', (e) => {
        const customInput = document.getElementById('customEventType');
        customInput.disabled = e.target.value !== 'custom';
    });
}

async function loadEvents(eventType = '', search = '') {
    try {
        const params = new URLSearchParams();
        if (eventType) params.append('event_type', eventType);
        if (search) params.append('search', search);

        const response = await fetch(`/api/ai-event/logs?${params.toString()}`);
        const events = await response.json();

        allEvents = events;
        renderEventList(events);
        updateEventCount(events.length);
        updateFilterChips(events);
    } catch (error) {
        console.error('Failed to load events:', error);
    }
}

function renderEventList(events) {
    const container = document.getElementById('eventList');

    if (events.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <h3>No events found</h3>
                <p>Events will appear here as they are published.</p>
            </div>
        `;
        return;
    }

    container.innerHTML = events.map(event => `
        <div class="event-card" data-id="${event.id}">
            <div class="event-header">
                <div class="event-type">
                    <i class="fas fa-bolt"></i>
                    ${escapeHtml(event.event_type)}
                </div>
                <div class="event-time">${formatTime(event.timestamp)}</div>
            </div>
            <div class="event-body">
                <div class="event-section">
                    <h4>Event Data</h4>
                    <pre class="event-json">${escapeHtml(JSON.stringify(event.data, null, 2))}</pre>
                </div>
                <div class="event-section">
                    <h4>Metadata</h4>
                    <div class="event-meta">
                        ${event.user_id ? `<span><i class="fas fa-user"></i> ${escapeHtml(event.user_id)}</span>` : ''}
                        <span><i class="fas fa-calendar"></i> ${new Date(event.timestamp).toLocaleDateString('vi-VN')}</span>
                        <span><i class="fas fa-clock"></i> ${new Date(event.timestamp).toLocaleTimeString('vi-VN')}</span>
                    </div>
                    ${event.metadata ? `<pre class="event-json" style="margin-top:8px">${escapeHtml(JSON.stringify(event.metadata, null, 2))}</pre>` : ''}
                </div>
            </div>
        </div>
    `).join('');
}

async function loadStats() {
    try {
        const response = await fetch('/api/ai-event/stats');
        const stats = await response.json();

        document.getElementById('statTotal').textContent = stats.total.toLocaleString();
        document.getElementById('statRecent').textContent = stats.recent_1h.toLocaleString();
        document.getElementById('statTypes').textContent = Object.keys(stats.by_type).length;
        document.getElementById('statChannels').textContent = Object.keys(stats.by_channel).length;

        updateCharts(stats);
    } catch (error) {
        console.error('Failed to load stats:', error);
    }
}

function updateCharts(stats) {
    // Type chart
    const typeCtx = document.getElementById('typeChart').getContext('2d');
    const typeData = Object.entries(stats.by_type)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 10);

    if (eventChart) eventChart.destroy();
    eventChart = new Chart(typeCtx, {
        type: 'bar',
        data: {
            labels: typeData.map(([type]) => type),
            datasets: [{
                label: 'Events',
                data: typeData.map(([, count]) => count),
                backgroundColor: 'rgba(99, 102, 241, 0.7)',
                borderColor: 'rgb(99, 102, 241)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: { beginAtZero: true, ticks: { stepSize: 1 } }
            }
        }
    });

    // Channel chart
    const channelCtx = document.getElementById('channelChart').getContext('2d');
    const channelData = Object.entries(stats.by_channel);

    if (channelChart) channelChart.destroy();
    channelChart = new Chart(channelCtx, {
        type: 'doughnut',
        data: {
            labels: channelData.map(([channel]) => channel),
            datasets: [{
                data: channelData.map(([, count]) => count),
                backgroundColor: [
                    'rgba(99, 102, 241, 0.8)',
                    'rgba(16, 185, 129, 0.8)',
                    'rgba(245, 158, 11, 0.8)',
                    'rgba(239, 68, 68, 0.8)',
                    'rgba(139, 92, 246, 0.8)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'bottom' }
            }
        }
    });

    // Update table
    const tableBody = document.querySelector('#typeTable tbody');
    const total = stats.total || 1;
    tableBody.innerHTML = Object.entries(stats.by_type)
        .sort((a, b) => b[1] - a[1])
        .map(([type, count]) => `
            <tr>
                <td><code>${escapeHtml(type)}</code></td>
                <td>${count.toLocaleString()}</td>
                <td>${((count / total) * 100).toFixed(1)}%</td>
            </tr>
        `).join('');
}

function updateEventCount(count) {
    document.getElementById('eventCount').textContent = `${count} event${count !== 1 ? 's' : ''}`;
}

function updateFilterChips(events) {
    const types = [...new Set(events.map(e => e.event_type))];
    const container = document.getElementById('filterChips');
    const activeType = container.querySelector('.filter-chip.active').dataset.type;

    container.innerHTML = `
        <span class="filter-chip ${!activeType ? 'active' : ''}" data-type="">All</span>
        ${types.map(type => `
            <span class="filter-chip ${type === activeType ? 'active' : ''}" data-type="${escapeHtml(type)}">
                ${escapeHtml(type)}
            </span>
        `).join('')}
    `;
}

async function publishTestEvent(e) {
    e.preventDefault();

    const eventTypeSelect = document.getElementById('testEventType');
    const customInput = document.getElementById('customEventType');
    const channelSelect = document.getElementById('testChannel');
    const userIdInput = document.getElementById('testUserId');
    const dataInput = document.getElementById('testData');

    const eventType = eventTypeSelect.value === 'custom'
        ? customInput.value.trim()
        : eventTypeSelect.value;

    if (!eventType) {
        alert('Please specify an event type');
        return;
    }

    let eventData;
    try {
        eventData = JSON.parse(dataInput.value || '{}');
    } catch (err) {
        alert('Invalid JSON in event data');
        return;
    }

    const payload = {
        event_type: eventType,
        channel: channelSelect.value,
        user_id: userIdInput.value.trim() || undefined,
        data: eventData
    };

    try {
        const response = await fetch('/api/ai-event/publish', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const result = await response.json();

        if (response.ok) {
            showTestResult(result);
            loadEvents();
            loadStats();
        } else {
            alert(`Error: ${result.detail || 'Failed to publish event'}`);
        }
    } catch (error) {
        alert(`Network error: ${error.message}`);
    }
}

function showTestResult(result) {
    const resultDiv = document.getElementById('testResult');
    const resultJson = document.getElementById('resultJson');

    resultDiv.style.display = 'block';
    resultJson.textContent = JSON.stringify(result, null, 2);
}

function clearLogs() {
    if (!confirm('Are you sure you want to clear all event logs?')) return;

    fetch('/api/ai-event/logs', { method: 'DELETE' })
        .then(() => {
            loadEvents();
            loadStats();
        })
        .catch(err => alert(`Error: ${err.message}`));
}

function refreshFeed() {
    loadEvents();
    loadStats();
}

function autoRefresh() {
    const btn = document.querySelector('.btn-primary');
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
        btn.innerHTML = '<i class="fas fa-play"></i> Auto Refresh';
        btn.style.background = '';
    } else {
        autoRefreshInterval = setInterval(() => {
            loadEvents();
            loadStats();
        }, 2000);
        btn.innerHTML = '<i class="fas fa-pause"></i> Stop Refresh';
        btn.style.background = '#ef4444';
    }
}

function searchEvents() {
    const query = document.getElementById('searchInput').value.trim();
    const activeFilter = document.querySelector('#filterChips .filter-chip.active').dataset.type;
    loadEvents(activeFilter, query);
}

function switchView(btn) {
    // Update nav buttons
    document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');

    // Update view title
    const viewTitle = document.getElementById('viewTitle');
    viewTitle.textContent = btn.textContent.trim();

    // Show/hide containers
    document.querySelectorAll('.view-container').forEach(v => v.classList.remove('active'));
    const viewId = `view-${btn.dataset.view}`;
    document.getElementById(viewId).classList.add('active');

    // Refresh data when switching
    if (btn.dataset.view === 'stats') {
        loadStats();
    }
}

function formatTime(isoString) {
    const date = new Date(isoString);
    const now = new Date();
    const diff = now - date;

    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return date.toLocaleDateString('vi-VN');
}

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

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Keyboard shortcut
document.addEventListener('keydown', (e) => {
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        document.getElementById('searchInput').focus();
    }
});
