/* ============================================
   EXPORT JSON
   ============================================ */
function collectEditableFields() {
    document.querySelectorAll('.editable[data-field]').forEach(el => {
        setNestedValue(data, 'cadrage.' + el.dataset.field, el.textContent.trim());
    });
    document.querySelectorAll('.editable[data-module-field]').forEach(el => {
        const code = el.dataset.moduleCode;
        const field = el.dataset.moduleField;
        if (data.moduleSpecs[code]) {
            data.moduleSpecs[code][field] = el.textContent.trim();
        }
    });
}

function buildModuleSpecsExport() {
    var result = {};
    data.modules.forEach(function(m) {
        var spec = data.moduleSpecs[m.code] || {};
        result[m.code] = {
            module: m,
            useCases: (spec.useCases || []).map(function(uc, i) {
                return Object.assign({ id: 'UC-' + String(i + 1).padStart(3, '0') }, uc);
            }),
            businessRules: (spec.businessRules || []).map(function(br, i) {
                return Object.assign({ id: 'BR-' + (br.category || 'GEN').toUpperCase().substring(0, 4) + '-' + String(i + 1).padStart(3, '0') }, br);
            }),
            entities: spec.entities || [],
            permissions: spec.permissions || [],
            notes: spec.notes || ''
        };
    });
    return result;
}

function exportJSON() {
    collectEditableFields();
    data.metadata.lastModified = new Date().toISOString();
    data.metadata.exportedAt = new Date().toISOString();

    const exportData = {
        metadata: data.metadata,
        cadrage: data.cadrage,
        modules: data.modules,
        dependencies: data.dependencies,
        moduleSpecifications: buildModuleSpecsExport(),
        consolidation: data.consolidation,
        artifacts: EMBEDDED_ARTIFACTS,
        wireframeComments: data.wireframeComments,
        specComments: data.specComments,
        customRoles: data.customRoles,
        customActions: data.customActions,
        comments: data.comments
    };

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = (data.metadata.applicationId || 'analyse') + '-export.json';
    a.click();
    URL.revokeObjectURL(url);
    showNotification('Export JSON téléchargé');
}

/* ============================================
   SAVE REVIEW JSON (corrections for new version)
   ============================================ */
function detectChanges(original, current) {
    const changes = { cadrage: false, modulesAdded: [], modulesRemoved: [], modulesModified: [], commentsCount: 0 };

    // Cadrage changes
    if (JSON.stringify(original.cadrage) !== JSON.stringify(current.cadrage)) {
        changes.cadrage = true;
    }

    // Module changes
    const origCodes = (original.modules || []).map(m => m.code);
    const currCodes = (current.modules || []).map(m => m.code);
    changes.modulesAdded = currCodes.filter(c => !origCodes.includes(c));
    changes.modulesRemoved = origCodes.filter(c => !currCodes.includes(c));
    currCodes.filter(c => origCodes.includes(c)).forEach(code => {
        const origSpec = JSON.stringify(original.moduleSpecs?.[code] || {});
        const currSpec = JSON.stringify(current.moduleSpecs?.[code] || {});
        if (origSpec !== currSpec) changes.modulesModified.push(code);
    });

    // Comments count
    changes.commentsCount = (current.comments || []).length;

    return changes;
}

function saveReviewJSON() {
    collectEditableFields();

    const changes = detectChanges(ORIGINAL_DATA, data);
    const hasChanges = changes.cadrage || changes.modulesAdded.length > 0
        || changes.modulesRemoved.length > 0 || changes.modulesModified.length > 0
        || changes.commentsCount > 0;

    const reviewData = {
        _reviewMeta: {
            sourceVersion: data.metadata.version || '1.0',
            sourceApplicationId: data.metadata.applicationId || '',
            exportedAt: new Date().toISOString(),
            hasChanges: hasChanges,
            changeSummary: {
                cadrageModified: changes.cadrage,
                modulesAdded: changes.modulesAdded,
                modulesRemoved: changes.modulesRemoved,
                modulesModified: changes.modulesModified,
                commentsCount: changes.commentsCount
            }
        },
        metadata: data.metadata,
        cadrage: data.cadrage,
        modules: data.modules,
        dependencies: data.dependencies,
        moduleSpecifications: buildModuleSpecsExport(),
        consolidation: data.consolidation,
        wireframeComments: data.wireframeComments,
        specComments: data.specComments,
        customRoles: data.customRoles,
        customActions: data.customActions,
        comments: data.comments
    };

    const blob = new Blob([JSON.stringify(reviewData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'ba-review.json';
    a.click();
    URL.revokeObjectURL(url);
    showNotification('ba-review.json téléchargé — sauvegardez-le à côté du HTML');
}
