// ── Save via API ─────────────────────────────────────────────────────
async function saveSection(section, data) {
    markSaving();
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/output/save`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ section, data })
        });
        const json = await res.json();
        if (json.success) {
            markSaved();
        } else {
            markDirty();
            Swal.fire('Error', json.message || 'Save failed.', 'error');
        }
        return json;
    } catch (err) {
        markDirty();
        Swal.fire('Error', 'Network error during save.', 'error');
        return { success: false };
    }
}

async function saveAll() {
    return await saveSection('all', readConfig());
}

// ── Auto-save debounce (per tab section) ─────────────────────────────
let autoSaveTimers = {};

function scheduleAutoSave(section) {
    if (isPageUnloading) return;
    markDirty();
    if (autoSaveTimers[section]) clearTimeout(autoSaveTimers[section]);
    autoSaveTimers[section] = setTimeout(async () => {
        const cfg = readConfig();
        await saveSection(section, cfg[section]);
    }, 700);
}

// ── Central Save button (projectSave event) ─────────────────────────
document.addEventListener('projectSave', (e) => {
    if (e.detail.module !== 'output') return;
    e.detail.payload = readConfig();
});

// ── Save on page hide (beacon) ──────────────────────────────────────
window.addEventListener('pagehide', () => {
    if (isPageUnloading) {
        const cfg = readConfig();
        const blob = new Blob([JSON.stringify({ section: 'all', data: cfg })], { type: 'application/json' });
        navigator.sendBeacon(`${baseUrl}/project/${projectSlug}/output/save`, blob);
    }
});

// ── Expose for manual triggers ──────────────────────────────────────
window.saveAll = saveAll;
window.saveSection = saveSection;
