/* ============================================
   REVIEW PANEL
   ============================================ */
let reviewPanelOpen = false;
let reviewFilter = 'all';

function toggleReviewPanel() {
    reviewPanelOpen = !reviewPanelOpen;
    const panel = document.getElementById('reviewPanel');
    const body = document.getElementById('appBody');
    const btn = document.getElementById('reviewToggleBtn');

    if (reviewPanelOpen) {
        panel.classList.add('visible');
        body.classList.add('review-open');
        btn.classList.add('active');
    } else {
        panel.classList.remove('visible');
        body.classList.remove('review-open');
        btn.classList.remove('active');
    }

    renderReviewPanel();
}

function filterReviewComments(filter) {
    reviewFilter = filter;
    // Update active filter button
    document.querySelectorAll('.review-filter-btn').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.filter === filter);
    });
    renderReviewPanel();
}

function renderReviewPanel() {
    const comments = data.comments || [];

    // Update header badge
    const toReviewCount = comments.filter(c => c.status === 'to-review').length;
    const badge = document.getElementById('reviewBadge');
    if (badge) {
        badge.textContent = toReviewCount;
        badge.classList.toggle('hidden', toReviewCount === 0);
    }

    // Update stats
    const totalEl = document.getElementById('reviewStatTotal');
    const toReviewEl = document.getElementById('reviewStatToReview');
    const validatedEl = document.getElementById('reviewStatValidated');
    if (totalEl) totalEl.textContent = comments.length;
    if (toReviewEl) toReviewEl.textContent = toReviewCount;
    if (validatedEl) validatedEl.textContent = comments.filter(c => c.status === 'validated').length;

    // Filter comments
    let filtered = comments;
    if (reviewFilter === 'to-review') {
        filtered = comments.filter(c => c.status === 'to-review');
    } else if (reviewFilter === 'validated') {
        filtered = comments.filter(c => c.status === 'validated');
    }

    // Render comment list
    const container = document.getElementById('reviewCommentsList');
    if (!container) return;

    if (filtered.length === 0) {
        container.innerHTML = '<div class="review-empty">Aucun commentaire' +
            (reviewFilter !== 'all' ? ' avec ce filtre' : '') + '.</div>';
        return;
    }

    container.innerHTML = filtered.map(function(c, i) {
        const globalIndex = data.comments.indexOf(c);
        const sectionLabel = getSectionLabel(c.sectionId);
        const date = c.timestamp ? new Date(c.timestamp).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit' }) : '';
        var elId = c.elementId || c.cardIndex;
        var safeElId = String(elId).replace(/[^a-zA-Z0-9_-]/g, '_');

        return `
            <div class="review-comment-item" onclick="navigateToComment('${c.sectionId}', '${safeElId}')">
                <div class="review-comment-section">${escapeHtml(sectionLabel)}</div>
                <div class="review-comment-text">${escapeHtml(c.content)}</div>
                <div class="review-comment-footer">
                    <span class="review-comment-author">${escapeHtml(c.author || 'Utilisateur')} - ${escapeHtml(date)}</span>
                    <div class="review-comment-actions">
                        <button class="review-action-btn ${c.status === 'validated' ? 'reject' : 'validate'}"
                            onclick="event.stopPropagation();toggleCommentStatus(${globalIndex})"
                            title="${c.status === 'validated' ? 'Remettre à revoir' : 'Valider'}">
                            ${c.status === 'validated' ? 'À revoir' : 'Valider'}
                        </button>
                        <button class="review-action-btn delete"
                            onclick="event.stopPropagation();deleteComment(${globalIndex})"
                            title="Supprimer">
                            &#10005;
                        </button>
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

function getSectionLabel(sectionId) {
    const labels = {
        'cadrage-context': 'Contexte',
        'cadrage-stakeholders': 'Parties prenantes',
        'cadrage-scope': 'Périmètre',
        'cadrage-success': 'Critères',
        'decomp-modules': 'Domaines',
        'decomp-dependencies': 'Dépendances',
        'consol-interactions': 'Interactions',
        'consol-permissions': 'Accès',
        'consol-flows': 'Parcours',
        'handoff-summary': 'Synthèse'
    };
    if (labels[sectionId]) return labels[sectionId];
    if (sectionId.startsWith('module-spec-')) {
        const code = sectionId.replace('module-spec-', '');
        const mod = data.modules.find(m => m.code === code);
        return mod ? mod.name : code;
    }
    // Handle module structure sections (module-struct-{code}-{section})
    const structMatch = sectionId.match(/^module-struct-(.+?)-(.+)$/);
    if (structMatch) {
        const mod = data.modules.find(m => m.code === structMatch[1]);
        const modName = mod ? mod.name : structMatch[1];
        return modName + ' > Structure > ' + structMatch[2];
    }
    // Handle list-based sectionIds (ucList-*, brList-*, entList-*)
    const listMatch = sectionId.match(/^(uc|br|ent)List-(.+)$/);
    if (listMatch) {
        const tabLabels = { uc: 'Cas d\'utilisation', br: 'Règles métier', ent: 'Données' };
        const mod = data.modules.find(m => m.code === listMatch[2]);
        const modName = mod ? mod.name : listMatch[2];
        return modName + ' > ' + (tabLabels[listMatch[1]] || listMatch[1]);
    }
    return sectionId;
}

function navigateToComment(sectionId, safeElId) {
    // Handle list-based sectionIds (ucList-*, brList-*, entList-*) → navigate to module + tab
    const listMatch = sectionId.match(/^(uc|br|ent)List-(.+)$/);
    if (listMatch) {
        const [, tabType, moduleCode] = listMatch;
        showSection('module-spec-' + moduleCode);
        setTimeout(function() {
            switchTab(moduleCode, tabType);
            scrollToCommentThread(sectionId, safeElId);
        }, 150);
    } else {
        showSection(sectionId);
        scrollToCommentThread(sectionId, safeElId);
    }
}

function scrollToCommentThread(sectionId, safeElId) {
    setTimeout(function() {
        const thread = document.getElementById('comment-thread-' + sectionId + '-' + safeElId);
        if (thread && !thread.classList.contains('visible')) {
            thread.classList.add('visible');
        }
        const container = document.querySelector('.comment-btn-container[data-section-id="' + sectionId + '"][data-element-id]');
        if (container) {
            container.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }, 100);
}
