// Chat Main - AI Chat frontend
// Manages chat history in localStorage and renders messages

const STORAGE_KEY = 'chat_history';
const MAX_STORED_MESSAGES = 100;

let chatMessages = [];
let isWaiting = false;

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

function loadHistory() {
    try {
        const stored = localStorage.getItem(STORAGE_KEY);
        if (stored) {
            chatMessages = JSON.parse(stored);
            if (!Array.isArray(chatMessages)) chatMessages = [];
        }
    } catch (e) {
        console.warn('Failed to load chat history:', e);
        chatMessages = [];
    }
}

function saveHistory() {
    // Keep only last MAX_STORED_MESSAGES
    if (chatMessages.length > MAX_STORED_MESSAGES) {
        chatMessages = chatMessages.slice(-MAX_STORED_MESSAGES);
    }
    try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(chatMessages));
    } catch (e) {
        console.warn('Failed to save chat history:', e);
    }
}

function clearHistory() {
    chatMessages = [];
    localStorage.removeItem(STORAGE_KEY);
    renderMessages();
}

function renderMessages() {
    const container = document.getElementById('chatMessages');
    const welcome = document.getElementById('chatWelcome');

    if (chatMessages.length === 0) {
        welcome.style.display = 'block';
        container.innerHTML = '';
        return;
    }

    welcome.style.display = 'none';
    let html = '';

    for (const msg of chatMessages) {
        if (msg.role === 'user') {
            html += `<div class="chat-msg chat-msg-user">
                <div class="chat-bubble chat-bubble-user">${escapeHtml(msg.content)}</div>
            </div>`;
        } else if (msg.role === 'assistant') {
            html += renderAssistantMessage(msg);
        }
    }

    container.innerHTML = html;
    container.scrollTop = container.scrollHeight;
}

function renderAssistantMessage(msg) {
    let html = `<div class="chat-msg chat-msg-assistant"><div class="chat-bubble chat-bubble-assistant">`;

    // Error display
    if (msg.error) {
        html += `<div class="chat-error">${escapeHtml(msg.error)}</div>`;
    }

    // AI response text
    if (msg.content) {
        html += `<div class="chat-text">${formatResponseText(msg.content)}</div>`;
    }

    // SQL block (collapsible)
    if (msg.sql) {
        html += `<details class="chat-details">
            <summary>Show SQL</summary>
            <pre class="chat-sql">${escapeHtml(msg.sql)}</pre>
        </details>`;
    }

    // Results table (collapsible)
    if (msg.columns && msg.columns.length > 0 && msg.row_count > 0) {
        const displayRows = msg.results ? msg.results.slice(0, 50) : [];
        html += `<details class="chat-details">
            <summary>Show data (${msg.row_count} row${msg.row_count !== 1 ? 's' : ''})</summary>
            <div class="chat-table-wrap">
                <table class="chat-table">
                    <thead><tr>${msg.columns.map(c => `<th>${escapeHtml(c)}</th>`).join('')}</tr></thead>
                    <tbody>`;
        for (const row of displayRows) {
            html += '<tr>' + row.map(cell => `<td>${escapeHtml(cell)}</td>`).join('') + '</tr>';
        }
        html += `</tbody></table>`;
        if (msg.row_count > 50) {
            html += `<div class="chat-table-note">(showing first 50 of ${msg.row_count} rows)</div>`;
        }
        html += `</div></details>`;
    }

    html += `</div></div>`;
    return html;
}

function formatResponseText(text) {
    // Simple markdown-like formatting: **bold**, `code`, newlines
    let escaped = escapeHtml(text);
    // Bold
    escaped = escaped.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
    // Inline code
    escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
    // Newlines
    escaped = escaped.replace(/\n/g, '<br>');
    return escaped;
}

function showThinking() {
    const container = document.getElementById('chatMessages');
    const indicator = document.createElement('div');
    indicator.id = 'thinkingIndicator';
    indicator.className = 'chat-msg chat-msg-assistant';
    indicator.innerHTML = `<div class="chat-bubble chat-bubble-assistant chat-thinking">Thinking<span class="thinking-dots"></span></div>`;
    container.appendChild(indicator);
    container.scrollTop = container.scrollHeight;
}

function hideThinking() {
    const indicator = document.getElementById('thinkingIndicator');
    if (indicator) indicator.remove();
}

async function sendMessage(text) {
    if (!text || !text.trim() || isWaiting) return;

    const content = text.trim();
    chatMessages.push({ role: 'user', content });
    saveHistory();
    renderMessages();

    // Clear input
    const input = document.getElementById('chatInput');
    input.value = '';
    input.focus();

    isWaiting = true;
    document.getElementById('chatSendBtn').disabled = true;
    showThinking();

    try {
        // Build messages array for API (only role + content for user/assistant)
        const apiMessages = chatMessages
            .filter(m => m.role === 'user' || m.role === 'assistant')
            .map(m => ({ role: m.role, content: m.content }));

        const res = await fetch('/api/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ messages: apiMessages })
        });

        const data = await res.json();

        const assistantMsg = {
            role: 'assistant',
            content: data.response || '',
            sql: data.sql || '',
            columns: data.columns || [],
            results: data.results || [],
            row_count: data.row_count || 0,
            error: data.error || ''
        };

        chatMessages.push(assistantMsg);
        saveHistory();
    } catch (e) {
        chatMessages.push({
            role: 'assistant',
            content: '',
            error: 'Network error: ' + e.message,
            sql: '', columns: [], results: [], row_count: 0
        });
        saveHistory();
    } finally {
        isWaiting = false;
        document.getElementById('chatSendBtn').disabled = false;
        hideThinking();
        renderMessages();
    }
}

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

function initChat() {
    loadHistory();
    renderMessages();

    const input = document.getElementById('chatInput');
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage(input.value);
        }
    });

    document.getElementById('chatSendBtn').addEventListener('click', () => {
        sendMessage(input.value);
    });

    document.getElementById('chatClearBtn').addEventListener('click', () => {
        clearHistory();
    });
}
