<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EESA | Archive Intelligence Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/htmx.org@1.9.10"></script>
    <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Outfit', sans-serif;
            background-color: #0a0a0c;
            color: #fff;
            background-image: radial-gradient(circle at top left, #1e1b4b 0%, #0a0a0c 40%);
            min-height: 100vh;
        }

        .glass {
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .text-gradient {
            background: linear-gradient(to right, #fff, #94a3b8);
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        [x-cloak] {
            display: none !important;
        }

        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }

        ::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .input-glass {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: #fff;
            border-radius: 0.75rem;
            padding: 0.6rem 1rem;
            width: 100%;
            transition: all 0.2s;
        }

        .input-glass:focus {
            outline: none;
            border-color: rgba(99, 102, 241, 0.5);
            background: rgba(255, 255, 255, 0.06);
        }
    </style>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#6366f1',
                        secondary: '#a855f7',
                    }
                }
            }
        }
    </script>
</head>

<body x-data="eesaDashboard()">
    <div class="flex h-screen overflow-hidden">
        <!-- Sidebar -->
        <aside class="w-20 glass flex flex-col items-center py-8 gap-12 z-20">
            <div class="w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center text-primary font-bold shadow-lg shadow-primary/20 cursor-pointer"
                @click="activeTab = 'dashboard'">
                E
            </div>
            <nav class="flex flex-col gap-8">
                <button @click="activeTab = 'dashboard'"
                    :class="activeTab === 'dashboard' ? 'bg-primary/10 text-primary' : 'text-slate-500 hover:text-slate-300'"
                    class="p-2 rounded-lg transition-colors">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                    </svg>
                </button>
                <button @click="activeTab = 'settings'"
                    :class="activeTab === 'settings' ? 'bg-primary/10 text-primary' : 'text-slate-500 hover:text-slate-300'"
                    class="p-2 rounded-lg transition-colors">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                </button>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="flex-1 flex flex-col overflow-hidden p-8">
            <header class="flex justify-between items-center mb-8">
                <div>
                    <h1 class="text-2xl font-bold text-gradient"
                        x-text="activeTab === 'dashboard' ? 'Archive Intelligence' : 'System Configuration'"></h1>
                    <p class="text-sm text-slate-500"
                        x-text="activeTab === 'dashboard' ? 'System Dashboard v0.7.4' : 'Global Settings & AI Model Control'">
                    </p>
                </div>
                <div class="flex gap-4 items-center">
                    <!-- Search Bar -->
                    <div class="relative hidden lg:block">
                        <input type="text" x-model="search" @input.debounce.500ms="resetAndFetch()"
                            class="w-64 glass rounded-xl px-10 py-2 text-xs focus:ring-1 focus:ring-primary/50 outline-none"
                            placeholder="Search archive...">
                        <span class="absolute left-3 top-2.5 text-slate-500 text-sm">🔍</span>
                    </div>
                    <div class="px-3 py-1 glass rounded-full text-xs font-semibold text-slate-400">
                        <span :class="status.is_running ? 'text-green-400 animate-pulse' : 'text-slate-500'">●</span>
                        <span x-text="status.is_running ? 'SYNC ACTIVE' : 'SYSTEM READY'"></span>
                    </div>
                </div>
            </header>

            <!-- Dashboard View -->
            <div x-show="activeTab === 'dashboard'" class="flex-1 overflow-y-auto space-y-8 pr-2">

                <!-- Connection Wizard / Welcome -->
                <div x-show="!authStatus.gmail && !authStatus.m365 && stats.total_archived === 0"
                    class="glass p-8 rounded-3xl border border-indigo-500/20 bg-indigo-500/5 mb-8 animate-in slide-in-from-top duration-500">
                    <div class="flex flex-col md:flex-row gap-8 items-center">
                        <div class="flex-1 space-y-4">
                            <h2 class="text-2xl font-bold text-white">Welcome to Email Archiver</h2>
                            <p class="text-slate-400 text-sm leading-relaxed">Connect your first email provider to start
                                building your intelligence archive. No technical setup required.</p>
                            <div class="flex gap-4">
                                <button @click="startAuth('gmail')"
                                    class="px-6 py-2 bg-white/10 hover:bg-white/20 rounded-xl text-xs font-bold text-white transition-all flex items-center gap-2 border border-white/5">
                                    <span>📩</span> Connect Gmail
                                </button>
                                <button @click="startAuth('m365')"
                                    class="px-6 py-2 bg-white/10 hover:bg-white/20 rounded-xl text-xs font-bold text-white transition-all flex items-center gap-2 border border-white/5">
                                    <span>☁️</span> Connect Microsoft 365
                                </button>
                            </div>
                        </div>
                        <div
                            class="w-24 h-24 bg-indigo-500/10 rounded-full flex items-center justify-center text-4xl animate-bounce">
                            🚀
                        </div>
                    </div>
                </div>

                <!-- Stats Grid -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="glass p-6 rounded-2xl">
                        <div class="flex justify-between items-start mb-2">
                            <span class="text-xs font-medium text-slate-500 tracking-wider">TOTAL ARCHIVED</span>
                            <span class="text-primary text-xl">📁</span>
                        </div>
                        <div class="text-3xl font-bold mb-1" x-text="stats.total_archived.toLocaleString()">0</div>
                        <div class="text-[10px] text-slate-500">Updated: Just Now</div>
                    </div>
                    <div class="glass p-6 rounded-2xl">
                        <div class="flex justify-between items-start mb-2">
                            <span class="text-xs font-medium text-slate-500 tracking-wider">AI CLASSIFIED</span>
                            <span class="text-secondary text-xl">🧠</span>
                        </div>
                        <div class="text-3xl font-bold mb-1" x-text="stats.classified.toLocaleString()">0</div>
                        <div class="text-[10px] text-green-400/80">Active Categories: <span
                                x-text="Object.keys(stats.categories).length">0</span></div>
                    </div>
                    <div class="glass p-6 rounded-2xl">
                        <div class="flex justify-between items-start mb-2">
                            <span class="text-xs font-medium text-slate-500 tracking-wider">DATA ENTITIES</span>
                            <span class="text-indigo-400 text-xl">📊</span>
                        </div>
                        <div class="text-3xl font-bold mb-1" x-text="stats.extracted.toLocaleString()">0</div>
                        <div class="text-[10px] text-indigo-400/80">Structured Extraction Enabled</div>
                    </div>
                </div>

                <!-- Sync Console -->
                <div class="glass rounded-2xl p-6 relative overflow-hidden">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="font-bold text-slate-300">Synchronization Engine</h2>
                    </div>

                    <div class="flex flex-col xl:flex-row gap-8 items-start justify-center">
                        <div class="flex flex-col items-center gap-6">
                            <!-- Big Sync Button -->
                            <div class="relative group">
                                <button @click="status.is_running ? stopSync() : triggerSync()"
                                    class="w-40 h-40 rounded-full glass border-2 border-primary/20 flex flex-col items-center justify-center transition-all duration-500 hover:scale-105 active:scale-95 group relative z-10 overflow-hidden">

                                    <div x-show="status.is_running"
                                        class="absolute inset-0 border-2 border-primary animate-[spin_2s_linear_infinite] border-t-transparent rounded-full">
                                    </div>

                                    <div class="text-xl font-bold tracking-widest text-white"
                                        x-text="status.is_running ? (status.is_cancelled ? 'HALTING' : 'STOP') : 'SYNC'">
                                        SYNC</div>
                                    <div class="text-[9px] text-slate-500 mt-1 uppercase"
                                        x-text="status.is_running ? (status.is_cancelled ? 'Stopping...' : 'Abort Sync') : 'Initiate Task'">
                                        Initiate Task</div>
                                    <div class="mt-3 text-2xl transition-transform"
                                        :class="status.is_running ? 'rotate-180 text-red-400' : 'group-hover:rotate-12'">
                                        🔄</div>
                                </button>
                                <!-- Glow effect -->
                                <div class="absolute inset-0 bg-primary/20 blur-3xl -z-0 opacity-0 group-hover:opacity-100 transition-opacity"
                                    :class="status.is_running ? 'opacity-100' : ''"></div>
                            </div>

                            <!-- Quick Context -->
                            <div class="w-full max-w-md space-y-4">
                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-slate-500 mb-1 uppercase tracking-wider">Provider</label>
                                        <select x-model="syncConfig.provider"
                                            class="w-full bg-white/5 border border-white/10 rounded-lg p-2 text-sm focus:outline-none focus:border-primary/50 text-white">
                                            <option class="bg-slate-900" value="gmail">Gmail</option>
                                            <option class="bg-slate-900" value="m365">Microsoft 365</option>
                                        </select>
                                    </div>
                                    <div class="flex items-end">
                                        <label class="flex items-center gap-2 cursor-pointer group">
                                            <input type="checkbox" x-model="syncConfig.incremental" class="hidden">
                                            <div class="w-10 h-5 bg-white/10 rounded-full relative transition-colors"
                                                :class="syncConfig.incremental ? 'bg-primary/40' : ''">
                                                <div class="absolute top-1 left-1 w-3 h-3 bg-slate-400 rounded-full transition-transform"
                                                    :class="syncConfig.incremental ? 'translate-x-5 bg-white' : ''">
                                                </div>
                                            </div>
                                            <span
                                                class="text-[10px] font-bold text-slate-500 uppercase">Incremental</span>
                                        </label>
                                    </div>
                                </div>
                                <div class="flex gap-4">
                                    <label
                                        class="flex items-center gap-3 glass px-3 py-2 rounded-xl cursor-pointer hover:bg-white/10 transition-colors flex-1">
                                        <input type="checkbox" x-model="syncConfig.classify" class="accent-primary">
                                        <span class="text-[11px] font-semibold text-slate-300">AI Classify</span>
                                    </label>
                                    <label
                                        class="flex items-center gap-3 glass px-3 py-2 rounded-xl cursor-pointer hover:bg-white/10 transition-colors flex-1">
                                        <input type="checkbox" x-model="syncConfig.extract" class="accent-indigo-500">
                                        <span class="text-[11px] font-semibold text-slate-300">Deep Extract</span>
                                    </label>
                                </div>

                                <!-- Advanced Filters -->
                                <div x-data="{ open: false }" class="border-t border-white/5 pt-4">
                                    <button @click="open = !open"
                                        class="flex items-center justify-between w-full text-[10px] font-bold text-slate-500 uppercase tracking-widest hover:text-slate-300 transition-colors">
                                        <span>Advanced Filters</span>
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 transition-transform"
                                            :class="open ? 'rotate-180' : ''" fill="none" viewBox="0 0 24 24"
                                            stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M19 9l-7 7-7-7" />
                                        </svg>
                                    </button>
                                    <div x-show="open" x-cloak class="mt-4 space-y-4">
                                        <div class="grid grid-cols-2 gap-4">
                                            <div>
                                                <label
                                                    class="block text-[10px] text-slate-500 mb-1 uppercase font-bold">Since
                                                    Date</label>
                                                <input type="date" x-model="syncConfig.since"
                                                    class="bg-white/5 border border-white/10 rounded-lg p-2 text-xs w-full focus:outline-none focus:border-primary/50 text-white">
                                            </div>
                                            <div>
                                                <label
                                                    class="block text-[10px] text-slate-500 mb-1 uppercase font-bold">After
                                                    ID</label>
                                                <input type="text" x-model="syncConfig.after_id"
                                                    class="bg-white/5 border border-white/10 rounded-lg p-2 text-xs w-full focus:outline-none focus:border-primary/50 text-white"
                                                    placeholder="Message ID">
                                            </div>
                                        </div>
                                        <div>
                                            <label
                                                class="block text-[10px] text-slate-500 mb-1 uppercase font-bold">Custom
                                                Query</label>
                                            <input type="text" x-model="syncConfig.query"
                                                class="bg-white/5 border border-white/10 rounded-lg p-2 text-xs w-full focus:outline-none focus:border-primary/50 text-white"
                                                placeholder="e.g. from:boss subject:urgent">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Real-time Log Console -->
                        <div
                            class="flex-1 w-full flex flex-col h-full min-h-[250px] glass rounded-2xl overflow-hidden border border-white/10 self-stretch">
                            <div class="bg-white/5 px-4 py-2 border-b border-white/5 flex justify-between items-center">
                                <span class="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Process
                                    Output</span>
                                <div class="flex gap-2">
                                    <span
                                        class="w-2.5 h-2.5 rounded-full bg-red-500/20 border border-red-500/40"></span>
                                    <span
                                        class="w-2.5 h-2.5 rounded-full bg-yellow-500/20 border border-yellow-500/40"></span>
                                    <span
                                        class="w-2.5 h-2.5 rounded-full bg-green-500/20 border border-green-500/40"></span>
                                </div>
                            </div>
                            <div x-ref="logConsole"
                                class="flex-1 p-4 font-mono text-[11px] space-y-1 overflow-y-auto max-h-[350px] leading-relaxed">
                                <template x-for="log in status.logs">
                                    <div class="flex gap-3">
                                        <span class="text-slate-600 shrink-0"
                                            x-text="log.includes(' - ') ? log.split(' - ')[0].split(' ')[1] : ''"></span>
                                        <span
                                            :class="log.includes('ERROR') ? 'text-red-400' : log.includes('WARNING') ? 'text-yellow-400' : 'text-slate-300'"
                                            x-text="log.includes(' - ') ? log.substring(log.indexOf(' - ') + 3) : log"></span>
                                    </div>
                                </template>
                                <div x-show="status.logs.length === 0" class="text-slate-600 italic">
                                    System idle. Waiting for task initiation...
                                </div>
                                <div x-show="status.is_running"
                                    class="inline-block w-1.5 h-3 bg-primary animate-pulse ml-1 align-middle"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Emails -->
                <div class="glass rounded-2xl overflow-hidden">
                    <div class="p-6 border-b border-white/10 flex justify-between items-center">
                        <h2 class="font-bold flex items-center gap-2 text-slate-300">
                            <span class="w-1.5 h-1.5 rounded-full bg-primary shadow shadow-primary"></span>
                            Intelligence Feed
                        </h2>
                        <div class="flex items-center gap-4">
                            <span class="text-[10px] text-slate-500" x-show="search">Showing results for: "<span
                                    x-text="search"></span>"</span>
                            <button @click="resetAndFetch()"
                                class="text-[10px] font-bold text-primary hover:text-primary/80 uppercase tracking-widest transition-colors">Refresh
                                View</button>
                        </div>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left text-sm border-collapse">
                            <thead>
                                <tr
                                    class="text-slate-500 uppercase text-[10px] tracking-widest border-b border-white/5">
                                    <th class="px-6 py-4 font-medium">Subject</th>
                                    <th class="px-6 py-4 font-medium">Sender</th>
                                    <th class="px-6 py-4 font-medium">Date</th>
                                    <th class="px-6 py-4 font-medium">Classification</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-white/5">
                                <template x-for="(email, index) in emails" :key="index">
                                    <tr @click="openEmail(email)"
                                        class="hover:bg-white/5 transition-colors group cursor-pointer border-l-2 border-transparent hover:border-primary">
                                        <td class="px-6 py-4 font-medium truncate max-w-xs text-slate-200"
                                            x-text="email.subject"></td>
                                        <td class="px-6 py-4 text-slate-400 truncate max-w-[150px]"
                                            x-text="email.sender">
                                        </td>
                                        <td class="px-6 py-4 text-[10px] text-slate-500 whitespace-nowrap"
                                            x-text="formatDate(email.received_at)"></td>
                                        <td class="px-6 py-4">
                                            <div class="flex items-center gap-2">
                                                <template x-if="email.classification">
                                                    <span :class="getBadgeClass(email.classification.category)"
                                                        class="px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider"
                                                        x-text="email.classification.category"></span>
                                                </template>
                                                <template x-if="!email.classification">
                                                    <span class="text-slate-700 text-[10px]">UNPROCESSED</span>
                                                </template>
                                                <span x-show="email.extraction" class="text-xs"
                                                    title="Deep Extraction Available">🧩</span>
                                            </div>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                        <div x-show="emails.length === 0" class="p-12 text-center text-slate-600">
                            No emails found matching your current filter.
                        </div>
                        <div class="p-4 flex justify-center border-t border-white/5" x-show="emails.length > 0">
                            <button @click="loadMore()" :disabled="isLoadingMore"
                                class="px-6 py-1 glass rounded-lg text-[10px] font-bold text-slate-400 hover:text-primary transition-all uppercase tracking-widest flex items-center gap-2">
                                <span x-show="isLoadingMore"
                                    class="w-3 h-3 border border-slate-500 border-t-primary rounded-full animate-spin"></span>
                                Load More Messages
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Settings View -->
            <div x-show="activeTab === 'settings'" x-cloak class="flex-1 overflow-y-auto space-y-8 pr-2">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <!-- General Settings -->
                    <div class="glass p-8 rounded-3xl space-y-6">
                        <h3 class="text-lg font-bold text-slate-200 flex items-center gap-3">
                            <span class="p-2 bg-primary/20 rounded-lg text-primary text-base">⚙️</span>
                            System Settings
                        </h3>

                        <div class="space-y-4">
                            <div>
                                <label class="block text-xs font-semibold text-slate-500 mb-2 uppercase">Download
                                    Directory</label>
                                <input type="text" x-model="config.app.download_dir" class="input-glass"
                                    placeholder="e.g. downloads/">
                            </div>

                            <div class="pt-4 border-t border-white/5">
                                <h4 class="text-sm font-bold text-slate-400 mb-4">Webhook Notification</h4>
                                <div class="space-y-4">
                                    <label class="flex items-center gap-3 cursor-pointer group">
                                        <input type="checkbox" x-model="config.webhook.enabled" class="accent-primary">
                                        <span class="text-sm text-slate-300">Enable Webhooks</span>
                                    </label>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-slate-500 mb-1 uppercase">Endpoint
                                            URL</label>
                                        <input type="text" x-model="config.webhook.url" class="input-glass"
                                            placeholder="https://..." :disabled="!config.webhook.enabled">
                                    </div>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-slate-500 mb-1 uppercase">Authorization
                                            Secret</label>
                                        <input type="password" x-model="config.webhook.headers.Authorization"
                                            class="input-glass" placeholder="Optional token"
                                            :disabled="!config.webhook.enabled">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- AI Hub Settings -->
                    <div class="glass p-8 rounded-3xl space-y-6">
                        <h3 class="text-lg font-bold text-slate-200 flex items-center gap-3">
                            <span class="p-2 bg-secondary/20 rounded-lg text-secondary text-base">🧠</span>
                            Intelligence Hub
                        </h3>

                        <div class="space-y-6">
                            <!-- Classification -->
                            <div class="p-5 bg-white/5 rounded-2xl border border-white/5 space-y-4">
                                <div class="flex justify-between items-center">
                                    <h4 class="text-sm font-bold text-slate-300">AI Classification</h4>
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" x-model="config.classification.enabled" class="hidden">
                                        <div class="w-8 h-4 bg-white/10 rounded-full relative"
                                            :class="config.classification.enabled ? 'bg-secondary/40' : ''">
                                            <div class="absolute top-0.5 left-0.5 w-3 h-3 bg-slate-400 rounded-full transition-transform"
                                                :class="config.classification.enabled ? 'translate-x-4 bg-white' : ''">
                                            </div>
                                        </div>
                                    </label>
                                </div>

                                <div class="grid grid-cols-2 gap-4" x-show="config.classification.enabled">
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-slate-500 mb-1 uppercase">Provider</label>
                                        <select x-model="config.classification.provider" class="input-glass py-2 px-3">
                                            <option class="bg-slate-900" value="openai">OpenAI</option>
                                            <option class="bg-slate-900" value="ollama">Ollama</option>
                                            <option class="bg-slate-900" value="lm_studio">LM Studio</option>
                                            <option class="bg-slate-900" value="local">Custom Local</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-slate-500 mb-1 uppercase">Model</label>
                                        <input type="text" x-model="config.classification.model"
                                            class="input-glass py-2 px-3" placeholder="gpt-4o-mini">
                                    </div>
                                </div>

                                <div
                                    x-show="config.classification.enabled && config.classification.provider === 'openai'">
                                    <label class="block text-[10px] font-bold text-slate-500 mb-1 uppercase">API
                                        Key</label>
                                    <input type="password" x-model="config.classification.openai_api_key"
                                        class="input-glass" placeholder="sk-...">
                                </div>

                                <div
                                    x-show="config.classification.enabled && config.classification.provider !== 'openai'">
                                    <label class="block text-[10px] font-bold text-slate-500 mb-1 uppercase">Base
                                        URL</label>
                                    <input type="text" x-model="config.classification.base_url" class="input-glass"
                                        placeholder="http://localhost:11434/v1">
                                </div>
                            </div>

                            <!-- Extraction -->
                            <div class="p-5 bg-white/5 rounded-2xl border border-white/5 space-y-4">
                                <div class="flex justify-between items-center">
                                    <h4 class="text-sm font-bold text-slate-300">Data Extraction</h4>
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" x-model="config.extraction.enabled" class="hidden">
                                        <div class="w-8 h-4 bg-white/10 rounded-full relative"
                                            :class="config.extraction.enabled ? 'bg-indigo-500/40' : ''">
                                            <div class="absolute top-0.5 left-0.5 w-3 h-3 bg-slate-400 rounded-full transition-transform"
                                                :class="config.extraction.enabled ? 'translate-x-4 bg-white' : ''">
                                            </div>
                                        </div>
                                    </label>
                                </div>
                                <p class="text-[11px] text-slate-500">Enable advanced metadata extraction of summaries,
                                    action items, and entities.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Action Bar -->
                <div class="flex justify-end gap-4 pb-12">
                    <button @click="fetchSettings()"
                        class="px-6 py-2 glass rounded-xl text-sm font-bold text-slate-400 hover:text-white transition-colors">Discard</button>
                    <button @click="saveSettings()"
                        class="px-10 py-2 bg-primary rounded-xl text-sm font-bold text-white shadow-lg shadow-primary/20 hover:brightness-110 active:scale-95 transition-all flex items-center gap-2">
                        <span x-show="isSaving"
                            class="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></span>
                        Save Changes
                    </button>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-8 pb-12">
                    <!-- Google Secrets -->
                    <div class="glass p-8 rounded-3xl space-y-4">
                        <div class="flex justify-between items-center">
                            <h4 class="text-sm font-bold text-slate-300">Google Client Secrets</h4>
                            <span :class="authStatus.gmail ? 'text-green-400' : 'text-slate-500'"
                                class="text-[10px] font-bold uppercase"
                                x-text="authStatus.gmail ? 'Connected' : 'Disconnected'"></span>
                        </div>
                        <p class="text-[10px] text-slate-500">Paste your <code>credentials.json</code> content here to
                            enable Gmail sync.</p>
                        <textarea x-model="gmailSecretJson" rows="4"
                            class="w-full bg-slate-900/50 border border-white/5 rounded-xl p-3 text-[10px] font-mono text-slate-300 focus:outline-none focus:border-primary/50 transition-all"
                            placeholder='{ "installed": { ... } }'></textarea>
                        <button @click="saveSecret('gmail')" :disabled="!gmailSecretJson"
                            class="w-full py-2 bg-white/5 hover:bg-white/10 rounded-xl text-[10px] font-bold text-slate-300 transition-all border border-white/5">
                            Update Gmail Secrets
                        </button>
                    </div>

                    <!-- M365 Secrets -->
                    <div class="glass p-8 rounded-3xl space-y-4">
                        <div class="flex justify-between items-center">
                            <h4 class="text-sm font-bold text-slate-300">M365 Configuration</h4>
                            <span :class="authStatus.m365 ? 'text-green-400' : 'text-slate-500'"
                                class="text-[10px] font-bold uppercase"
                                x-text="authStatus.m365 ? 'Connected' : 'Disconnected'"></span>
                        </div>
                        <p class="text-[10px] text-slate-500">Paste your MSAL <code>config.json</code> or leave empty if
                            using settings above.</p>
                        <textarea x-model="m365SecretJson" rows="4"
                            class="w-full bg-slate-900/50 border border-white/5 rounded-xl p-3 text-[10px] font-mono text-slate-300 focus:outline-none focus:border-indigo-500/50 transition-all"
                            placeholder='{ "client_id": "...", "authority": "..." }'></textarea>
                        <button @click="saveSecret('m365')" :disabled="!m365SecretJson"
                            class="w-full py-2 bg-white/5 hover:bg-white/10 rounded-xl text-[10px] font-bold text-slate-300 transition-all border border-white/5">
                            Update M365 Secrets
                        </button>
                    </div>
                </div>
            </div>

            <!-- Auth Flow Modal -->
            <div x-show="authFlow" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4">
                <div @click="authFlow = null" class="absolute inset-0 bg-slate-950/80 backdrop-blur-sm"></div>
                <div
                    class="relative w-full max-w-md glass rounded-3xl p-8 shadow-2xl border border-white/10 animate-in fade-in zoom-in duration-200">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-xl font-bold text-white"
                            x-text="'Connect ' + (authFlow?.provider === 'gmail' ? 'Gmail' : 'Microsoft 365')"></h3>
                        <button @click="authFlow = null" class="text-slate-500 hover:text-white">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>

                    <!-- Gmail Flow -->
                    <template x-if="authFlow?.provider === 'gmail'">
                        <div class="space-y-6">
                            <div class="space-y-2">
                                <p class="text-xs font-bold text-slate-500 uppercase tracking-widest">Step 1:
                                    Authorization</p>
                                <p class="text-sm text-slate-400">Open the link below to authorize access to your Gmail
                                    account:</p>
                                <a :href="authFlow.url" target="_blank"
                                    class="block p-4 bg-white/5 rounded-2xl text-primary text-[10px] font-mono break-all border border-primary/20 hover:bg-primary/5 transition-all"
                                    x-text="authFlow.url"></a>
                            </div>
                            <div class="space-y-2">
                                <p class="text-xs font-bold text-slate-500 uppercase tracking-widest">Step 2: Validation
                                </p>
                                <p class="text-sm text-slate-400">Paste the authorization code provided by Google below:
                                </p>
                                <input type="text" x-model="authCode" placeholder="Paste code here..."
                                    class="w-full bg-slate-900/50 border border-white/10 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary transition-all">
                            </div>
                        </div>
                    </template>

                    <!-- M365 Flow -->
                    <template x-if="authFlow?.provider === 'm365'">
                        <div class="space-y-6">
                            <div class="space-y-4">
                                <p class="text-sm text-slate-400" x-text="authFlow.flow.message"></p>
                                <div
                                    class="p-6 bg-indigo-500/10 border border-indigo-500/20 rounded-2xl text-center shadow-inner">
                                    <span class="text-3xl font-mono font-bold text-indigo-400 tracking-[0.2em]"
                                        x-text="authFlow.flow.user_code"></span>
                                </div>
                                <div class="flex items-start gap-3 p-4 bg-white/5 rounded-xl border border-white/5">
                                    <span class="text-xl">ℹ️</span>
                                    <p class="text-[11px] text-slate-500 leading-relaxed">Once you enter the code in the
                                        Microsoft portal, this dashboard will automatically detect the connection.</p>
                                </div>
                            </div>
                        </div>
                    </template>

                    <div class="flex justify-end gap-3 mt-10">
                        <button @click="authFlow = null"
                            class="px-6 py-2 glass rounded-xl text-xs font-bold text-slate-400 hover:text-white transition-colors">Cancel</button>
                        <button @click="completeAuth()" :disabled="isAuthenticating"
                            class="px-8 py-2 bg-primary rounded-xl text-xs font-bold text-white shadow-lg shadow-primary/20 hover:brightness-110 active:scale-95 transition-all flex items-center gap-2">
                            <span x-show="isAuthenticating"
                                class="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin"></span>
                            <span x-text="isAuthenticating ? 'Validating...' : 'Complete Connection'"></span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Email Detail Modal -->
            <div x-show="selectedEmail" x-cloak
                class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
                @keydown.escape.window="selectedEmail = null">
                <div class="glass w-full max-w-3xl max-h-[90vh] rounded-3xl overflow-hidden flex flex-col shadow-2xl"
                    @click.away="selectedEmail = null">
                    <div class="p-6 border-b border-white/10 flex justify-between items-start">
                        <div>
                            <h3 class="text-xl font-bold text-slate-200" x-text="selectedEmail?.subject"></h3>
                            <div class="flex gap-4 mt-2">
                                <span class="text-xs text-slate-500">From: <span class="text-slate-300"
                                        x-text="selectedEmail?.sender"></span></span>
                                <span class="text-xs text-slate-500">Date: <span class="text-slate-300"
                                        x-text="formatDate(selectedEmail?.received_at)"></span></span>
                            </div>
                        </div>
                        <button @click="selectedEmail = null" class="text-slate-500 hover:text-white transition-colors">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>

                    <div class="flex-1 overflow-y-auto p-8 space-y-8">
                        <!-- Intelligence Panel -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="bg-primary/5 rounded-2xl p-5 border border-primary/10">
                                <h4 class="text-[10px] font-bold text-primary uppercase tracking-widest mb-3">
                                    Classification</h4>
                                <template x-if="selectedEmail?.classification">
                                    <div class="space-y-4">
                                        <div class="flex items-center gap-3">
                                            <span :class="getBadgeClass(selectedEmail.classification.category)"
                                                class="px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest"
                                                x-text="selectedEmail.classification.category"></span>
                                            <span x-show="selectedEmail.classification.reasoning"
                                                class="text-[10px] text-slate-500">AI Confidence: High</span>
                                        </div>
                                        <p class="text-sm text-slate-300 leading-relaxed"
                                            x-text="selectedEmail.classification.reasoning"></p>
                                    </div>
                                </template>
                                <template x-if="!selectedEmail?.classification">
                                    <p class="text-xs text-slate-600 italic">No AI classification metadata available for
                                        this item.</p>
                                </template>
                            </div>

                            <div class="bg-secondary/5 rounded-2xl p-5 border border-secondary/10">
                                <h4 class="text-[10px] font-bold text-secondary uppercase tracking-widest mb-3">System
                                    Info</h4>
                                <div class="space-y-3">
                                    <div class="flex justify-between">
                                        <span class="text-[10px] text-slate-500 font-bold uppercase">Source</span>
                                        <span class="text-[10px] text-slate-300 font-bold uppercase"
                                            x-text="selectedEmail?.provider"></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-[10px] text-slate-500 font-bold uppercase">Archived</span>
                                        <span class="text-[10px] text-slate-300 font-bold uppercase"
                                            x-text="formatDate(selectedEmail?.processed_at)"></span>
                                    </div>
                                    <div class="pt-2 border-t border-white/5">
                                        <span class="text-[10px] text-slate-500 font-bold uppercase block mb-1">Local
                                            Path</span>
                                        <code
                                            class="text-[10px] text-indigo-300/80 block break-all font-mono bg-black/20 p-2 rounded"
                                            x-text="selectedEmail?.file_path"></code>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Extraction Results -->
                        <template x-if="selectedEmail?.extraction">
                            <div class="glass rounded-2xl p-6 border border-white/5">
                                <h4 class="text-[10px] font-bold text-indigo-400 uppercase tracking-widest mb-4">Deep
                                    Extraction Results</h4>

                                <div class="space-y-6">
                                    <div>
                                        <span
                                            class="text-[10px] text-slate-500 font-bold uppercase block mb-1">Summary</span>
                                        <p class="text-sm text-slate-200 leading-relaxed"
                                            x-text="selectedEmail.extraction.summary"></p>
                                    </div>

                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div x-show="selectedEmail.extraction.action_items?.length">
                                            <span
                                                class="text-[10px] text-slate-500 font-bold uppercase block mb-2">Action
                                                Items</span>
                                            <ul class="space-y-2">
                                                <template x-for="item in selectedEmail.extraction.action_items">
                                                    <li class="text-xs text-slate-400 flex gap-2">
                                                        <span class="text-indigo-500">▹</span>
                                                        <span x-text="item"></span>
                                                    </li>
                                                </template>
                                            </ul>
                                        </div>
                                        <div x-show="selectedEmail.extraction.organizations?.length">
                                            <span
                                                class="text-[10px] text-slate-500 font-bold uppercase block mb-2">Relevant
                                                Entities</span>
                                            <div class="flex flex-wrap gap-2">
                                                <template x-for="org in selectedEmail.extraction.organizations">
                                                    <span
                                                        class="px-2 py-1 bg-white/5 rounded text-[10px] text-slate-400"
                                                        x-text="org"></span>
                                                </template>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        function eesaDashboard() {
            return {
                activeTab: 'dashboard',
                stats: { total_archived: 0, classified: 0, extracted: 0, categories: {} },
                emails: [],
                status: { is_running: false, logs: [] },
                search: '',
                skip: 0,
                selectedEmail: null,
                isLoadingMore: false,
                syncConfig: {
                    provider: 'gmail',
                    incremental: true,
                    classify: true,
                    extract: false,
                    since: new Date().toISOString().split('T')[0],
                    after_id: '',
                    query: ''
                },
                config: {
                    app: { download_dir: 'downloads/' },
                    webhook: { enabled: false, url: '', headers: { Authorization: '' } },
                    classification: { enabled: false, provider: 'openai', model: '', openai_api_key: '', base_url: '' },
                    extraction: { enabled: false }
                },
                isSaving: false,
                authStatus: { gmail: false, m365: false },
                authFlow: null,
                authCode: '',
                isAuthenticating: false,
                gmailSecretJson: '',
                m365SecretJson: '',
                init() {
                    this.resetAndFetch();
                    this.fetchSettings();
                    this.checkAuthStatus();

                    setInterval(() => {
                        this.fetchStatus();
                        if (this.status.is_running) {
                            this.fetchData(false); // Update stats/logs, but don't reset list if syncing
                            this.$nextTick(() => {
                                const el = this.$refs.logConsole;
                                if (el) el.scrollTop = el.scrollHeight;
                            });
                        }
                    }, 2000);
                },
                async saveSecret(provider) {
                    const jsonStr = provider === 'gmail' ? this.gmailSecretJson : this.m365SecretJson;
                    if (!jsonStr) return;
                    try {
                        const data = JSON.parse(jsonStr);
                        const res = await fetch(`/api/secrets?provider=${provider}`, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(data)
                        });
                        const result = await res.json();
                        if (res.ok) {
                            alert(result.message);
                            if (provider === 'gmail') this.gmailSecretJson = '';
                            else this.m365SecretJson = '';
                        } else {
                            alert('Error: ' + result.detail);
                        }
                    } catch (e) {
                        alert('Invalid JSON: ' + e.message);
                    }
                },
                async checkAuthStatus() {
                    try {
                        const res = await fetch('/api/auth/status');
                        this.authStatus = await res.json();
                    } catch (e) { }
                },
                async startAuth(provider) {
                    this.isAuthenticating = true;
                    this.authFlow = null;
                    this.authCode = '';
                    try {
                        const res = await fetch('/api/auth/init', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ provider })
                        });
                        this.authFlow = await res.json();
                        this.authFlow.provider = provider;
                    } catch (e) {
                        alert('Auth init failed: ' + e);
                    } finally {
                        this.isAuthenticating = false;
                    }
                },
                async completeAuth() {
                    this.isAuthenticating = true;
                    try {
                        const res = await fetch('/api/auth/complete', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                provider: this.authFlow.provider,
                                code: this.authCode,
                                flow: this.authFlow.flow
                            })
                        });
                        const data = await res.json();
                        if (res.ok) {
                            this.authFlow = null;
                            this.checkAuthStatus();
                        } else {
                            alert(data.detail || 'Auth failed');
                        }
                    } catch (e) {
                        alert('Auth failed: ' + e);
                    } finally {
                        this.isAuthenticating = false;
                    }
                },
                resetAndFetch() {
                    this.skip = 0;
                    this.fetchData(true);
                },
                async fetchData(reset = true) {
                    try {
                        const [statsRes, emailsRes] = await Promise.all([
                            fetch('/api/stats'),
                            fetch(`/api/emails?search=${encodeURIComponent(this.search)}&skip=${this.skip}`)
                        ]);
                        this.stats = await statsRes.json();
                        const newEmails = await emailsRes.json();
                        if (reset) {
                            this.emails = newEmails;
                        } else {
                            // Append uniquely or just replace? Replace for now if skip is 0, append otherwise
                            if (this.skip === 0) this.emails = newEmails;
                            else this.emails = [...this.emails, ...newEmails];
                        }
                    } catch (e) { console.error('Data fetch error:', e); }
                },
                async loadMore() {
                    this.isLoadingMore = true;
                    this.skip += 50;
                    await this.fetchData(false);
                    this.isLoadingMore = false;
                },
                openEmail(email) {
                    this.selectedEmail = email;
                },
                async fetchStatus() {
                    try {
                        const res = await fetch('/api/status');
                        this.status = await res.json();
                    } catch (e) { }
                },
                async fetchSettings() {
                    try {
                        const res = await fetch('/api/settings');
                        const data = await res.json();
                        // Initialize nested objects if missing
                        if (!data.app) data.app = { download_dir: 'downloads/' };
                        if (!data.webhook) data.webhook = { enabled: false, url: '', headers: { Authorization: '' } };
                        if (!data.webhook.headers) data.webhook.headers = { Authorization: '' };
                        if (!data.classification) data.classification = { enabled: false, provider: 'openai', model: 'gpt-4o-mini' };
                        if (!data.extraction) data.extraction = { enabled: false };

                        this.config = data;

                        // Sync quick sync config with settings
                        this.syncConfig.classify = data.classification.enabled;
                        this.syncConfig.extract = data.extraction.enabled;
                    } catch (e) { console.error('Settings fetch error:', e); }
                },
                async saveSettings() {
                    this.isSaving = true;
                    try {
                        await fetch('/api/settings', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(this.config)
                        });
                        // Update syncConfig to match
                        this.syncConfig.classify = this.config.classification.enabled;
                        this.syncConfig.extract = this.config.extraction.enabled;
                        setTimeout(() => this.isSaving = false, 500);
                    } catch (e) {
                        console.error('Save error:', e);
                        this.isSaving = false;
                    }
                },
                async triggerSync() {
                    try {
                        await fetch('/api/sync', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(this.syncConfig)
                        });
                        this.status.is_running = true;
                        this.status.logs = ["Initiating background task..."];
                    } catch (e) { }
                },
                async stopSync() {
                    try {
                        await fetch('/api/sync/stop', { method: 'POST' });
                        this.status.is_cancelled = true;
                    } catch (e) { }
                },
                formatDate(dateStr) {
                    if (!dateStr) return '';
                    const d = new Date(dateStr);
                    return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                },
                getBadgeClass(cat) {
                    const classes = {
                        important: "bg-red-500/20 text-red-400 border border-red-500/30",
                        promotional: "bg-yellow-500/20 text-yellow-400 border border-yellow-500/30",
                        transactional: "bg-blue-500/20 text-blue-400 border border-blue-500/30",
                        newsletter: "bg-green-500/20 text-green-400 border border-green-500/30",
                        social: "bg-purple-500/20 text-purple-400 border border-purple-500/30",
                        spam: "bg-gray-500/20 text-gray-400 border border-gray-500/30"
                    };
                    return classes[cat.toLowerCase()] || "bg-slate-500/20 text-slate-400 border border-slate-500/30";
                }
            }
        }
    </script>
</body>

</html>