// ==========================================
// Debug Modal — Network Tab
// ==========================================
// Fetch log with expandable request/response details.
// Newest entries first.
//
// v0.37.18: Preact rebuild from debug.js _renderNetworkTab().

const html = window.html;
const { useState } = window.hooks;

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

function NetEntry({ req }) {
    const [open, setOpen] = useState(false);

    const isErr = req.error || (req.status && req.status >= 400) || req.proxyDetected;
    const statusColor = req.proxyDetected ? '#ff6b35' : (isErr ? '#e74c3c' : '#2ecc71');
    const statusText = req.proxyDetected
        ? `PROXY (${req.status})`
        : req.error
        ? `ERR ${req.error}`
        : (req.status ? `${req.status} ${req.statusText}` : 'pending');

    return html`
        <div class="debug-net-entry">
            <div class="debug-net-summary" onClick=${() => setOpen(!open)}>
                <span class="debug-net-arrow">${open ? '\u25be' : '\u25b8'}</span>
                <span class="debug-net-method">${req.method}</span>${' '}
                <span class="debug-net-url">${_esc(req.url)}</span>${' '}
                <span style="color:${statusColor}">${statusText}</span>
                ${req.duration != null && html`${' '}<span class="debug-time">${req.duration}ms</span>`}
            </div>
            ${open && html`
                <div class="debug-net-detail">
                    ${req.contentType && html`<div><strong>Content-Type:</strong> <code>${_esc(req.contentType)}</code></div>`}
                    ${req.requestBodyPreview && html`<div><strong>Request:</strong> <code>${_esc(req.requestBodyPreview)}</code></div>`}
                    ${req.responsePreview && html`<div><strong>Response:</strong> <pre class="debug-pre">${_esc(req.responsePreview)}</pre></div>`}
                    <div class="debug-time">${req.ts}</div>
                </div>`}
        </div>`;
}

/**
 * @param {{ networkLog: Array }} props
 */
export function NetworkTab({ networkLog }) {
    const reversed = [...networkLog].reverse();

    return html`
        <div class="debug-network-tab">
            <div class="debug-toolbar">
                <span class="debug-badge">${networkLog.length}</span>
            </div>
            <div class="debug-content">
                ${reversed.length === 0
                    ? html`<div class="debug-empty">No network requests logged</div>`
                    : reversed.map((req, i) => html`<${NetEntry} key=${req.id || i} req=${req} />`)}
            </div>
        </div>`;
}
