(function () {
    const form = document.getElementById('inspection-form');
    if (!form) { return; }

    const inspectionId = form.dataset.id;
    const url = form.dataset.autosaveUrl;
    const serverTs = parseInt(form.dataset.serverTs ? Date.parse(form.dataset.serverTs.replace(' ', 'T')) : 0, 10) || 0;
    const storageKey = 'sim_insp_' + inspectionId;
    const statusEl = document.getElementById('autosave-status');

    function setStatus(text, cls = '') {
        if (!statusEl) return;
        statusEl.textContent = text;
        statusEl.className = 'muted ' + cls;
    }

    function setByPath(obj, path, value) {
        const parts = path.split('.');
        let cur = obj;
        for (let i = 0; i < parts.length - 1; i++) {
            cur[parts[i]] = cur[parts[i]] || {};
            cur = cur[parts[i]];
        }
        cur[parts[parts.length - 1]] = value;
    }

    function getByPath(obj, path) {
        return path.split('.').reduce((a, k) => (a ? a[k] : undefined), obj);
    }

    function serialize() {
        const data = { header: {}, items: {}, observaciones: '' };
        form.querySelectorAll('[data-bind]').forEach((el) => {
            const path = el.dataset.bind;
            let value;
            if (el.type === 'checkbox') {
                value = el.checked ? 1 : 0;
            } else if (el.type === 'radio') {
                if (!el.checked) return;
                value = el.value;
            } else {
                value = el.value;
            }
            setByPath(data, path, value);
        });
        return data;
    }

    function hydrate(data) {
        if (!data) return;
        form.querySelectorAll('[data-bind]').forEach((el) => {
            const v = getByPath(data, el.dataset.bind);
            if (v === undefined || v === null) return;
            if (el.type === 'radio') {
                el.checked = String(el.value) === String(v);
            } else if (el.type === 'checkbox') {
                el.checked = !!Number(v);
            } else {
                el.value = v;
            }
        });
    }

    // Restore from localStorage if newer than server snapshot
    try {
        const raw = localStorage.getItem(storageKey);
        if (raw) {
            const parsed = JSON.parse(raw);
            if (parsed && parsed.ts && parsed.ts > serverTs) {
                hydrate(parsed.data);
                setStatus('Borrador local restaurado · ' + new Date(parsed.ts).toLocaleTimeString());
            }
        }
    } catch (e) {}

    let pending = false;
    let timer = null;
    let lastPayload = null;

    function csrfToken() {
        return document.querySelector('meta[name="csrf-token"]')?.content || '';
    }

    async function flush() {
        if (timer) { clearTimeout(timer); timer = null; }
        if (!lastPayload) return;
        const payload = lastPayload;
        lastPayload = null;
        try {
            const r = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': csrfToken(),
                },
                body: JSON.stringify(payload),
                credentials: 'same-origin',
            });
            if (r.ok) {
                try {
                    const j = await r.clone().json();
                    if (j && j.csrf_token) {
                        document.querySelector('meta[name="csrf-token"]').setAttribute('content', j.csrf_token);
                    }
                } catch (e) {}
            }
            if (r.ok) {
                setStatus('Guardado · ' + new Date().toLocaleTimeString(), 'ok');
            } else {
                setStatus('Solo guardado localmente · sin conexión', 'warn');
                lastPayload = payload;
            }
        } catch (e) {
            setStatus('Sin conexión · borrador local', 'warn');
            lastPayload = payload;
        }
    }

    function scheduleSave() {
        const data = serialize();
        const ts = Date.now();
        try {
            localStorage.setItem(storageKey, JSON.stringify({ ts, data }));
        } catch (e) {}
        lastPayload = data;
        setStatus('Guardando…');
        if (timer) clearTimeout(timer);
        timer = setTimeout(flush, 800);
    }

    form.addEventListener('input', scheduleSave);
    form.addEventListener('change', scheduleSave);

    // Flush on visibility hidden
    document.addEventListener('visibilitychange', () => { if (document.hidden) flush(); });
    window.addEventListener('beforeunload', flush);

    // Clear local draft when finalize redirects (status badge shows signed → already navigated)
    window.SimprofireAutosave = {
        flush: flush,
        clearDraft: () => { try { localStorage.removeItem(storageKey); } catch (e) {} },
    };
})();
