// ── Load / Save Query State ─────────────────────────────────────────
let autoSaveTimer = null;

function autoSaveCurrentQueryState() {
    if (!currentTableName) return;

    // Gather current state from DOM rows
    const fields = [];
    document.querySelectorAll('#designerRows tr').forEach(row => {
        const output = row.querySelector('.output-check').checked;
        const field = queryRowField(row);
        const alias = row.querySelector('.field-alias').value.trim();
        const sortType = row.querySelector('.sort-type').value;
        const sortOrder = row.querySelector('.sort-order').value;
        const groupBy = row.querySelector('.group-by').value;
        const criteria = row.querySelector('.criteria').value.trim();
        if (field && output) {
            fields.push({ output, field, alias, sortType, sortOrder, groupBy, criteria });
        }
    });
    const positions = [];
    document.querySelectorAll('.diagram-table-card').forEach(card => {
        positions.push({ table: card.dataset.table, left: parseInt(card.style.left), top: parseInt(card.style.top) });
    });
    const state = {
        fields,
        tables: selectedTables,
        joins,
        sql: document.getElementById('sqlEditor').value,
        whereTabs,
        whereTabsShowAll,
        distinct: queryDistinct(),
        limit: queryLimit(),
        positions
    };

    // Update global cache
    if (typeof allQueryStates === 'undefined') window.allQueryStates = {};
    allQueryStates[currentTableName] = state;

    // Debounce server save (300ms for faster feedback)
    if (autoSaveTimer) clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => {
        fetch(`${baseUrl}/project/${projectSlug}/query/save-state`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ tableName: currentTableName, state })
        }).catch(err => console.warn('Auto-save failed', err));
    }, 300);
}

window.autoSaveCurrentQueryState = autoSaveCurrentQueryState;

async function loadQueryState(query) {
    if (typeof updateDesignerFromSql === 'function') {
        await updateDesignerFromSql(query);
    } else {
        console.error('updateDesignerFromSql not available');
        return;
    }

    whereTabs = query.whereTabs || [];
    whereTabsShowAll = query.whereTabsShowAll !== false;  // default: show the All tab
    const dEl = document.getElementById('queryDistinct'); if (dEl) dEl.checked = !!query.distinct;
    const lEl = document.getElementById('queryLimit'); if (lEl) lEl.value = query.limit ? String(query.limit) : '';
    renderWhereTabs();

    allQueryStates[currentTableName] = {
        fields: query.fields || [],
        tables: query.tables || [],
        joins: query.joins || [],
        sql: query.sql || '',
        whereTabs: whereTabs,
        positions: query.positions || []
    };

    if (currentTableName && tablePresets) {
        tablePresets[currentTableName] = {
            fields: query.fields || [],
            tables: query.tables || [],
            joins: query.joins || [],
            sql: query.sql || '',
            whereTabs: whereTabs,
            positions: query.positions || []
        };
    }

    const editor = document.getElementById('sqlEditor');
    if (editor && (!editor.value || editor.value.trim() === '') && query.sql) {
        if (typeof setSqlEditorValue === 'function') setSqlEditorValue(query.sql);
        else editor.value = query.sql;
        currentSql = query.sql;
        if (typeof autoExecuteSql === 'function') autoExecuteSql();
    }
    const dropMsg = document.getElementById('diagramDropZone');
    if (dropMsg) dropMsg.style.display = 'none';
}

async function saveQueryAs() {
    const name = document.getElementById('querySaveName').value.trim() || 'Untitled';
    const fields = [];
    document.querySelectorAll('#designerRows tr').forEach(row => {
        const output = row.querySelector('.output-check').checked;
        const field = queryRowField(row);
        const alias = row.querySelector('.field-alias').value.trim();
        const sortType = row.querySelector('.sort-type').value;
        const sortOrder = row.querySelector('.sort-order').value;
        const groupBy = row.querySelector('.group-by').value;
        const criteria = row.querySelector('.criteria').value.trim();
        if (field && output) {
            fields.push({ output, field, alias, sortType, sortOrder, groupBy, criteria });
        }
    });
    const positions = [];
    document.querySelectorAll('.diagram-table-card').forEach(card => {
        positions.push({ table: card.dataset.table, left: parseInt(card.style.left), top: parseInt(card.style.top) });
    });
    const payload = { name, fields, tables: selectedTables, joins, sql: document.getElementById('sqlEditor').value, whereTabs, whereTabsShowAll, distinct: queryDistinct(), limit: queryLimit(), positions };
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/query/save`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
        });
        const data = await res.json();
        if (data.success) {
            Swal.fire('Saved', data.message, 'success');
            bootstrap.Modal.getInstance(document.getElementById('saveQueryModal')).hide();
            location.reload();
        } else { Swal.fire('Error', data.message, 'error'); }
    } catch (err) { Swal.fire('Error', 'Failed to save.', 'error'); }
}

// Create a real database VIEW from the current SQL.
async function saveAsView() {
    const sql = (document.getElementById('sqlEditor').value || '').trim();
    if (!sql) { Swal.fire('Nothing to save', 'Build or write a query first.', 'info'); return; }
    const { value: name } = await Swal.fire({
        title: 'Save as database View',
        input: 'text',
        inputLabel: 'View name (letters, numbers, underscore)',
        inputPlaceholder: 'e.g. active_customers_v',
        showCancelButton: true,
        confirmButtonText: 'Create View',
        inputValidator: (v) => (!v || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(v)) ? 'Use letters, numbers, and underscores; start with a letter.' : undefined
    });
    if (!name) return;
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/query/save-view`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, sql, replace: true })
        });
        const data = await res.json();
        if (data.success) Swal.fire('View created', data.message, 'success');
        else Swal.fire('Could not create view', data.message || 'Unknown error.', 'error');
    } catch (err) { Swal.fire('Error', 'Failed to create the view.', 'error'); }
}
window.saveAsView = saveAsView;

// Save on page hide
window.addEventListener('pagehide', () => {
    if (!currentTableName) return;
    const state = allQueryStates[currentTableName];
    if (state) {
        navigator.sendBeacon(
            `${baseUrl}/project/${projectSlug}/query/save-state`,
            JSON.stringify({ tableName: currentTableName, state })
        );
    }
});

window.loadQueryState = loadQueryState;
window.saveQueryAs = saveQueryAs;