// ── Core State & Helpers ──────────────────────────────────────────────
let selectedTables = [];
let joins = [];
let currentSql = '';
let tableFieldCache = {};
let tableFkCache = {};   // tableName → foreign_keys[] (for smart auto-joins)
let whereTabs = [];
let whereTabsShowAll = true;  // whether the generated list shows an "All" tab
let allQueryStates = {};  // stores query state for each table { tableName: {...} }


async function getTableDetails(tableName) {
    if (!tableFieldCache[tableName]) {
        try {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/tables/details/${tableName}`);
            const data = await res.json();
            tableFieldCache[tableName] = data.success ? data.columns : [];
            tableFkCache[tableName] = data.success ? (data.foreign_keys || []) : [];
        } catch (err) {
            console.error('Failed to fetch fields for', tableName, err);
            tableFieldCache[tableName] = [];
            tableFkCache[tableName] = [];
        }
    }
    return tableFieldCache[tableName];
}

function updateJoinTip() {
    const tip = document.getElementById('joinTip');
    if (tip) tip.classList.toggle('d-none', selectedTables.length <= 1);
}

// The Designer shows a SHORT field name but keeps the canonical `table.field`
// in data-qualified. Every reader of a designer row MUST use this so saved
// queries / auto-save / the central Save keep the fully-qualified identity.
function queryRowField(row) {
    const el = row.querySelector('.field-name');
    return el ? (el.dataset.qualified || el.value).trim() : '';
}

// Query-level options (DISTINCT + LIMIT) live in the designer toolbar.
function queryDistinct() { return !!document.getElementById('queryDistinct')?.checked; }
function queryLimit() { const v = parseInt(document.getElementById('queryLimit')?.value, 10); return Number.isFinite(v) && v > 0 ? v : 0; }

// Make critical helpers globally available
window.updateJoinTip = updateJoinTip;
window.getTableDetails = getTableDetails;
window.queryRowField = queryRowField;
window.queryDistinct = queryDistinct;
window.queryLimit = queryLimit;
