/* ============================================
   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;

    var html = renderNavGroup('cadrage', 'Cadrage', buildCadrageItems());

    // Multi-app: group modules by application
    if (data.applications && data.applications.length > 1) {
        data.applications.forEach(function(app) {
            var appModules = data.modules.filter(function(m) { return m.applicationCode === app.code; });
            var appModuleItems = '';
            appModules.forEach(function(mod) {
                appModuleItems += renderModuleNavItem(mod);
            });
            // Global views at bottom of each app group
            appModuleItems += renderNavItem('decomp-modules', 'Vue d\'ensemble', data.modules.length);
            html += renderNavGroup('app-' + app.code, app.name || app.code, appModuleItems);
        });
        // Modules without applicationCode
        var orphanModules = data.modules.filter(function(m) { return !m.applicationCode; });
        if (orphanModules.length > 0) {
            var orphanItems = '';
            orphanModules.forEach(function(mod) {
                orphanItems += renderModuleNavItem(mod);
            });
            html += renderNavGroup('modules-other', 'Autres modules (' + orphanModules.length + ')', orphanItems);
        }
        html += renderNavItem('decomp-dependencies', 'Dépendances', data.dependencies.length);
    } else {
        html += renderNavGroup('modules', 'Modules (' + data.modules.length + ')', buildModuleItems());
    }

    html += renderNavGroup('consolidation', 'Consolidation', buildConsolidationItems());
    html += renderNavGroup('synthese', 'Synthèse', buildSyntheseItems());

    nav.innerHTML = html;
    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', 'Périmètre fonctionnel') +
        renderNavItem('cadrage-success', 'Critères de réussite');
}

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', 'Dépendances', 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', 'Modèle de données', totalEntities) +
        renderNavItem('consol-interactions', 'Interactions') +
        renderNavItem('consol-permissions', 'Cohérence des accès') +
        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 totalItems = ucCount + brCount + entCount;

    // Flat module link — sections/resources are accessible via tabs (Structure, Maquettes)
    return '<a class="nav-item nav-module-header" onclick="showSection(\'module-spec-' + code + '\')" data-section="module-spec-' + code + '">' +
        '<span class="nav-icon">&#9679;</span> ' +
        (mod.name || mod.code) +
        (totalItems > 0 ? ' <span class="nav-badge">' + totalItems + '</span>' : '') +
    '</a>';
}

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>';
}

function scrollToMockup(moduleCode, sectionCode) {
    setTimeout(function() {
        var el = document.getElementById('screen-' + moduleCode + '-' + sectionCode);
        if (el) {
            el.scrollIntoView({ behavior: 'smooth', block: 'start' });
            el.style.outline = '2px solid var(--accent)';
            el.style.borderRadius = '10px';
            setTimeout(function() { el.style.outline = ''; el.style.borderRadius = ''; }, 2000);
        }
    }, 150);
}

/* ---------- 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');
}

/* ---------- Mobile Sidebar ---------- */

function toggleMobileSidebar() {
    var sidebar = document.getElementById('sidebarAside');
    var overlay = document.getElementById('sidebarOverlay');
    if (!sidebar) return;
    var isOpen = sidebar.classList.contains('mobile-open');
    sidebar.classList.toggle('mobile-open', !isOpen);
    if (overlay) overlay.classList.toggle('visible', !isOpen);
}

/* ---------- Search / Filter ---------- */

var _searchTimer;
function filterNavItems(query) {
    clearTimeout(_searchTimer);
    _searchTimer = setTimeout(function() { doFilterNavItems(query); }, 200);
}

function doFilterNavItems(query) {
    var q = (query || '').toLowerCase().trim();
    var nav = document.getElementById('sidebarNav');
    if (!nav) return;

    // Clear previous highlights
    nav.querySelectorAll('.search-highlight').forEach(function(el) {
        el.outerHTML = el.textContent;
    });

    if (!q) {
        // Show all items
        nav.querySelectorAll('.nav-item, .nav-group, .nav-module, .nav-section-item').forEach(function(el) {
            el.classList.remove('search-hidden');
        });
        return;
    }

    // Filter nav items
    var allItems = nav.querySelectorAll('.nav-item');
    var visibleSections = new Set();

    allItems.forEach(function(item) {
        var text = item.textContent.toLowerCase();
        if (text.includes(q)) {
            item.classList.remove('search-hidden');
            // Show parent groups
            var parent = item.parentElement;
            while (parent && parent.id !== 'sidebarNav') {
                parent.classList.remove('search-hidden');
                if (parent.querySelector(':scope > .nav-children')) {
                    var children = parent.querySelector(':scope > .nav-children');
                    if (children) children.style.display = '';
                }
                parent = parent.parentElement;
            }
            // Track section for content search
            var sectionId = item.dataset.section;
            if (sectionId) visibleSections.add(sectionId);
        } else {
            item.classList.add('search-hidden');
        }
    });

    // Hide groups that have no visible children
    nav.querySelectorAll('.nav-group, .nav-module').forEach(function(group) {
        var visibleChildren = group.querySelectorAll('.nav-item:not(.search-hidden)');
        if (visibleChildren.length === 0) {
            group.classList.add('search-hidden');
        } else {
            group.classList.remove('search-hidden');
        }
    });

    // Also search in section content and show matching sections
    document.querySelectorAll('.section').forEach(function(section) {
        var text = section.textContent.toLowerCase();
        if (text.includes(q) && !visibleSections.has(section.id)) {
            // Unhide corresponding nav item
            var navItem = nav.querySelector('[data-section="' + section.id + '"]');
            if (navItem) {
                navItem.classList.remove('search-hidden');
                var parent = navItem.parentElement;
                while (parent && parent.id !== 'sidebarNav') {
                    parent.classList.remove('search-hidden');
                    parent = parent.parentElement;
                }
            }
        }
    });
}
