// "Create project" page: autosaves typed fields to the ProjectDraft via
// /api/draft/ (debounced, no explicit Save Draft button). File uploads are
// handled by the shared uploads.js engine (per-file XHR to /api/uploads/).
(function () {
    const form = document.getElementById('project-form');
    if (!form) return;

    const pending = JSON.parse(
        (document.getElementById('packs-draft-uploads') || { textContent: '[]' }).textContent
    );

    const draftUuidEl = document.getElementById('packs-draft-uuid');
    let draftUuid = '';
    if (draftUuidEl) {
        try { draftUuid = JSON.parse(draftUuidEl.textContent || '""'); }
        catch (e) { draftUuid = draftUuidEl.textContent; }
    }

    const autosaveStatus = document.getElementById('autosave-status');
    const csrf = getCookie('csrftoken');
    const csrfHeader = csrf ? { 'X-CSRFToken': csrf } : {};
    const FIELDS = ['title', 'summary', 'category', 'description', 'version_name', 'changelog'];

    function setStatus(text, state) {
        autosaveStatus.innerHTML = text;
        autosaveStatus.className = 'autosave-status ' + (state || '');
    }

    let saveTimer = null;

    function scheduleSave() {
        setStatus('<i class="fas fa-circle-notch fa-spin"></i> Saving…', 'saving');
        clearTimeout(saveTimer);
        saveTimer = setTimeout(saveDraft, 600);
    }

    function saveDraft() {
        const data = {};
        FIELDS.forEach((name) => {
            const el = document.getElementById('id_' + name);
            if (el) data[name] = el.value;
        });
        const tags = document.getElementById('id_tags');
        if (tags) data.tags = tags.value;

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/draft/');
        xhr.setRequestHeader('Content-Type', 'application/json');
        for (const k in csrfHeader) xhr.setRequestHeader(k, csrfHeader[k]);
        xhr.onload = function () {
            if (xhr.status === 200) {
                setStatus('<i class="fas fa-check"></i> Saved just now', 'saved');
            } else {
                setStatus('<i class="fas fa-exclamation-triangle"></i> Save failed', 'error');
            }
        };
        xhr.onerror = function () {
            setStatus('<i class="fas fa-exclamation-triangle"></i> Save failed', 'error');
        };
        xhr.send(JSON.stringify({ draft: draftUuid, data }));
    }

    function initAutosave() {
        FIELDS.forEach((name) => {
            const el = document.getElementById('id_' + name);
            if (el) {
                el.addEventListener('input', scheduleSave);
                if (el.tagName === 'SELECT') el.addEventListener('change', scheduleSave);
            }
        });
        document.addEventListener('tags-changed', scheduleSave);

        setStatus('<i class="fas fa-cloud-upload-alt"></i> Autosave on', 'idle');
        setTimeout(() => setStatus('<i class="fas fa-check"></i> Saved just now', 'saved'), 2000);
    }

    PacksUploads.init({ pending: pending, draftUuid: draftUuid, onReady: initAutosave });

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
})();
