// assets/js/auto-sync.js – Real-time auto-sync using Server-Sent Events

(function() {
    'use strict';
    
    const CSRF = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
    let eventSource = null;
    let lastEventId = 0;
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    const reconnectDelay = 3000;
    
    const handlers = {
        tasks: [],
        notes: [],
        calendar: [],
        pomodoro: [],
        flashcards: []
    };
    
    function connect() {
        if (eventSource) {
            eventSource.close();
        }
        
        const url = `/space/api/sse.php?last_id=${lastEventId}`;
        eventSource = new EventSource(url);
        
        eventSource.onopen = function() {
            reconnectAttempts = 0;
            console.log('[Auto-sync] Connected');
        };
        
        eventSource.onerror = function(e) {
            console.error('[Auto-sync] Error:', e);
            eventSource.close();
            
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                setTimeout(connect, reconnectDelay);
            }
        };
        
        eventSource.addEventListener('tasks_update', function(e) {
            const tasks = JSON.parse(e.data);
            lastEventId = Math.max(lastEventId, ...tasks.map(t => t.id));
            handlers.tasks.forEach(fn => fn(tasks));
        });
        
        eventSource.addEventListener('notes_update', function(e) {
            const notes = JSON.parse(e.data);
            lastEventId = Math.max(lastEventId, ...notes.map(n => n.id));
            handlers.notes.forEach(fn => fn(notes));
        });
        
        eventSource.addEventListener('calendar_update', function(e) {
            const events = JSON.parse(e.data);
            lastEventId = Math.max(lastEventId, ...events.map(ev => ev.id));
            handlers.calendar.forEach(fn => fn(events));
        });
        
        eventSource.addEventListener('pomodoro_update', function(e) {
            const data = JSON.parse(e.data);
            handlers.pomodoro.forEach(fn => fn(data));
        });
        
        eventSource.addEventListener('flashcards_update', function(e) {
            const cards = JSON.parse(e.data);
            lastEventId = Math.max(lastEventId, ...cards.map(c => c.id));
            handlers.flashcards.forEach(fn => fn(cards));
        });
    }
    
    window.AutoSync = {
        start: function() {
            connect();
        },
        
        stop: function() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
        },
        
        onTasks: function(callback) {
            handlers.tasks.push(callback);
        },
        
        onNotes: function(callback) {
            handlers.notes.push(callback);
        },
        
        onCalendar: function(callback) {
            handlers.calendar.push(callback);
        },
        
        onPomodoro: function(callback) {
            handlers.pomodoro.push(callback);
        },
        
        onFlashcards: function(callback) {
            handlers.flashcards.push(callback);
        },
        
        refresh: function(type) {
            return window.apiFetch(`api/${type}.php?action=list`);
        }
    };
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => window.AutoSync.start());
    } else {
        window.AutoSync.start();
    }
})();
