// ── Sync Database ────────────────────────────────────────────────────
document.getElementById('btnSync')?.addEventListener('click', async () => {
    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(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/sync`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        const data = await res.json();
        if (data.success) {
            allTables = data.tables;
            savedTables = data.selectedTables;
            savedPositions = data.positions;
            savedExpandedTables = data.expandedTables || [];
            selectedTablesSet = new Set(savedTables);
            window.expandedTablesSet = new Set(savedExpandedTables);
            updateTableTypeMap(allTables);
            renderTableList(allTables);
            document.querySelectorAll('.table-check').forEach(cb => {
                if (selectedTablesSet.has(cb.value)) cb.checked = true;
            });
            renderSelectedCards();
            Swal.fire('Sync', data.message, 'success');
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (err) {
        console.error('Sync error:', err);
        Swal.fire('Error', 'Failed to sync.', 'error');
    }
});
