/* ============================================
   CONSOLIDATION
   ============================================ */
function renderConsolidation() {
    renderDataModel();
    renderConsolInteractions();
    renderConsolPermissions();
}

/* ============================================
   DATA MODEL (cross-module entity overview)
   ============================================ */
function renderDataModel() {
    const container = document.getElementById('dataModelContainer');
    if (!container) return;

    // Collect all entities from all modules
    const allEntities = [];
    data.modules.forEach(m => {
        const spec = data.moduleSpecs[m.code] || {};
        (spec.entities || []).forEach(ent => {
            allEntities.push({ ...ent, moduleCode: m.code, moduleName: m.name || m.code });
        });
    });

    if (allEntities.length === 0) {
        container.innerHTML = '<p style="color:var(--text-muted);text-align:center;padding:2rem;">Aucune entité définie. Spécifiez les données dans chaque domaine (Phase 3 > onglet Données).</p>';
        return;
    }

    // Build relationship index for cross-module links
    const entityModuleMap = {};
    allEntities.forEach(e => { entityModuleMap[e.name] = e.moduleName; });

    // Render grouped by module
    let html = '';

    // Summary bar
    const moduleCount = data.modules.filter(m => (data.moduleSpecs[m.code]?.entities || []).length > 0).length;
    const relCount = allEntities.reduce((sum, e) => sum + (e.relationships || []).length, 0);
    html += `
        <div class="dm-summary">
            <div class="dm-summary-item"><span class="dm-summary-value">${allEntities.length}</span><span class="dm-summary-label">Entités</span></div>
            <div class="dm-summary-item"><span class="dm-summary-value">${moduleCount}</span><span class="dm-summary-label">Domaines</span></div>
            <div class="dm-summary-item"><span class="dm-summary-value">${relCount}</span><span class="dm-summary-label">Relations</span></div>
        </div>`;

    // Entity cards grouped by module
    data.modules.forEach(m => {
        const spec = data.moduleSpecs[m.code] || {};
        const entities = spec.entities || [];
        if (entities.length === 0) return;

        html += `<div class="dm-module-group">`;
        html += `<div class="dm-module-header">
            <span class="dm-module-name">${escapeHtml(m.name || m.code)}</span>
            <span class="dm-module-count">${entities.length} entité${entities.length > 1 ? 's' : ''}</span>
        </div>`;

        html += `<div class="dm-entity-grid">`;
        entities.forEach(ent => {
            const attrs = ent.attributes || [];
            const rels = ent.relationships || [];
            html += `
                <div class="dm-entity-card">
                    <div class="dm-entity-header">
                        <span class="dm-entity-name">${escapeHtml(ent.name)}</span>
                        <span class="dm-entity-attr-count">${attrs.length} champ${attrs.length > 1 ? 's' : ''}</span>
                    </div>
                    ${ent.description ? `<div class="dm-entity-desc">${escapeHtml(ent.description)}</div>` : ''}
                    ${attrs.length > 0 ? `
                    <table class="dm-attr-table">
                        <thead><tr><th>Champ</th><th style="width:100px;">Type</th><th>Description</th></tr></thead>
                        <tbody>
                            ${attrs.map(a => `<tr><td class="dm-attr-name">${escapeHtml(a.name)}</td><td style="font-family:monospace;font-size:0.8rem;color:var(--accent);">${escapeHtml(a.type || 'string')}</td><td class="dm-attr-desc">${escapeHtml(a.description || '')}</td></tr>`).join('')}
                        </tbody>
                    </table>` : ''}
                    ${rels.length > 0 ? `
                    <div class="dm-relations">
                        <div class="dm-relations-title">Relations</div>
                        ${rels.map(r => {
                            const relText = typeof r === 'string' ? r : (r.target + ' (' + r.type + ') - ' + (r.description || ''));
                            return `<div class="dm-relation-item">${escapeHtml(relText)}</div>`;
                        }).join('')}
                    </div>` : ''}
                </div>`;
        });
        html += `</div></div>`;
    });

    container.innerHTML = html;
}

function renderConsolInteractions() {
    const container = document.getElementById('consolInteractions');
    if (!container || data.dependencies.length === 0) return;

    container.innerHTML = data.dependencies.map(d => {
        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 class="interaction-type">Dépendance</span>
                <span style="flex:1;font-size:0.8rem;color:var(--text-muted);">${escapeHtml(d.description || '')}</span>
            </div>`;
    }).join('');
}

function renderConsolPermissions() {
    const container = document.getElementById('consolPermissions');
    if (!container || data.modules.length === 0) return;

    const roles = getPermRoles();

    let html = '<table class="mock-table" style="background:var(--bg-card);border-radius:8px;overflow:hidden;">';
    html += '<thead><tr><th>Profil</th>';
    data.modules.forEach(m => { html += `<th style="text-align:center;">${escapeHtml(m.name || m.code)}</th>`; });
    html += '</tr></thead><tbody>';

    roles.forEach(role => {
        html += `<tr><td style="font-weight:500;color:var(--text-bright);">${escapeHtml(role)}</td>`;
        data.modules.forEach(m => {
            const allPerms = data.moduleSpecs[m.code]?.permissions || [];
            const hasWildcard = allPerms.includes(role + '|*');
            const perms = hasWildcard
                ? getPermActions()
                : allPerms.filter(p => p.startsWith(role + '|'));
            const count = perms.length;
            const color = count > 4 ? 'var(--success)' : count > 2 ? 'var(--warning)' : count > 0 ? 'var(--text-muted)' : 'var(--border)';
            const label = hasWildcard ? 'Tous' : (count > 0 ? count + ' droits' : 'Aucun');
            html += `<td style="text-align:center;color:${color};font-weight:600;">${label}</td>`;
        });
        html += '</tr>';
    });

    html += '</tbody></table>';
    container.innerHTML = html;
}

/* ============================================
   E2E FLOWS
   ============================================ */
function addE2EFlow() {
    const name = document.getElementById('flow-name').value.trim();
    if (!name) return;

    const steps = document.getElementById('flow-steps').value.split('\n').filter(l => l.trim()).map(l => {
        const parts = l.split(' - ');
        return { module: parts[0]?.trim() || '', action: parts.slice(1).join(' - ').trim() || l.trim() };
    });

    data.consolidation.e2eFlows.push({
        name: name,
        steps: steps,
        actors: document.getElementById('flow-actors').value.trim()
    });

    renderE2EFlows();
    toggleForm('addFlowForm');
    clearForm('addFlowForm');
    autoSave();
}

function removeE2EFlow(index) {
    if (!confirm('Supprimer ce parcours bout en bout ?')) return;
    data.consolidation.e2eFlows.splice(index, 1);
    renderE2EFlows();
    autoSave();
}

function renderE2EFlows() {
    const container = document.getElementById('e2eFlowsList');
    if (!container) return;

    container.innerHTML = data.consolidation.e2eFlows.map((flow, fi) => `
        <div class="card" style="margin-bottom:1rem;">
            <div class="card-header">
                <span class="card-title">${escapeHtml(flow.name)}</span>
                <button class="btn btn-sm" onclick="removeE2EFlow(${fi})" style="opacity:0.5;">Supprimer</button>
            </div>
            ${flow.actors ? `<div style="font-size:0.8rem;color:var(--text-muted);margin-bottom:0.5rem;">Intervenants : ${escapeHtml(flow.actors)}</div>` : ''}
            <div class="e2e-flow">
                ${flow.steps.map((s, i) => `
                    <div class="e2e-step">
                        <div class="e2e-step-module">${escapeHtml(s.module)}</div>
                        <div class="e2e-step-action">${escapeHtml(s.action)}</div>
                    </div>
                    ${i < flow.steps.length - 1 ? '<div class="process-arrow">&#8594;</div>' : ''}
                `).join('')}
            </div>
        </div>
    `).join('');
}
