// ==========================================
// Debug Modal — Console Tab
// ==========================================
// Filterable console log display with type coloring,
// elapsed timestamps, and auto-scroll.
//
// v0.37.18: Preact rebuild from debug.js _renderConsoleTab().

const html = window.html;
const { useState, useMemo, useRef, useEffect } = window.hooks;

const TYPE_COLORS = {
    'ERROR': '#e74c3c', 'EXCEPTION': '#e74c3c', 'REJECTION': '#e74c3c',
    'NET:ERR': '#e74c3c', 'NET:PROXY': '#ff6b35',
    'WARN': '#f39c12', 'WARNING': '#f39c12',
    'LOG': '#95a5a6', 'INFO': '#3498db', 'DEBUG': '#7f8c8d',
    'NET': '#2ecc71',
    'DIAG': '#9b59b6'
};

const ERROR_TYPES = new Set(['ERROR', 'EXCEPTION', 'REJECTION', 'NET:ERR', 'NET:PROXY', 'WARN']);

function _esc(s) {
    if (!s) return '';
    return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

/**
 * @param {{ entries: Array }} props
 */
export function ConsoleTab({ entries }) {
    const [errorsOnly, setErrorsOnly] = useState(false);
    const [autoScroll, setAutoScroll] = useState(true);
    const contentRef = useRef(null);

    const filtered = useMemo(() => {
        if (!errorsOnly) return entries;
        return entries.filter(e => ERROR_TYPES.has(e.type));
    }, [entries, errorsOnly]);

    useEffect(() => {
        if (autoScroll && contentRef.current) {
            contentRef.current.scrollTop = contentRef.current.scrollHeight;
        }
    }, [filtered, autoScroll]);

    return html`
        <div class="debug-console-tab">
            <div class="debug-toolbar">
                <label class="debug-check">
                    <input type="checkbox" checked=${errorsOnly}
                           onChange=${e => setErrorsOnly(e.target.checked)} />
                    Errors only
                </label>
                <label class="debug-check">
                    <input type="checkbox" checked=${autoScroll}
                           onChange=${e => setAutoScroll(e.target.checked)} />
                    Auto-scroll
                </label>
                <span class="debug-badge">${filtered.length}</span>
            </div>
            <div class="debug-content" ref=${contentRef}>
                ${filtered.length === 0
                    ? html`<div class="debug-empty">No log entries yet</div>`
                    : filtered.map((entry, i) => html`
                        <div class="debug-entry" key=${i}>
                            <span class="debug-time">${entry.ts.slice(11, 23)} +${(entry.elapsed / 1000).toFixed(1)}s</span>${' '}
                            <span style="color:${TYPE_COLORS[entry.type] || '#95a5a6'};font-weight:bold;">[${_esc(entry.type)}]</span>${' '}
                            <span class="debug-msg">${_esc(entry.message)}</span>
                        </div>`)}
            </div>
        </div>`;
}
