{% extends "base.html" %}

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

{% block content %}
<div class="dashboard">
    <h1>{% if current_project == all_projects_value %}All Projects{% elif current_project %}{{ current_project|display_name }}{% else %}Memory Dashboard{% endif %}</h1>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-value">{{ total_count }}</div>
            <div class="stat-label">Memories</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">{{ projects|length if projects else 0 }}</div>
            <div class="stat-label">Projects</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 class="stat-card">
            <div class="stat-value">{{ info.embedding_dim if info else 384 }}</div>
            <div class="stat-label">Dimensions</div>
        </div>
    </div>

    <div class="memory-list">
        <div class="section-header">
            <h2>All Memories</h2>
            <span class="memory-count">{{ total_count }} total</span>
            <div class="debug-mode-toggle" title="When enabled, CLI sessions create JSONL files for debugging">
                <label class="toggle-switch">
                    <input type="checkbox" id="debug-mode-toggle" {% if debug_mode %}checked{% endif %}>
                    <span class="toggle-slider"></span>
                </label>
                <span class="toggle-label">Debug</span>
            </div>
            <div class="auto-refresh-toggle">
                <label class="toggle-switch">
                    <input type="checkbox" id="auto-refresh-toggle">
                    <span class="toggle-slider"></span>
                </label>
                <span class="toggle-label">Auto-refresh</span>
                <span id="refresh-status" class="refresh-status"></span>
            </div>
        </div>

        <!-- Filter Bar -->
        <div class="filter-bar">
            <div class="filter-group">
                <label>Type:</label>
                <div class="filter-chips" id="type-filters">
                    <button type="button" class="filter-chip" data-value="bugfix">Bugfix</button>
                    <button type="button" class="filter-chip" data-value="feature">Feature</button>
                    <button type="button" class="filter-chip" data-value="discovery">Discovery</button>
                    <button type="button" class="filter-chip" data-value="decision">Decision</button>
                    <button type="button" class="filter-chip" data-value="refactor">Refactor</button>
                    <button type="button" class="filter-chip" data-value="optimization">Optimization</button>
                    <button type="button" class="filter-chip" data-value="gotcha">Gotcha</button>
                </div>
                <button type="button" id="clear-type-filter" class="btn-clear" title="Clear filter" style="display: none;">×</button>
            </div>
            <div class="filter-group file-filter">
                <label for="file-filter">File:</label>
                <input type="text"
                       id="file-filter"
                       placeholder="Filter by file..."
                       list="file-suggestions"
                       autocomplete="off">
                <datalist id="file-suggestions"></datalist>
                <button type="button" id="clear-file-filter" class="btn-clear" title="Clear filter" style="display: none;">×</button>
            </div>
            <div class="filter-group">
                <label for="sort-order">Sort:</label>
                <select id="sort-order">
                    <option value="newest">Newest First</option>
                    <option value="oldest">Oldest First</option>
                </select>
            </div>
            <span id="filter-status" class="filter-status"></span>
        </div>

        {% if memories %}
        <div class="memory-cards">
            {% for m in memories %}
            <div class="memory-card type-{{ m.type }}">
                <div class="memory-card-header">
                    <span class="type-badge">{{ m.type }}</span>
                    {% if current_project == all_projects_value %}
                    <span class="project-tag">{{ m.project|display_name }}</span>
                    {% endif %}
                    {% if m.created_at %}
                    <span class="memory-date" data-utc-time="{{ m.created_at }}">{{ m.formatted_date }}</span>
                    {% endif %}
                </div>
                <div class="memory-card-body">
                    <h3 class="memory-card-title">{{ m.title }}</h3>
                    <p class="memory-card-fact">{{ m.fact }}</p>
                </div>
                {% if m.files %}
                <div class="memory-card-footer">
                    <div class="memory-card-footer-label">Related Files</div>
                    <div class="memory-card-files">
                        {% for f in m.files %}
                        <code class="clickable-file" data-file="{{ f }}">{{ f }}</code>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
            </div>
            {% endfor %}
        </div>

        <!-- Infinite scroll elements -->
        <div id="scroll-sentinel" style="height: 1px;"></div>
        <div id="loading-indicator" style="display: none; text-align: center; padding: 1rem;">
            <span class="loading-text">Loading more...</span>
        </div>
        <div id="end-of-list" style="display: none; text-align: center; padding: 1rem; color: var(--text-secondary);">
            No more memories
        </div>
        {% else %}
        <div class="empty-state">
            <p>No memories yet. Start a coding session to generate memories!</p>
        </div>
        {% endif %}
    </div>
</div>

<script>
(function() {
    const LIMIT = 20;
    let offset = {{ memories|length }};
    let loading = false;
    let hasMore = {{ 'true' if memories|length >= 20 else 'false' }};
    const project = '{{ current_project }}';
    const allProjectsValue = '{{ all_projects_value }}';
    const isAllProjects = project === allProjectsValue;

    const container = document.querySelector('.memory-cards');
    const sentinel = document.getElementById('scroll-sentinel');
    const loadingIndicator = document.getElementById('loading-indicator');
    const endOfList = document.getElementById('end-of-list');

    // Filter elements
    const formatFilterContainer = document.getElementById('type-filters');
    const sortOrder = document.getElementById('sort-order');
    const clearTypeBtn = document.getElementById('clear-type-filter');
    const filterStatus = document.getElementById('filter-status');

    // File filter elements
    const fileFilter = document.getElementById('file-filter');
    const clearFileBtn = document.getElementById('clear-file-filter');
    let fileFilterTimeout = null;

    // Don't initialize if no container (empty state)
    if (!container) return;

    // === FILTER FUNCTIONS ===
    function getFilterParams() {
        const activeChips = Array.from(document.querySelectorAll('.filter-chip.active'));
        const selectedTypes = activeChips.map(chip => chip.dataset.value);
        const sort = sortOrder.value;
        const file = fileFilter?.value?.trim() || '';

        return {
            type: selectedTypes.join(','),
            sort: sort,
            file: file
        };
    }

    function updateFilterStatus() {
        const params = getFilterParams();
        const hasTypeFilter = params.type.length > 0;
        const hasFileFilter = params.file.length > 0;

        if (hasTypeFilter || hasFileFilter) {
            const parts = [];
            if (hasTypeFilter) {
                const count = params.type.split(',').length;
                parts.push(`${count} type${count > 1 ? 's' : ''}`);
            }
            if (hasFileFilter) {
                parts.push('file');
            }
            filterStatus.textContent = `Filtering: ${parts.join(', ')}`;
            filterStatus.classList.add('active');
            if (clearTypeBtn) clearTypeBtn.style.display = hasTypeFilter ? 'flex' : 'none';
        } else {
            filterStatus.textContent = '';
            filterStatus.classList.remove('active');
            if (clearTypeBtn) clearTypeBtn.style.display = 'none';
        }

        // Update clear file button visibility
        if (clearFileBtn) clearFileBtn.style.display = hasFileFilter ? 'flex' : 'none';
    }

    async function resetAndReload() {
        // Clear current memories
        container.innerHTML = '';
        offset = 0;
        hasMore = true;

        // Reset end of list / sentinel visibility
        if (endOfList) endOfList.style.display = 'none';
        if (sentinel) sentinel.style.display = 'block';

        // Update filter status display
        updateFilterStatus();

        // Load fresh data with new filters
        await loadMore();
    }

    function createMemoryCard(m) {
        const card = document.createElement('div');
        card.className = `memory-card type-${m.type}`;

        let filesHtml = '';
        if (m.files && m.files.length) {
            filesHtml = `
                <div class="memory-card-footer">
                    <div class="memory-card-footer-label">Related Files</div>
                    <div class="memory-card-files">
                        ${m.files.map(f => `<code class="clickable-file" data-file="${f}">${f}</code>`).join('')}
                    </div>
                </div>
            `;
        }

        // Only show project tag when viewing All Projects
        const projectTagHtml = isAllProjects ? `<span class="project-tag">${getProjectDisplayName(m.project)}</span>` : '';

        // Format date using formatLocalTime from base.html
        const formattedDate = m.created_at ? formatLocalTime(m.created_at) : '';

        card.innerHTML = `
            <div class="memory-card-header">
                <span class="type-badge">${m.type}</span>
                ${projectTagHtml}
                ${formattedDate ? `<span class="memory-date">${formattedDate}</span>` : ''}
            </div>
            <div class="memory-card-body">
                <h3 class="memory-card-title">${m.title}</h3>
                <p class="memory-card-fact">${m.fact}</p>
            </div>
            ${filesHtml}
        `;
        return card;
    }

    async function loadMore() {
        if (loading || !hasMore) return;

        loading = true;
        loadingIndicator.style.display = 'block';

        try {
            const params = getFilterParams();
            let url = `/api/memories?project=${encodeURIComponent(project)}&offset=${offset}&limit=${LIMIT}`;

            // Add filter params if set
            if (params.type) {
                url += `&type=${encodeURIComponent(params.type)}`;
            }
            if (params.file) {
                url += `&file=${encodeURIComponent(params.file)}`;
            }
            if (params.sort && params.sort !== 'newest') {
                url += `&sort=${encodeURIComponent(params.sort)}`;
            }

            const response = await fetch(url);
            const data = await response.json();

            data.memories.forEach(m => {
                container.appendChild(createMemoryCard(m));
            });

            offset += data.memories.length;
            hasMore = data.has_more;

            if (!hasMore) {
                endOfList.style.display = 'block';
                sentinel.style.display = 'none';
            }
        } catch (err) {
            console.error('Failed to load memories:', err);
        } finally {
            loading = false;
            loadingIndicator.style.display = 'none';
        }
    }

    // IntersectionObserver for infinite scroll
    const observer = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore && !loading) {
            loadMore();
        }
    }, { rootMargin: '100px' });

    if (sentinel) observer.observe(sentinel);

    // === FILTER EVENT LISTENERS ===
    if (formatFilterContainer) {
        formatFilterContainer.addEventListener('click', (e) => {
            if (e.target.classList.contains('filter-chip')) {
                e.target.classList.toggle('active');
                resetAndReload();
            }
        });
    }

    if (sortOrder) {
        sortOrder.addEventListener('change', resetAndReload);
    }

    if (clearTypeBtn) {
        clearTypeBtn.addEventListener('click', () => {
            // Deselect all chips
            document.querySelectorAll('.filter-chip.active').forEach(chip => chip.classList.remove('active'));
            resetAndReload();
        });
    }

    // === FILE FILTER EVENT LISTENERS ===
    if (fileFilter) {
        fileFilter.addEventListener('input', (e) => {
            clearTimeout(fileFilterTimeout);
            fileFilterTimeout = setTimeout(() => {
                resetAndReload();
            }, 300);  // Debounce 300ms
        });
    }

    if (clearFileBtn) {
        clearFileBtn.addEventListener('click', () => {
            fileFilter.value = '';
            clearFileBtn.style.display = 'none';
            resetAndReload();
        });
    }

    // Load file suggestions on page load
    async function loadFileSuggestions() {
        try {
            const response = await fetch(`/api/files?project=${encodeURIComponent(project)}`);
            const data = await response.json();
            const datalist = document.getElementById('file-suggestions');
            if (datalist) {
                datalist.innerHTML = data.files.map(f => `<option value="${f}">`).join('');
            }
        } catch (e) {
            console.error('Failed to load file suggestions:', e);
        }
    }

    loadFileSuggestions();

    // === CLICKABLE FILE TAGS ===
    // Use event delegation on the container for dynamically created cards
    container.addEventListener('click', (e) => {
        if (e.target.classList.contains('clickable-file')) {
            const file = e.target.dataset.file;
            if (fileFilter) {
                fileFilter.value = file;
                if (clearFileBtn) clearFileBtn.style.display = 'flex';
                resetAndReload();
            }
        }
    });

    // === DEBUG MODE TOGGLE ===
    document.getElementById('debug-mode-toggle')?.addEventListener('change', async (e) => {
        try {
            const response = await fetch(`/api/settings/debug-mode?enabled=${e.target.checked}`, {
                method: 'POST'
            });
            if (!response.ok) {
                // Revert toggle on failure
                e.target.checked = !e.target.checked;
                console.error('Failed to update debug mode setting');
            }
        } catch (err) {
            // Revert toggle on error
            e.target.checked = !e.target.checked;
            console.error('Error updating debug mode:', err);
        }
    });

    // === AUTO-REFRESH FEATURE ===
    const REFRESH_INTERVAL = 500; // 500ms for instant feedback
    // Default to enabled if not explicitly set
    let autoRefreshEnabled = localStorage.getItem('autoRefresh') !== 'false';
    let refreshTimer = null;
    let knownCount = {{ total_count }};

    const toggleCheckbox = document.getElementById('auto-refresh-toggle');
    const refreshStatus = document.getElementById('refresh-status');
    const totalCountEl = document.querySelector('.stat-value'); // First stat card
    const memoryCountSpan = document.querySelector('.memory-count');

    // Initialize toggle state
    if (toggleCheckbox) {
        toggleCheckbox.checked = autoRefreshEnabled;
        if (autoRefreshEnabled) startAutoRefresh();

        toggleCheckbox.addEventListener('change', (e) => {
            autoRefreshEnabled = e.target.checked;
            localStorage.setItem('autoRefresh', autoRefreshEnabled);

            if (autoRefreshEnabled) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        });
    }

    function startAutoRefresh() {
        if (refreshTimer) return;
        refreshStatus.textContent = 'Live';
        refreshStatus.classList.add('active');
        refreshTimer = setInterval(checkForUpdates, REFRESH_INTERVAL);
    }

    function stopAutoRefresh() {
        if (refreshTimer) {
            clearInterval(refreshTimer);
            refreshTimer = null;
        }
        refreshStatus.textContent = '';
        refreshStatus.classList.remove('active');
    }

    async function checkForUpdates() {
        // Skip auto-refresh if filters are active (would cause confusion)
        const params = getFilterParams();
        if (params.type) return;

        try {
            const response = await fetch(`/api/memories/new?project=${encodeURIComponent(project)}&since_count=${knownCount}`);
            const data = await response.json();

            if (data.memories.length > 0) {
                // Prepend new memories to container (reverse to show newest first)
                data.memories.reverse().forEach(m => {
                    container.insertBefore(createMemoryCard(m), container.firstChild);
                });

                // Update counts
                knownCount = data.total_count;
                offset += data.memories.length;

                if (totalCountEl) totalCountEl.textContent = knownCount;
                if (memoryCountSpan) memoryCountSpan.textContent = `${knownCount} total`;

                // Also update nav status count
                const navStatusCount = document.querySelector('.status-count');
                if (navStatusCount) navStatusCount.textContent = `${knownCount} memories`;
            }
        } catch (err) {
            console.error('Auto-refresh check failed:', err);
        }
    }
})();
</script>
{% endblock %}
