/* ==========================================
   MERMAID DIAGRAM RENDERING
   Renders ERD, state machines, and sequence diagrams
   from consolidation.mermaidDiagrams data.
   ========================================== */

function renderMermaidDiagrams() {
    const data = window.FEATURE_DATA;
    if (!data) return;

    const diagrams = data.consolidation?.mermaidDiagrams;
    if (!diagrams) return;

    // 1. ERD in consol-datamodel (prepend before entity cards)
    if (diagrams.erd) {
        const erdContainer = document.getElementById('dataModelContainer');
        if (erdContainer) {
            const erdDiv = document.createElement('div');
            erdDiv.className = 'diagram-container diagram-erd';
            erdDiv.innerHTML =
                '<div class="diagram-section-header">Diagramme Entit\u00e9-Relation (ERD)</div>' +
                '<div class="mermaid">' + escapeHtml(diagrams.erd) + '</div>';
            erdContainer.insertBefore(erdDiv, erdContainer.firstChild);
        }
    }

    // 1b. MCD (Modèle Conceptuel de Données) — after ERD
    if (diagrams.mcd) {
        var erdContainer = document.getElementById('dataModelContainer');
        if (erdContainer) {
            var mcdDiv = document.createElement('div');
            mcdDiv.className = 'diagram-container diagram-mcd';
            mcdDiv.innerHTML =
                '<div class="diagram-section-header" style="font-size:0.95rem;font-weight:600;color:var(--text-bright);margin-bottom:0.75rem;">Mod\u00e8le Conceptuel de Donn\u00e9es (MCD)</div>' +
                '<div class="mermaid">' + escapeHtml(diagrams.mcd) + '</div>';
            var erdDiv = erdContainer.querySelector('.diagram-erd');
            if (erdDiv && erdDiv.nextSibling) {
                erdContainer.insertBefore(mcdDiv, erdDiv.nextSibling);
            } else {
                erdContainer.appendChild(mcdDiv);
            }
        }
    }

    // 2. State machine diagrams — inject in module spec sections or consol-datamodel
    if (diagrams.stateMachines && Object.keys(diagrams.stateMachines).length > 0) {
        const smContainer = document.getElementById('dataModelContainer');
        if (smContainer) {
            const smSection = document.createElement('div');
            smSection.innerHTML = '<div class="diagram-section-header">Cycles de vie (State Machines)</div>';

            Object.entries(diagrams.stateMachines).forEach(function(entry) {
                var entity = entry[0];
                var def = entry[1];
                var smDiv = document.createElement('div');
                smDiv.className = 'diagram-container diagram-state-machine';
                smDiv.innerHTML =
                    '<h4>' + escapeHtml(entity) + '</h4>' +
                    '<div class="mermaid">' + escapeHtml(def) + '</div>';
                smSection.appendChild(smDiv);
            });

            smContainer.appendChild(smSection);
        }
    }

    // 2b. Use Case diagrams — inject in each module's UC tab
    if (diagrams.useCases && Object.keys(diagrams.useCases).length > 0) {
        Object.entries(diagrams.useCases).forEach(function(entry) {
            var moduleCode = entry[0];
            var def = entry[1];
            var ucTab = document.getElementById('tab-' + moduleCode + '-uc');
            if (!ucTab) {
                // Try kebab-case version
                var kebab = moduleCode.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
                ucTab = document.getElementById('tab-' + kebab + '-uc');
            }
            if (ucTab) {
                var ucDiagramDiv = document.createElement('div');
                ucDiagramDiv.className = 'diagram-container diagram-usecase';
                ucDiagramDiv.innerHTML =
                    '<div class="diagram-section-header" style="font-size:0.95rem;font-weight:600;color:var(--text-bright);margin-bottom:0.75rem;">Diagramme de cas d\'utilisation</div>' +
                    '<div class="mermaid">' + escapeHtml(def) + '</div>';
                // Insert after the first paragraph (description text)
                var firstP = ucTab.querySelector('p');
                if (firstP && firstP.nextSibling) {
                    ucTab.insertBefore(ucDiagramDiv, firstP.nextSibling);
                } else {
                    ucTab.insertBefore(ucDiagramDiv, ucTab.firstChild);
                }
            }
        });
    }

    // 3. Sequence diagrams in consol-flows
    if (diagrams.sequences && Object.keys(diagrams.sequences).length > 0) {
        var flowsContainer = document.getElementById('consolFlowsContainer');
        // Fallback: try the consol-flows section
        if (!flowsContainer) {
            var consolFlows = document.getElementById('consol-flows');
            if (consolFlows) {
                flowsContainer = consolFlows.querySelector('.section-body') || consolFlows;
            }
        }

        if (flowsContainer) {
            var seqSection = document.createElement('div');
            seqSection.innerHTML = '<div class="diagram-section-header">Diagrammes de s\u00e9quence</div>';

            Object.entries(diagrams.sequences).forEach(function(entry) {
                var flowName = entry[0];
                var def = entry[1];
                var seqDiv = document.createElement('div');
                seqDiv.className = 'diagram-container diagram-sequence';
                seqDiv.innerHTML =
                    '<h4>' + escapeHtml(flowName) + '</h4>' +
                    '<div class="mermaid">' + escapeHtml(def) + '</div>';
                seqSection.appendChild(seqDiv);
            });

            flowsContainer.appendChild(seqSection);
        }
    }

    // 4. Render all mermaid elements
    try {
        if (typeof mermaid !== 'undefined' && mermaid.run) {
            mermaid.run({ querySelector: '.mermaid' });
        }
    } catch (e) {
        console.warn('Mermaid rendering failed:', e);
        // Fallback: show raw text
        document.querySelectorAll('.mermaid').forEach(function(el) {
            if (!el.querySelector('svg')) {
                el.style.whiteSpace = 'pre-wrap';
                el.style.fontFamily = 'monospace';
                el.style.fontSize = '0.85rem';
                el.style.color = 'var(--text-muted)';
            }
        });
    }
}

// Escape HTML for safe injection
function escapeHtml(text) {
    if (!text) return '';
    // For mermaid content, we need to preserve the syntax
    // Only escape actual HTML tags, not mermaid arrows
    return text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

// Auto-run after consolidation rendering
(function() {
    // Wait for DOM and other render functions to complete
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(renderMermaidDiagrams, 500);
        });
    } else {
        setTimeout(renderMermaidDiagrams, 500);
    }
})();
