{% extends "orbit/base.html" %}

{% block title %}Django Orbit{% endblock %}

{% block body %}
<div x-data="orbitDashboard()" x-init="init()" class="h-full flex bg-grid">
    
    <!-- Sidebar Navigation -->
    <aside class="w-64 border-r border-orbit-border bg-orbit-bg-secondary flex flex-col">
        <!-- Logo / Header -->
        <div class="p-6 border-b border-orbit-border">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-cyan-500 to-violet-500 flex items-center justify-center glow-cyan">
                    <i data-lucide="orbit" class="w-6 h-6 text-white"></i>
                </div>
                <div>
                    <h1 class="text-lg font-semibold text-gradient">Django Orbit</h1>
                    <p class="text-xs text-orbit-text-muted">
                        Obvservability and Debugging
                    </p>
                </div>
            </div>
        </div>
        
        <!-- Navigation Links (scrollable) -->
        <nav class="flex-1 p-4 space-y-1 overflow-y-auto">
            <button 
               @click="setType('all')"
               :class="currentType === 'all' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="layers" class="w-4 h-4"></i>
                <span class="flex-1">All Events</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.all }}</span>
            </button>
            
            <button
               @click="setType('cache')"
               :class="currentType === 'cache' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="hard-drive" class="w-4 h-4 text-orange-400"></i>
                <span class="flex-1">Cache</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.cache }}</span>
            </button>
            
            <button
               @click="setType('command')"
               :class="currentType === 'command' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="terminal" class="w-4 h-4 text-violet-400"></i>
                <span class="flex-1">Commands</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.command }}</span>
            </button>
            
            <button
               @click="setType('dump')"
               :class="currentType === 'dump' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="bug" class="w-4 h-4 text-lime-400"></i>
                <span class="flex-1">Dumps</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.dump }}</span>
            </button>
            
            <button
               @click="setType('exception')"
               :class="currentType === 'exception' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="alert-triangle" class="w-4 h-4 text-rose-400"></i>
                <span class="flex-1">Exceptions</span>
                {% if counts.exception > 0 %}
                <span class="text-xs bg-rose-500/20 text-rose-400 px-2 py-0.5 rounded-full">{{ counts.exception }}</span>
                {% else %}
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">0</span>
                {% endif %}
            </button>
            
            <button
               @click="setType('http_client')"
               :class="currentType === 'http_client' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="send" class="w-4 h-4 text-pink-400"></i>
                <span class="flex-1">HTTP Client</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.http_client }}</span>
            </button>
            
            <button
               @click="setType('job')"
               :class="currentType === 'job' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="clock" class="w-4 h-4 text-amber-400"></i>
                <span class="flex-1">Jobs</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.job }}</span>
            </button>
            
            <button
               @click="setType('log')"
               :class="currentType === 'log' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="file-text" class="w-4 h-4 text-slate-400"></i>
                <span class="flex-1">Logs</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.log }}</span>
            </button>
            
            <button
               @click="setType('model')"
               :class="currentType === 'model' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="box" class="w-4 h-4 text-blue-400"></i>
                <span class="flex-1">Models</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.model }}</span>
            </button>
            
            <button
               @click="setType('query')"
               :class="currentType === 'query' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="database" class="w-4 h-4 text-emerald-400"></i>
                <span class="flex-1">Queries</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.query }}</span>
            </button>
            
            <button
               @click="setType('request')"
               :class="currentType === 'request' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="globe" class="w-4 h-4 text-cyan-400"></i>
                <span class="flex-1">Requests</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.request }}</span>
            </button>
            
            <button
               @click="setType('mail')"
               :class="currentType === 'mail' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="mail" class="w-4 h-4 text-fuchsia-400"></i>
                <span class="flex-1">Mail</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.mail }}</span>
            </button>
            
            <button
               @click="setType('signal')"
               :class="currentType === 'signal' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="zap" class="w-4 h-4 text-yellow-400"></i>
                <span class="flex-1">Signals</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.signal }}</span>
            </button>
            
            <button
               @click="setType('redis')"
               :class="currentType === 'redis' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="server" class="w-4 h-4 text-red-400"></i>
                <span class="flex-1">Redis</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.redis }}</span>
            </button>
            
            <button
               @click="setType('gate')"
               :class="currentType === 'gate' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="shield" class="w-4 h-4 text-indigo-400"></i>
                <span class="flex-1">Gates</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.gate }}</span>
            </button>
            <button
               @click="setType('transaction')"
               :class="currentType === 'transaction' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="layers" class="w-4 h-4 text-teal-400"></i>
                <span class="flex-1">Transactions</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.transaction }}</span>
            </button>
            <button
               @click="setType('storage')"
               :class="currentType === 'storage' ? 'bg-orbit-bg-tertiary text-orbit-accent-cyan border-l-2 border-orbit-accent-cyan' : 'text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-bg-tertiary/50'"
               class="w-full flex items-center gap-3 px-4 py-2.5 rounded-r-lg transition-all group text-left">
                <i data-lucide="archive" class="w-4 h-4 text-sky-400"></i>
                <span class="flex-1">Storage</span>
                <span class="text-xs bg-orbit-bg-tertiary px-2 py-0.5 rounded-full">{{ counts.storage }}</span>
            </button>
        </nav>
        
        <!-- Sidebar Footer -->
        <div class="p-4 border-t border-orbit-border">
            <!-- Status Indicator -->
            <div class="flex items-center gap-2 mb-4 px-2">
                <div class="w-2 h-2 rounded-full status-dot" :class="isPaused ? 'bg-amber-400' : 'bg-emerald-400'"></div>
                <span class="text-xs text-orbit-text-muted" x-text="isPaused ? 'Paused' : 'Recording Active'"></span>
            </div>
            
            <!-- Export All Button -->
            <button 
                @click="exportAll()"
                class="w-full flex items-center justify-center gap-2 px-4 py-2 mb-2 text-sm text-orbit-text-secondary hover:text-orbit-accent-cyan bg-orbit-bg-tertiary/50 hover:bg-orbit-accent-cyan/10 rounded-lg transition-all">
                <i data-lucide="download" class="w-4 h-4"></i>
                <span>Export Filtered</span>
            </button>
            
            <!-- Clear Button -->
            <button 
                @click="clearAll()"
                class="w-full flex items-center justify-center gap-2 px-4 py-2 text-sm text-orbit-text-secondary hover:text-rose-400 bg-orbit-bg-tertiary/50 hover:bg-rose-500/10 rounded-lg transition-all">
                <i data-lucide="trash-2" class="w-4 h-4"></i>
                <span>Clear All</span>
            </button>
        </div>
    </aside>
    
    <!-- Main Content Area -->
    <main class="flex-1 flex flex-col overflow-hidden">
        <!-- Top Bar -->
        <header class="h-14 border-b border-orbit-border bg-orbit-bg-secondary/50 backdrop-blur flex items-center justify-between px-6">
            <div class="flex items-center gap-4">
                <h2 class="text-lg font-medium">
                    <span x-text="getTypeLabel()"></span>
                </h2>
                
                <!-- Live Indicator -->
                <div x-show="!isPaused" class="flex items-center gap-2 text-xs text-emerald-400">
                    <div class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></div>
                    <span>Live</span>
                </div>
            </div>
            
            <!-- Search Bar -->
            <div class="flex-1 px-6">
                <div class="relative">
                    <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-orbit-text-muted"></i>
                    <input 
                        type="search" 
                        x-model="searchQuery"
                        @input.debounce.300ms="search()"
                        placeholder="Search entries (UUID or text content)..."
                        class="w-full bg-orbit-bg-primary border border-orbit-border rounded-lg pl-9 pr-4 py-1.5 text-sm text-orbit-text-primary placeholder-orbit-text-muted focus:outline-none focus:border-orbit-accent-cyan transition-colors"
                    >
                </div>
            </div>

            <div class="flex items-center gap-3">
                <!-- Pause/Resume Button -->
                <button 
                    @click="togglePause()"
                    :class="isPaused ? 'text-amber-400 bg-amber-500/10' : 'text-orbit-text-secondary hover:text-orbit-text-primary'"
                    class="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm transition-all">
                    <i :data-lucide="isPaused ? 'play' : 'pause'" class="w-4 h-4"></i>
                    <span x-text="isPaused ? 'Resume' : 'Pause'"></span>
                </button>
                
                <!-- Refresh Button -->
                <button 
                    @click="refreshFeed()"
                    class="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-orbit-text-secondary hover:text-orbit-text-primary transition-all">
                    <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                    <span>Refresh</span>
                </button>
                
                <!-- Stats Page Link -->
                <a href="{% url 'orbit:stats' %}"
                   class="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-orbit-text-secondary hover:text-orbit-text-primary hover:bg-orbit-accent-cyan/10 transition-all">
                    <i data-lucide="bar-chart-2" class="w-4 h-4"></i>
                    <span>Stats</span>
                </a>
            </div>
        </header>
        
        <!-- Statistics Panel (only visible for All Events) -->
        <div x-show="showStats && currentType === 'all'" 
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0 -translate-y-4"
             x-transition:enter-end="opacity-100 translate-y-0"
             x-transition:leave="transition ease-in duration-200"
             x-transition:leave-start="opacity-100 translate-y-0"
             x-transition:leave-end="opacity-0 -translate-y-4"
             class="p-6 border-b border-orbit-border bg-orbit-bg-primary/50">
            {% include "orbit/partials/stats.html" %}
        </div>
        
        <!-- Feed Container -->
        <div class="flex-1 overflow-hidden flex relative">
            <!-- Feed List -->
            <div id="feed-container" class="flex-1 overflow-y-auto">
                <!-- Initial loading state -->
                <div class="flex items-center justify-center h-full text-orbit-text-muted">
                    <div class="text-center">
                        <i data-lucide="loader-2" class="w-8 h-8 mx-auto mb-3 animate-spin"></i>
                        <p>Loading telemetry data...</p>
                    </div>
                </div>
            </div>
            
            <!-- Loading Overlay -->
            <div x-show="isLoading" 
                 x-transition:enter="transition ease-out duration-200"
                 x-transition:enter-start="opacity-0"
                 x-transition:enter-end="opacity-100"
                 x-transition:leave="transition ease-in duration-150"
                 x-transition:leave-start="opacity-100"
                 x-transition:leave-end="opacity-0"
                 class="absolute inset-0 bg-orbit-bg-primary/80 backdrop-blur-sm flex items-center justify-center z-10">
                <div class="text-center">
                    <div class="w-12 h-12 mx-auto mb-4 relative">
                        <div class="absolute inset-0 border-4 border-orbit-accent-cyan/20 rounded-full"></div>
                        <div class="absolute inset-0 border-4 border-transparent border-t-orbit-accent-cyan rounded-full animate-spin"></div>
                    </div>
                    <p class="text-orbit-text-muted text-sm">Loading entries...</p>
                </div>
            </div>
            
            <!-- Detail Panel (Slide-over) -->
            <div 
                x-show="detailOpen"
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="translate-x-full"
                x-transition:enter-end="translate-x-0"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="translate-x-0"
                x-transition:leave-end="translate-x-full"
                class="w-[600px] border-l border-orbit-border bg-orbit-bg-secondary overflow-hidden flex flex-col"
                @click.away="closeDetail()">
                
                <!-- Detail Header -->
                <div class="h-14 border-b border-orbit-border flex items-center justify-between px-4">
                    <h3 class="text-sm font-medium text-orbit-text-secondary">Entry Details</h3>
                    <button @click="closeDetail()" class="p-1 hover:bg-orbit-bg-tertiary rounded transition-colors">
                        <i data-lucide="x" class="w-5 h-5"></i>
                    </button>
                </div>
                
                <!-- Detail Content -->
                <div id="detail-container" class="flex-1 overflow-y-auto p-4 min-h-[200px]">
                    <!-- Loading state shown when isLoadingDetail is true -->
                    <template x-if="isLoadingDetail">
                        <div class="flex flex-col items-center justify-center h-full min-h-[200px] gap-3">
                            <div class="animate-spin rounded-full h-8 w-8 border-2 border-orbit-accent-cyan border-t-transparent"></div>
                            <span class="text-sm text-orbit-text-muted">Loading details...</span>
                        </div>
                    </template>
                    <!-- Content loaded via fetch will replace this -->
                </div>
            </div>
        </div>
    </main>
</div>

<script>
function orbitDashboard() {
    // URLs passed from Django view context
    const URLS = {
        feed: '{{ orbit_urls.feed }}',
        detail: '{{ orbit_urls.detail_base }}',
        clear: '{{ orbit_urls.clear }}',
        export_all: '{{ orbit_urls.export_all }}'
    };

    return {
        currentType: '{{ current_type }}',
        isPaused: false,
        detailOpen: false,
        detailEntryId: null,
        pollingInterval: null,
        currentPage: 1,
        searchQuery: '',
        showStats: true,
        isLoading: false,
        isLoadingDetail: false,
        
        search() {
            this.currentPage = 1;
            this.refreshFeed();
        },
        
        init() {
            // Initial load
            this.refreshFeed();
            
            // Start polling
            this.startPolling();
            
            // Handle entry clicks
            document.addEventListener('click', (e) => {
                const row = e.target.closest('[data-entry-id]');
                if (row) {
                    this.openDetail(row.dataset.entryId);
                }
            });
            
            // Handle custom event for opening details (from duplicate queries, etc.)
            document.addEventListener('orbit:open-detail', (e) => {
                if (e.detail && e.detail.entryId) {
                    this.openDetail(e.detail.entryId);
                }
            });
        },
        
        startPolling() {
            // Clear existing interval
            if (this.pollingInterval) {
                clearInterval(this.pollingInterval);
            }
            
            // Poll every 3 seconds
            this.pollingInterval = setInterval(() => {
                if (!this.isPaused) {
                    this.refreshFeed();
                }
            }, 3000);
        },
        
        setType(type) {
            this.currentType = type;
            this.currentPage = 1;  // Reset to page 1 when changing type
            this.refreshFeed(false, true);  // Don't preserve page, show loading
        },
        
        getTypeLabel() {
            const labels = {
                'all': 'All Events',
                'request': 'Requests',
                'query': 'Queries',
                'log': 'Logs',
                'exception': 'Exceptions',
                'job': 'Jobs',
                'transaction': 'Transactions',
                'storage': 'Storage'
            };
            return labels[this.currentType] || 'Events';
        },
        
        togglePause() {
            this.isPaused = !this.isPaused;
            // Reinitialize icons for the button
            this.$nextTick(() => lucide.createIcons());
        },
        
        async refreshFeed(preservePage = true, showLoading = false) {
            const container = document.getElementById('feed-container');
            const page = preservePage ? this.currentPage : 1;
            
            // Only show loading for user-initiated actions (not polling)
            if (showLoading) {
                this.isLoading = true;
            }
            
            try {
                const queryParams = new URLSearchParams({
                    type: this.currentType,
                    page: page,
                    q: this.searchQuery
                });
                const response = await fetch(`${URLS.feed}?${queryParams}`);
                if (response.ok) {
                    container.innerHTML = await response.text();
                    htmx.process(container);  // Process HTMX attributes on new content
                    lucide.createIcons();
                    
                    // Update current page from response (listen for page changes via HTMX)
                    this.setupPageTracking();
                }
            } catch (error) {
                console.error('Failed to refresh feed:', error);
            } finally {
                this.isLoading = false;
            }
        },
        
        setupPageTracking() {
            // Track page changes from pagination buttons
            document.querySelectorAll('#feed-container [hx-get]').forEach(el => {
                el.addEventListener('htmx:afterRequest', (e) => {
                    const url = new URL(e.detail.pathInfo.requestPath, window.location.origin);
                    const page = url.searchParams.get('page');
                    if (page) {
                        this.currentPage = parseInt(page);
                    }
                });
            });
        },
        
        async openDetail(entryId) {
            // If clicking the same entry while panel is open, close it
            if (this.detailOpen && this.detailEntryId === entryId) {
                this.closeDetail();
                return;
            }
            
            // If clicking a different entry, just update the content (don't close/reopen)
            this.detailEntryId = entryId;
            this.isLoadingDetail = true;
            
            // Small delay to prevent click.away from immediately closing
            await new Promise(resolve => setTimeout(resolve, 10));
            this.detailOpen = true;
            
            const container = document.getElementById('detail-container');
            
            // Show loading spinner immediately
            container.innerHTML = `
                <div class="flex flex-col items-center justify-center h-full min-h-[200px] gap-3">
                    <div class="animate-spin rounded-full h-8 w-8 border-2 border-orbit-accent-cyan border-t-transparent"></div>
                    <span class="text-sm text-orbit-text-muted">Loading details...</span>
                </div>
            `;
            
            try {
                const response = await fetch(`${URLS.detail}${entryId}/`);
                if (response.ok) {
                    container.innerHTML = await response.text();
                    lucide.createIcons();
                    
                    // Apply syntax highlighting to JSON
                    const jsonEl = document.getElementById('json-payload');
                    if (jsonEl) {
                        jsonEl.innerHTML = syntaxHighlight(jsonEl.textContent);
                    }
                }
            } catch (error) {
                console.error('Failed to load detail:', error);
                container.innerHTML = '<p class="text-rose-400">Failed to load details</p>';
            } finally {
                this.isLoadingDetail = false;
            }
        },
        
        closeDetail() {
            this.detailOpen = false;
            this.detailEntryId = null;
        },
        
        async clearAll() {
            if (!confirm('Clear all Orbit entries?')) return;
            
            try {
                const response = await fetch(URLS.clear, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': this.getCSRFToken()
                    }
                });
                
                if (response.ok) {
                    this.refreshFeed();
                }
            } catch (error) {
                console.error('Failed to clear entries:', error);
            }
        },
        
        exportAll() {
            const queryParams = new URLSearchParams({
                type: this.currentType,
                q: this.searchQuery
            });
            window.location.href = `${URLS.export_all}?${queryParams}`;
        },
        
        getCSRFToken() {
            // Try to get from cookie
            const cookies = document.cookie.split(';');
            for (let cookie of cookies) {
                const [name, value] = cookie.trim().split('=');
                if (name === 'csrftoken') {
                    return value;
                }
            }
            return '';
        }
    };
}
</script>
{% endblock %}
