<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Debug Console - Interactive PHP REPL</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;
            background: #1e1e1e;
            color: #d4d4d4;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: #252526;
            border-bottom: 1px solid #3c3c3c;
            padding: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 1.2rem;
            color: #569cd6;
        }

        .header-info {
            display: flex;
            gap: 2rem;
            font-size: 0.85rem;
            color: #858585;
        }

        .container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .sidebar {
            width: 300px;
            background: #252526;
            border-right: 1px solid #3c3c3c;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 1rem;
            border-bottom: 1px solid #3c3c3c;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .sidebar-header h2 {
            font-size: 0.9rem;
            color: #cccccc;
        }

        .clear-history-btn {
            background: #c5c5c5;
            color: #1e1e1e;
            border: none;
            padding: 0.3rem 0.8rem;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.75rem;
            font-family: inherit;
        }

        .clear-history-btn:hover {
            background: #e0e0e0;
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
            padding: 0.5rem;
        }

        .history-item {
            background: #2d2d30;
            border: 1px solid #3c3c3c;
            border-radius: 4px;
            padding: 0.8rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: background 0.2s;
        }

        .history-item:hover {
            background: #37373d;
        }

        .history-item-code {
            color: #ce9178;
            font-size: 0.85rem;
            margin-bottom: 0.3rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .history-item-meta {
            font-size: 0.75rem;
            color: #858585;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .editor-section {
            padding: 1rem;
            border-bottom: 1px solid #3c3c3c;
        }

        .editor-label {
            font-size: 0.9rem;
            color: #cccccc;
            margin-bottom: 0.5rem;
        }

        #code-editor {
            width: 100%;
            min-height: 150px;
            background: #1e1e1e;
            color: #d4d4d4;
            border: 1px solid #3c3c3c;
            border-radius: 4px;
            padding: 1rem;
            font-family: inherit;
            font-size: 0.95rem;
            resize: vertical;
        }

        #code-editor:focus {
            outline: 1px solid #569cd6;
        }

        .controls {
            display: flex;
            gap: 1rem;
            margin-top: 1rem;
        }

        .execute-btn {
            background: #0e639c;
            color: white;
            border: none;
            padding: 0.6rem 1.5rem;
            border-radius: 4px;
            cursor: pointer;
            font-family: inherit;
            font-size: 0.9rem;
        }

        .execute-btn:hover {
            background: #1177bb;
        }

        .execute-btn:disabled {
            background: #3c3c3c;
            cursor: not-allowed;
        }

        .output-section {
            flex: 1;
            padding: 1rem;
            overflow-y: auto;
        }

        .output-label {
            font-size: 0.9rem;
            color: #cccccc;
            margin-bottom: 0.5rem;
        }

        .output-container {
            background: #1e1e1e;
            border: 1px solid #3c3c3c;
            border-radius: 4px;
            padding: 1rem;
            min-height: 100px;
        }

        .output-entry {
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #3c3c3c;
        }

        .output-entry:last-child {
            border-bottom: none;
        }

        .output-success {
            color: #4ec9b0;
        }

        .output-error {
            color: #f48771;
        }

        .output-meta {
            font-size: 0.8rem;
            color: #858585;
            margin-top: 0.3rem;
        }

        .output-trace {
            background: #2d2d30;
            border-left: 3px solid #f48771;
            padding: 0.5rem;
            margin-top: 0.5rem;
            font-size: 0.8rem;
            overflow-x: auto;
        }

        .context-info {
            padding: 1rem;
            background: #2d2d30;
            border-top: 1px solid #3c3c3c;
            font-size: 0.8rem;
            color: #858585;
        }

        pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        ::-webkit-scrollbar {
            width: 10px;
            height: 10px;
        }

        ::-webkit-scrollbar-track {
            background: #1e1e1e;
        }

        ::-webkit-scrollbar-thumb {
            background: #424242;
            border-radius: 5px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #4e4e4e;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🐛 Debug Console - Interactive PHP REPL</h1>
        <div class="header-info">
            <span>PHP {context.php_version}</span>
            <span>Memory: {context.memory_usage} bytes</span>
        </div>
    </div>

    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>Command History</h2>
                <button class="clear-history-btn" onclick="clearHistory()">Clear</button>
            </div>
            <div class="history-list" id="history-list">
                <for items="history" as="entry">
                    <div class="history-item" onclick="loadHistory(this)"
                         data-code="{entry.code}">
                        <div class="history-item-code">{entry.code}</div>
                        <div class="history-item-meta">
                            {entry.type} · {entry.executionTime}ms
                        </div>
                    </div>
                </for>
            </div>
        </div>

        <div class="main-content">
            <div class="editor-section">
                <div class="editor-label">PHP Code (without &lt;?php tags)</div>
                <textarea id="code-editor" placeholder="Enter PHP code here...
Example:
return 2 + 2;

or

$users = ['Alice', 'Bob', 'Charlie'];
foreach ($users as $user) {
    echo $user . &quot;\n&quot;;
}
return count($users);"></textarea>
                <div class="controls">
                    <button class="execute-btn" onclick="executeCode()" id="execute-btn">
                        Execute (Ctrl+Enter)
                    </button>
                    <span id="status" style="color: #858585; align-self: center;"></span>
                </div>
            </div>

            <div class="output-section">
                <div class="output-label">Output</div>
                <div class="output-container" id="output"></div>
            </div>
        </div>
    </div>

    <script>
        const codeEditor = document.getElementById('code-editor');
        const executeBtn = document.getElementById('execute-btn');
        const outputContainer = document.getElementById('output');
        const statusEl = document.getElementById('status');
        const historyList = document.getElementById('history-list');

        // Ctrl+Enter to execute
        codeEditor.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                executeCode();
            }
        });

        async function executeCode() {
            const code = codeEditor.value.trim();

            if (!code) {
                return;
            }

            executeBtn.disabled = true;
            statusEl.textContent = 'Executing...';

            try {
                const response = await fetch('/debug/console/execute', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ code })
                });

                const result = await response.json();

                if (result.success) {
                    addOutput('success', result.result, result.type, result.executionTime);
                    // Reload history
                    await loadHistoryList();
                } else {
                    addOutput('error', result.error, null, null, result.trace);
                }

                statusEl.textContent = '';
            } catch (error) {
                addOutput('error', error.message);
                statusEl.textContent = '';
            } finally {
                executeBtn.disabled = false;
            }
        }

        function addOutput(type, content, dataType = null, execTime = null, trace = null) {
            const entry = document.createElement('div');
            entry.className = 'output-entry';

            const output = document.createElement('pre');
            output.className = type === 'success' ? 'output-success' : 'output-error';
            output.textContent = content;
            entry.appendChild(output);

            if (dataType || execTime) {
                const meta = document.createElement('div');
                meta.className = 'output-meta';
                meta.textContent = `Type: ${dataType} · Execution: ${execTime.toFixed(4)}ms`;
                entry.appendChild(meta);
            }

            if (trace) {
                const traceEl = document.createElement('div');
                traceEl.className = 'output-trace';
                traceEl.innerHTML = '<strong>Stack Trace:</strong>\n' +
                    trace.map(t => `${t.file}:${t.line} ${t.class || ''}${t.function}()`).join('\n');
                entry.appendChild(traceEl);
            }

            outputContainer.prepend(entry);
        }

        async function loadHistoryList() {
            try {
                const response = await fetch('/debug/console/history');
                const data = await response.json();

                historyList.innerHTML = data.history.map(entry => `
                    <div class="history-item" onclick="loadHistory(this)"
                         data-code="${escapeHtml(entry.code)}">
                        <div class="history-item-code">${escapeHtml(entry.code)}</div>
                        <div class="history-item-meta">
                            ${entry.type} · ${entry.executionTime.toFixed(4)}ms
                        </div>
                    </div>
                `).join('');
            } catch (error) {
                console.error('Failed to load history:', error);
            }
        }

        function loadHistory(element) {
            const code = element.dataset.code;
            codeEditor.value = code;
            codeEditor.focus();
        }

        async function clearHistory() {
            if (!confirm('Clear all command history?')) {
                return;
            }

            try {
                await fetch('/debug/console/history/clear', { method: 'POST' });
                historyList.innerHTML = '';
                statusEl.textContent = 'History cleared';
                setTimeout(() => statusEl.textContent = '', 2000);
            } catch (error) {
                statusEl.textContent = 'Failed to clear history';
            }
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Focus editor on load
        codeEditor.focus();
    </script>
</body>
</html>
