// Log tab — dedicated, free-wrapping, newest-on-top. Each entry is a
// single block so multi-line messages (stack traces, LLM excerpts) wrap
// naturally instead of getting cropped to a column. The copy button
// serializes the current snapshot to plain text — useful when asking a
// user to send a log from a running app where text selection is clunky.

import {escapeHtml} from './utils.js';

let lastLogSignature = '';
let lastEntries = [];

export function renderLog(entries) {
    const container = document.getElementById('log-entries');
    if (!container || !entries || entries.length === 0) return;

    const last = entries[entries.length - 1];
    const signature = `${entries.length}:${last.tick}:${last.timestamp}`;
    if (signature === lastLogSignature) return;

    // If the user has scrolled down to read older entries, don't yank
    // the view back to the top mid-read. We'll catch up the next time
    // they scroll home.
    if (container.scrollTop > 2) {
        lastEntries = entries;
        return;
    }

    lastLogSignature = signature;
    lastEntries = entries;

    container.innerHTML = entries.slice().reverse().map(e => {
        const [r, g, b] = e.rgb;
        return `<div class="log-entry" style="color: rgb(${r},${g},${b})">${escapeHtml(e.message)}</div>`;
    }).join('');
}

export function initLog() {
    const btn = document.getElementById('btn-log-copy');
    const label = btn?.querySelector('.log-copy-label');
    if (!btn) return;

    btn.addEventListener('click', async () => {
        const text = lastEntries
            .slice()
            .reverse()
            .map((e) => `[t${e.tick}] ${e.message}`)
            .join('\n');
        try {
            await navigator.clipboard.writeText(text);
            if (label) {
                const prev = label.textContent;
                label.textContent = 'Copied';
                setTimeout(() => { label.textContent = prev; }, 1500);
            }
        } catch (e) {
            if (label) {
                label.textContent = 'Copy failed';
                setTimeout(() => { label.textContent = 'Copy'; }, 1500);
            }
        }
    });
}
