let currentCollection = null;

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    loadStats();
    loadCollections();
    setupTabs();
    setupEventListeners();
});

// Setup tabs
function setupTabs() {
    document.querySelectorAll('.tab').forEach(tab => {
        tab.addEventListener('click', () => {
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            tab.classList.add('active');
            document.getElementById(`tab-${tab.dataset.tab}`).classList.add('active');
        });
    });
}

// Load DB stats
async function loadStats() {
    const res = await fetch('/api/stats');
    const stats = await res.json();
    document.getElementById('db-stats').innerHTML = `
        Collections: ${stats.collection_count} | Documents: ${stats.total_documents}
    `;
}

// Load collections
async function loadCollections() {
    const res = await fetch('/api/collections');
    const collections = await res.json();
    const list = document.getElementById('collections-list');
    list.innerHTML = collections.map(c => `
        <div class="collection-item" onclick="selectCollection('${c.name}')">
            ${c.name} (${c.document_count})
        </div>
    `).join('');
}

// Select collection
async function selectCollection(name) {
    currentCollection = name;
    document.querySelectorAll('.collection-item').forEach(i => i.classList.remove('active'));
    event.target.classList.add('active');
    document.getElementById('current-collection').textContent = name;
    loadDocuments();
}

// Load documents
async function loadDocuments() {
    if (!currentCollection) return;
    const res = await fetch(`/api/collections/${currentCollection}/docs?limit=20`);
    const data = await res.json();
    const container = document.getElementById('documents-container');
    container.innerHTML = data.documents.map(doc => `
        <div class="document">
            <pre>${JSON.stringify(doc, null, 2)}</pre>
        </div>
    `).join('');
}

// Setup event listeners
function setupEventListeners() {
    document.getElementById('run-query')?.addEventListener('click', runQuery);
    document.getElementById('get-suggestions')?.addEventListener('click', getSuggestions);
}

// Run query
async function runQuery() {
    if (!currentCollection) return alert('Select a collection first');
    const query = document.getElementById('query-input').value;
    const res = await fetch(`/api/collections/${currentCollection}/query`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ query: query ? JSON.parse(query) : {} })
    });
    const data = await res.json();
    document.getElementById('query-results').innerHTML = data.documents.map(doc => `
        <div class="document"><pre>${JSON.stringify(doc, null, 2)}</pre></div>
    `).join('');
}

// Get index suggestions
async function getSuggestions() {
    if (!currentCollection) return alert('Select a collection first');
    const res = await fetch(`/api/collections/${currentCollection}/suggestions`);
    const suggestions = await res.json();
    document.getElementById('suggestions-list').innerHTML = suggestions.map(s => `
        <div class="suggestion-item">
            <strong>${s.fields.join(', ')}</strong><br>
            ${s.reason}<br>
            Speedup: ${s.estimated_speedup}
        </div>
    `).join('') || 'No suggestions';
}
