/* ============================================
   INLINE COMMENTS SYSTEM
   ============================================ */

/**
 * Comments are stored in data.comments[] with structure:
 * { id, sectionId, elementId, author, timestamp, content, status, category }
 *
 * - sectionId: matches the section div id (e.g. "cadrage-context", "module-spec-Clients")
 * - elementId: stable identifier for the element (name, role, or generated id)
 * - cardIndex: (deprecated, kept for backward compat) positional index
 * - status: "to-review" | "validated"
 * - category: "clarification" | "correction" | "suggestion"
 */

function getElementId(item, sectionId, index) {
    // Extract a stable ID from the element's data
    var title = item.querySelector('.uc-title, .entity-name, .stakeholder-role, .card-title');
    if (title) return title.textContent.trim();
    var nameEl = item.querySelector('[data-field]');
    if (nameEl) return nameEl.dataset.field;
    return sectionId + '-' + index;
}

function initInlineComments() {
    // Cadrage sections: direct card children
    document.querySelectorAll('.section > .card, .section > .stakeholder-card, .section > .uc-item').forEach(function(card) {
        if (card.dataset.commentInitialized) return;
        card.dataset.commentInitialized = 'true';
        var section = card.closest('.section');
        var sectionId = section ? section.id : 'unknown';
        var siblings = Array.from(section.querySelectorAll(':scope > .card, :scope > .stakeholder-card, :scope > .uc-item'));
        var index = siblings.indexOf(card);
        var elementId = getElementId(card, sectionId, index);
        card.appendChild(createCommentUI(sectionId, elementId));
    });

    // Module spec lists: nested items in ucList, brList, entList containers
    document.querySelectorAll('[id^="ucList-"] > .uc-item, [id^="brList-"] > div, [id^="entList-"] > .entity-block').forEach(function(item) {
        if (item.dataset.commentInitialized) return;
        item.dataset.commentInitialized = 'true';
        var list = item.parentElement;
        var listId = list.id;
        var siblings = Array.from(list.children);
        var index = siblings.indexOf(item);
        var elementId = getElementId(item, listId, index);
        item.appendChild(createCommentUI(listId, elementId));
    });

    // Stakeholder cards in grid
    document.querySelectorAll('.stakeholder-grid > .stakeholder-card').forEach(function(card) {
        if (card.dataset.commentInitialized) return;
        card.dataset.commentInitialized = 'true';
        var grid = card.parentElement;
        var section = card.closest('.section');
        var sectionId = section ? section.id : 'stakeholders';
        var siblings = Array.from(grid.children);
        var index = siblings.indexOf(card);
        var elementId = getElementId(card, sectionId, index);
        card.appendChild(createCommentUI(sectionId, elementId));
    });

    // Scope items
    ['scopeInScope', 'scopeOutOfScope'].forEach(function(containerId) {
        var container = document.getElementById(containerId);
        if (!container) return;
        container.querySelectorAll('.uc-item').forEach(function(item, index) {
            if (item.dataset.commentInitialized) return;
            item.dataset.commentInitialized = 'true';
            var elementId = getElementId(item, containerId, index);
            item.appendChild(createCommentUI(containerId, elementId));
        });
    });
}

function createCommentUI(sectionId, elementId) {
    const comments = getCommentsForCard(sectionId, elementId);
    const count = comments.length;
    const safeElId = String(elementId).replace(/[^a-zA-Z0-9_-]/g, '_');
    const threadId = 'comment-thread-' + sectionId + '-' + safeElId;

    const container = document.createElement('div');
    container.className = 'comment-btn-container';
    container.dataset.sectionId = sectionId;
    container.dataset.elementId = elementId;

    container.innerHTML = `
        <button class="comment-toggle-btn" onclick="toggleCommentThread('${sectionId}', '${safeElId}')">
            Commentaires <span class="comment-count ${count === 0 ? 'empty' : ''}">${count}</span>
        </button>
        <div class="comment-thread" id="${threadId}">
            <div class="comment-items" id="comment-items-${sectionId}-${safeElId}">
                ${renderCommentItems(sectionId, elementId)}
            </div>
            <div class="comment-add-form">
                <textarea id="comment-text-${sectionId}-${safeElId}" placeholder="Ajouter un commentaire..."></textarea>
                <select id="comment-cat-${sectionId}-${safeElId}">
                    <option value="clarification">Clarification</option>
                    <option value="correction">Correction</option>
                    <option value="suggestion">Suggestion</option>
                </select>
                <button onclick="addInlineComment('${sectionId}', '${elementId.replace(/'/g, "\\'")}')">Ajouter</button>
            </div>
        </div>
    `;

    return container;
}

function getCommentsForCard(sectionId, elementId) {
    return (data.comments || []).filter(function(c) {
        if (c.elementId) return c.sectionId === sectionId && c.elementId === elementId;
        // Backward compat: match by cardIndex if elementId not set
        return c.sectionId === sectionId && c.cardIndex === elementId;
    });
}

function toggleCommentThread(sectionId, safeElId) {
    const thread = document.getElementById('comment-thread-' + sectionId + '-' + safeElId);
    if (thread) thread.classList.toggle('visible');
}

function renderCommentItems(sectionId, elementId) {
    const comments = getCommentsForCard(sectionId, elementId);
    if (comments.length === 0) {
        return '<div style="font-size:0.8rem;color:var(--text-muted);padding:0.5rem 0;font-style:italic;">Aucun commentaire</div>';
    }

    return comments.map(function(c, i) {
        const initials = escapeHtml((c.author || 'U').substring(0, 2).toUpperCase());
        const date = c.timestamp ? new Date(c.timestamp).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : '';
        const globalIndex = data.comments.indexOf(c);

        return `
            <div class="comment-item">
                <div class="comment-avatar">${initials}</div>
                <div class="comment-body">
                    <div class="comment-meta">
                        <span class="comment-author">${escapeHtml(c.author || 'Utilisateur')}</span>
                        <span class="comment-date">${escapeHtml(date)}</span>
                        <span class="comment-category comment-category-${escapeHtml(c.category)}">${escapeHtml(c.category)}</span>
                        <span class="comment-status comment-status-${c.status}">${c.status === 'validated' ? 'Validé' : 'À revoir'}</span>
                    </div>
                    <div class="comment-text">${escapeHtml(c.content)}</div>
                    <div class="comment-actions">
                        <button class="comment-action-btn" onclick="toggleCommentStatus(${globalIndex})">${c.status === 'validated' ? 'Remettre à revoir' : 'Valider'}</button>
                        <button class="comment-action-btn" onclick="deleteComment(${globalIndex})" style="color:var(--error);">Supprimer</button>
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

function addInlineComment(sectionId, elementId) {
    var safeElId = String(elementId).replace(/[^a-zA-Z0-9_-]/g, '_');
    const textEl = document.getElementById('comment-text-' + sectionId + '-' + safeElId);
    const catEl = document.getElementById('comment-cat-' + sectionId + '-' + safeElId);
    const content = textEl.value.trim();
    if (!content) return;

    const comment = {
        id: 'comment-' + Date.now(),
        sectionId: sectionId,
        elementId: elementId,
        author: 'Utilisateur',
        timestamp: new Date().toISOString(),
        content: content,
        status: 'to-review',
        category: catEl.value
    };

    data.comments.push(comment);
    textEl.value = '';

    refreshCommentUI(sectionId, elementId);
    renderReviewPanel();
    autoSave();
}

function toggleCommentStatus(globalIndex) {
    const comment = data.comments[globalIndex];
    if (!comment) return;
    comment.status = comment.status === 'validated' ? 'to-review' : 'validated';
    var elId = comment.elementId || comment.cardIndex;
    refreshCommentUI(comment.sectionId, elId);
    renderReviewPanel();
    autoSave();
}

function deleteComment(globalIndex) {
    if (!confirm('Supprimer ce commentaire ?')) return;
    const comment = data.comments[globalIndex];
    if (!comment) return;
    var sectionId = comment.sectionId;
    var elId = comment.elementId || comment.cardIndex;
    data.comments.splice(globalIndex, 1);
    refreshCommentUI(sectionId, elId);
    renderReviewPanel();
    autoSave();
}

function refreshCommentUI(sectionId, elementId) {
    var safeElId = String(elementId).replace(/[^a-zA-Z0-9_-]/g, '_');
    // Update comment items
    const itemsContainer = document.getElementById('comment-items-' + sectionId + '-' + safeElId);
    if (itemsContainer) {
        itemsContainer.innerHTML = renderCommentItems(sectionId, elementId);
    }

    // Update count badge
    const count = getCommentsForCard(sectionId, elementId).length;
    const container = document.querySelector('.comment-btn-container[data-section-id="' + sectionId + '"][data-element-id="' + elementId + '"]');
    if (container) {
        const badge = container.querySelector('.comment-count');
        if (badge) {
            badge.textContent = count;
            badge.className = 'comment-count' + (count === 0 ? ' empty' : '');
        }
    }
}
