{% extends "admin/change_form.html" %}
{% load i18n %}

{% block extrahead %}
    {{ block.super }}
    <style>
        .exception-detail {
            max-width: 95%;
            margin: 0 auto;
            overflow: hidden;
            color: #111827;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        }
        .tn-nav-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
        .tn-time { font-size: 0.875rem; color: #6b7280; }
        .tn-header { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-bottom: 16px; }
        .tn-level-icon { display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; border-radius: 50%; font-size: 1.25rem; flex-shrink: 0; }
        .tn-level-icon--error { background: #fee2e2; color: #dc2626; }
        .tn-level-icon--warning { background: #fef9c3; color: #ca8a04; }
        .tn-level-icon--info { background: #dbeafe; color: #2563eb; }
        .tn-header-text { min-width: 0; flex: 1; }
        .tn-header-text h2 { font-size: 1.5rem; font-weight: 700; color: #1f2937; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin: 0; }
        .tn-subtitle { color: #6b7280; font-size: 0.875rem; margin: 2px 0 0; }
        .tn-badges { display: flex; flex-wrap: wrap; gap: 8px; }
        .tn-badge { display: inline-block; padding: 4px 12px; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; white-space: nowrap; }
        .tn-badge--critical { background: #fee2e2; color: #b91c1c; }
        .tn-badge--high { background: #ffedd5; color: #c2410c; }
        .tn-badge--moderate { background: #fef9c3; color: #a16207; }
        .tn-badge--low { background: #f3f4f6; color: #4b5563; }
        .tn-badge--status-new { background: #dbeafe; color: #1d4ed8; }
        .tn-badge--status-seen { background: #ede9fe; color: #6d28d9; }
        .tn-badge--status-resolved { background: #dcfce7; color: #15803d; }
        .tn-badge--status-ignored { background: #f3f4f6; color: #4b5563; }
        .tn-badge--sent { background: #dcfce7; color: #15803d; }
        .tn-badge--not-sent { background: #fee2e2; color: #b91c1c; }
        .tn-occurrence { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; margin-bottom: 16px; padding: 0 4px; }
        .tn-occurrence a { font-size: 0.875rem; color: #6b7280; text-decoration: none; transition: color 0.15s; }
        .tn-occurrence a:hover { color: #2563eb; }
        .tn-occurrence .tn-stat-value { font-weight: 600; color: #374151; }
        .tn-actions-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 24px; padding: 12px; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 12px; }
        .tn-actions-label { font-size: 0.75rem; font-weight: 600; color: #6b7280; text-transform: uppercase; letter-spacing: 0.05em; margin-right: 4px; }
        .tn-divider { width: 1px; height: 24px; background: #d1d5db; margin: 0 4px; }
        #action-feedback { font-size: 0.875rem; font-weight: 500; margin-left: 8px; }
        .tn-error-box { background: #fef2f2; border-left: 4px solid #f87171; padding: 16px; border-radius: 0 8px 8px 0; margin-bottom: 24px; }
        .tn-error-box p { color: #991b1b; font-family: monospace; font-size: 0.875rem; word-break: break-all; margin: 0; }
        .tn-info-grid { display: grid; grid-template-columns: 1fr; gap: 24px; margin-bottom: 24px; }
        @media (min-width: 1024px) { .tn-info-grid { grid-template-columns: 1fr 1fr; } }
        .tn-card { background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 2px rgba(0,0,0,0.05); border-radius: 12px; padding: 20px; }
        .tn-card-mb { margin-bottom: 24px; }
        .tn-card h3 { font-size: 1.125rem; font-weight: 600; color: #374151; margin: 0 0 16px; display: flex; align-items: center; gap: 8px; }
        .tn-card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
        .tn-card-header h3 { margin-bottom: 0; }
        .tn-btn-group { display: flex; gap: 4px; }
        .tn-icon-blue { color: #3b82f6; }
        .tn-icon-purple { color: #a855f7; }
        .tn-icon-red { color: #ef4444; }
        .tn-card table { table-layout: fixed; width: 100%; font-size: 0.875rem; border-collapse: collapse; }
        .tn-card table td { overflow: hidden; text-overflow: ellipsis; padding: 8px 0; color: #111827; }
        .tn-card table tr { border-bottom: 1px solid #f3f4f6; }
        .tn-card table tr:last-child { border-bottom: none; }
        .tn-label { font-weight: 500; color: #6b7280 !important; width: 33.333%; }
        .tn-mono { font-family: monospace; font-size: 0.875rem; }
        .tn-break { word-break: break-all; }
        .tn-method-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 700; }
        .tn-method-badge--get { background: #dcfce7; color: #15803d; }
        .tn-method-badge--post { background: #dbeafe; color: #1d4ed8; }
        .tn-method-badge--put { background: #fef9c3; color: #a16207; }
        .tn-method-badge--delete { background: #fee2e2; color: #b91c1c; }
        .tn-method-badge--default { background: #f3f4f6; color: #374151; }
        .tn-env-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 600; }
        .tn-env-badge--production { background: #fee2e2; color: #b91c1c; }
        .tn-env-badge--other { background: #dcfce7; color: #15803d; }
        .monaco-section { border-radius: 8px; overflow: hidden; }
        .editor-btn { padding: 4px 12px; font-size: 13px; border-radius: 8px; border: none; cursor: pointer; background: #f3f4f6; color: #4b5563; transition: background 0.15s; }
        .editor-btn:hover { background: #e5e7eb; }
        .action-btn { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; font-size: 13px; font-weight: 500; border-radius: 8px; border: 1px solid; cursor: pointer; transition: all 0.15s; text-decoration: none !important; }
        .action-btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .action-btn--resolve { border-color: #16a34a; color: #16a34a; background: transparent; }
        .action-btn--resolve:hover { background: #16a34a; color: #fff; }
        .action-btn--ignore { border-color: #9ca3af; color: #6b7280; background: transparent; }
        .action-btn--ignore:hover { background: #6b7280; color: #fff; }
        .action-btn--seen { border-color: #7c3aed; color: #7c3aed; background: transparent; }
        .action-btn--seen:hover { background: #7c3aed; color: #fff; }
        .action-btn--resend { border-color: #2563eb; color: #2563eb; background: transparent; }
        .action-btn--resend:hover { background: #2563eb; color: #fff; }
        .action-btn svg { width: 14px; height: 14px; }
        .nav-btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; font-size: 13px; font-weight: 500; border-radius: 8px; text-decoration: none !important; border: 1px solid #d1d5db; background: #fff; color: #374151 !important; transition: all 0.15s; }
        .nav-btn:hover { background: #f3f4f6; border-color: #9ca3af; }
        .nav-btn--disabled { opacity: 0.35; pointer-events: none; }
        .nav-btn svg { width: 16px; height: 16px; }
        .copy-tooltip { position: absolute; bottom: 100%; left: 50%; translate: -50% 0; margin-bottom: 6px; padding: 4px 10px; font-size: 12px; font-weight: 500; white-space: nowrap; border-radius: 6px; background: #1f2937; color: #fff; pointer-events: none; opacity: 0; transition: opacity 0.15s; }
        .copy-tooltip.show { opacity: 1; }
        .copy-tooltip::after { content: ''; position: absolute; top: 100%; left: 50%; translate: -50% 0; border: 5px solid transparent; border-top-color: #1f2937; }
        .tn-bottom-nav { display: flex; align-items: center; justify-content: space-between; margin-top: 32px; margin-bottom: 16px; }
        .tn-bottom-nav-right { display: flex; gap: 8px; }
        .tn-cursor-pointer { cursor: pointer; }
        .tn-relative { position: relative; }
    </style>
{% endblock %}

{% block content %}
<div class="exception-detail">

    <!-- Prev / Next Navigation -->
    <div class="tn-nav-row">
        <a href="{% if prev_url %}{{ prev_url }}{% else %}#{% endif %}"
           class="nav-btn {% if not prev_url %}nav-btn--disabled{% endif %}">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/></svg>
            Newer
        </a>
        <span class="tn-time">
            {{ time_ago }}
        </span>
        <a href="{% if next_url %}{{ next_url }}{% else %}#{% endif %}"
           class="nav-btn {% if not next_url %}nav-btn--disabled{% endif %}">
            Older
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>
        </a>
    </div>

    <!-- Header -->
    <div class="tn-header">
        {% if original.level == "critical" or original.level == "error" %}
            <span class="tn-level-icon tn-level-icon--error">
                {% if original.level == "critical" %}&#9940;{% else %}&#128308;{% endif %}
            </span>
        {% elif original.level == "warning" %}
            <span class="tn-level-icon tn-level-icon--warning">&#128993;</span>
        {% else %}
            <span class="tn-level-icon tn-level-icon--info">&#128309;</span>
        {% endif %}
        <div class="tn-header-text">
            <h2>{{ original.exception_class }}</h2>
            <p class="tn-subtitle">{{ original.created_at|date:"Y-m-d H:i:s" }} &middot; {{ original.environment|default:"unknown" }}</p>
        </div>
        <div class="tn-badges">
            <span class="tn-badge
                {% if original.severity == 'critical' %}tn-badge--critical
                {% elif original.severity == 'high' %}tn-badge--high
                {% elif original.severity == 'moderate' %}tn-badge--moderate
                {% else %}tn-badge--low{% endif %}">
                {{ original.severity|upper }}
            </span>
            <span id="status-badge" class="tn-badge
                {% if original.status == 'new' %}tn-badge--status-new
                {% elif original.status == 'seen' %}tn-badge--status-seen
                {% elif original.status == 'resolved' %}tn-badge--status-resolved
                {% else %}tn-badge--status-ignored{% endif %}">
                {{ original.status|upper }}
            </span>
            <span id="sent-badge" class="tn-badge
                {% if original.is_sent %}tn-badge--sent{% else %}tn-badge--not-sent{% endif %}">
                {% if original.is_sent %}Sent to Telegram{% else %}Not Sent{% endif %}
            </span>
        </div>
    </div>

    <!-- Occurrence Stats -->
    <div class="tn-occurrence">
        <a href="../?exception_class={{ original.exception_class|urlencode }}">
            <span class="tn-stat-value">{{ occurrence_24h }}</span> in 24h
            &middot;
            <span class="tn-stat-value">{{ occurrence_7d }}</span> in 7d
            &middot;
            <span class="tn-stat-value">{{ occurrence_total }}</span> total
        </a>
    </div>

    <!-- Action Toolbar -->
    <div class="tn-actions-bar">
        <span class="tn-actions-label">Actions</span>
        <button class="action-btn action-btn--resolve" data-action="resolved">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
            Resolve
        </button>
        <button class="action-btn action-btn--seen" data-action="seen">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
            Mark Seen
        </button>
        <button class="action-btn action-btn--ignore" data-action="ignored">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728L5.636 5.636"/></svg>
            Ignore
        </button>
        <span class="tn-divider"></span>
        <button class="action-btn action-btn--resend" data-action="resend">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
            Resend to Telegram
        </button>
        <span id="action-feedback" style="display:none"></span>
    </div>

    <!-- Error Message -->
    <div class="tn-error-box">
        <p>{{ original.message }}</p>
    </div>

    <!-- Grid: Request + Server Info -->
    <div class="tn-info-grid">
        <div class="tn-card">
            <h3>
                <span class="tn-icon-blue">&#128463;</span> Request
            </h3>
            <table>
                <tbody>
                    <tr>
                        <td class="tn-label">Method</td>
                        <td>
                            <span class="tn-method-badge
                                {% if original.method == 'GET' %}tn-method-badge--get
                                {% elif original.method == 'POST' %}tn-method-badge--post
                                {% elif original.method == 'PUT' or original.method == 'PATCH' %}tn-method-badge--put
                                {% elif original.method == 'DELETE' %}tn-method-badge--delete
                                {% else %}tn-method-badge--default{% endif %}">
                                {{ original.method|default:"-" }}
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td class="tn-label">Path</td>
                        <td class="tn-mono tn-break">{{ original.path|default:"-" }}</td>
                    </tr>
                    <tr>
                        <td class="tn-label">User</td>
                        <td>{{ original.user_info|default:"-" }}</td>
                    </tr>
                    <tr>
                        <td class="tn-label">IP Address</td>
                        <td class="tn-mono">{{ original.ip_address|default:"-" }}</td>
                    </tr>
                    <tr>
                        <td class="tn-label">View</td>
                        <td class="tn-mono tn-break">{{ original.view_name|default:"-" }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="tn-card">
            <h3>
                <span class="tn-icon-purple">&#128421;</span> Server
            </h3>
            <table>
                <tbody>
                    <tr>
                        <td class="tn-label">Hostname</td>
                        <td class="tn-mono">{{ original.hostname|default:"-" }}</td>
                    </tr>
                    <tr>
                        <td class="tn-label">Environment</td>
                        <td>
                            <span class="tn-env-badge
                                {% if original.environment == 'production' %}tn-env-badge--production
                                {% else %}tn-env-badge--other{% endif %}">
                                {{ original.environment|default:"unknown" }}
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td class="tn-label">Level</td>
                        <td>{{ original.level|upper }}</td>
                    </tr>
                    <tr>
                        <td class="tn-label">Timestamp</td>
                        <td>{{ original.created_at|date:"Y-m-d H:i:s T" }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Query Params -->
    {% if original.query_params %}
    <div class="tn-card tn-card-mb">
        <div class="tn-card-header">
            <h3>Query Parameters</h3>
            <div class="tn-btn-group">
                <button id="mc-query-params-copy" class="editor-btn tn-relative">Copy</button>
                <button id="mc-query-params-fmt" class="editor-btn tn-relative">Format</button>
                <button id="mc-query-params-min" class="editor-btn tn-relative">Minify</button>
            </div>
        </div>
        <div class="monaco-section" id="mc-query-params" style="height:200px;"></div>
    </div>
    {% endif %}

    <!-- Request Body -->
    {% if original.body %}
    <div class="tn-card tn-card-mb">
        <div class="tn-card-header">
            <h3>Request Body</h3>
            <div class="tn-btn-group">
                <button id="mc-body-copy" class="editor-btn tn-relative">Copy</button>
                <button id="mc-body-fmt" class="editor-btn tn-relative">Format</button>
                <button id="mc-body-min" class="editor-btn tn-relative">Minify</button>
            </div>
        </div>
        <div class="monaco-section" id="mc-body" style="height:250px;"></div>
    </div>
    {% endif %}

    <!-- Headers -->
    {% if original.headers %}
    <div class="tn-card tn-card-mb">
        <div class="tn-card-header">
            <h3 class="tn-cursor-pointer" id="headers-toggle">
                <span id="headers-arrow">&#9660;</span> Request Headers
            </h3>
            <div class="tn-btn-group">
                <button id="mc-headers-copy" class="editor-btn tn-relative">Copy</button>
                <button id="mc-headers-fmt" class="editor-btn tn-relative">Format</button>
                <button id="mc-headers-min" class="editor-btn tn-relative">Minify</button>
            </div>
        </div>
        <div class="monaco-section" id="mc-headers" style="height:300px;"></div>
    </div>
    {% endif %}

    <!-- Traceback -->
    <div class="tn-card tn-card-mb">
        <div class="tn-card-header">
            <h3>
                <span class="tn-icon-red">&#128027;</span> Traceback
            </h3>
            <div class="tn-btn-group">
                <button id="mc-traceback-copy" class="editor-btn tn-relative">Copy</button>
            </div>
        </div>
        <div class="monaco-section" id="mc-traceback" style="height:400px;"></div>
    </div>

    <!-- Bottom Navigation -->
    <div class="tn-bottom-nav">
        <a href="{{ list_url }}" class="nav-btn">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
            Back to List
        </a>
        <div class="tn-bottom-nav-right">
            <a href="{% if prev_url %}{{ prev_url }}{% else %}#{% endif %}"
               class="nav-btn {% if not prev_url %}nav-btn--disabled{% endif %}">
                <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/></svg>
                Newer
            </a>
            <a href="{% if next_url %}{{ next_url }}{% else %}#{% endif %}"
               class="nav-btn {% if not next_url %}nav-btn--disabled{% endif %}">
                Older
                <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>
            </a>
        </div>
    </div>
</div>

{{ original.traceback|json_script:"data-traceback" }}

<script>
(() => {
    const MONACO_CDN = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
    const editors = {};
    const ACTION_URL = '{{ action_url }}';
    const CSRF = document.querySelector('[name=csrfmiddlewaretoken]')?.value
        || '{{ csrf_token }}';

    // --- Theme ---
    // Monaco editors always use dark theme for readability
    const MONACO_THEME = 'vs-dark';

    // --- Tooltip ---
    const showTooltip = (btn, text) => {
        let tip = btn.querySelector('.copy-tooltip');
        if (!tip) {
            tip = document.createElement('span');
            tip.className = 'copy-tooltip';
            btn.appendChild(tip);
        }
        tip.textContent = text;
        tip.classList.add('show');
        setTimeout(() => tip.classList.remove('show'), 1200);
    };

    // --- Action Toolbar ---
    const STATUS_STYLES = {
        new: 'tn-badge--status-new',
        seen: 'tn-badge--status-seen',
        resolved: 'tn-badge--status-resolved',
        ignored: 'tn-badge--status-ignored',
    };

    const feedback = document.getElementById('action-feedback');
    const statusBadge = document.getElementById('status-badge');
    const sentBadge = document.getElementById('sent-badge');

    const showFeedback = (msg, ok) => {
        feedback.textContent = msg;
        feedback.style.display = '';
        feedback.style.color = ok ? '#16a34a' : '#dc2626';
        setTimeout(() => { feedback.style.display = 'none'; }, 2500);
    };

    const updateStatusBadge = (status) => {
        // Remove all status classes
        Object.values(STATUS_STYLES).forEach(c => statusBadge.classList.remove(c));
        // Add new one
        if (STATUS_STYLES[status]) statusBadge.classList.add(STATUS_STYLES[status]);
        statusBadge.textContent = status.toUpperCase();
    };

    const updateSentBadge = (sent) => {
        sentBadge.className = 'tn-badge ' + (sent ? 'tn-badge--sent' : 'tn-badge--not-sent');
        sentBadge.textContent = sent ? 'Sent to Telegram' : 'Not Sent';
    };

    document.querySelectorAll('[data-action]').forEach(btn => {
        btn.addEventListener('click', async () => {
            btn.disabled = true;
            try {
                const res = await fetch(ACTION_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': CSRF,
                    },
                    body: JSON.stringify({ action: btn.dataset.action }),
                });
                const data = await res.json();
                if (data.ok) {
                    if (data.status) {
                        updateStatusBadge(data.status);
                        showFeedback(`Status: ${data.status}`, true);
                    }
                    if (data.is_sent !== undefined) {
                        updateSentBadge(data.is_sent);
                        showFeedback(data.is_sent ? 'Sent!' : 'Send failed', data.is_sent);
                    }
                } else {
                    showFeedback(data.error || 'Failed', false);
                }
            } catch (e) {
                showFeedback('Network error', false);
            }
            btn.disabled = false;
        });
    });

    // --- Monaco loader ---
    const loadMonaco = () => new Promise(resolve => {
        if (globalThis.monaco) return resolve();
        const s = document.createElement('script');
        s.src = `${MONACO_CDN}/loader.min.js`;
        s.onload = () => {
            require.config({ paths: { vs: MONACO_CDN } });
            require(['vs/editor/editor.main'], resolve);
        };
        document.head.appendChild(s);
    });

    // --- Editor factory ---
    const createEditor = (id, content, language) => {
        const el = document.getElementById(id);
        if (!el) return null;
        const editor = monaco.editor.create(el, {
            value: content,
            language,
            theme: MONACO_THEME,
            readOnly: true,
            minimap: { enabled: false },
            fontSize: 13,
            lineNumbers: 'on',
            scrollBeyondLastLine: false,
            wordWrap: 'on',
            tabSize: 2,
            automaticLayout: true,
        });
        editors[id] = editor;
        return editor;
    };

    // --- Button wiring ---
    const bindButtons = (id) => {
        const editor = () => editors[id];

        document.getElementById(`${id}-copy`)?.addEventListener('click', (e) => {
            navigator.clipboard.writeText(editor().getValue())
                .then(() => showTooltip(e.currentTarget, 'Copied!'));
        });

        document.getElementById(`${id}-fmt`)?.addEventListener('click', (e) => {
            try {
                editor().setValue(JSON.stringify(JSON.parse(editor().getValue()), null, 2));
                showTooltip(e.currentTarget, 'Formatted!');
            } catch {}
        });

        document.getElementById(`${id}-min`)?.addEventListener('click', (e) => {
            try {
                editor().setValue(JSON.stringify(JSON.parse(editor().getValue())));
                showTooltip(e.currentTarget, 'Minified!');
            } catch {}
        });
    };

    // --- Headers toggle ---
    const toggle = document.getElementById('headers-toggle');
    const arrow = document.getElementById('headers-arrow');
    if (toggle) {
        toggle.addEventListener('click', () => {
            const section = toggle.closest('.tn-card').querySelector('.monaco-section');
            const hidden = section.style.display === 'none';
            section.style.display = hidden ? '' : 'none';
            arrow.textContent = hidden ? '\u25BC' : '\u25B6';
        });
    }

    // --- JSON formatter ---
    const toJson = (data) => {
        try {
            return JSON.stringify(typeof data === 'string' ? JSON.parse(data) : data, null, 2);
        } catch {
            return typeof data === 'string' ? data : JSON.stringify(data);
        }
    };

    // --- Init ---
    loadMonaco().then(() => {
        const tb = JSON.parse(document.getElementById('data-traceback').textContent);
        createEditor('mc-traceback', tb, 'python');
        bindButtons('mc-traceback');

        {% if original.query_params %}
        createEditor('mc-query-params', toJson({{ original.query_params|safe }}), 'json');
        bindButtons('mc-query-params');
        {% endif %}

        {% if original.body %}
        try {
            createEditor('mc-body', toJson({{ original.body|safe }}), 'json');
        } catch {
            createEditor('mc-body', {{ original.body|safe|default:"''" }}, 'plaintext');
        }
        bindButtons('mc-body');
        {% endif %}

        {% if original.headers %}
        createEditor('mc-headers', toJson({{ original.headers|safe }}), 'json');
        bindButtons('mc-headers');
        {% endif %}
    });
})();
</script>
{% endblock %}
