/* ============================================
   PERSISTENCE
   ============================================ */
let _saveTimer;
function autoSave() {
    clearTimeout(_saveTimer);
    _saveTimer = setTimeout(function() {
        data.metadata.lastModified = new Date().toISOString();
        localStorage.setItem(APP_KEY, JSON.stringify(data));
    }, 500);
}

function saveToLocalStorage() {
    autoSave();
    showNotification('Modifications sauvegardées');
}

function resetToEmbedded() {
    if (!confirm('Réinitialiser toutes les données depuis la version d\'origine ? Vos modifications locales (commentaires, notes) seront perdues.')) return;
    localStorage.removeItem(APP_KEY);
    // Restore data from ORIGINAL_DATA
    Object.keys(data).forEach(k => delete data[k]);
    Object.assign(data, JSON.parse(JSON.stringify(ORIGINAL_DATA)));
    // Re-render everything
    initEditableFields();
    renderStakeholders();
    renderScope();
    renderCriteria();
    renderModules();
    renderDependencies();
    renderAllModuleSpecs();
    renderConsolidation();
    renderHandoff();
    renderE2EFlows();
    updateCounts();
    renderReviewPanel();
    showNotification('Données réinitialisées depuis la version d\'origine');
}

function loadFromLocalStorage() {
    const saved = localStorage.getItem(APP_KEY);
    if (!saved) return;

    try {
        const parsed = JSON.parse(saved);

        // Build fingerprint of embedded structural data to detect HTML regeneration
        const embeddedFingerprint = ORIGINAL_DATA.modules.map(m => m.code).sort().join(',')
            + '|' + (ORIGINAL_DATA.metadata?.createdAt || '')
            + '|' + ORIGINAL_DATA.modules.length;
        const cachedFingerprint = parsed._structureFingerprint || '';

        const structureChanged = embeddedFingerprint !== cachedFingerprint;
        const embeddedModuleCount = ORIGINAL_DATA.modules?.length || 0;
        const cachedModuleCount = (parsed.modules || []).length;
        const hasNewModules = embeddedModuleCount > cachedModuleCount;
        const embeddedModuleCodes = new Set(ORIGINAL_DATA.modules.map(m => m.code));
        const cachedModuleCodes = new Set((parsed.modules || []).map(m => m.code));
        const missingModules = [...embeddedModuleCodes].filter(c => !cachedModuleCodes.has(c));

        if (structureChanged || hasNewModules || missingModules.length > 0) {
            // HTML was regenerated or has new modules — keep embedded structural data
            // Only restore user-specific edits (comments, custom roles, notes)
            data.wireframeComments = parsed.wireframeComments || {};
            data.specComments = parsed.specComments || {};
            data.customRoles = parsed.customRoles || [];
            data.customActions = parsed.customActions || [];
            data.comments = parsed.comments || [];

            // Merge user-added notes per module (preserve existing module notes)
            for (const code of Object.keys(parsed.moduleSpecs || {})) {
                if (data.moduleSpecs[code] && parsed.moduleSpecs[code]?.notes) {
                    data.moduleSpecs[code].notes = parsed.moduleSpecs[code].notes;
                }
            }

            // Save fresh embedded data with fingerprint
            data._structureFingerprint = embeddedFingerprint;
            autoSave();
        } else {
            // Cache matches current structure — safe to restore user edits on cadrage/notes
            // IMPORTANT: Always keep embedded modules and moduleSpecs as structural source of truth
            // Only merge cadrage user-editable fields and notes
            if (parsed.cadrage) {
                // Merge cadrage context (user may have edited text fields)
                if (parsed.cadrage.context) {
                    data.cadrage.context = { ...data.cadrage.context, ...parsed.cadrage.context };
                }
                // Merge scope only if user added items interactively
                if (parsed.cadrage.scope) {
                    data.cadrage.scope = { ...data.cadrage.scope, ...parsed.cadrage.scope };
                }
                // Merge stakeholders if user edited them
                if (parsed.cadrage.stakeholders) data.cadrage.stakeholders = parsed.cadrage.stakeholders;
            }
            data.dependencies = parsed.dependencies || data.dependencies;
            data.consolidation = { ...data.consolidation, ...(parsed.consolidation || {}) };

            // Merge moduleSpecs: keep embedded structure, overlay user-editable fields (notes, custom permissions)
            for (const code of Object.keys(data.moduleSpecs)) {
                const cached = parsed.moduleSpecs?.[code];
                if (cached) {
                    // Preserve user notes
                    if (cached.notes) data.moduleSpecs[code].notes = cached.notes;
                    // Preserve user-added use cases/rules/entities (merged with embedded)
                    // Only add items that don't exist in embedded (by name match)
                    const embeddedUcNames = new Set((data.moduleSpecs[code].useCases || []).map(uc => uc.name));
                    (cached.useCases || []).forEach(uc => {
                        if (!embeddedUcNames.has(uc.name)) data.moduleSpecs[code].useCases.push(uc);
                    });
                    const embeddedBrNames = new Set((data.moduleSpecs[code].businessRules || []).map(br => br.name));
                    (cached.businessRules || []).forEach(br => {
                        if (!embeddedBrNames.has(br.name)) data.moduleSpecs[code].businessRules.push(br);
                    });
                    // Preserve user permissions edits
                    if (cached.permissions) data.moduleSpecs[code].permissions = cached.permissions;
                }
            }

            data.wireframeComments = parsed.wireframeComments || {};
            data.specComments = parsed.specComments || {};
            data.customRoles = parsed.customRoles || [];
            data.customActions = parsed.customActions || [];
            data.comments = parsed.comments || [];

            // Update fingerprint
            data._structureFingerprint = embeddedFingerprint;
            autoSave();
        }

        // Restore editable fields
        document.querySelectorAll('.editable[data-field]').forEach(el => {
            const value = getNestedValue(data, 'cadrage.' + el.dataset.field);
            if (value) el.textContent = value;
        });
    } catch (e) { console.error('Error loading saved data:', e); }
}
