/**
 * Shared card builder functions for CodeContext
 * Dependencies: shared-ui.js (escapeHtml), base.html (formatLocalTime)
 */

/**
 * Create a conflict card element dynamically
 * @param {Object} c - Conflict data object
 * @param {boolean} isAllProjects - Whether viewing all projects (shows project tag)
 * @returns {HTMLElement} The constructed card element
 */
function createConflictCard(c, isAllProjects = false) {
    const card = document.createElement('div');
    card.className = 'conflict-card';
    card.dataset.conflictId = c.id;
    card.dataset.status = c.conflict_status;
    card.dataset.project = c.project;

    // Build confidence badge HTML
    let confidenceBadgeHtml = '';
    if (c.confidence) {
        const confidenceIcons = {
            'auto': '⚡ Auto',
            'high': '🎯 High',
            'medium': '📊 Medium',
            'low': '🔍 Low'
        };
        confidenceBadgeHtml = `
            <span class="confidence-badge confidence-${c.confidence}" title="Confidence: ${c.confidence}">
                ${confidenceIcons[c.confidence] || c.confidence}
            </span>
        `;
    }

    // Build distance badge HTML
    let distanceBadgeHtml = '';
    if (c.distance) {
        distanceBadgeHtml = `
            <span class="distance-badge" title="L2 distance (lower = more similar)">
                📏 ${c.distance.toFixed(2)}
            </span>
        `;
    }

    // Build files HTML for new memory
    let newFilesHtml = '';
    if (c.files && c.files.length) {
        newFilesHtml = `
            <div class="conflict-files">
                ${c.files.map(f => `<code>${escapeHtml(f)}</code>`).join('')}
            </div>
        `;
    }

    // Build existing memory side
    let existingSideHtml = '';
    if (c.conflict_with) {
        let existingFilesHtml = '';
        if (c.conflict_with.files && c.conflict_with.files.length) {
            existingFilesHtml = `
                <div class="conflict-files">
                    ${c.conflict_with.files.map(f => `<code>${escapeHtml(f)}</code>`).join('')}
                </div>
            `;
        }
        const existingDateFormatted = c.conflict_with.created_at ? formatLocalTime(c.conflict_with.created_at) : '';
        existingSideHtml = `
            <div class="conflict-side-header">
                <span class="conflict-side-label">EXISTING</span>
                <span class="type-badge type-${c.conflict_with.type}">${c.conflict_with.type}</span>
                <span class="conflict-side-date">${existingDateFormatted}</span>
            </div>
            <h4 class="conflict-title">${escapeHtml(c.conflict_with.title)}</h4>
            <p class="conflict-fact">${escapeHtml(c.conflict_with.fact)}</p>
            ${existingFilesHtml}
        `;
    } else {
        existingSideHtml = `
            <div class="conflict-missing">
                <p>Original memory not found (may have been deleted)</p>
            </div>
        `;
    }

    // Build resolved info (pending conflicts are read-only, resolved via Auto-Resolve)
    let actionsHtml = '';
    if (c.conflict_status === 'resolved') {
        actionsHtml = `
            <div class="conflict-resolved-info">
                <span class="resolved-label">Resolution:</span>
                <span class="resolved-value">${c.conflict_resolution || 'N/A'}</span>
            </div>
        `;
    }

    // Format dates using formatLocalTime from base.html
    const detectedDateFormatted = c.detected_at ? formatLocalTime(c.detected_at) : '';
    const newDateFormatted = c.created_at ? formatLocalTime(c.created_at) : '';

    card.innerHTML = `
        <div class="conflict-card-header">
            <span class="conflict-status-badge ${c.conflict_status}">${c.conflict_status.toUpperCase()}</span>
            ${isAllProjects ? `<span class="project-tag">${c.project}</span>` : ''}
            ${confidenceBadgeHtml}
            ${distanceBadgeHtml}
            ${detectedDateFormatted ? `<span class="memory-date">Detected: ${detectedDateFormatted}</span>` : ''}
        </div>

        <div class="conflict-comparison">
            <div class="conflict-side conflict-new">
                <div class="conflict-side-header">
                    <span class="conflict-side-label">NEW</span>
                    <span class="type-badge type-${c.type}">${c.type}</span>
                    <span class="conflict-side-date">${newDateFormatted}</span>
                </div>
                <h4 class="conflict-title">${escapeHtml(c.title)}</h4>
                <p class="conflict-fact">${escapeHtml(c.fact)}</p>
                ${newFilesHtml}
            </div>

            <div class="conflict-arrow">
                <span>vs</span>
            </div>

            <div class="conflict-side conflict-existing">
                ${existingSideHtml}
            </div>
        </div>

        ${actionsHtml}
    `;

    return card;
}

/**
 * Create an archive card element dynamically
 * @param {Object} m - Archived memory data object
 * @param {string} currentProject - Current project name (fallback for restore/delete)
 * @returns {HTMLElement} The constructed card element
 */
function createArchiveCard(m, currentProject = '') {
    const card = document.createElement('div');
    card.className = 'archive-card';
    card.dataset.memoryId = m.id;

    const filesHtml = m.files ? m.files.filter(f => f).map(f => `<code>${escapeHtml(f)}</code>`).join('') : '';
    const deletedDate = m.deleted_at ? formatLocalTime(m.deleted_at) : 'Unknown';
    const project = m.project || currentProject;

    card.innerHTML = `
        <div class="archive-card-header">
            <span class="type-badge type-${m.type}">${m.type}</span>
            <span class="archive-reason-badge reason-${m.deletion_reason}">
                ${(m.deletion_reason || '').replace('_', ' ')}
            </span>
            <span class="memory-date">Deleted: ${deletedDate}</span>
        </div>
        <h4 class="archive-title">${escapeHtml(m.title)}</h4>
        <p class="archive-fact">${escapeHtml(m.fact)}</p>
        ${filesHtml ? `<div class="archive-files">${filesHtml}</div>` : ''}
        <div class="archive-actions">
            <button class="btn btn-restore" onclick="restoreMemory('${m.id}', '${project}')">
                Restore
            </button>
            <button class="btn btn-danger" onclick="permanentlyDelete('${m.id}', '${project}')">
                Delete Forever
            </button>
        </div>
    `;
    return card;
}
