/* ============================================
   NAVIGATION - Hierarchical Tree
   ============================================ */
let currentSectionId = 'cadrage-context';
let navCollapseState = {};

/* ---------- Core ---------- */

function showSection(sectionId) {
    currentSectionId = sectionId;
    document.querySelectorAll('.section').forEach(s => s.style.display = 'none');
    const section = document.getElementById(sectionId);
    if (section) section.style.display = 'block';

    // Highlight active nav item
    document.querySelectorAll('#sidebarNav .nav-item').forEach(n => n.classList.remove('active'));
    const navItem = document.querySelector('#sidebarNav [data-section="' + sectionId + '"]');
    if (navItem) {
        navItem.classList.add('active');
        // Auto-expand parent groups to reveal active item
        let parent = navItem.parentElement;
        while (parent && parent.id !== 'sidebarNav') {
            if (parent.classList.contains('nav-children') && parent.style.display === 'none') {
                parent.style.display = '';
                const groupEl = parent.parentElement;
                if (groupEl) {
                    const groupId = groupEl.dataset.groupId;
                    if (groupId) {
                        navCollapseState[groupId] = false;
                        const chevron = groupEl.querySelector(':scope > .nav-group-title .nav-chevron, :scope > .nav-item.nav-module-header .nav-chevron');
                        if (chevron) chevron.classList.add('expanded');
                    }
                }
            }
            parent = parent.parentElement;
        }
        saveNavState();
    }
}

function restoreCurrentSection() {
    if (currentSectionId) {
        const section = document.getElementById(currentSectionId);
        if (section) section.style.display = 'block';
    }
}

/* ---------- Tree Builder ---------- */

function buildNavTree() {
    const nav = document.getElementById('sidebarNav');
    if (!nav) return;

    nav.innerHTML =
        renderNavGroup('cadrage', 'Cadrage', buildCadrageItems()) +
        renderNavGroup('modules', 'Modules (' + data.modules.length + ')', buildModuleItems()) +
        renderNavGroup('consolidation', 'Consolidation', buildConsolidationItems()) +
        renderNavGroup('synthese', 'Synthese', buildSyntheseItems());

    restoreNavState();
    highlightActiveNavItem();
}

function renderNavGroup(id, title, itemsHtml) {
    const collapsed = navCollapseState[id] === true;
    return '<div class="nav-group" data-group-id="' + id + '">' +
        '<div class="nav-group-title" onclick="toggleNavGroup(\'' + id + '\')">' +
            '<span class="nav-chevron ' + (collapsed ? '' : 'expanded') + '">&#9656;</span> ' +
            title +
        '</div>' +
        '<div class="nav-children"' + (collapsed ? ' style="display:none;"' : '') + '>' +
            itemsHtml +
        '</div>' +
    '</div>';
}

function renderNavItem(sectionId, label, badge) {
    return '<a class="nav-item" onclick="showSection(\'' + sectionId + '\')" data-section="' + sectionId + '">' +
        '<span class="nav-icon">&#9679;</span> ' + label +
        (badge !== undefined ? ' <span class="nav-badge">' + badge + '</span>' : '') +
    '</a>';
}

/* ---------- Group Builders ---------- */

function buildCadrageItems() {
    return renderNavItem('cadrage-context', 'Contexte') +
        renderNavItem('cadrage-stakeholders', 'Parties prenantes', data.cadrage.stakeholders.length) +
        renderNavItem('cadrage-scope', 'Perimetre fonctionnel') +
        renderNavItem('cadrage-risks', 'Risques et hypotheses', data.cadrage.risks.length) +
        renderNavItem('cadrage-success', 'Criteres de reussite');
}

function buildModuleItems() {
    let html = '';
    data.modules.forEach(function(mod) {
        html += renderModuleNavItem(mod);
    });
    // Global module views at bottom
    html += renderNavItem('decomp-modules', 'Vue d\'ensemble', data.modules.length);
    html += renderNavItem('decomp-dependencies', 'Dependances', data.dependencies.length);
    return html;
}

function buildConsolidationItems() {
    var totalEntities = data.modules.reduce(function(sum, m) {
        return sum + (data.moduleSpecs[m.code]?.entities || []).length;
    }, 0);
    return renderNavItem('consol-datamodel', 'Modele de donnees', totalEntities) +
        renderNavItem('consol-interactions', 'Interactions') +
        renderNavItem('consol-permissions', 'Coherence des acces') +
        renderNavItem('consol-flows', 'Parcours bout en bout', data.consolidation.e2eFlows.length);
}

function buildSyntheseItems() {
    return renderNavItem('handoff-summary', 'Vue d\'ensemble');
}

/* ---------- Module Sub-Tree ---------- */

function renderModuleNavItem(mod) {
    var code = mod.code;
    var spec = data.moduleSpecs[code] || {};
    var ucCount = (spec.useCases || []).length;
    var brCount = (spec.businessRules || []).length;
    var entCount = (spec.entities || []).length;
    var sections = mod.anticipatedSections || [];
    var groupId = 'mod-' + code;
    var collapsed = navCollapseState[groupId] === true;

    var html = '<div class="nav-module" data-group-id="' + groupId + '">';

    // Module header (clickable to expand + navigate to module spec)
    html += '<a class="nav-item nav-module-header" onclick="toggleNavGroup(\'' + groupId + '\');showSection(\'module-spec-' + code + '\')" data-section="module-spec-' + code + '">';
    html += '<span class="nav-chevron ' + (collapsed ? '' : 'expanded') + '">&#9656;</span> ';
    html += (mod.name || mod.code);
    html += '</a>';

    // Children: tabs
    html += '<div class="nav-children"' + (collapsed ? ' style="display:none;"' : '') + '>';
    html += renderModuleTabNavItem(code, 'uc', 'Cas d\'utilisation', ucCount);
    html += renderModuleTabNavItem(code, 'br', 'Regles metier', brCount);
    html += renderModuleTabNavItem(code, 'ent', 'Donnees', entCount);
    html += renderModuleTabNavItem(code, 'perm', 'Droits d\'acces');
    html += renderModuleTabNavItem(code, 'mock', 'Maquettes');
    html += renderModuleTabNavItem(code, 'struct', 'Structure', sections.length);

    // Children: sections/resources (deeper tree)
    if (sections.length > 0) {
        sections.forEach(function(section) {
            var resources = section.resources || [];
            html += '<div class="nav-section-item">';
            html += '<a class="nav-item nav-section-link" onclick="showSection(\'module-spec-' + code + '\');switchTab(\'' + code + '\',\'struct\')" data-section="module-struct-' + code + '-' + section.code + '">';
            html += '<span class="nav-icon nav-icon-section">&#9655;</span> ' + section.code;
            if (resources.length > 0) html += ' <span class="nav-badge">' + resources.length + '</span>';
            html += '</a>';
            if (resources.length > 0) {
                html += '<div class="nav-children nav-resources">';
                resources.forEach(function(res) {
                    var resName = typeof res === 'string' ? res : (res.code || res.name || '');
                    html += '<a class="nav-item nav-resource-link">';
                    html += '<span class="nav-icon nav-icon-resource">&#8226;</span> ' + resName;
                    html += '</a>';
                });
                html += '</div>';
            }
            html += '</div>';
        });
    }

    html += '</div>'; // nav-children
    html += '</div>'; // nav-module
    return html;
}

function renderModuleTabNavItem(code, tabId, label, badge) {
    var sectionId = 'module-spec-' + code;
    return '<a class="nav-item" onclick="showSection(\'' + sectionId + '\');switchTab(\'' + code + '\',\'' + tabId + '\')" data-section="' + sectionId + '-' + tabId + '">' +
        '<span class="nav-icon">&#9679;</span> ' + label +
        (badge !== undefined ? ' <span class="nav-badge">' + badge + '</span>' : '') +
    '</a>';
}

/* ---------- Collapse/Expand ---------- */

function toggleNavGroup(groupId) {
    navCollapseState[groupId] = !navCollapseState[groupId];
    var groupEl = document.querySelector('[data-group-id="' + groupId + '"]');
    if (groupEl) {
        var children = groupEl.querySelector(':scope > .nav-children');
        var chevron = groupEl.querySelector(':scope > .nav-group-title .nav-chevron, :scope > .nav-item.nav-module-header .nav-chevron');
        if (children) children.style.display = navCollapseState[groupId] ? 'none' : '';
        if (chevron) chevron.classList.toggle('expanded', !navCollapseState[groupId]);
    }
    saveNavState();
}

function saveNavState() {
    try { localStorage.setItem(APP_KEY + '-nav', JSON.stringify(navCollapseState)); } catch(e) {}
}

function restoreNavState() {
    try {
        var saved = localStorage.getItem(APP_KEY + '-nav');
        if (saved) {
            navCollapseState = JSON.parse(saved);
            // Apply collapse state to all groups
            Object.keys(navCollapseState).forEach(function(groupId) {
                if (navCollapseState[groupId]) {
                    var groupEl = document.querySelector('[data-group-id="' + groupId + '"]');
                    if (groupEl) {
                        var children = groupEl.querySelector(':scope > .nav-children');
                        var chevron = groupEl.querySelector(':scope > .nav-group-title .nav-chevron, :scope > .nav-item.nav-module-header .nav-chevron');
                        if (children) children.style.display = 'none';
                        if (chevron) chevron.classList.remove('expanded');
                    }
                }
            });
        }
    } catch(e) {}
}

function highlightActiveNavItem() {
    if (!currentSectionId) return;
    var navItem = document.querySelector('#sidebarNav [data-section="' + currentSectionId + '"]');
    if (navItem) navItem.classList.add('active');
}
