/* ============================================
   DATA STORE
   ============================================ */
const APP_KEY = 'ba-{{APPLICATION_ID}}';
let data = {{FEATURE_DATA}};
const ORIGINAL_DATA = JSON.parse(JSON.stringify(data));
const EMBEDDED_ARTIFACTS = {{EMBEDDED_ARTIFACTS}};

// Initialize applications array (multi-app support)
data.applications = data.applications || [];

// Initialize optional data structures
data.wireframeComments = data.wireframeComments || {};
data.specComments = data.specComments || {};
data.customRoles = data.customRoles || [];
data.customActions = data.customActions || [];
data.cadrage.criteria = data.cadrage.criteria || [];
data.cadrage.risks = data.cadrage.risks || [];
data.consolidation = data.consolidation || {};
data.consolidation.e2eFlows = data.consolidation.e2eFlows || [];

// Backward compat: merge old problem/current/vision into context
if (!data.cadrage.context) {
    data.cadrage.context = {
        problem: data.cadrage.problem?.description || data.cadrage.problem || '',
        trigger: data.cadrage.problem?.trigger || '',
        currentSituation: data.cadrage.current?.tools || '',
        desiredSituation: data.cadrage.vision?.changes || '',
        painPoints: data.cadrage.current?.painPoints || (data.cadrage.stakeholders || []).flatMap(s => (s.frustrations || '').split('\n').filter(Boolean)).join('\n'),
        acceptanceCriteria: data.cadrage.vision?.results || (data.cadrage.criteria || []).map(c => c.text).join('\n')
    };
}
data.cadrage.context = data.cadrage.context || { problem: '', trigger: '', currentSituation: '', desiredSituation: '', painPoints: '', acceptanceCriteria: '' };

// Initialize comments array
data.comments = data.comments || [];

// Defensive mapping: globalScope (JSON format) -> scope (HTML format)
// Handles cases where FEATURE_DATA contains raw globalScope instead of pre-mapped scope
if (!data.cadrage.scope || (!data.cadrage.scope.vital?.length && data.cadrage.globalScope)) {
    const gs = data.cadrage.globalScope || {};
    data.cadrage.scope = {
        vital: (gs.mustHave || []).map(s => typeof s === 'string' ? { name: s, description: '' } : s),
        important: (gs.shouldHave || []).map(s => typeof s === 'string' ? { name: s, description: '' } : s),
        optional: (gs.couldHave || []).map(s => typeof s === 'string' ? { name: s, description: '' } : s),
        excluded: (gs.outOfScope || []).map(s => typeof s === 'string' ? { name: s, description: '' } : s)
    };
}
data.cadrage.scope = data.cadrage.scope || { vital: [], important: [], optional: [], excluded: [] };

// Backward compat: mustHave/shouldHave/couldHave/wontHave → vital/important/optional/excluded
if (data.cadrage.scope.mustHave && !data.cadrage.scope.vital?.length) {
    data.cadrage.scope.vital = data.cadrage.scope.mustHave;
    data.cadrage.scope.important = data.cadrage.scope.shouldHave || data.cadrage.scope.important || [];
    data.cadrage.scope.optional = data.cadrage.scope.couldHave || data.cadrage.scope.optional || [];
    data.cadrage.scope.excluded = data.cadrage.scope.wontHave || data.cadrage.scope.excluded || [];
}

// Defensive init: moduleSpecs (may be missing if LLM didn't follow mapping)
data.moduleSpecs = data.moduleSpecs || {};
// Ensure ALL modules have a moduleSpecs entry (prevents missing schemas)
(data.modules || []).forEach(function(m) {
    if (!data.moduleSpecs[m.code]) {
        data.moduleSpecs[m.code] = { useCases: [], businessRules: [], entities: [], permissions: [], notes: '' };
    }
    // Ensure anticipatedSections array exists
    m.anticipatedSections = m.anticipatedSections || [];
    m.applicationCode = m.applicationCode || '';
    // Initialize screens array for interface specs
    if (!data.moduleSpecs[m.code].screens) {
        data.moduleSpecs[m.code].screens = [];
    }
});

// Vibe coding mode: hide non-relevant sections
const isVibeCoding = data.metadata?.vibeCoding === true;
if (isVibeCoding) {
    document.querySelectorAll('[data-vibe-hide]').forEach(el => el.style.display = 'none');
}

/* ============================================
   UTILITIES
   ============================================ */
function showNotification(message) {
    const el = document.getElementById('notification');
    el.textContent = message;
    el.classList.add('visible');
    setTimeout(() => el.classList.remove('visible'), 2500);
}

function toggleForm(formId) {
    document.getElementById(formId).classList.toggle('visible');
}

function clearForm(formId) {
    document.querySelectorAll('#' + formId + ' input, #' + formId + ' textarea').forEach(el => el.value = '');
}

function getNestedValue(obj, path) {
    return path.split('.').reduce((o, k) => (o || {})[k], obj);
}

function setNestedValue(obj, path, value) {
    const keys = path.split('.');
    let current = obj;
    for (let i = 0; i < keys.length - 1; i++) {
        if (!current[keys[i]]) current[keys[i]] = {};
        current = current[keys[i]];
    }
    current[keys[keys.length - 1]] = value;
}

function updateCounts() {
    buildNavTree();
    updateDepSelects();
}

function formatFrequency(f) {
    return { daily: 'Quotidien', weekly: 'Hebdomadaire', monthly: 'Mensuel', occasional: 'Occasionnel' }[f] || f;
}

function formatAccess(a) {
    return { admin: 'Administration', manager: 'Supervision', contributor: 'Contribution', viewer: 'Consultation' }[a] || a;
}

function formatPriority(p) {
    return { vital: 'Indispensable', important: 'Important', optional: 'Optionnel', excluded: 'Hors perimetre' }[p] || p;
}

function formatLevel(l) {
    return { high: 'Fort', medium: 'Moyen', low: 'Faible' }[l] || l;
}

function formatModuleType(t) {
    return { 'data-centric': 'Donnees', 'workflow': 'Processus', 'reporting': 'Rapports', 'integration': 'Integration', 'full-module': 'Complet' }[t] || t;
}

function formatModulePriority(p) {
    return { must: 'Indispensable', should: 'Important', could: 'Optionnel' }[p] || p;
}

/* ============================================
   INITIALIZATION
   ============================================ */
document.addEventListener('DOMContentLoaded', function() {
    loadFromLocalStorage();
    initEditableFields();
    // Re-apply vibe hiding after DOM init (in case loadFromLocalStorage changed data)
    if (isVibeCoding) {
        document.querySelectorAll('[data-vibe-hide]').forEach(el => el.style.display = 'none');
    }
    renderStakeholders();
    renderScope();
    renderRisks();
    renderCriteria();
    renderModules();
    renderDependencies();
    renderAllModuleSpecs();
    renderConsolidation();
    renderHandoff();
    renderE2EFlows();
    buildNavTree();
    updateDepSelects();
    initInlineComments();
    renderReviewPanel();
});
