// Partial: _file-viewer.js.j2 — Unified file viewer with markdown rendering toggle
// Uses apiFetch() for both edit mode (real API) and view mode (embedded data)

// =====================================================================
// File Viewer State
// =====================================================================

var fvState = {
    currentFile: null,
    fileViewMode: 'source',  // 'source' or 'rendered'
    lastData: null            // cached API response for re-rendering
};

// =====================================================================
// Show Source File
// =====================================================================

async function showSource(filePath, lineNumber) {
    var panel = document.getElementById('file-viewer-panel');
    var divider = document.getElementById('divider-right');
    var pathEl = document.getElementById('fv-path');
    var statusEl = document.getElementById('fv-status');
    var langEl = document.getElementById('fv-lang');
    var modeToggle = document.getElementById('fv-mode-toggle');
    var vscodeLink = document.getElementById('fv-vscode');
    var body = document.getElementById('fv-body');

    fvState.currentFile = filePath;
    var fileName = filePath.split('/').pop();
    var isMarkdown = fileName.endsWith('.md');

    pathEl.textContent = fileName;
    pathEl.title = filePath;
    if (statusEl) {
        statusEl.textContent = '';
        statusEl.className = 'fv-status';
    }
    langEl.textContent = '';

    // Show panel and divider
    panel.classList.add('open');
    divider.style.display = '';

    // Show loading state
    body.innerHTML = '<div style="padding:24px;color:#adb5bd;text-align:center;">Loading...</div>';

    var data = await apiFetch('/api/file-content?path=' + encodeURIComponent(filePath));
    if (!data) {
        body.innerHTML = '<div style="padding:24px;color:#dc3545;text-align:center;">' +
            'Failed to load file</div>';
        return;
    }
    fvState.lastData = data;

    // Update status badge (edit mode only — shows pending mutation count)
    if (statusEl) {
        if (data.has_pending_mutations) {
            statusEl.textContent = data.pending_mutation_count + ' pending edit' +
                (data.pending_mutation_count !== 1 ? 's' : '');
            statusEl.className = 'fv-status has-mutations';
            statusEl.title = 'Unsaved mutations would modify this file: ' +
                (data.affected_nodes || []).join(', ');
        } else {
            statusEl.textContent = 'on disk';
            statusEl.className = 'fv-status on-disk';
            statusEl.title = 'Showing current file contents from disk';
        }
    }

    // Language badge
    langEl.textContent = data.language || '';

    // VS Code link
    var basePath = document.body.dataset.basePath || '';
    var absPath = basePath ? (basePath + '/' + filePath) : filePath;
    vscodeLink.href = 'vscode://file/' + absPath + ':' + (lineNumber || 1) + ':1';
    vscodeLink.style.display = '';

    // Rendered/Source toggle for markdown files
    if (isMarkdown) {
        modeToggle.style.display = 'flex';
        fvState.fileViewMode = 'rendered';
        modeToggle.querySelectorAll('.file-viewer-mode-btn').forEach(function(btn) {
            btn.classList.toggle('active', btn.dataset.mode === 'rendered');
        });
    } else {
        modeToggle.style.display = 'none';
        fvState.fileViewMode = 'source';
    }

    // Render content
    fvRenderContent(data, lineNumber);
}

// =====================================================================
// Render Content
// =====================================================================

function fvRenderContent(data, lineNumber) {
    var body = document.getElementById('fv-body');

    if (fvState.fileViewMode === 'rendered' && fvState.currentFile && fvState.currentFile.endsWith('.md')) {
        // Rendered markdown view
        var rawLines = data.lines || [];
        var html = '<div class="source-lines">';
        for (var i = 0; i < rawLines.length; i++) {
            var num = i + 1;
            html += '<div class="source-line" data-line="' + num + '" id="fv-line-' + num + '">' +
                '<span class="line-num">' + num + '</span>' +
                '<div class="line-content rendered-line">' + fvRenderMarkdown(rawLines[i]) + '</div>' +
                '</div>';
        }
        html += '</div>';
        body.innerHTML = html;
        fvScrollAndFlash(body, lineNumber);
        return;
    }

    // Source view with syntax highlighting
    var lines = data.highlighted_lines || data.lines || [];
    var html = '<div class="source-lines">';
    for (var i = 0; i < lines.length; i++) {
        var num = i + 1;
        html += '<div class="source-line" data-line="' + num + '" id="fv-line-' + num + '">' +
            '<span class="line-num">' + num + '</span>' +
            '<code class="line-content highlight">' + (lines[i] || '') + '</code>' +
            '</div>';
    }
    html += '</div>';
    body.innerHTML = html;
    fvScrollAndFlash(body, lineNumber);
}

// =====================================================================
// Scroll & Flash
// =====================================================================

function fvScrollAndFlash(container, lineNumber) {
    if (!lineNumber) return;
    setTimeout(function() {
        // Clear any previous highlight
        var prev = container.querySelector('.source-line.highlighted');
        if (prev) {
            prev.classList.remove('highlighted');
            prev.style.backgroundColor = '';
            prev.style.transition = '';
            var prevCells = prev.querySelectorAll('.line-num, .line-content');
            for (var i = 0; i < prevCells.length; i++) {
                prevCells[i].style.backgroundColor = '';
                prevCells[i].style.transition = '';
            }
        }

        var target = container.querySelector('.source-line[data-line="' + lineNumber + '"]');
        if (!target) return;

        target.scrollIntoView({ behavior: 'smooth', block: 'center' });
        target.classList.add('highlighted');

        // Flash after scroll completes
        var fired = false;
        function flash() {
            if (fired) return;
            fired = true;
            var cells = target.querySelectorAll('.line-num, .line-content');
            for (var i = 0; i < cells.length; i++) {
                cells[i].style.transition = 'none';
                cells[i].style.backgroundColor = '#ffc107';
            }
            setTimeout(function() {
                for (var i = 0; i < cells.length; i++) {
                    cells[i].style.transition = 'background-color 1s ease-out';
                    cells[i].style.backgroundColor = '';
                }
            }, 400);
        }

        container.addEventListener('scrollend', function onScrollEnd() {
            container.removeEventListener('scrollend', onScrollEnd);
            flash();
        });
        setTimeout(flash, 800);
    }, 50);
}

// =====================================================================
// View Mode Toggle
// =====================================================================

function setFileViewMode(mode) {
    fvState.fileViewMode = mode;
    document.querySelectorAll('#fv-mode-toggle .file-viewer-mode-btn').forEach(function(btn) {
        btn.classList.toggle('active', btn.dataset.mode === mode);
    });
    if (fvState.lastData) {
        fvRenderContent(fvState.lastData, null);
    }
}

// =====================================================================
// Markdown Renderer (simple inline)
// =====================================================================

function fvRenderMarkdown(text) {
    var html = text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/^### (.+)$/gm, '<h3>$1</h3>')
        .replace(/^## (.+)$/gm, '<h2>$1</h2>')
        .replace(/^# (.+)$/gm, '<h1>$1</h1>')
        .replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>')
        .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.+?)\*/g, '<em>$1</em>')
        .replace(/`([^`]+)`/g, '<code>$1</code>')
        .replace(/^---+$/gm, '<hr>')
        .replace(/^- (.+)$/gm, '<li>$1</li>')
        .replace(/^(\d+)\. (.+)$/gm, '<li>$2</li>')
        .replace(/\n\n/g, '</p><p>')
        .replace(/\n/g, '<br>');
    return '<p>' + html + '</p>';
}

// =====================================================================
// Close & Link Interception
// =====================================================================

function closeFileViewer() {
    document.getElementById('file-viewer-panel').classList.remove('open');
    document.getElementById('divider-right').style.display = 'none';
    fvState.currentFile = null;
    fvState.lastData = null;
}

// Intercept vscode:// links in rendered content to show in file viewer
(function() {
    document.addEventListener('click', function(e) {
        var link = e.target.closest('a[href^="vscode://file/"]');
        if (!link) return;
        // Don't intercept the file viewer's own VS Code link (let it open VS Code)
        if (link.id === 'fv-vscode') return;
        e.preventDefault();
        var href = link.getAttribute('href');
        var match = href.match(/^vscode:\/\/file\/(.+?)(?::(\d+))?(?::(\d+))?$/);
        if (match) {
            var filePath = match[1];
            var lineNum = match[2] ? parseInt(match[2], 10) : 1;
            showSource(filePath, lineNum);
        }
    });
})();
