<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JustEmbed</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <style>
        [x-cloak] { display: none !important; }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
    <div class="flex-1" x-data="{ activeTab: 'query' }">
        <!-- Header -->
        <header class="bg-white border-b border-gray-200">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900">JustEmbed</h1>
                        <p class="text-sm text-gray-500 mt-1">Workspace: <span class="font-mono">{{ workspace }}</span></p>
                    </div>
                    <div class="flex space-x-2">
                        <button onclick="showRegisterWorkspace()" class="px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
                            Register Workspace
                        </button>
                        <button onclick="showDeregisterWorkspace()" class="px-4 py-2 text-sm bg-orange-600 text-white rounded-md hover:bg-orange-700 transition-colors">
                            Deregister Workspace
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- Register Workspace Modal -->
        <div id="registerWorkspaceModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Register Workspace</h3>
                    <form method="post" action="/register-workspace">
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Workspace Path</label>
                            <input type="text" name="workspace" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                   placeholder="/path/to/workspace">
                        </div>
                        <div class="bg-blue-50 border border-blue-200 rounded-md p-3 mb-4">
                            <p class="text-sm text-blue-800">✓ Registers a workspace for access. Creates folder structure if needed.</p>
                            <p class="text-sm text-blue-700 mt-1">✓ Does NOT delete any existing data.</p>
                            <p class="text-sm text-blue-700 mt-1">✓ Perfect for shared workspaces: unzip → register → use!</p>
                        </div>
                        {% if registered_workspaces %}
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Or select from registered:</label>
                            <select onchange="if(this.value) document.querySelector('input[name=workspace]').value = this.value"
                                    class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500">
                                <option value="">-- Select --</option>
                                {% for ws in registered_workspaces %}
                                <option value="{{ ws }}">{{ ws }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        {% endif %}
                        <div class="flex space-x-2">
                            <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                                Register
                            </button>
                            <button type="button" onclick="hideRegisterWorkspace()" class="flex-1 px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                                Cancel
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Deregister Workspace Modal -->
        <div id="deregisterWorkspaceModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <h3 class="text-lg font-medium text-orange-600 mb-4">⚠️ Deregister Workspace</h3>
                    <form method="post" action="/deregister-workspace" onsubmit="return validateDeregister()">
                        <div class="bg-green-50 border border-green-200 rounded-md p-4 mb-4">
                            <p class="text-sm text-green-800 font-semibold mb-2">✓ Data stays on disk - NOT deleted!</p>
                            <p class="text-sm text-green-700">This only removes the workspace from the registry. All your files remain intact.</p>
                            <p class="text-sm text-green-700 mt-2">You can zip/share the folder and re-register it later!</p>
                        </div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Type the workspace path to confirm:
                            </label>
                            <p class="text-xs text-gray-500 mb-2 font-mono bg-gray-100 p-2 rounded">{{ workspace }}</p>
                            <input type="text" id="deregisterConfirm" name="confirm_path" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                                   placeholder="Enter workspace path">
                        </div>
                        <div class="flex space-x-2">
                            <button type="submit" class="flex-1 px-4 py-2 bg-orange-600 text-white rounded-md hover:bg-orange-700">
                                Deregister
                            </button>
                            <button type="button" onclick="hideDeregisterWorkspace()" class="flex-1 px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                                Cancel
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mt-6">
            <div class="border-b border-gray-200">
                <nav class="-mb-px flex space-x-8" aria-label="Tabs">
                    <button @click="activeTab = 'query'" 
                            :class="activeTab === 'query' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                            class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
                        Query
                    </button>
                    <button @click="activeTab = 'kbs'" 
                            :class="activeTab === 'kbs' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                            class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
                        Knowledge Bases
                    </button>
                    <button @click="activeTab = 'models'" 
                            :class="activeTab === 'models' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                            class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
                        Models
                    </button>
                    <button @click="activeTab = 'history'" 
                            :class="activeTab === 'history' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                            class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
                        Upload History
                    </button>
                </nav>
            </div>

            <!-- Tab Content -->
            <div class="mt-6 pb-12">
                <!-- Query Tab -->
                <div x-show="activeTab === 'query'" x-cloak>
                    <div class="bg-white rounded-lg shadow p-6">
                        <h2 class="text-xl font-semibold text-gray-900 mb-4">Search Knowledge Bases</h2>
                        <form method="post" action="/query" class="space-y-4">
                            <div>
                                <label for="query" class="block text-sm font-medium text-gray-700 mb-1">Query</label>
                                <input type="text" name="query" id="query" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                       placeholder="Enter your search query...">
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label for="kbs" class="block text-sm font-medium text-gray-700 mb-1">Knowledge Base</label>
                                    <select name="kbs" id="kbs" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="all">All KBs</option>
                                        {% for kb in kbs %}
                                        <option value="{{ kb.name }}">{{ kb.name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div>
                                    <label for="top_k" class="block text-sm font-medium text-gray-700 mb-1">Results</label>
                                    <input type="number" name="top_k" id="top_k" value="5" min="1" max="50"
                                           class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label for="mode" class="block text-sm font-medium text-gray-700 mb-1">Mode</label>
                                    <select name="mode" id="mode" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="retrieve">Retrieve</option>
                                        <option value="count">Count</option>
                                    </select>
                                </div>
                            </div>
                            <button type="submit" class="w-full md:w-auto px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors font-medium">
                                Search
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Knowledge Bases Tab -->
                <div x-show="activeTab === 'kbs'" x-cloak>
                    <!-- Create KB Form -->
                    <div class="bg-white rounded-lg shadow p-6 mb-6">
                        <h2 class="text-xl font-semibold text-gray-900 mb-4">Create Knowledge Base</h2>
                        <form method="post" action="/create-kb" class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label for="name" class="block text-sm font-medium text-gray-700 mb-1">KB Name</label>
                                    <input type="text" name="name" id="name" required pattern="[a-zA-Z0-9_]+"
                                           class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                           placeholder="my_knowledge_base">
                                </div>
                                <div>
                                    <label for="model_type" class="block text-sm font-medium text-gray-700 mb-1">Model Type</label>
                                    <select name="model_type" id="model_type" onchange="updateModelName()"
                                            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="e5">General (Drop-In)</option>
                                        <option value="custom">Custom Model</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="model_name" class="block text-sm font-medium text-gray-700 mb-1">Model</label>
                                    <select name="model_name" id="model_name"
                                            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="e5-small">Inbuilt Model (E5-Small)</option>
                                    </select>
                                </div>
                            </div>
                            <button type="submit" class="w-full md:w-auto px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors font-medium">
                                Create KB
                            </button>
                        </form>
                    </div>

                    <!-- KB List -->
                    <div class="bg-white rounded-lg shadow p-6 mb-6">
                        <h2 class="text-xl font-semibold text-gray-900 mb-4">Your Knowledge Bases</h2>
                        {% if kbs %}
                        <div class="space-y-2">
                            {% for kb in kbs %}
                            <div class="flex items-center justify-between p-4 border border-gray-200 rounded-md hover:bg-gray-50 transition-colors {% if new_kb == kb.name %}ring-2 ring-blue-500 bg-blue-50{% endif %}">
                                <div class="flex-1">
                                    <h3 class="font-medium text-gray-900">{{ kb.name }}</h3>
                                    <div class="flex items-center space-x-4 text-sm text-gray-500 mt-1">
                                        <span>
                                            {% if kb.model_type == 'custom' %}
                                            🎯 Custom: {{ kb.model_name }}
                                            {% else %}
                                            🔤 General (E5-Small)
                                            {% endif %}
                                        </span>
                                        <span>
                                            {% if kb.chunk_count == 0 %}
                                            <span class="text-orange-600">⚠️ No knowledge added yet</span>
                                            {% else %}
                                            {{ kb.chunk_count }} chunks
                                            {% endif %}
                                        </span>
                                    </div>
                                </div>
                                <div class="flex space-x-2">
                                    <a href="/upload-to-kb?kb={{ kb.name }}" 
                                       class="px-4 py-2 {% if new_kb == kb.name %}bg-green-600 animate-pulse{% else %}bg-blue-600{% endif %} text-white text-sm rounded-md hover:bg-blue-700 transition-colors">
                                        {% if kb.chunk_count == 0 %}Add Knowledge{% else %}Update KB{% endif %}
                                    </a>
                                    <form method="post" action="/delete-kb" onsubmit="return confirm('Delete KB \'{{ kb.name }}\'? This cannot be undone.');">
                                        <input type="hidden" name="name" value="{{ kb.name }}">
                                        <button type="submit" class="px-4 py-2 bg-red-600 text-white text-sm rounded-md hover:bg-red-700 transition-colors">
                                            Delete
                                        </button>
                                    </form>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        {% else %}
                        <p class="text-gray-500 italic">No knowledge bases yet. Create one above.</p>
                        {% endif %}
                    </div>
                </div>

                <!-- Models Tab -->
                <div x-show="activeTab === 'models'" x-cloak>
                    <!-- Train Model Form -->
                    <div class="bg-white rounded-lg shadow p-6 mb-6">
                        <h2 class="text-xl font-semibold text-gray-900 mb-4">Train Custom Model</h2>
                        <form method="post" action="/train-model" enctype="multipart/form-data" class="space-y-4" id="trainModelForm" onsubmit="showModelTrainingProgress()">
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label for="model_name" class="block text-sm font-medium text-gray-700 mb-1">Model Name</label>
                                    <input type="text" name="model_name" id="model_name" required
                                           class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                           placeholder="my_custom_model_to_be_trained">
                                </div>
                                <div>
                                    <label for="embedding_dim" class="block text-sm font-medium text-gray-700 mb-1">Embedding Dim</label>
                                    <input type="number" name="embedding_dim" id="embedding_dim" value="128" min="32" max="512"
                                           class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label for="max_features" class="block text-sm font-medium text-gray-700 mb-1">Max Features</label>
                                    <input type="number" name="max_features" id="max_features" value="5000" min="1000" max="20000"
                                           class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                            </div>
                            <div>
                                <label for="train_file" class="block text-sm font-medium text-gray-700 mb-1">Training Text (TXT, MD)</label>
                                <input type="file" name="file" id="train_file" accept=".txt,.md" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <button type="submit" id="trainModelBtn" class="w-full md:w-auto px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors font-medium">
                                🚀 Train Model
                            </button>
                            
                            <!-- Progress indicator (hidden by default) -->
                            <div id="modelTrainingProgress" class="hidden mt-4">
                                <div class="flex items-center justify-center space-x-3">
                                    <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600"></div>
                                    <div class="text-gray-700">
                                        <p class="font-medium">Training custom model...</p>
                                        <p class="text-sm text-gray-500">This may take 5-60 seconds depending on corpus size. Please wait...</p>
                                    </div>
                                </div>
                                <div class="mt-3 w-full bg-gray-200 rounded-full h-2.5">
                                    <div class="bg-green-600 h-2.5 rounded-full animate-pulse" style="width: 100%"></div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Custom Models List -->
                    <div class="bg-white rounded-lg shadow p-6">
                        <h2 class="text-xl font-semibold text-gray-900 mb-4">Your Custom Models</h2>
                        {% if custom_models %}
                        <div class="space-y-2">
                            {% for model in custom_models %}
                            <div class="p-4 border border-gray-200 rounded-md hover:bg-gray-50 transition-colors">
                                <h3 class="font-medium text-gray-900">{{ model.name }}</h3>
                                <p class="text-sm text-gray-500">
                                    {{ model.embedding_dim }}d embeddings • {{ model.num_chunks }} training chunks
                                </p>
                            </div>
                            {% endfor %}
                        </div>
                        {% else %}
                        <p class="text-gray-500 italic">No custom models yet. Train one above.</p>
                        {% endif %}
                    </div>
                </div>

                <!-- Upload History Tab -->
                <div x-show="activeTab === 'history'" x-cloak>
                    <div class="bg-white rounded-lg shadow p-6">
                        <h2 class="text-xl font-semibold text-gray-900 mb-4">Upload History</h2>
                        {% if upload_history %}
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Filename</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Target</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Uploaded At</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    {% for entry in upload_history %}
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm">
                                            {% if entry.type == 'kb_upload' %}
                                            <span class="px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded">KB Upload</span>
                                            {% else %}
                                            <span class="px-2 py-1 text-xs font-medium bg-green-100 text-green-800 rounded">Model Training</span>
                                            {% endif %}
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-900 font-mono">{{ entry.filename }}</td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            {% if entry.type == 'kb_upload' %}
                                            KB: {{ entry.kb_name }}
                                            {% else %}
                                            Model: {{ entry.model_name }}
                                            {% endif %}
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ entry.uploaded_at }}</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        {% if total_purged > 0 %}
                        <div class="mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
                            <p class="text-sm text-yellow-800">
                                ⚠️ {{ total_purged }} older entries have been purged (keeping last 50 entries)
                            </p>
                        </div>
                        {% endif %}
                        {% else %}
                        <p class="text-gray-500 italic">No upload history yet. Upload documents or train models to see history.</p>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-white border-t border-gray-200 mt-auto">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <p class="text-center text-sm text-gray-500">
                Copyright © Krishnamoorthy Sankaran | 
                <a href="https://github.com/sekarkrishna/justembed" target="_blank" class="text-blue-600 hover:text-blue-800">GitHub</a> | 
                <a href="https://pypi.org/project/justembed" target="_blank" class="text-blue-600 hover:text-blue-800">PyPI</a>
            </p>
        </div>
    </footer>

    <script>
        const customModels = {{ custom_models | tojson }};
        const workspacePath = {{ workspace | tojson }};
        
        function updateModelName() {
            const modelType = document.getElementById('model_type').value;
            const modelNameSelect = document.getElementById('model_name');
            
            // Clear existing options
            modelNameSelect.innerHTML = '';
            
            if (modelType === 'e5') {
                const option = document.createElement('option');
                option.value = 'e5-small';
                option.textContent = 'Inbuilt Model (E5-Small)';
                modelNameSelect.appendChild(option);
            } else if (modelType === 'custom') {
                if (customModels.length === 0) {
                    const option = document.createElement('option');
                    option.value = '';
                    option.textContent = 'No custom models available';
                    modelNameSelect.appendChild(option);
                } else {
                    customModels.forEach(model => {
                        const option = document.createElement('option');
                        option.value = model.name;
                        option.textContent = `${model.name} (${model.embedding_dim}d, ${model.num_chunks} chunks)`;
                        modelNameSelect.appendChild(option);
                    });
                }
            }
        }

        // Auto-switch to KB tab if new_kb parameter is present or tab parameter
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const newKb = urlParams.get('new_kb');
            const tab = urlParams.get('tab');
            
            // Get Alpine.js component
            const tabsDiv = document.querySelector('[x-data]');
            if (tabsDiv && tabsDiv.__x) {
                if (newKb) {
                    tabsDiv.__x.$data.activeTab = 'kbs';
                } else if (tab) {
                    tabsDiv.__x.$data.activeTab = tab;
                }
            }
        });

        function showRegisterWorkspace() {
            document.getElementById('registerWorkspaceModal').classList.remove('hidden');
        }

        function hideRegisterWorkspace() {
            document.getElementById('registerWorkspaceModal').classList.add('hidden');
        }

        function showDeregisterWorkspace() {
            document.getElementById('deregisterWorkspaceModal').classList.remove('hidden');
        }

        function hideDeregisterWorkspace() {
            document.getElementById('deregisterWorkspaceModal').classList.add('hidden');
            document.getElementById('deregisterConfirm').value = '';
        }

        function validateDeregister() {
            const confirmPath = document.getElementById('deregisterConfirm').value;
            if (confirmPath !== workspacePath) {
                alert('Workspace path does not match. Please type the exact path to confirm deregistration.');
                return false;
            }
            return confirm('Deregister this workspace? (Data will stay on disk - not deleted)');
        }
        
        function showModelTrainingProgress() {
            // Hide the form button
            document.getElementById('trainModelBtn').disabled = true;
            document.getElementById('trainModelBtn').classList.add('opacity-50', 'cursor-not-allowed');
            document.getElementById('trainModelBtn').textContent = 'Training...';
            
            // Show progress indicator
            document.getElementById('modelTrainingProgress').classList.remove('hidden');
        }
    </script>
</body>
</html>
