// ═══ MERMAID INIT (light theme matching Canifa) ═══
mermaid.initialize({
    startOnLoad: false,
    theme: 'default',
    themeVariables: {
        primaryColor: '#eef1f8',
        primaryTextColor: '#1c1917',
        primaryBorderColor: '#3b5998',
        secondaryColor: '#f0efec',
        tertiaryColor: '#fef3c7',
        lineColor: '#78716c',
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: '13px',
    },
    flowchart: { useMaxWidth: true, htmlLabels: true, curve: 'basis' },
    sequence: { useMaxWidth: true, showSequenceNumbers: true },
});

const SESSION_ID = 'diagram_' + Date.now().toString(36);
let currentMermaidCode = '';
let currentZoom = 1;
let panX = 0, panY = 0;
let isDragging = false, dragStartX = 0, dragStartY = 0, panStartX = 0, panStartY = 0;

const canvas = document.getElementById('diagramCanvas');
const output = document.getElementById('diagramOutput');

// Show session badge
document.getElementById('sessionBadge').textContent = SESSION_ID.substring(0, 16);

// ═══ PAN & ZOOM ═══
function applyTransform() {
    output.style.transform = `translate(${panX}px, ${panY}px) scale(${currentZoom})`;
    document.getElementById('zoomLabel').textContent = Math.round(currentZoom * 100) + '%';
}

// Mouse wheel zoom
canvas.addEventListener('wheel', (e) => {
    e.preventDefault();
    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    const oldZoom = currentZoom;
    const delta = e.deltaY > 0 ? -0.1 : 0.1;
    currentZoom = Math.min(Math.max(currentZoom + delta, 0.1), 5);

    // Zoom towards mouse position
    const scale = currentZoom / oldZoom;
    panX = mouseX - scale * (mouseX - panX);
    panY = mouseY - scale * (mouseY - panY);

    applyTransform();
}, { passive: false });

// Click-drag pan
canvas.addEventListener('mousedown', (e) => {
    if (e.button !== 0) return;
    isDragging = true;
    dragStartX = e.clientX;
    dragStartY = e.clientY;
    panStartX = panX;
    panStartY = panY;
    canvas.classList.add('grabbing');
});

window.addEventListener('mousemove', (e) => {
    if (!isDragging) return;
    panX = panStartX + (e.clientX - dragStartX);
    panY = panStartY + (e.clientY - dragStartY);
    applyTransform();
});

window.addEventListener('mouseup', () => {
    isDragging = false;
    canvas.classList.remove('grabbing');
});

// ═══ SEND MESSAGE ═══
async function sendMessage() {
    const input = document.getElementById('chatInput');
    const query = input.value.trim();
    if (!query) return;

    input.value = '';
    input.style.height = 'auto';
    appendMessage('user', query);

    const typingEl = showTyping();
    const btn = document.getElementById('btnSend');
    btn.disabled = true;

    try {
        const resp = await fetch('/api/diagram/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query, session_id: SESSION_ID }),
        });

        const data = await resp.json();
        removeTyping(typingEl);

        if (data.status === 'success') {
            if (data.pipeline && data.pipeline.length > 0) {
                showPipeline(data.pipeline);
            }
            if (data.diagram && data.diagram.mermaid_code) {
                await renderDiagram(data.diagram.mermaid_code, data.diagram.title, data.diagram.diagram_type);
            }
            if (data.response) {
                appendMessage('ai', data.response);
            }
            document.getElementById('diagramTime').textContent = `⏱ ${data.elapsed_ms}ms · ${data.agent_path}`;
        } else {
            appendMessage('error', `❌ ${data.message || 'Unknown error'}`);
        }
    } catch (err) {
        removeTyping(typingEl);
        appendMessage('error', `❌ Lỗi kết nối: ${err.message}`);
    } finally {
        btn.disabled = false;
        input.focus();
    }
}

function sendQuick(text) {
    document.getElementById('chatInput').value = text;
    sendMessage();
}

// ═══ RENDER ═══
async function renderDiagram(code, title, type) {
    currentMermaidCode = code;
    document.getElementById('mermaidCode').textContent = code;

    if (title) {
        document.getElementById('diagramTitle').textContent = `📊 ${title}`;
    }
    document.getElementById('diagramType').textContent = `${type || 'diagram'} · ${code.split('\n').length} lines`;

    try {
        const { svg } = await mermaid.render('mermaid-svg-' + Date.now(), code);
        output.innerHTML = svg;
        // Auto-fit after render
        requestAnimationFrame(() => fitToView());
    } catch (err) {
        console.error('Mermaid render error:', err);
        output.innerHTML = `
            <div class="empty-state" style="position:relative">
                <div class="icon">⚠️</div>
                <h3>Lỗi render diagram</h3>
                <p style="color:#dc2626">${escHtml(err.message || String(err))}</p>
                <pre style="text-align:left;font-size:10px;color:var(--muted-fg);margin-top:8px;max-width:360px;overflow:auto;white-space:pre-wrap">${escHtml(code)}</pre>
            </div>`;
    }
}

// ═══ CHAT UI ═══
function appendMessage(role, content) {
    const c = document.getElementById('chatMessages');
    const div = document.createElement('div');
    div.className = `msg ${role}`;

    if (role === 'ai') {
        try { div.innerHTML = marked.parse(content); }
        catch { div.textContent = content; }
    } else {
        div.textContent = content;
    }

    c.appendChild(div);
    c.scrollTop = c.scrollHeight;
}

function showPipeline(steps) {
    const c = document.getElementById('chatMessages');
    const wrapper = document.createElement('div');
    wrapper.className = 'pipeline-trace';

    for (const step of steps) {
        if (step.step === 'user') continue;
        const div = document.createElement('div');
        div.className = `p-step s-${step.step}`;
        div.innerHTML = `<div class="step-label">${escHtml(step.label)}</div>
                         <div class="step-content">${escHtml((step.content || '').substring(0, 200))}</div>`;
        wrapper.appendChild(div);
    }

    c.appendChild(wrapper);
    c.scrollTop = c.scrollHeight;
}

function showTyping() {
    const c = document.getElementById('chatMessages');
    const div = document.createElement('div');
    div.className = 'thinking';
    div.innerHTML = '<span></span><span></span><span></span>';
    c.appendChild(div);
    c.scrollTop = c.scrollHeight;
    return div;
}

function removeTyping(el) { if (el && el.parentNode) el.remove(); }

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

// ═══ ACTIONS ═══
async function clearChat() {
    document.getElementById('chatMessages').innerHTML =
        '<div class="msg system">💬 Chat đã xoá. Bắt đầu lại nào!</div>';
    document.getElementById('diagramOutput').innerHTML = `
        <div class="empty-state"><div class="icon">📊</div><h3>Chưa có diagram</h3><p>Nhập yêu cầu ở panel trái.</p></div>`;
    document.getElementById('mermaidCode').textContent = '// Mermaid code sẽ hiện ở đây';
    document.getElementById('diagramType').textContent = 'Chưa có diagram';
    document.getElementById('diagramTime').textContent = '';
    currentMermaidCode = '';
    try { await fetch('/api/diagram/clear', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({session_id:SESSION_ID}) }); } catch {}
}

function toggleCode() { document.getElementById('codeViewer').classList.toggle('show'); }

// ═══ ZOOM CONTROLS ═══
function zoomIn() { currentZoom = Math.min(currentZoom + 0.15, 5); applyTransform(); }
function zoomOut() { currentZoom = Math.max(currentZoom - 0.15, 0.1); applyTransform(); }

function resetZoom() {
    currentZoom = 1; panX = 0; panY = 0;
    applyTransform();
}

function fitToView() {
    const svg = output.querySelector('svg');
    if (!svg) return;

    // Step 1: Reset to identity so getBoundingClientRect measures natural SVG size
    currentZoom = 1;
    panX = 0;
    panY = 0;
    output.style.transform = 'translate(0px, 0px) scale(1)';

    // Step 2: Force browser layout recalc, then measure natural dimensions
    const canvasRect = canvas.getBoundingClientRect();
    const svgRect = svg.getBoundingClientRect();
    const svgW = svgRect.width;
    const svgH = svgRect.height;
    if (!svgW || !svgH) return;

    // Step 3: Calculate scale to fit — NEVER zoom in beyond 100%
    const padding = 40;
    const scaleX = (canvasRect.width - padding) / svgW;
    const scaleY = (canvasRect.height - padding) / svgH;
    currentZoom = Math.min(scaleX, scaleY, 1);  // cap at 100%
    currentZoom = Math.max(currentZoom, 0.05);   // min 5%

    // Step 4: Center in canvas
    const fittedW = svgW * currentZoom;
    const fittedH = svgH * currentZoom;
    panX = Math.max(0, (canvasRect.width - fittedW) / 2);
    panY = Math.max(0, (canvasRect.height - fittedH) / 2);
    applyTransform();
}

// ═══ EXPORT PNG ═══
function exportDiagramPNG() {
    const svg = document.querySelector('#diagramOutput svg');
    if (!svg) { alert('Chưa có diagram để export!'); return; }
    const svgData = new XMLSerializer().serializeToString(svg);
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    img.onload = () => {
        canvas.width = img.width * 2; canvas.height = img.height * 2;
        ctx.scale(2, 2);
        ctx.fillStyle = '#faf9f7';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0);
        const a = document.createElement('a');
        a.download = 'diagram.png'; a.href = canvas.toDataURL('image/png'); a.click();
    };
    img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
}

// Auto-resize textarea
document.getElementById('chatInput').addEventListener('input', function() {
    this.style.height = 'auto';
    this.style.height = Math.min(this.scrollHeight, 100) + 'px';
});