// Simulation Status Monitor JavaScript

let eventSource = null;
let simId = null;
let simName = null;
let startTime = null;
let activityLogEntries = [];

// Initialize on page load
$(document).ready(function() {
    initializeMonitor();
    bindEvents();
});

function initializeMonitor() {
    // Get simulation ID from URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    simId = urlParams.get('sim_id');
    simName = urlParams.get('name') || 'Unknown';

    if (!simId) {
        showError('No simulation ID provided');
        return;
    }

    // Display simulation info
    $('#simName').text(simName);
    $('#simMode').text(urlParams.get('mode') || 'Unknown');

    startTime = new Date();
    $('#simStartTime').text(startTime.toLocaleTimeString());

    // Start monitoring
    startMonitoring();
}

function bindEvents() {
    $('#backToBuilderBtn').click(function() {
        if (confirm('Are you sure? The simulation will continue in the background.')) {
            cleanup();
            window.location.href = '/builder';
        }
    });

    $('#viewResultsBtn').click(function() {
        cleanup();
        window.location.href = '/results';
    });

    $('#cancelSimBtn').click(function() {
        if (confirm('Are you sure you want to cancel this simulation?')) {
            cancelSimulation();
        }
    });
}

function startMonitoring() {
    if (!simId) return;

    addLogEntry('Connecting to simulation monitor...', 'starting');

    // Create EventSource for Server-Sent Events
    eventSource = new EventSource(`/api/simulation/monitor/${simId}`);

    eventSource.onmessage = function(event) {
        const data = JSON.parse(event.data);
        handleUpdate(data);
    };

    eventSource.onerror = function(error) {
        console.error('EventSource error:', error);

        // Check if connection was closed normally
        if (eventSource.readyState === EventSource.CLOSED) {
            addLogEntry('Connection closed', 'info');
        } else {
            showError('Lost connection to simulation monitor');
            cleanup();
        }
    };

    eventSource.onopen = function() {
        addLogEntry('Connected to simulation monitor', 'starting');
    };
}

function handleUpdate(data) {
    console.log('Update received:', data);

    // Ignore keepalive messages
    if (data.status === 'alive') {
        return;
    }

    // Update progress bar
    if (data.progress !== undefined) {
        updateProgress(data.progress);
    }

    // Update status message
    if (data.message) {
        updateStatusMessage(data.message, data.status);
    }

    // Update status badge
    updateStatusBadge(data.status);

    // Add to activity log
    if (data.message && data.status !== 'alive') {
        addLogEntry(data.message, data.status);
    }

    // Handle completion or failure
    if (data.status === 'complete') {
        handleCompletion(data);
    } else if (data.status === 'failed' || data.status === 'error') {
        handleFailure(data);
    }
}

function updateProgress(progress) {
    const $progressBar = $('#progressBar');
    $progressBar.css('width', progress + '%');
    $progressBar.attr('aria-valuenow', progress);
    $('#progressText').text(progress + '%');

    // Change color based on progress
    if (progress >= 100) {
        $progressBar.removeClass('bg-info bg-warning').addClass('bg-success');
    } else if (progress >= 50) {
        $progressBar.removeClass('bg-info').addClass('bg-warning');
    }
}

function updateStatusMessage(message, status) {
    let icon = '<i class="bi bi-hourglass-split"></i>';

    switch(status) {
        case 'starting':
            icon = '<i class="bi bi-play-circle"></i>';
            break;
        case 'running':
            icon = '<i class="bi bi-gear-fill"></i>';
            break;
        case 'complete':
            icon = '<i class="bi bi-check-circle"></i>';
            break;
        case 'failed':
        case 'error':
            icon = '<i class="bi bi-x-circle"></i>';
            break;
    }

    $('#statusMessage').html(`${icon} ${message}`);

    // Update alert style
    const $alert = $('#statusAlert');
    $alert.removeClass('alert-info alert-warning alert-success alert-danger');

    if (status === 'complete') {
        $alert.addClass('alert-success');
        $('#statusSpinner').hide();
    } else if (status === 'failed' || status === 'error') {
        $alert.addClass('alert-danger');
        $('#statusSpinner').hide();
    } else if (status === 'running') {
        $alert.addClass('alert-warning');
    } else {
        $alert.addClass('alert-info');
    }
}

function updateStatusBadge(status) {
    const $badge = $('#simStatus');
    $badge.removeClass('bg-info bg-warning bg-success bg-danger');

    switch(status) {
        case 'starting':
            $badge.addClass('bg-info').text('Starting');
            break;
        case 'running':
            $badge.addClass('bg-warning').text('Running');
            break;
        case 'complete':
            $badge.addClass('bg-success').text('Complete');
            break;
        case 'failed':
        case 'error':
            $badge.addClass('bg-danger').text('Failed');
            break;
    }
}

function addLogEntry(message, status) {
    const timestamp = new Date().toLocaleTimeString();

    const entry = {
        timestamp: timestamp,
        message: message,
        status: status
    };

    activityLogEntries.push(entry);

    // Create log entry HTML
    const entryHtml = `
        <div class="activity-log-entry status-${status}">
            <span class="timestamp">[${timestamp}]</span>
            <span class="message">${message}</span>
        </div>
    `;

    const $log = $('#activityLog');

    // Clear "waiting" message if present
    if ($log.find('.text-muted').length > 0) {
        $log.empty();
    }

    $log.append(entryHtml);

    // Auto-scroll to bottom
    $log.scrollTop($log[0].scrollHeight);
}

function handleCompletion(data) {
    cleanup();

    // Show success card
    $('#successCard').slideDown();

    // Show view results button
    $('#viewResultsBtn').show();

    // Update progress to 100%
    updateProgress(100);

    addLogEntry('Simulation completed successfully!', 'complete');

    // Optional: Auto-redirect after delay
    setTimeout(function() {
        if (confirm('Simulation complete! View results now?')) {
            window.location.href = '/results';
        }
    }, 2000);
}

function handleFailure(data) {
    cleanup();

    // Show error card
    $('#errorMessage').text(data.message || 'Unknown error occurred');
    $('#errorCard').slideDown();

    addLogEntry(`Error: ${data.message}`, 'failed');
}

function showError(message) {
    $('#errorMessage').text(message);
    $('#errorCard').slideDown();
    $('#statusAlert').addClass('alert-danger').removeClass('alert-info');
    $('#statusMessage').html(`<i class="bi bi-x-circle"></i> ${message}`);
    $('#statusSpinner').hide();

    addLogEntry(`Error: ${message}`, 'error');
}

function cancelSimulation() {
    // This would require a backend endpoint to cancel simulations
    // For now, just cleanup and redirect
    cleanup();
    window.location.href = '/builder';
}

function cleanup() {
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
}

// Cleanup on page unload
window.addEventListener('beforeunload', function() {
    cleanup();
});