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

/**
 * Comments are stored in data.comments[] with structure:
 * { id, sectionId, cardIndex, author, timestamp, content, status, category }
 *
 * - sectionId: matches the section div id (e.g. "cadrage-problem", "module-spec-Clients")
 * - cardIndex: index of the card within that section (0-based)
 * - status: "to-review" | "validated"
 * - category: "clarification" | "correction" | "suggestion"
 */

function initInlineComments() {
    // Cadrage sections: direct card children
    document.querySelectorAll('.section > .card, .section > .stakeholder-card, .section > .uc-item, .section > .risk-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, :scope > .risk-item'));
        var index = siblings.indexOf(card);
        card.appendChild(createCommentUI(sectionId, index));
    });

    // 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);
        item.appendChild(createCommentUI(listId, index));
    });

    // 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);
        card.appendChild(createCommentUI(sectionId, index));
    });

    // Scope items
    ['scopeVital', 'scopeImportant', 'scopeOptional', 'scopeExcluded'].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';
            item.appendChild(createCommentUI(containerId, index));
        });
    });
}

function createCommentUI(sectionId, cardIndex) {
    const comments = getCommentsForCard(sectionId, cardIndex);
    const count = comments.length;

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

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

    return container;
}

function getCommentsForCard(sectionId, cardIndex) {
    return (data.comments || []).filter(c =>
        c.sectionId === sectionId && c.cardIndex === cardIndex
    );
}

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

function renderCommentItems(sectionId, cardIndex) {
    const comments = getCommentsForCard(sectionId, cardIndex);
    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((c, i) => {
        const initials = (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">${c.author || 'Utilisateur'}</span>
                        <span class="comment-date">${date}</span>
                        <span class="comment-category comment-category-${c.category}">${c.category}</span>
                        <span class="comment-status comment-status-${c.status}">${c.status === 'validated' ? 'Valide' : 'A revoir'}</span>
                    </div>
                    <div class="comment-text">${c.content}</div>
                    <div class="comment-actions">
                        <button class="comment-action-btn" onclick="toggleCommentStatus(${globalIndex})">${c.status === 'validated' ? 'Remettre a revoir' : 'Valider'}</button>
                        <button class="comment-action-btn" onclick="deleteComment(${globalIndex})" style="color:var(--error);">Supprimer</button>
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

function addInlineComment(sectionId, cardIndex) {
    const textEl = document.getElementById('comment-text-' + sectionId + '-' + cardIndex);
    const catEl = document.getElementById('comment-cat-' + sectionId + '-' + cardIndex);
    const content = textEl.value.trim();
    if (!content) return;

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

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

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

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

function deleteComment(globalIndex) {
    const comment = data.comments[globalIndex];
    if (!comment) return;
    const sectionId = comment.sectionId;
    const cardIndex = comment.cardIndex;
    data.comments.splice(globalIndex, 1);
    refreshCommentUI(sectionId, cardIndex);
    renderReviewPanel();
    autoSave();
}

function refreshCommentUI(sectionId, cardIndex) {
    // Update comment items
    const itemsContainer = document.getElementById('comment-items-' + sectionId + '-' + cardIndex);
    if (itemsContainer) {
        itemsContainer.innerHTML = renderCommentItems(sectionId, cardIndex);
    }

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