<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}CodeContext{% endblock %}</title>
    <link rel="stylesheet" href="/static/style.css">
    <script src="/static/shared-ui.js"></script>
    <script src="/static/card-builders.js"></script>
    <script src="/static/polling-manager.js"></script>
    <script>
        // Theme initialization - runs before page renders to prevent flash
        (function() {
            const saved = localStorage.getItem('theme');
            if (saved === 'dark' || saved === 'light') {
                document.documentElement.setAttribute('data-theme', saved);
            }
            // If no saved preference, system preference is used via CSS media query
        })();

        // Format ISO UTC timestamp to user's local time (12hr with AM/PM)
        function formatLocalTime(isoString) {
            if (!isoString) return '';
            const date = new Date(isoString); // ISO strings with +00:00 are already UTC-aware
            return date.toLocaleString('en-US', {
                month: 'short',
                day: 'numeric',
                year: 'numeric',
                hour: 'numeric',
                minute: '2-digit',
                hour12: true
            });
        }

        // Auto-convert all UTC timestamps on page load
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('[data-utc-time]').forEach(el => {
                const formatted = formatLocalTime(el.dataset.utcTime);
                if (formatted) {
                    // Preserve any prefix text (like "Detected: ")
                    const prefix = el.dataset.timePrefix || '';
                    el.textContent = prefix + formatted;
                }
            });
        });
    </script>
</head>
<body>
    <nav class="navbar">
        <div class="nav-brand">CodeContext</div>
        <div class="nav-links">
            <a href="/?project={{ current_project }}" class="{% if request.url.path == '/' %}active{% endif %}">Dashboard</a>
            <a href="/search?project={{ current_project }}" class="{% if request.url.path == '/search' %}active{% endif %}">Search</a>
            <a href="/conflicts?project={{ current_project }}" class="{% if request.url.path == '/conflicts' %}active{% endif %} nav-conflicts">
                Conflicts
                {% if info and info.get('pending_conflicts', 0) > 0 %}
                <span class="nav-badge">{{ info.pending_conflicts }}</span>
                {% endif %}
            </a>
            <a href="/consolidation?project={{ current_project }}" class="{% if request.url.path == '/consolidation' %}active{% endif %}">
                Consolidate
            </a>
            <a href="/summaries?project={{ current_project }}" class="{% if request.url.path == '/summaries' %}active{% endif %}">
                Summaries
            </a>
            <a href="/archive?project={{ current_project }}" class="{% if request.url.path == '/archive' %}active{% endif %}">
                Archive
            </a>
            <a href="/health" target="_blank">API Health</a>
        </div>

        <!-- Project Selector -->
        <div class="project-selector">
            <label for="project-select">Project:</label>
            <select id="project-select" onchange="switchProject(this.value)">
                <option value="{{ all_projects_value }}" {% if current_project == all_projects_value %}selected{% endif %}>
                    All Projects
                </option>
                {% if projects %}
                    {% for p in projects %}
                    <option value="{{ p }}" {% if p == current_project %}selected{% endif %}>{{ p|display_name }}</option>
                    {% endfor %}
                {% endif %}
            </select>
        </div>

        <div class="nav-status">
            {% if info %}
            <span class="status-badge {{ 'gpu' if info.device == 'cuda' else 'cpu' }}">
                {{ info.device|upper }}
            </span>
            <span class="status-count">{{ info.memory_count if info.memory_count else 0 }} memories</span>
            {% if info.token_count %}
            <span class="status-count status-tokens" title="Estimated tokens in all memories">~{{ "{:,}".format(info.token_count) }} tokens</span>
            {% endif %}
            {% endif %}
            <button class="theme-toggle" id="theme-toggle" title="Toggle theme">
                <svg id="theme-icon-light" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
                </svg>
                <svg id="theme-icon-dark" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" style="display:none;">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
                </svg>
            </button>
        </div>
    </nav>

    <main class="container">
        {% block content %}{% endblock %}
    </main>

    <footer class="footer">
        <p>Project: <strong>{{ current_project|display_name if current_project else 'None' }}</strong> |
           Device: {{ info.device|upper if info else '...' }} |
           Dimensions: {{ info.embedding_dim if info else '...' }}</p>
    </footer>

    <script>
        function switchProject(project) {
            const url = new URL(window.location.href);
            url.searchParams.set('project', project);
            window.location.href = url.toString();
        }

        // === PROJECT DISPLAY NAMES ===
        // Mapping of encoded project names to display names
        const projectDisplayNames = {
            {% for p in projects %}'{{ p }}': '{{ p|display_name }}'{% if not loop.last %}, {% endif %}{% endfor %}
        };

        function getProjectDisplayName(encodedName) {
            return projectDisplayNames[encodedName] || encodedName;
        }

        // === THEME TOGGLE ===
        (function initThemeToggle() {
            const toggle = document.getElementById('theme-toggle');
            const iconLight = document.getElementById('theme-icon-light');
            const iconDark = document.getElementById('theme-icon-dark');

            function getEffectiveTheme() {
                const saved = localStorage.getItem('theme');
                if (saved) return saved;
                return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
            }

            function updateIcons(theme) {
                if (theme === 'dark') {
                    iconLight.style.display = 'none';
                    iconDark.style.display = 'block';
                } else {
                    iconLight.style.display = 'block';
                    iconDark.style.display = 'none';
                }
            }

            function setTheme(theme) {
                document.documentElement.setAttribute('data-theme', theme);
                localStorage.setItem('theme', theme);
                updateIcons(theme);
            }

            // Initialize icons based on current theme
            updateIcons(getEffectiveTheme());

            // Toggle on click
            if (toggle) {
                toggle.addEventListener('click', () => {
                    const current = getEffectiveTheme();
                    const newTheme = current === 'dark' ? 'light' : 'dark';
                    setTheme(newTheme);
                });
            }

            // Listen for system preference changes
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
                // Only update if user hasn't set a manual preference
                if (!localStorage.getItem('theme')) {
                    updateIcons(e.matches ? 'dark' : 'light');
                }
            });
        })();

        // Live badge update - polls pending conflicts count on all pages
        async function updateConflictsBadge() {
            // Skip updates while auto-resolve is in progress (spinner would be overwritten)
            if (window.autoResolveInProgress) return;

            const projectSelect = document.getElementById('project-select');
            const project = projectSelect ? projectSelect.value : '';
            if (!project) return;

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

                const navConflicts = document.querySelector('.nav-conflicts');
                if (!navConflicts) return;

                let badge = navConflicts.querySelector('.nav-badge');

                if (data.count > 0) {
                    if (!badge) {
                        badge = document.createElement('span');
                        badge.className = 'nav-badge';
                        navConflicts.appendChild(badge);
                    }
                    badge.textContent = data.count;
                } else if (badge) {
                    badge.remove();
                }
            } catch (err) {
                console.error('Failed to update conflicts badge:', err);
            }
        }

        // Update immediately on page load, then use PollingManager for 500ms polling
        updateConflictsBadge();
        PollingManager.subscribe('conflicts-badge', updateConflictsBadge, 500);
    </script>
</body>
</html>
