<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Preview</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css">
<style>
    :root { color-scheme: dark; }
    body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        max-width: 800px; margin: 0 auto; padding: 24px 32px;
        background: #0d1117; color: #e6edf3; line-height: 1.6;
    }
    .preview-header {
        display: flex; justify-content: space-between; align-items: center;
        padding: 8px 0 16px; border-bottom: 1px solid #30363d; margin-bottom: 20px;
    }
    .preview-header h3 { margin: 0; font-size: 14px; color: #8b949e; font-weight: 400; }
    .preview-header button {
        padding: 6px 14px; background: #238636; color: #fff; border: none;
        border-radius: 6px; cursor: pointer; font-size: 12px; font-weight: 600; margin-left: 6px;
    }
    .preview-header button:hover { background: #2ea043; }
    .preview-header button.secondary { background: #30363d; }
    .preview-header button.secondary:hover { background: #484f58; }
    #editor {
        width: 100%; min-height: 400px; padding: 12px; background: #161b22;
        border: 1px solid #30363d; border-radius: 6px; color: #e6edf3;
        font-family: 'SF Mono', Consolas, monospace; font-size: 13px;
        line-height: 1.5; resize: vertical; display: none; box-sizing: border-box;
    }
    #editor:focus { outline: none; border-color: #58a6ff; }
    #loading { text-align: center; padding: 60px; color: #8b949e; }
    h1, h2, h3, h4, h5, h6 { color: #e6edf3; border-bottom: 1px solid #21262d; padding-bottom: 6px; }
    h1 { font-size: 24px; } h2 { font-size: 20px; } h3 { font-size: 16px; }
    a { color: #58a6ff; }
    code { background: #161b22; padding: 2px 6px; border-radius: 4px; font-size: 90%; }
    pre { background: #161b22; padding: 12px; border-radius: 6px; overflow-x: auto; }
    pre code { background: none; padding: 0; }
    blockquote { border-left: 3px solid #30363d; margin: 8px 0; padding: 4px 16px; color: #8b949e; }
    table { border-collapse: collapse; width: 100%; margin: 12px 0; }
    th, td { border: 1px solid #30363d; padding: 6px 12px; text-align: left; }
    th { background: #161b22; }
    ul, ol { padding-left: 24px; }
    li { margin: 4px 0; }
    hr { border: none; border-top: 1px solid #30363d; margin: 16px 0; }
    img { max-width: 100%; }
</style>
</head>
<body>
    <div id="loading">Loading...</div>
    <div id="preview-container" style="display:none">
        <div class="preview-header">
            <h3 id="filepath-label"></h3>
            <div>
                <button class="secondary" onclick="toggleEdit()" id="edit-btn">Edit</button>
                <button onclick="saveFile()" id="save-btn">Save</button>
            </div>
        </div>
        <div id="rendered"></div>
        <textarea id="editor"></textarea>
    </div>

<script>
    const params = new URLSearchParams(window.location.search);
    const agentName = params.get('agent');
    const filepath = params.get('file');
    const sessionId = params.get('session_id') || '';
    let editing = false;
    let rawContent = '';

    document.getElementById('filepath-label').textContent = filepath;
    document.title = filepath;

    // Basic markdown to HTML
    function renderMarkdown(md) {
        let html = md
            .replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) =>
                `<pre><code>${code.replace(/\x3c/g, '&lt;').replace(/>/g, '&gt;')}</code></pre>`)
            .replace(/`([^`]+)`/g, '<code>$1</code>')
            .replace(/^### (.+)$/gm, '<h3>$1</h3>')
            .replace(/^## (.+)$/gm, '<h2>$1</h2>')
            .replace(/^# (.+)$/gm, '<h1>$1</h1>')
            .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.+?)\*/g, '<em>$1</em>')
            .replace(/^> (.+)$/gm, '<blockquote>$1</blockquote>')
            .replace(/^---$/gm, '<hr>')
            .replace(/^\- (.+)$/gm, '<li>$1</li>')
            .replace(/^\d+\. (.+)$/gm, '<li>$1</li>')
            .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
            .replace(/\n\n/g, '</p><p>')
            .replace(/\n/g, '<br>');
        return '<p>' + html + '</p>';
    }

    function isMarkdown(fp) {
        return /\.(md|mdx|rst|txt)$/i.test(fp);
    }

    function getLangFromPath(fp) {
        const ext = (fp.match(/\.(\w+)$/) || [])[1] || '';
        const map = {
            js: 'javascript', ts: 'typescript', tsx: 'typescript', jsx: 'javascript',
            py: 'python', rb: 'ruby', rs: 'rust', go: 'go', java: 'java',
            sh: 'bash', zsh: 'bash', bash: 'bash', yml: 'yaml', yaml: 'yaml',
            json: 'json', toml: 'toml', css: 'css', scss: 'scss',
            html: 'html', xml: 'xml', sql: 'sql', c: 'c', cpp: 'cpp',
            h: 'c', hpp: 'cpp', cs: 'csharp', swift: 'swift', kt: 'kotlin',
            md: 'markdown', dockerfile: 'dockerfile',
        };
        return map[ext.toLowerCase()] || ext.toLowerCase() || 'plaintext';
    }

    function renderCode(content, fp) {
        const lang = getLangFromPath(fp);
        const escaped = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        return `<pre><code class="language-${lang}">${escaped}</code></pre>`;
    }

    async function loadFile() {
        try {
            const qs = new URLSearchParams({ filepath });
            if (sessionId) qs.set('session_id', sessionId);
            const resp = await fetch(`/api/sessions/live/${encodeURIComponent(agentName)}/file-content?${qs}`);
            const data = await resp.json();
            if (data.error) {
                document.getElementById('loading').textContent = 'Error: ' + data.error;
                return;
            }
            rawContent = data.content || '';
            const rendered = document.getElementById('rendered');
            if (isMarkdown(filepath)) {
                rendered.innerHTML = renderMarkdown(rawContent);
            } else {
                rendered.innerHTML = renderCode(rawContent, filepath);
                // Apply highlight.js if loaded
                if (window.hljs) {
                    rendered.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
                }
            }
            document.getElementById('editor').value = rawContent;
            document.getElementById('loading').style.display = 'none';
            document.getElementById('preview-container').style.display = 'block';
        } catch (e) {
            document.getElementById('loading').textContent = 'Failed to load file';
        }
    }

    function toggleEdit() {
        editing = !editing;
        document.getElementById('rendered').style.display = editing ? 'none' : 'block';
        document.getElementById('editor').style.display = editing ? 'block' : 'none';
        document.getElementById('edit-btn').textContent = editing ? 'Preview' : 'Edit';
        if (!editing) {
            rawContent = document.getElementById('editor').value;
            const rendered = document.getElementById('rendered');
            if (isMarkdown(filepath)) {
                rendered.innerHTML = renderMarkdown(rawContent);
            } else {
                rendered.innerHTML = renderCode(rawContent, filepath);
                if (window.hljs) rendered.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
            }
        }
    }

    async function saveFile() {
        const content = document.getElementById('editor').value;
        try {
            const qs = new URLSearchParams({ filepath });
            if (sessionId) qs.set('session_id', sessionId);
            const resp = await fetch(`/api/sessions/live/${encodeURIComponent(agentName)}/file-content?${qs}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ content }),
            });
            const data = await resp.json();
            if (data.error) { alert('Error: ' + data.error); return; }
            document.title = filepath + ' (saved)';
            setTimeout(() => { document.title = filepath; }, 2000);
        } catch (e) {
            alert('Failed to save: ' + e.message);
        }
    }

    loadFile();
</script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
<script>
    // Re-highlight after hljs loads if content already rendered
    if (window.hljs && document.querySelector('#rendered pre code')) {
        document.querySelectorAll('#rendered pre code').forEach(block => hljs.highlightElement(block));
    }
</script>
</body>
</html>
