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

function autoSaveCurrentState() {
    if (isPageUnloading) return;
    if (autoSaveTimer) clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => {
        saveCurrentConfig();
    }, 600);
}

function saveCurrentConfig() {
    if (!currentTableName || isPageUnloading) return;

    const deviceFields = {};
    document.querySelectorAll('.field-check').forEach(cb => {
        const field = cb.dataset.field;
        const page = cb.dataset.page;
        if (!deviceFields[field]) deviceFields[field] = { ...defaultFieldDefaults };
        deviceFields[field][page] = cb.checked;
    });

    if (!currentConfig) currentConfig = { activeDevice: 'desktop', devices: {}, searchSettings: {} };
    if (!currentConfig.devices) currentConfig.devices = {};
    if (!currentConfig.searchSettings || Array.isArray(currentConfig.searchSettings)) currentConfig.searchSettings = Object.assign({}, currentConfig.searchSettings);
    currentConfig.activeDevice = currentDevice;
    currentConfig.devices[currentDevice] = deviceFields;

    if (!fieldsConfig) window.fieldsConfig = {};
    fieldsConfig[currentTableName] = currentConfig;
    allFieldsStates[currentTableName] = currentConfig;

    fetch(`${baseUrl}/project/${projectSlug}/fields/save`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            tableName: currentTableName,
            device: currentDevice,
            fields: deviceFields,
            searchSettings: currentConfig.searchSettings || {}
        })
    }).catch(() => { });
}

// Save on page hide (navigation, refresh)
window.addEventListener('pagehide', () => {
    isPageUnloading = true;
    if (!currentTableName) return;
    const deviceFields = {};
    document.querySelectorAll('.field-check').forEach(cb => {
        const field = cb.dataset.field, page = cb.dataset.page;
        if (!deviceFields[field]) deviceFields[field] = { ...defaultFieldDefaults };
        deviceFields[field][page] = cb.checked;
    });
    if (!currentConfig) currentConfig = { activeDevice: 'desktop', devices: {}, searchSettings: {} };
    if (!currentConfig.searchSettings || Array.isArray(currentConfig.searchSettings)) currentConfig.searchSettings = Object.assign({}, currentConfig.searchSettings);
    currentConfig.activeDevice = currentDevice;
    currentConfig.devices[currentDevice] = deviceFields;
    const payload = {
        tableName: currentTableName,
        device: currentDevice,
        fields: deviceFields,
        searchSettings: currentConfig.searchSettings || {}
    };
    navigator.sendBeacon(`${baseUrl}/project/${projectSlug}/fields/save`, JSON.stringify(payload));
});
window.addEventListener('beforeunload', () => { isPageUnloading = true; });

// Central Save button (projectSave)
document.addEventListener('projectSave', (e) => {
    if (e.detail.module !== 'fields') return;
    const deviceFields = {};
    document.querySelectorAll('.field-check').forEach(cb => {
        const field = cb.dataset.field, page = cb.dataset.page;
        if (!deviceFields[field]) deviceFields[field] = { ...defaultFieldDefaults };
        deviceFields[field][page] = cb.checked;
    });
    let ss = currentConfig?.searchSettings || {};
    if (Array.isArray(ss)) ss = Object.assign({}, ss);
    const config = {
        activeDevice: currentDevice,
        devices: { [currentDevice]: deviceFields },
        searchSettings: ss
    };
    e.detail.payload = {
        byTable: { [currentTableName]: config },
        activeTable: currentTableName
    };
});

window.autoSaveCurrentState = autoSaveCurrentState;
window.saveCurrentConfig = saveCurrentConfig;