// logs.js — SSE 实时日志流
(function() {
    const logEl = document.getElementById('log-content');
    const accountSelect = document.getElementById('account-filter');
    const autoScrollCheck = document.getElementById('auto-scroll');
    let evtSource = null;

    function connect() {
        if (evtSource) {
            evtSource.close();
        }
        const account = accountSelect ? accountSelect.value : '';
        const url = '/logs/stream' + (account ? '?account=' + encodeURIComponent(account) : '');
        evtSource = new EventSource(url);

        evtSource.onmessage = function(e) {
            logEl.textContent += e.data + '\n';
            if (autoScrollCheck.checked) {
                logEl.scrollTop = logEl.scrollHeight;
            }
        };

        evtSource.onerror = function() {
            evtSource.close();
            setTimeout(connect, 3000);
        };
    }

    if (accountSelect) {
        accountSelect.addEventListener('change', function() {
            logEl.textContent = '';
            connect();
        });
    }

    connect();

    window.clearLog = function() {
        logEl.textContent = '';
    };
})();
