// ── Save & Auto‑save (with debounce) ─────────────────────────────────
let autoSaveTimer = null;

function autoSaveTablesState() {
    if (window.isPageUnloading) return;
    if (autoSaveTimer) clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => {
        saveTablesState();  // uses your existing /tables/save-state endpoint
    }, 600);
}

async function saveTablesState() {
    if (window.isPageUnloading) return false;
    const cards = document.querySelectorAll('.table-card');
    const positions = Array.from(cards).map(c => ({
        table: c.dataset.table,
        left: parseInt(c.style.left),
        top: parseInt(c.style.top)
    }));
    const payload = {
        selectedTables: Array.from(window.selectedTablesSet),
        positions: positions,
        expandedTables: Array.from(window.expandedTablesSet || []),
        tableListFilter: document.getElementById('tableFilter')?.value || '',
        tableListSort: window.tableListSort || 'name_asc'
    };
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/tables/save-state`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        const data = await res.json();
        return data.success === true;
    } catch (err) {
        return false;
    }
}

// Page hide / beforeunload (already present)
window.addEventListener('pagehide', () => {
    window.isPageUnloading = true;
    if (window.selectedTablesSet.size === 0) return;
    const cards = document.querySelectorAll('.table-card');
    const positions = Array.from(cards).map(c => ({
        table: c.dataset.table,
        left: parseInt(c.style.left),
        top: parseInt(c.style.top)
    }));
    const payload = {
        selectedTables: Array.from(window.selectedTablesSet),
        positions,
        expandedTables: Array.from(window.expandedTablesSet || []),
        tableListFilter: document.getElementById('tableFilter')?.value || '',
        tableListSort: window.tableListSort || 'name_asc'
    };
    navigator.sendBeacon(`${baseUrl}/project/${projectSlug}/tables/save-state`, JSON.stringify(payload));
});
window.addEventListener('beforeunload', () => { window.isPageUnloading = true; });

// Central Save button (projectSave event)
document.addEventListener('projectSave', async (e) => {
    if (e.detail.module !== 'tables') return;
    await saveTablesState();
});

// Expose the auto‑save function for overriding
window.autoSaveTablesState = autoSaveTablesState;
window.saveTablesState = saveTablesState;
