// ── Additional WHERE Tabs ────────────────────────────────────────────
// Two kinds of tab:
//   • clause  — one fixed WHERE ({name, clause})
//   • dynamic — auto-generate one tab per distinct value of a field ({field}),
//               resolved live on the generated list page.

function renderWhereTabs() {
    const list = document.getElementById('whereTabsList');
    list.innerHTML = '';
    if (whereTabs.length === 0) { list.innerHTML = '<div class="text-muted small py-2">No additional WHERE tabs defined.</div>'; return; }
    const allNote = document.getElementById('whereTabsAllNote');
    if (allNote) allNote.textContent = whereTabsShowAll ? 'The list also shows an “All” tab.' : 'The “All” tab is hidden — only the tabs above show.';
    whereTabs.forEach((tab, index) => {
        const div = document.createElement('div');
        div.className = 'list-group-item d-flex justify-content-between align-items-center py-1 px-2';
        const countBadge = tab.showCount ? ' <span class="badge bg-secondary">count</span>' : '';
        let label;
        if (tab.type === 'dynamic') {
            label = `<span><span class="badge bg-info me-1">auto</span><strong>${qEsc(tab.field)}</strong> <span class="text-muted small">→ one tab per distinct value</span>${countBadge}</span>`;
        } else {
            label = `<span>${qEsc(tab.name)} <code class="text-muted small">${qEsc(tab.clause)}</code>${countBadge}</span>`;
        }
        div.innerHTML = `
            ${label}
            <div><button class="btn btn-sm btn-outline-secondary edit-where-btn" data-index="${index}" title="Edit"><i class="bi bi-pencil"></i></button>
            <button class="btn btn-sm btn-outline-danger delete-where-btn" data-index="${index}" title="Delete"><i class="bi bi-trash"></i></button></div>
        `;
        list.appendChild(div);
    });
    list.querySelectorAll('.edit-where-btn').forEach(btn => { btn.addEventListener('click', () => openWhereTabModal(parseInt(btn.dataset.index))); });
    list.querySelectorAll('.delete-where-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const idx = parseInt(btn.dataset.index);
            whereTabs.splice(idx, 1);
            renderWhereTabs();
            if (typeof autoSaveCurrentQueryState === 'function') autoSaveCurrentQueryState();
        });
    });
}

function toggleWhereTabMode() {
    const type = document.getElementById('whereTabType').value;
    document.getElementById('whereTabClauseMode').classList.toggle('d-none', type === 'dynamic');
    document.getElementById('whereTabDynamicMode').classList.toggle('d-none', type !== 'dynamic');
    document.getElementById('whereTabPreview').innerHTML = '';
}

// Fill the field dropdown from the active table's columns.
async function populateWhereTabFields(selected) {
    const sel = document.getElementById('whereTabField');
    if (!sel) return;
    if (!currentTableName) { sel.innerHTML = '<option value="">(drop a table into the designer first)</option>'; return; }
    const cols = await getTableDetails(currentTableName);
    const opts = (cols || []).map(c => {
        const n = c.name || c.COLUMN_NAME || '';
        return `<option value="${n}"${n === selected ? ' selected' : ''}>${n}</option>`;
    }).join('');
    sel.innerHTML = opts || '<option value="">(no fields)</option>';
}

function openWhereTabModal(index = -1) {
    document.getElementById('whereTabEditIndex').value = index;
    const typeSel = document.getElementById('whereTabType');
    // Wire the type switch + field-list lazy load once.
    if (!typeSel._wired) {
        typeSel._wired = 1;
        typeSel.addEventListener('change', () => {
            toggleWhereTabMode();
            if (typeSel.value === 'dynamic') populateWhereTabFields();
        });
    }

    const tab = index >= 0 ? whereTabs[index] : null;
    const isDynamic = !!(tab && tab.type === 'dynamic');
    document.getElementById('whereTabModalTitle').textContent = index >= 0 ? 'Edit WHERE Tab' : 'Add WHERE Tab';
    typeSel.value = isDynamic ? 'dynamic' : 'clause';
    document.getElementById('whereTabName').value = tab && !isDynamic ? (tab.name || '') : '';
    document.getElementById('whereTabClause').value = tab && !isDynamic ? (tab.clause || '') : '';
    document.getElementById('whereTabShowCount').checked = tab ? !!tab.showCount : false;
    document.getElementById('whereTabHideEmpty').checked = tab ? !!tab.hideEmpty : false;
    document.getElementById('whereTabShowAll').checked = whereTabsShowAll;
    document.getElementById('whereTabPreview').innerHTML = '';
    toggleWhereTabMode();
    if (isDynamic || typeSel.value === 'dynamic') populateWhereTabFields(tab ? tab.field : '');

    new bootstrap.Modal(document.getElementById('whereTabModal')).show();
}

function saveWhereTab() {
    const type = document.getElementById('whereTabType').value;
    const showCount = document.getElementById('whereTabShowCount').checked;
    const hideEmpty = document.getElementById('whereTabHideEmpty').checked;
    whereTabsShowAll = document.getElementById('whereTabShowAll').checked;  // shared tab-bar setting
    let newTab;
    if (type === 'dynamic') {
        const field = document.getElementById('whereTabField').value;
        if (!field) { Swal.fire('Error', 'Choose a field to generate tabs from.', 'warning'); return; }
        newTab = { type: 'dynamic', field, showCount, hideEmpty };
    } else {
        const name = document.getElementById('whereTabName').value.trim();
        const clause = document.getElementById('whereTabClause').value.trim();
        if (!name || !clause) { Swal.fire('Error', 'Name and clause are required.', 'warning'); return; }
        newTab = { type: 'clause', name, clause, showCount, hideEmpty };
    }
    const index = parseInt(document.getElementById('whereTabEditIndex').value);
    if (index >= 0) { whereTabs[index] = newTab; } else { whereTabs.push(newTab); }
    renderWhereTabs();
    bootstrap.Modal.getInstance(document.getElementById('whereTabModal')).hide();
    if (typeof autoSaveCurrentQueryState === 'function') autoSaveCurrentQueryState();
}

async function previewWhere() {
    const type = document.getElementById('whereTabType').value;
    const previewDiv = document.getElementById('whereTabPreview');
    previewDiv.innerHTML = '<div class="text-center py-2"><div class="spinner-border spinner-border-sm"></div></div>';

    if (type === 'dynamic') {
        const field = document.getElementById('whereTabField').value;
        if (!field) { previewDiv.innerHTML = ''; Swal.fire('Error', 'Choose a field first.', 'warning'); return; }
        try {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/query/field-values`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ table: currentTableName, field })
            });
            const data = await res.json();
            if (!data.success) { previewDiv.innerHTML = `<div class="alert alert-danger small py-1">${qEsc(data.message)}</div>`; return; }
            const chips = data.values.map(v => `<span class="badge bg-secondary me-1 mb-1">${qEsc(v)}</span>`).join('');
            const more = data.capped ? ' <span class="text-muted small">(showing first 60)</span>' : '';
            previewDiv.innerHTML = `<div class="small mb-1"><span class="badge bg-info">${data.count} tab(s)</span> will be generated${more}:</div><div>${chips || '<span class="text-muted small">no values</span>'}</div>`;
        } catch (err) { previewDiv.innerHTML = '<div class="alert alert-danger small py-1">Preview failed.</div>'; }
        return;
    }

    const clause = document.getElementById('whereTabClause').value.trim();
    if (!clause) { previewDiv.innerHTML = ''; Swal.fire('Error', 'Enter a WHERE clause.', 'warning'); return; }
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/query/preview-where`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clause, baseSql: currentSql })
        });
        const data = await res.json();
        if (data.success) previewDiv.innerHTML = `<span class="badge bg-info">${data.count} row(s)</span>`;
        else previewDiv.innerHTML = `<div class="alert alert-danger small py-1">${qEsc(data.message)}</div>`;
    } catch (err) { previewDiv.innerHTML = '<div class="alert alert-danger small py-1">Preview failed.</div>'; }
}


window.renderWhereTabs = renderWhereTabs;
window.openWhereTabModal = openWhereTabModal;
window.saveWhereTab = saveWhereTab;
window.previewWhere = previewWhere;
