{% extends "base.html" %}

{% block title %}Conflicts - {% if current_project == all_projects_value %}All Projects{% else %}{{ current_project|display_name }}{% endif %} - CodeContext{% endblock %}

{% block content %}
<div class="conflicts-page">
    <h1>Conflict Resolution{% if current_project == all_projects_value %} - All Projects{% endif %}</h1>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-value">{{ pending_count }}</div>
            <div class="stat-label">Pending</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ conflicts|length if conflicts else 0 }}</div>
            <div class="stat-label">Showing</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ resolved_count|default(0) }}</div>
            <div class="stat-label">Resolved</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ info.device|upper if info else 'CPU' }}</div>
            <div class="stat-label">Device</div>
        </div>
    </div>

    <!-- Status Tabs -->
    <div class="conflict-tabs">
        <a href="/conflicts?project={{ current_project }}&status=pending"
           class="conflict-tab {% if current_status == 'pending' %}active{% endif %}">
            Pending
            {% if pending_count > 0 %}
            <span class="tab-badge">{{ pending_count }}</span>
            {% endif %}
        </a>
        <a href="/conflicts?project={{ current_project }}&status=resolved"
           class="conflict-tab {% if current_status == 'resolved' %}active{% endif %}">
            Resolved
        </a>
        <a href="/conflicts?project={{ current_project }}&status=all"
           class="conflict-tab {% if current_status == 'all' %}active{% endif %}">
            All
        </a>

        <!-- Auto-Resolve Toggle -->
        <div class="auto-resolve-toggle" title="When enabled, new conflicts are automatically resolved by AI as they're detected">
            <label class="toggle-switch">
                <input type="checkbox" id="auto-resolve-toggle"
                       onchange="toggleAutoResolve(this.checked)"
                       {% if auto_resolve_enabled %}checked{% endif %}>
                <span class="toggle-slider"></span>
            </label>
            <span class="toggle-label">Auto-Resolve</span>
        </div>

        {% if pending_count > 0 %}
        <button id="auto-resolve-btn" class="btn btn-primary auto-resolve-btn" onclick="autoResolveAll()">
            <span class="btn-text">✨ Auto-Resolve</span>
            <span class="btn-spinner" style="display: none;">
                <span class="spinner"></span>
                <span class="btn-progress">Resolving...</span>
            </span>
        </button>
        {% endif %}
    </div>

    <!-- Progress Indicator (hidden by default) -->
    <div id="progress-container" class="progress-container" style="display: none;">
        <div class="progress-header">
            <span class="progress-phase" id="progress-phase">Initializing...</span>
            <span class="progress-time" id="progress-time"></span>
        </div>
        <div class="progress-bar-wrapper">
            <div class="progress-bar" id="progress-bar"></div>
        </div>
        <div class="progress-detail" id="progress-detail">Preparing to analyze conflicts...</div>
    </div>

    <div class="conflict-list" id="conflict-list">
        {% if conflicts %}
        {% for c in conflicts %}
        <div class="conflict-card" data-conflict-id="{{ c.id }}" data-status="{{ c.conflict_status }}" data-project="{{ c.project }}">
            <div class="conflict-card-header">
                <span class="conflict-status-badge {{ c.conflict_status }}">{{ c.conflict_status|upper }}</span>
                {% if current_project == all_projects_value %}
                <span class="project-tag">{{ c.project|display_name }}</span>
                {% endif %}
                {% if c.confidence %}
                <span class="confidence-badge confidence-{{ c.confidence }}" title="Confidence: {{ c.confidence }}">
                    {% if c.confidence == 'auto' %}⚡ Auto{% elif c.confidence == 'high' %}🎯 High{% elif c.confidence == 'medium' %}📊 Medium{% else %}🔍 Low{% endif %}
                </span>
                {% endif %}
                {% if c.distance %}
                <span class="distance-badge" title="L2 distance (lower = more similar)">
                    📏 {{ '%.2f'|format(c.distance) }}
                </span>
                {% endif %}
                {% if c.detected_at %}
                <span class="memory-date" data-utc-time="{{ c.detected_at }}" data-time-prefix="Detected: ">Detected: {{ c.formatted_date }}</span>
                {% endif %}
            </div>

            <div class="conflict-comparison">
                <!-- NEW Memory (left) -->
                <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" data-utc-time="{{ c.created_at or '' }}">{{ c.formatted_date if c.formatted_date else '' }}</span>
                    </div>
                    <h4 class="conflict-title">{{ c.title }}</h4>
                    <p class="conflict-fact">{{ c.fact }}</p>
                    {% if c.files %}
                    <div class="conflict-files">
                        {% for f in c.files %}
                        <code>{{ f }}</code>
                        {% endfor %}
                    </div>
                    {% endif %}
                </div>

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

                <!-- EXISTING Memory (right) -->
                <div class="conflict-side conflict-existing">
                    {% if c.conflict_with %}
                    <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" data-utc-time="{{ c.conflict_with.created_at or '' }}">{{ c.conflict_with.formatted_date if c.conflict_with.formatted_date else '' }}</span>
                    </div>
                    <h4 class="conflict-title">{{ c.conflict_with.title }}</h4>
                    <p class="conflict-fact">{{ c.conflict_with.fact }}</p>
                    {% if c.conflict_with.files %}
                    <div class="conflict-files">
                        {% for f in c.conflict_with.files %}
                        <code>{{ f }}</code>
                        {% endfor %}
                    </div>
                    {% endif %}
                    {% else %}
                    <div class="conflict-missing">
                        <p>Original memory not found (may have been deleted)</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            {% if c.conflict_status == 'resolved' %}
            <div class="conflict-resolved-info">
                <span class="resolved-label">Resolution:</span>
                <span class="resolved-value">{{ c.conflict_resolution or 'N/A' }}</span>
            </div>
            {% endif %}
        </div>
        {% endfor %}
        {% else %}
        <div class="empty-state" id="empty-state">
            {% if current_status == 'pending' %}
            <p>No pending conflicts. All memories are consistent!</p>
            {% elif current_status == 'resolved' %}
            <p>No resolved conflicts yet.</p>
            {% else %}
            <p>No conflicts found.</p>
            {% endif %}
        </div>
        {% endif %}
    </div>
</div>

<!-- Preview Auto-Resolve Modal -->
<div id="preview-modal" class="modal" style="display: none;">
    <div class="modal-backdrop" onclick="closePreviewModal()"></div>
    <div class="modal-content modal-large">
        <div class="modal-header">
            <h3>Preview Auto-Resolve Decisions</h3>
            <button class="modal-close" onclick="closePreviewModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p class="preview-summary">
                Claude analyzed <span id="preview-count">0</span> conflicts. Review decisions below:
            </p>
            <div id="preview-decisions" class="preview-list">
                <!-- Dynamically populated -->
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closePreviewModal()">Cancel</button>
            <button id="apply-all-btn" class="btn btn-primary" onclick="applyAllDecisions()">
                Apply All (<span id="apply-count">0</span>)
            </button>
        </div>
    </div>
</div>

<script>
const currentProject = '{{ current_project }}';
const allProjectsValue = '{{ all_projects_value }}';
const isAllProjects = currentProject === allProjectsValue;
const currentStatus = '{{ current_status }}';
let pendingDecisions = [];  // Store decisions for preview/apply
let progressStartTime = null;
let progressInterval = null;

// Track known conflicts for API-based refresh
let knownConflictIds = new Set(
    Array.from(document.querySelectorAll('.conflict-card')).map(c => c.dataset.conflictId)
);
let knownPendingCount = {{ pending_count }};

// Progress management functions
function showProgress(phase, detail, percent) {
    const container = document.getElementById('progress-container');
    const phaseEl = document.getElementById('progress-phase');
    const detailEl = document.getElementById('progress-detail');
    const barEl = document.getElementById('progress-bar');
    const statsGrid = document.querySelector('.stats-grid');

    container.style.display = 'block';
    phaseEl.textContent = phase;
    detailEl.textContent = detail;
    barEl.style.width = `${percent}%`;

    // Add pulsing effect to stats
    if (statsGrid) statsGrid.classList.add('processing');
}

function hideProgress() {
    const container = document.getElementById('progress-container');
    const statsGrid = document.querySelector('.stats-grid');

    container.style.display = 'none';
    if (statsGrid) statsGrid.classList.remove('processing');

    if (progressInterval) {
        clearInterval(progressInterval);
        progressInterval = null;
    }
}

function updateElapsedTime() {
    if (!progressStartTime) return;

    const elapsed = Math.floor((Date.now() - progressStartTime) / 1000);
    const timeEl = document.getElementById('progress-time');

    if (elapsed < 60) {
        timeEl.textContent = `${elapsed}s`;
    } else {
        const mins = Math.floor(elapsed / 60);
        const secs = elapsed % 60;
        timeEl.textContent = `${mins}m ${secs}s`;
    }
}

function startProgressTimer() {
    progressStartTime = Date.now();
    progressInterval = setInterval(updateElapsedTime, 1000);
}

// Toggle auto-resolve setting
async function toggleAutoResolve(enabled) {
    try {
        const response = await fetch(`/api/settings/auto-resolve?enabled=${enabled}`, {
            method: 'POST'
        });
        const data = await response.json();

        if (response.ok) {
            if (enabled && data.processing_existing) {
                showToast('⚡ Auto-resolve enabled - processing existing conflicts...', 'success');
                // Trigger a refresh after a short delay to show updated list
                setTimeout(() => checkForConflictUpdates(), 2000);
            } else if (enabled) {
                showToast('⚡ Auto-resolve enabled', 'success');
            } else {
                showToast('Auto-resolve disabled', 'success');
            }
        } else {
            showToast(data.detail || 'Failed to update setting', 'error');
            // Revert the toggle
            document.getElementById('auto-resolve-toggle').checked = !enabled;
        }
    } catch (err) {
        console.error('Toggle error:', err);
        showToast('Network error updating setting', 'error');
        // Revert the toggle
        document.getElementById('auto-resolve-toggle').checked = !enabled;
    }
}

// API-based refresh - fetches conflicts and updates DOM without page reload
async function checkForConflictUpdates() {
    // Skip if auto-resolve is in progress or modal is open
    if (window.autoResolveInProgress) return;
    if (document.getElementById('preview-modal').style.display === 'flex') return;

    try {
        const response = await fetch(`/api/conflicts?project=${encodeURIComponent(currentProject)}&status=${currentStatus}`);
        const data = await response.json();

        const conflictList = document.getElementById('conflict-list');
        const newConflictIds = new Set(data.conflicts.map(c => c.id));

        // Check if anything changed
        const addedIds = [...newConflictIds].filter(id => !knownConflictIds.has(id));
        const removedIds = [...knownConflictIds].filter(id => !newConflictIds.has(id));

        if (addedIds.length === 0 && removedIds.length === 0) {
            // No changes to conflict list, just update counts
            updatePendingCount();
            return;
        }

        // Remove cards that no longer exist
        removedIds.forEach(id => {
            const card = document.querySelector(`[data-conflict-id="${id}"]`);
            if (card) card.remove();
        });

        // Add new cards at the top
        addedIds.forEach(id => {
            const conflict = data.conflicts.find(c => c.id === id);
            if (conflict) {
                const card = createConflictCard(conflict, isAllProjects);
                conflictList.insertBefore(card, conflictList.firstChild);
            }
        });

        // Update known IDs
        knownConflictIds = newConflictIds;

        // Handle empty state
        const emptyState = document.getElementById('empty-state');
        if (data.conflicts.length === 0) {
            if (!emptyState) {
                const emptyDiv = document.createElement('div');
                emptyDiv.className = 'empty-state';
                emptyDiv.id = 'empty-state';
                emptyDiv.innerHTML = '<p>No pending conflicts. All memories are consistent!</p>';
                conflictList.appendChild(emptyDiv);
            }
        } else if (emptyState) {
            emptyState.remove();
        }

        // Update showing count stat
        const showingStatCards = document.querySelectorAll('.stat-card .stat-value');
        if (showingStatCards[1]) {
            showingStatCards[1].textContent = data.conflicts.length;
        }

        // Update pending count
        updatePendingCount();

    } catch (err) {
        console.error('Failed to check for conflict updates:', err);
    }
}

// Start polling via PollingManager
function startAutoRefresh() {
    PollingManager.subscribe('conflicts-list', checkForConflictUpdates, 500);
}

// Stop polling via PollingManager
function stopAutoRefresh() {
    PollingManager.unsubscribe('conflicts-list');
}

async function autoResolveAll() {
    // Signal to base.html's updateConflictsBadge() to skip updates (preserves spinner)
    window.autoResolveInProgress = true;

    // Stop auto-refresh while we're processing
    stopAutoRefresh();

    const btn = document.getElementById('auto-resolve-btn');
    const btnText = btn.querySelector('.btn-text');
    const btnSpinner = btn.querySelector('.btn-spinner');
    const btnProgress = btn.querySelector('.btn-progress');

    // Get badges to show loading state
    const navBadge = document.querySelector('.nav-conflicts .nav-badge');
    const tabBadge = document.querySelector('.conflict-tab.active .tab-badge');
    const pendingStat = document.querySelector('.stat-card .stat-value');

    // Store original values for restoration on error
    const originalNavBadge = navBadge ? navBadge.innerHTML : '';
    const originalTabBadge = tabBadge ? tabBadge.innerHTML : '';
    const originalStatValue = pendingStat ? pendingStat.innerHTML : '';

    // Set badges to loading state
    if (navBadge) navBadge.innerHTML = '<span class="badge-spinner"></span>';
    if (tabBadge) tabBadge.innerHTML = '<span class="badge-spinner"></span>';
    if (pendingStat) pendingStat.innerHTML = '<span class="stat-spinner"></span>';

    // Disable button and show spinner
    btn.disabled = true;
    btnText.style.display = 'none';
    btnSpinner.style.display = 'inline-flex';
    btnProgress.textContent = 'Starting...';

    // Show progress bar
    showProgress('Starting', 'Initializing auto-resolve...', 0);
    startProgressTimer();

    // Use Server-Sent Events for real-time progress
    const url = `/api/conflicts/auto-resolve/stream?project=${encodeURIComponent(currentProject)}`;
    const eventSource = new EventSource(url);

    eventSource.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);
            const phase = data.phase;
            const progress = data.progress || 0;
            const message = data.message || '';

            // Update button progress text and progress bar
            btnProgress.textContent = formatAutoResolvePhase(phase, data);
            showProgress(formatAutoResolvePhase(phase, data), message, progress);

            // Handle completion
            if (phase === 'complete') {
                eventSource.close();
                hideProgress();

                const results = data.results;
                if (!results || results.count === 0) {
                    showToast('No conflicts to resolve', 'info');
                    restoreAutoResolveButton(btn, btnText, btnSpinner, navBadge, tabBadge, pendingStat, originalNavBadge, originalTabBadge, originalStatValue);
                    return;
                }

                // Store decisions for preview/apply
                pendingDecisions = results.decisions || [];
                showPreviewModal(pendingDecisions);

                // Restore button only - keep badges as spinners until flow completes
                btn.disabled = false;
                btnText.style.display = 'inline';
                btnSpinner.style.display = 'none';
            }

            // Handle error
            if (phase === 'error') {
                eventSource.close();
                hideProgress();
                showToast(message || 'Auto-resolve failed', 'error');
                restoreAutoResolveButton(btn, btnText, btnSpinner, navBadge, tabBadge, pendingStat, originalNavBadge, originalTabBadge, originalStatValue);
            }
        } catch (e) {
            console.error('Error parsing SSE event:', e);
        }
    };

    eventSource.onerror = (error) => {
        console.error('SSE connection error:', error);
        eventSource.close();
        hideProgress();
        showToast('Connection lost during auto-resolve', 'error');
        restoreAutoResolveButton(btn, btnText, btnSpinner, navBadge, tabBadge, pendingStat, originalNavBadge, originalTabBadge, originalStatValue);
    };
}

function formatAutoResolvePhase(phase, data) {
    switch (phase) {
        case 'starting':
            return 'Starting...';
        case 'loading_conflicts':
            return 'Loading conflicts...';
        case 'loaded_conflicts':
            return `Found ${data.count || 0} conflicts`;
        case 'tiering':
            return 'Analyzing complexity...';
        case 'tiered':
            return `Auto: ${data.tiers?.auto || 0}, LLM: ${(data.tiers?.llm_batch || 0) + (data.tiers?.low_confidence || 0)}`;
        case 'processing_auto':
            return `Auto-resolving ${data.current || 0}/${data.total || 0}...`;
        case 'processing_llm':
            return `Analyzing ${data.count || 0} with Claude...`;
        case 'llm_complete':
            return 'Analysis complete';
        case 'processing_conflict':
            return `Processing ${data.current || 0}/${data.total || 0}...`;
        case 'complete':
            return 'Done!';
        case 'error':
            return 'Error';
        default:
            return phase.replace(/_/g, ' ');
    }
}

function restoreAutoResolveButton(btn, btnText, btnSpinner, navBadge, tabBadge, pendingStat, originalNavBadge, originalTabBadge, originalStatValue) {
    // Clear flag so badge polling resumes
    window.autoResolveInProgress = false;

    btn.disabled = false;
    btnText.style.display = 'inline';
    btnSpinner.style.display = 'none';

    if (navBadge) navBadge.innerHTML = originalNavBadge;
    if (tabBadge) tabBadge.innerHTML = originalTabBadge;
    if (pendingStat) pendingStat.innerHTML = originalStatValue;

    // Restart API-based auto-refresh
    startAutoRefresh();
}

function showPreviewModal(decisions) {
    document.getElementById('preview-count').textContent = decisions.length;
    document.getElementById('apply-count').textContent = decisions.length;

    const container = document.getElementById('preview-decisions');
    container.innerHTML = decisions.map((d, i) => {
        const conflict = d.conflict || {};
        const title = conflict.title || 'Unknown conflict';
        const isOrphaned = !conflict.conflict_with;

        // Build detail HTML for merge decisions (like consolidation)
        let detailHtml = '';
        if (d.decision === 'merge' && d.merged_fact) {
            detailHtml = `
                <div class="decision-merged">
                    <p><strong>Merged Fact:</strong> ${escapeHtml(d.merged_fact)}</p>
                </div>
            `;
        }

        return `
            <div class="preview-item" data-index="${i}">
                <div class="preview-item-header">
                    <span class="preview-number">#${i + 1}</span>
                    <span class="preview-title">${escapeHtml(title)}</span>
                    <span class="decision-badge decision-${d.decision}">${d.decision.replace('_', ' ')}</span>
                    ${isOrphaned ? '<span class="preview-orphan-badge">Orphaned</span>' : ''}
                </div>
                <div class="preview-item-body">
                    <p class="preview-reasoning">${escapeHtml(d.reasoning || 'No reasoning provided')}</p>
                    ${detailHtml}
                </div>
            </div>
        `;
    }).join('');

    document.getElementById('preview-modal').style.display = 'flex';
}

async function applyAllDecisions() {
    const btn = document.getElementById('apply-all-btn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span> Applying...';

    try {
        const response = await fetch(
            `/api/conflicts/apply-decisions?project=${encodeURIComponent(currentProject)}`,
            {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ decisions: pendingDecisions })
            }
        );
        const data = await response.json();

        if (response.ok) {
            showToast(`✨ Applied ${data.applied} resolution${data.applied !== 1 ? 's' : ''}!`, 'success');
            closePreviewModal();
            // Trigger immediate refresh to show updated state
            checkForConflictUpdates();
        } else {
            showToast(data.detail || 'Apply failed', 'error');
            btn.disabled = false;
            btn.innerHTML = `Apply All (<span id="apply-count">${pendingDecisions.length}</span>)`;
        }
    } catch (err) {
        console.error('Apply decisions error:', err);
        showToast('Network error', 'error');
        btn.disabled = false;
        btn.innerHTML = `Apply All (<span id="apply-count">${pendingDecisions.length}</span>)`;
    }
}

function closePreviewModal() {
    document.getElementById('preview-modal').style.display = 'none';
    pendingDecisions = [];

    // Clear flag so badge polling resumes
    window.autoResolveInProgress = false;

    // Restart API-based auto-refresh when modal closes
    startAutoRefresh();
}

async function updatePendingCount() {
    try {
        const response = await fetch(`/api/pending-conflicts-count?project=${encodeURIComponent(currentProject)}`);
        const data = await response.json();

        // Update nav badge
        const navBadge = document.querySelector('.nav-conflicts .nav-badge');
        if (data.count > 0) {
            if (navBadge) {
                navBadge.textContent = data.count;
            } else {
                const navLink = document.querySelector('.nav-conflicts');
                if (navLink) {
                    const badge = document.createElement('span');
                    badge.className = 'nav-badge';
                    badge.textContent = data.count;
                    navLink.appendChild(badge);
                }
            }
        } else if (navBadge) {
            navBadge.remove();
        }

        // Update stat card
        const pendingStat = document.querySelector('.stat-value');
        if (pendingStat) pendingStat.textContent = data.count;

        // Update tab badge
        const tabBadge = document.querySelector('.conflict-tab.active .tab-badge');
        if (tabBadge) tabBadge.textContent = data.count;
    } catch (err) {
        console.error('Failed to update pending count:', err);
    }
}

// Close modals on Escape key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        closePreviewModal();
    }
});

// Start API-based auto-refresh (500ms interval, no page reloads)
startAutoRefresh();
</script>
{% endblock %}
