/* ============================================
   MODULE MANAGEMENT
   ============================================ */
function addModule() {
    const name = document.getElementById('mod-name').value.trim();
    if (!name) return;
    const code = name.replace(/[^a-zA-Z0-9]/g, '');

    data.modules.push({
        code: code,
        name: name,
        description: document.getElementById('mod-desc').value.trim(),
        featureType: document.getElementById('mod-type').value,
        entities: document.getElementById('mod-entities').value.split('\n').filter(e => e.trim()),
        anticipatedSections: [],
        status: 'pending'
    });

    // Initialize module spec
    if (!data.moduleSpecs[code]) {
        data.moduleSpecs[code] = {
            useCases: [],
            businessRules: [],
            entities: [],
            permissions: [],
            notes: ''
        };
    }

    renderModules();
    renderDependencies();
    renderAllModuleSpecs();
    toggleForm('addModuleForm');
    clearForm('addModuleForm');
    updateCounts();
    autoSave();
}

function removeModule(index) {
    if (!confirm('Supprimer ce domaine fonctionnel ?')) return;
    const code = data.modules[index].code;
    data.modules.splice(index, 1);
    delete data.moduleSpecs[code];
    data.dependencies = data.dependencies.filter(d => d.from !== code && d.to !== code);
    renderModules();
    renderDependencies();
    renderAllModuleSpecs();
    updateCounts();
    autoSave();
}

function renderModules() {
    const grid = document.getElementById('moduleGrid');
    grid.innerHTML = data.modules.map((m, i) => `
        <div class="module-card" onclick="showSection('module-spec-${m.code}')">
            <button class="module-card-remove" onclick="event.stopPropagation();removeModule(${i})">&#10005;</button>
            <div class="module-card-header">
                <span class="module-card-code">${escapeHtml(m.name)}</span>
                <span class="module-card-type">${formatModuleType(m.featureType)}</span>
            </div>
            <div class="module-card-desc">${escapeHtml(m.description || '')}</div>
            <div class="module-card-meta">
                <span>${(m.entities || []).length} données</span>
                <span>${(data.moduleSpecs[m.code]?.useCases || []).length} cas d'utilisation</span>
            </div>
        </div>
    `).join('') || '<p style="color:var(--text-muted);text-align:center;padding:2rem;grid-column:1/-1;">Aucun domaine fonctionnel défini. Cliquez sur le bouton ci-dessous pour commencer.</p>';
}

function updateModulesNav() {
    buildNavTree();
}

/* ============================================
   DEPENDENCY MANAGEMENT
   ============================================ */
function updateDepSelects() {
    const fromSel = document.getElementById('dep-from');
    const toSel = document.getElementById('dep-to');
    if (!fromSel || !toSel) return;
    const opts = data.modules.map(m => `<option value="${m.code}">${m.name}</option>`).join('');
    fromSel.innerHTML = opts;
    toSel.innerHTML = opts;
}

function addDependency() {
    const from = document.getElementById('dep-from').value;
    const to = document.getElementById('dep-to').value;
    if (!from || !to || from === to) return;
    if (data.dependencies.some(d => d.from === from && d.to === to)) return;

    data.dependencies.push({
        from: from,
        to: to,
        description: document.getElementById('dep-desc').value.trim()
    });
    document.getElementById('dep-desc').value = '';

    renderDependencies();
    autoSave();
}

function removeDependency(index) {
    data.dependencies.splice(index, 1);
    renderDependencies();
    autoSave();
}

function renderDependencies() {
    // Render dependency list
    const depList = document.getElementById('depList');
    if (depList) {
        depList.innerHTML = data.dependencies.map((d, i) => {
            const fromName = data.modules.find(m => m.code === d.from)?.name || d.from;
            const toName = data.modules.find(m => m.code === d.to)?.name || d.to;
            return `
                <div class="interaction-item">
                    <span style="font-weight:600;color:var(--text-bright);">${escapeHtml(fromName)}</span>
                    <span class="interaction-arrow">&#8594;</span>
                    <span style="font-weight:600;color:var(--text-bright);">${escapeHtml(toName)}</span>
                    <span style="flex:1;font-size:0.8rem;color:var(--text-muted);">${escapeHtml(d.description || '')}</span>
                    <button class="btn btn-sm" onclick="removeDependency(${i})" style="opacity:0.5;">Supprimer</button>
                </div>
            `;
        }).join('');
    }

    // Render graph
    renderDepGraph();
    // Render processing order
    renderProcessingOrder();
}

function renderDepGraph() {
    const graph = document.getElementById('depGraph');
    if (!graph || data.modules.length === 0) return;

    const layers = computeTopologicalLayers();
    if (!layers) {
        graph.innerHTML = '<p style="color:var(--error);text-align:center;padding:1rem;">Dépendance circulaire détectée ! Corrigez les dépendances.</p>';
        return;
    }

    graph.innerHTML = layers.map((layer, i) => `
        <div class="dep-layer">
            <div class="dep-layer-label">Couche ${i + 1}</div>
            <div class="dep-layer-modules">
                ${layer.map(code => {
                    const m = data.modules.find(mod => mod.code === code);
                    return `<div class="dep-module">${escapeHtml(m ? (m.name || m.code) : code)}</div>`;
                }).join('')}
            </div>
        </div>
        ${i < layers.length - 1 ? '<div class="dep-arrow">&#8595;</div>' : ''}
    `).join('');
}

function computeTopologicalLayers() {
    const codes = data.modules.map(m => m.code);
    const inDeg = {};
    const adj = {};
    codes.forEach(c => { inDeg[c] = 0; adj[c] = []; });
    data.dependencies.forEach(d => {
        if (inDeg[d.from] !== undefined && adj[d.to] !== undefined) {
            adj[d.to].push(d.from);
            inDeg[d.from]++;
        }
    });

    const layers = [];
    let remaining = new Set(codes);
    while (remaining.size > 0) {
        const layer = [];
        remaining.forEach(c => {
            if (inDeg[c] === 0) layer.push(c);
        });
        if (layer.length === 0) return null; // cycle
        layers.push(layer);
        layer.forEach(c => {
            remaining.delete(c);
            (adj[c] || []).forEach(dep => { inDeg[dep]--; });
        });
    }
    return layers;
}

function renderProcessingOrder() {
    const container = document.getElementById('processingOrder');
    if (!container) return;
    const layers = computeTopologicalLayers();
    if (!layers) { container.innerHTML = ''; return; }
    const order = layers.flat();
    container.innerHTML = order.map((code, i) => {
        const m = data.modules.find(mod => mod.code === code);
        return `
            <div class="process-step">
                <div class="process-step-number">Étape ${i + 1}</div>
                <div class="process-step-label">${escapeHtml(m ? (m.name || m.code) : code)}</div>
            </div>
            ${i < order.length - 1 ? '<div class="process-arrow">&#8594;</div>' : ''}
        `;
    }).join('');
}
