/* Loom Dashboard — Minimal JS */

// SSE connection for real-time updates
(function() {
    const evtSource = new EventSource('/dashboard/api/events');

    evtSource.addEventListener('task_update', function(e) {
        // Refresh the board when task state changes
        const board = document.getElementById('task-board');
        if (board) {
            htmx.trigger(board, 'sse:task_update');
        }
    });

    evtSource.addEventListener('project_update', function(e) {
        const projects = document.getElementById('project-list');
        if (projects) {
            htmx.trigger(projects, 'sse:project_update');
        }
    });

    evtSource.onerror = function() {
        console.log('SSE connection lost, will retry...');
    };
})();

// Initialize Mermaid if present
document.addEventListener('DOMContentLoaded', function() {
    if (typeof mermaid !== 'undefined') {
        mermaid.initialize({
            startOnLoad: true,
            theme: window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
            flowchart: { useMaxWidth: true, htmlLabels: true }
        });
    }
});

// Re-render Mermaid after HTMX swaps
document.addEventListener('htmx:afterSwap', function(e) {
    if (typeof mermaid !== 'undefined' && e.detail.target.querySelector('.mermaid')) {
        mermaid.run();
    }
});
