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

{% block title %}MCP Servers - Auth MCP Admin{% endblock %}

{% block content %}
<div x-data="mcpServersManager()" @click="handleAction($event)">
    <!-- Header -->
    <div class="flex items-center justify-between mb-8">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 flex items-center gap-3">
                <i data-lucide="server" class="w-8 h-8 text-blue-600"></i>
                MCP Servers
            </h1>
            <p class="text-gray-600 mt-1">Manage backend MCP server connections</p>
        </div>
        <button
            @click="showAddModal = true"
            class="px-4 py-2 bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white rounded-lg shadow-sm transition-colors flex items-center gap-2"
        >
            <i data-lucide="plus-circle" class="w-4 h-4"></i>
            Add Server
        </button>
    </div>

    <!-- Gateway Endpoints Info -->
    <div class="bg-blue-50 border-l-4 border-blue-500 rounded-lg p-4 mb-6">
        <div class="flex items-start gap-3">
            <i data-lucide="info" class="w-5 h-5 text-blue-600 mt-0.5"></i>
            <div class="flex-1">
                <p class="font-semibold text-blue-900 mb-2">Gateway Endpoints:</p>
                <div class="space-y-2">
                    <div class="flex items-center gap-2">
                        <code class="px-3 py-1 bg-white rounded border border-blue-200 text-blue-700 text-sm" id="aggregatedEndpoint">Loading...</code>
                        <button data-action="copy-aggregated"
                                class="p-1.5 text-blue-600 hover:bg-blue-100 rounded transition-colors" title="Copy URL">
                            <i data-lucide="clipboard" class="w-4 h-4"></i>
                        </button>
                        <span class="text-sm text-blue-700">All servers aggregated (with prefixes)</span>
                    </div>
                    <p class="text-sm text-blue-700">Each server below also has its own dedicated endpoint for individual access.</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Servers Grid -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6" id="serversList">
        <!-- Populated by JavaScript -->
    </div>

    <!-- Add Server Modal -->
    <div x-show="showAddModal" x-cloak
         role="dialog" aria-modal="true" aria-labelledby="addServerTitle"
         x-effect="if (showAddModal) { $nextTick(() => { window._addTrap = trapFocus($el); }) } else if (window._addTrap) { window._addTrap.release(); }"
         class="fixed inset-0 z-50 overflow-y-auto" @keydown.escape.window="showAddModal = false">
        <div class="flex items-end sm:items-center justify-center min-h-screen">
            <div class="fixed inset-0 bg-black/60 backdrop-blur-sm" @click="showAddModal = false"></div>

            <div class="bg-white sm:rounded-xl rounded-t-2xl shadow-2xl z-10 w-full sm:max-w-lg relative sm:my-8 max-h-[95vh] sm:max-h-[90vh] overflow-hidden border-t-2 sm:border-2 border-blue-100 animate-slide-up">
                <!-- Modal Header with Gradient -->
                <div class="bg-gradient-to-r from-blue-600 via-cyan-600 to-cyan-700 px-4 sm:px-6 py-4 sm:py-4 flex items-center justify-between sticky top-0 z-10">
                    <h3 id="addServerTitle" class="text-lg sm:text-xl font-bold text-white flex items-center gap-2">
                        <i data-lucide="server" class="w-5 sm:w-6 h-5 sm:h-6"></i>
                        Add MCP Server
                    </h3>
                    <button @click="showAddModal = false" class="text-white/80 hover:text-white hover:bg-white/10 rounded-lg p-2 transition-all touch-manipulation">
                        <i data-lucide="x" class="w-5 h-5"></i>
                    </button>
                </div>

                <!-- Modal Body -->
                <div class="p-4 sm:p-6 overflow-y-auto" style="max-height: calc(95vh - 140px);">
                    <form id="addServerForm" @submit.prevent="addServer">
                        <div class="space-y-4 sm:space-y-4">
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Name <span class="text-red-600">*</span></label>
                                <input type="text" id="serverName" required
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-medium text-base">
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Description</label>
                                <textarea id="serverDescription" rows="3"
                                          class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-medium text-base resize-none"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">URL <span class="text-red-600">*</span></label>
                                <input type="url" id="serverUrl" placeholder="http://localhost:8080/mcp" required
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-mono text-sm break-all">
                                <p class="text-xs text-gray-600 mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span>Full MCP endpoint URL</span>
                                </p>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Tool Prefix</label>
                                <input type="text" id="serverPrefix" placeholder="myserver_"
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-mono text-sm">
                                <p class="text-xs text-gray-600 mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span>Prefix for tool names (e.g., myserver_tool1)</span>
                                </p>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Auth Type</label>
                                <select id="serverAuthType" x-model="authType"
                                        class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-medium text-base">
                                    <option value="none">None</option>
                                    <option value="bearer">Bearer Token</option>
                                    <option value="basic">Basic Auth</option>
                                </select>
                            </div>
                            <div x-show="authType !== 'none'">
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Auth Token</label>
                                <input type="text" id="serverAuthToken"
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-mono text-sm break-all">
                                <p class="text-xs text-gray-600 mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span x-text="authType === 'bearer' ? 'JWT or API token' : 'Username:Password (base64 encoded)'"></span>
                                </p>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Request Timeout (seconds)</label>
                                <input type="number" id="serverTimeout" min="1" max="600" placeholder="{{ default_timeout }}"
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all font-medium text-base">
                                <p class="text-xs text-gray-600 mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span>Per-server timeout override. Current global default: <strong>{{ default_timeout }}s</strong></span>
                                </p>
                            </div>
                            <div class="flex items-center bg-blue-50 p-3 sm:p-3 rounded-lg border border-blue-200 gap-3">
                                <input type="checkbox" id="serverEnabled" checked
                                       class="w-5 h-5 sm:w-5 sm:h-5 text-blue-600 border-gray-400 rounded focus:ring-blue-500 flex-shrink-0">
                                <label for="serverEnabled" class="text-sm sm:text-sm font-bold text-gray-800 leading-tight">Enabled</label>
                            </div>
                        </div>

                        <div class="flex gap-3 mt-6 pt-4 border-t border-gray-200 sticky bottom-0 bg-white -mx-4 sm:-mx-0 px-4 sm:px-0 pb-4 sm:pb-0">
                            <button type="button" @click="showAddModal = false"
                                    class="flex-1 px-4 py-3 sm:py-2.5 border-2 border-gray-400 text-gray-700 font-bold rounded-lg hover:bg-gray-100 hover:border-gray-600 transition-all touch-manipulation">
                                Cancel
                            </button>
                            <button type="submit"
                                    class="flex-1 px-4 py-3 sm:py-2.5 bg-gradient-to-r from-blue-600 via-cyan-600 to-cyan-700 hover:from-blue-700 hover:via-cyan-700 hover:to-cyan-800 text-white font-bold rounded-lg shadow-lg hover:shadow-xl transition-all touch-manipulation">
                                <span class="flex items-center justify-center gap-2">
                                    <i data-lucide="plus-circle" class="w-4 h-4"></i>
                                    Add Server
                                </span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Server Modal -->
    <div x-show="showEditModal" x-cloak
         role="dialog" aria-modal="true" aria-labelledby="editServerTitle"
         x-effect="if (showEditModal) { $nextTick(() => { window._editTrap = trapFocus($el); }) } else if (window._editTrap) { window._editTrap.release(); }"
         class="fixed inset-0 z-50 overflow-y-auto" @keydown.escape.window="showEditModal = false">
        <div class="flex items-end sm:items-center justify-center min-h-screen">
            <div class="fixed inset-0 bg-black/60 backdrop-blur-sm" @click="showEditModal = false"></div>

            <div class="bg-white sm:rounded-xl rounded-t-2xl shadow-2xl z-10 w-full sm:max-w-lg relative sm:my-8 max-h-[95vh] sm:max-h-[90vh] overflow-hidden border-t-2 sm:border-2 border-orange-100 animate-slide-up">
                <!-- Modal Header with Gradient -->
                <div class="bg-gradient-to-r from-orange-600 via-red-600 to-red-700 px-4 sm:px-6 py-4 sm:py-4 flex items-center justify-between sticky top-0 z-10">
                    <h3 id="editServerTitle" class="text-lg sm:text-xl font-bold text-white flex items-center gap-2">
                        <i data-lucide="edit" class="w-5 sm:w-6 h-5 sm:h-6"></i>
                        Edit MCP Server
                    </h3>
                    <button @click="showEditModal = false" class="text-white/80 hover:text-white hover:bg-white/10 rounded-lg p-2 transition-all touch-manipulation">
                        <i data-lucide="x" class="w-5 h-5"></i>
                    </button>
                </div>

                <!-- Modal Body -->
                <div class="p-4 sm:p-6 overflow-y-auto" style="max-height: calc(95vh - 140px);">
                    <form id="editServerForm" @submit.prevent="updateServer">
                        <input type="hidden" id="editServerId">
                        <div class="space-y-4 sm:space-y-4">
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Name <span class="text-red-600">*</span></label>
                                <input type="text" id="editServerName" required
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all font-medium text-base">
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Description</label>
                                <textarea id="editServerDescription" rows="3"
                                          class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all font-medium text-base resize-none"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">URL <span class="text-red-600">*</span></label>
                                <input type="url" id="editServerUrl" placeholder="http://localhost:8080/mcp" required
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all font-mono text-sm break-all">
                                <p class="text-xs text-gray-600 mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span>Full MCP endpoint URL</span>
                                </p>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Tool Prefix</label>
                                <input type="text" id="editServerPrefix" placeholder="myserver_"
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all font-mono text-sm">
                                <p class="text-xs text-gray-600 mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span>Prefix for tool names (e.g., myserver_tool1)</span>
                                </p>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Auth Type</label>
                                <select id="editServerAuthType" x-model="editAuthType"
                                        class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all font-medium text-base">
                                    <option value="none">None</option>
                                    <option value="bearer">Bearer Token</option>
                                    <option value="basic">Basic Auth</option>
                                </select>
                            </div>
                            <div x-show="editAuthType !== 'none'">
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Auth Token</label>
                                <input type="text" id="editServerAuthToken"
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all font-mono text-sm break-all">
                                <p class="text-xs text-amber-800 bg-amber-50 p-2.5 rounded mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="alert-triangle" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span>Leave empty to keep existing token</span>
                                </p>
                            </div>
                            <div>
                                <label class="block text-sm sm:text-sm font-bold text-gray-800 mb-2">Request Timeout (seconds)</label>
                                <input type="number" id="editServerTimeout" min="1" max="600" placeholder="{{ default_timeout }}"
                                       class="w-full px-3 sm:px-4 py-3 sm:py-2.5 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all font-medium text-base">
                                <p class="text-xs text-gray-600 mt-2 flex items-start gap-1.5 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                    <span>Per-server timeout override. Current global default: <strong>{{ default_timeout }}s</strong></span>
                                </p>
                            </div>
                            <div class="flex items-center bg-orange-50 p-3 sm:p-3 rounded-lg border border-orange-200 gap-3">
                                <input type="checkbox" id="editServerEnabled" class="w-5 h-5 sm:w-5 sm:h-5 text-orange-600 border-gray-400 rounded focus:ring-orange-500 flex-shrink-0">
                                <label for="editServerEnabled" class="text-sm sm:text-sm font-bold text-gray-800 leading-tight">Enabled</label>
                            </div>
                        </div>

                        <div class="flex gap-3 mt-6 pt-4 border-t border-gray-200 sticky bottom-0 bg-white -mx-4 sm:-mx-0 px-4 sm:px-0 pb-4 sm:pb-0">
                            <button type="button" @click="showEditModal = false"
                                    class="flex-1 px-4 py-3 sm:py-2.5 border-2 border-gray-400 text-gray-700 font-bold rounded-lg hover:bg-gray-100 hover:border-gray-600 transition-all touch-manipulation">
                                Cancel
                            </button>
                            <button type="submit"
                                    class="flex-1 px-4 py-3 sm:py-2.5 bg-gradient-to-r from-orange-600 via-red-600 to-red-700 hover:from-orange-700 hover:via-red-700 hover:to-red-800 text-white font-bold rounded-lg shadow-lg hover:shadow-xl transition-all touch-manipulation">
                                <span class="flex items-center justify-center gap-2">
                                    <i data-lucide="save" class="w-4 h-4"></i>
                                    Update Server
                                </span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- End of mcpServersManager -->

{% endblock %}

{% block extra_scripts %}
<script>
    function mcpServersManager() {
        return {
            showAddModal: false,
            showEditModal: false,
            authType: 'none',
            editAuthType: 'none',
            currentServers: [],

            init() {
                document.getElementById('aggregatedEndpoint').textContent = window.location.origin + '/mcp';
                this.loadServers();
            },

            handleAction(event) {
                const btn = event.target.closest('[data-action]');
                if (!btn) return;
                const action = btn.dataset.action;
                const id = btn.dataset.id ? parseInt(btn.dataset.id) : null;

                if (action === 'edit') this.editServer(id);
                else if (action === 'test') this.testServer(id);
                else if (action === 'delete') this.deleteServer(id);
                else if (action === 'toggle-tools') this.toggleTools(id);
                else if (action === 'copy-endpoint') this.copyServerEndpoint(btn);
                else if (action === 'copy-aggregated') this.copyToClipboard(document.getElementById('aggregatedEndpoint').textContent, btn);
            },

            async loadServers() {
                try {
                    const [serversResponse, tokenStatusResponse] = await Promise.all([
                        fetch('/admin/api/mcp-servers'),
                        fetch('/admin/api/mcp-servers/token-status')
                    ]);

                    const serversData = await serversResponse.json();
                    const tokenData = await tokenStatusResponse.json();

                    this.currentServers = serversData.servers || [];

                    const tokenStatusMap = {};
                    tokenData.servers.forEach(s => {
                        tokenStatusMap[s.id] = s.token_status;
                    });

                    const container = document.getElementById('serversList');
                    container.innerHTML = '';

                    if (this.currentServers.length === 0) {
                        container.innerHTML = '<div class="col-span-2"><div class="bg-blue-50 border border-blue-200 rounded-lg p-6 text-center"><i data-lucide="info" class="w-8 h-8 text-blue-600 mx-auto mb-2"></i><p class="text-blue-800">No MCP servers configured yet. Click "Add Server" to get started!</p></div></div>';
                        setTimeout(() => lucide.createIcons(), 100);
                        return;
                    }

                    this.currentServers.forEach(server => {
                        server.token_status = tokenStatusMap[server.id] || { status: 'none' };
                        container.innerHTML += this.createServerCard(server);
                    });

                    setTimeout(() => lucide.createIcons(), 100);
                } catch (error) {
                    console.error('Failed to load servers:', error);
                    document.getElementById('serversList').innerHTML =
                        '<div class="col-span-2 bg-red-50 border border-red-200 rounded-lg p-4 text-red-800">Failed to load servers</div>';
                }
            },

            createServerCard(server) {
                const statusColors = {
                    'online': 'border-green-600 bg-gradient-to-br from-green-50 to-emerald-50',
                    'offline': 'border-red-600 bg-gradient-to-br from-red-50 to-orange-50',
                    'error': 'border-amber-600 bg-gradient-to-br from-amber-50 to-yellow-50',
                    'unknown': 'border-gray-400 bg-gradient-to-br from-gray-50 to-slate-50'
                };

                const statusIcons = {
                    'online': '<i data-lucide="check-circle" class="w-5 h-5 text-green-600"></i>',
                    'offline': '<i data-lucide="x-circle" class="w-5 h-5 text-red-600"></i>',
                    'error': '<i data-lucide="alert-triangle" class="w-5 h-5 text-amber-600"></i>',
                    'unknown': '<i data-lucide="help-circle" class="w-5 h-5 text-gray-600"></i>'
                };

                const statusBadgeColors = {
                    'online': 'bg-green-600 text-white shadow-sm',
                    'offline': 'bg-red-600 text-white shadow-sm',
                    'error': 'bg-amber-600 text-white shadow-sm',
                    'unknown': 'bg-gray-600 text-white shadow-sm'
                };

                return `
                    <div class="bg-white rounded-lg shadow-md border-l-4 ${statusColors[server.status] || statusColors.unknown} overflow-hidden hover:shadow-lg transition-all duration-200">
                        <div class="p-4">
                            <div class="flex justify-between items-start gap-3">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-2">
                                        ${statusIcons[server.status] || statusIcons.unknown}
                                        <h3 class="text-lg font-bold text-gray-900 truncate">
                                            ${esc(server.name)}
                                        </h3>
                                        ${!server.enabled ? '<span class="px-2 py-0.5 text-xs font-bold rounded-full bg-gray-600 text-white">Disabled</span>' : ''}
                                    </div>
                                    ${server.description ? `<p class="text-gray-700 text-sm mb-2 line-clamp-2">${esc(server.description)}</p>` : ''}

                                    <div class="space-y-1.5 text-sm">
                                        <p class="text-gray-700 flex items-center gap-1.5">
                                            <i data-lucide="link" class="w-3.5 h-3.5 text-gray-500"></i>
                                            <code class="text-xs bg-gray-200 px-1.5 py-0.5 rounded font-mono text-gray-800">${esc(server.url)}</code>
                                        </p>
                                        ${server.tool_prefix ? `
                                            <p class="text-gray-700 flex items-center gap-1.5">
                                                <i data-lucide="tag" class="w-3.5 h-3.5 text-gray-500"></i>
                                                <code class="text-xs bg-blue-100 px-1.5 py-0.5 rounded font-mono text-blue-800">${esc(server.tool_prefix)}</code>
                                            </p>
                                        ` : ''}
                                        ${server.timeout ? `
                                            <p class="text-gray-700 flex items-center gap-1.5">
                                                <i data-lucide="clock" class="w-3.5 h-3.5 text-gray-500"></i>
                                                <span class="text-xs">Timeout: <strong>${server.timeout}s</strong></span>
                                            </p>
                                        ` : ''}
                                    </div>

                                    <!-- Gateway Endpoint -->
                                    <div class="mt-3 p-2.5 bg-gradient-to-r from-blue-100 to-cyan-100 border-l-2 border-blue-600 rounded">
                                        <p class="text-xs font-bold text-blue-900 mb-1 flex items-center gap-1">
                                            <i data-lucide="arrow-right-circle" class="w-3.5 h-3.5"></i>
                                            Gateway Endpoint
                                        </p>
                                        <div class="flex items-center gap-1.5">
                                            <code class="flex-1 text-xs text-blue-800 font-mono font-semibold" data-path="/mcp/${esc(server.name.toLowerCase().replace(/\s+/g, ''))}">/mcp/${esc(server.name.toLowerCase().replace(/\s+/g, ''))}</code>
                                            <button data-action="copy-endpoint"
                                                    class="p-1 text-blue-700 hover:bg-blue-200 rounded transition-colors" title="Copy full URL">
                                                <i data-lucide="clipboard" class="w-3.5 h-3.5"></i>
                                            </button>
                                        </div>
                                    </div>

                                    <div class="flex items-center gap-2 mt-3 flex-wrap">
                                        <span class="px-2.5 py-1 text-xs font-bold rounded-full ${statusBadgeColors[server.status] || statusBadgeColors.unknown}">
                                            ${server.status.toUpperCase()}
                                        </span>
                                        <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-cyan-600 text-white shadow-sm">
                                            ${server.tools_count || 0} tools
                                        </span>
                                        ${server.token_status && server.token_status.status === 'warning' ? `
                                            <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-yellow-500 text-white shadow-sm flex items-center gap-1" title="Expires: ${server.token_status.expires_at_formatted}">
                                                <i data-lucide="clock" class="w-3 h-3"></i>
                                                Expires in ${server.token_status.days_left}d
                                            </span>
                                        ` : ''}
                                        ${server.token_status && server.token_status.status === 'expired' ? `
                                            <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-red-500 text-white shadow-sm flex items-center gap-1" title="Expired: ${server.token_status.expires_at_formatted}">
                                                <i data-lucide="alert-circle" class="w-3 h-3"></i>
                                                Expired ${Math.abs(server.token_status.days_left)}d ago
                                            </span>
                                        ` : ''}
                                        ${server.token_status && server.token_status.status === 'ok' ? `
                                            <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-emerald-600 text-white shadow-sm flex items-center gap-1" title="Expires: ${server.token_status.expires_at_formatted}">
                                                <i data-lucide="check-circle" class="w-3 h-3"></i>
                                                Valid (${server.token_status.days_left}d left)
                                            </span>
                                        ` : ''}
                                        ${server.token_status && server.token_status.status === 'never' ? `
                                            <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-blue-600 text-white shadow-sm flex items-center gap-1" title="Token never expires">
                                                <i data-lucide="infinity" class="w-3 h-3"></i>
                                                Never expires
                                            </span>
                                        ` : ''}
                                        ${server.token_status && server.token_status.status === 'unknown' ? `
                                            <span class="px-2.5 py-1 text-xs font-bold rounded-full bg-gray-500 text-white shadow-sm flex items-center gap-1" title="${esc(server.token_status.message || 'Not a JWT token')}">
                                                <i data-lucide="help-circle" class="w-3 h-3"></i>
                                                Unknown expiration
                                            </span>
                                        ` : ''}
                                    </div>

                                    ${server.last_error ? `
                                        <div class="mt-2 p-2 bg-amber-100 border-l-2 border-amber-600 rounded">
                                            <p class="text-xs text-amber-900 flex items-start gap-1.5 font-medium">
                                                <i data-lucide="alert-triangle" class="w-3.5 h-3.5 mt-0.5 flex-shrink-0"></i>
                                                <span class="line-clamp-2">${esc(server.last_error)}</span>
                                            </p>
                                        </div>
                                    ` : ''}

                                    <div class="mt-2">
                                        <button data-action="toggle-tools" data-id="${server.id}" id="toolsBtn${server.id}"
                                                class="text-xs px-2.5 py-1.5 border-2 border-gray-400 text-gray-800 font-semibold rounded-lg hover:bg-gray-100 hover:border-gray-600 transition-all flex items-center gap-1.5">
                                            <i data-lucide="wrench" class="w-3.5 h-3.5"></i>
                                            Show Tools (${server.tools_count || 0})
                                        </button>
                                        <div id="tools${server.id}" class="hidden mt-2 p-2 bg-gray-100 rounded border border-gray-300">
                                            <p class="text-sm text-gray-600">Loading tools...</p>
                                        </div>
                                    </div>
                                </div>

                                <div class="flex lg:flex-col flex-row gap-1.5 ml-3 lg:ml-0">
                                    <button data-action="edit" data-id="${server.id}"
                                            class="p-2.5 lg:p-2 text-blue-700 hover:bg-blue-100 rounded-lg transition-colors border border-blue-300 hover:border-blue-500 touch-manipulation" title="Edit">
                                        <i data-lucide="edit" class="w-5 h-5 lg:w-4 lg:h-4"></i>
                                    </button>
                                    <button data-action="test" data-id="${server.id}"
                                            class="p-2.5 lg:p-2 text-cyan-700 hover:bg-cyan-100 rounded-lg transition-colors border border-cyan-300 hover:border-cyan-500 touch-manipulation" title="Test">
                                        <i data-lucide="activity" class="w-5 h-5 lg:w-4 lg:h-4"></i>
                                    </button>
                                    <button data-action="delete" data-id="${server.id}"
                                            class="p-2.5 lg:p-2 text-red-700 hover:bg-red-100 rounded-lg transition-colors border border-red-300 hover:border-red-500 touch-manipulation" title="Delete">
                                        <i data-lucide="trash-2" class="w-5 h-5 lg:w-4 lg:h-4"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            },

            async toggleTools(serverId) {
                const toolsDiv = document.getElementById(`tools${serverId}`);

                if (!toolsDiv.classList.contains('hidden')) {
                    toolsDiv.classList.add('hidden');
                    return;
                }

                toolsDiv.classList.remove('hidden');

                try {
                    const response = await fetch(`/admin/api/mcp-servers/${serverId}/tools`);
                    const tools = await response.json();

                    if (tools.length === 0) {
                        toolsDiv.innerHTML = '<p class="text-sm text-gray-500">No tools available</p>';
                    } else {
                        toolsDiv.innerHTML = `<div class="flex flex-wrap gap-2">${tools.map(tool =>
                            `<span class="px-2 py-1 text-xs bg-white border border-gray-300 text-gray-700 rounded">${esc(tool)}</span>`
                        ).join('')}</div>`;
                    }
                } catch (error) {
                    toolsDiv.innerHTML = '<p class="text-sm text-red-600">Failed to load tools</p>';
                }
            },

            async addServer() {
                const timeoutVal = document.getElementById('serverTimeout').value;
                const data = {
                    name: document.getElementById('serverName').value,
                    url: document.getElementById('serverUrl').value,
                    description: document.getElementById('serverDescription').value,
                    tool_prefix: document.getElementById('serverPrefix').value,
                    auth_type: document.getElementById('serverAuthType').value,
                    auth_token: document.getElementById('serverAuthToken').value,
                    enabled: document.getElementById('serverEnabled').checked,
                    timeout: timeoutVal ? parseInt(timeoutVal) : null
                };

                try {
                    const response = await fetch('/admin/api/mcp-servers', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify(data)
                    });

                    if (response.ok) {
                        document.getElementById('addServerForm').reset();
                        this.authType = 'none';
                        this.showAddModal = false;
                        await this.loadServers();
                    } else {
                        const error = await response.json();
                        showToast('Failed to add server: ' + (error.detail || 'Unknown error'), 'error');
                    }
                } catch (error) {
                    showToast(error.message, 'error');
                }
            },

            async testServer(serverId) {
                try {
                    const response = await fetch(`/admin/api/mcp-servers/${serverId}/test`, {
                        method: 'POST'
                    });
                    const result = await response.json();

                    if (result.status === 'online') {
                        showToast(`Server is online! Tools found: ${result.tools_count || 0}`);
                    } else {
                        showToast(result.error || 'Server check failed', 'error');
                    }

                    await this.loadServers();
                } catch (error) {
                    showToast(error.message, 'error');
                }
            },

            async deleteServer(serverId) {
                const server = this.currentServers.find(s => s.id === serverId);
                const serverName = server ? server.name : `#${serverId}`;
                if (!confirm(`Are you sure you want to delete server "${serverName}"?`)) return;

                try {
                    const response = await fetch(`/admin/api/mcp-servers/${serverId}`, {
                        method: 'DELETE'
                    });

                    if (response.ok) {
                        await this.loadServers();
                    } else {
                        showToast('Failed to delete server', 'error');
                    }
                } catch (error) {
                    showToast(error.message, 'error');
                }
            },

            editServer(serverId) {
                const server = this.currentServers.find(s => s.id === serverId);
                if (!server) {
                    showToast('Server not found', 'error');
                    return;
                }

                document.getElementById('editServerId').value = server.id;
                document.getElementById('editServerName').value = server.name;
                document.getElementById('editServerDescription').value = server.description || '';
                document.getElementById('editServerUrl').value = server.url;
                document.getElementById('editServerPrefix').value = server.tool_prefix || '';
                document.getElementById('editServerAuthType').value = server.auth_type || 'none';
                document.getElementById('editServerTimeout').value = server.timeout || '';
                document.getElementById('editServerEnabled').checked = server.enabled;

                this.editAuthType = server.auth_type || 'none';

                document.getElementById('editServerAuthToken').value = '';

                this.showEditModal = true;
                setTimeout(() => lucide.createIcons(), 100);
            },

            async updateServer() {
                const serverId = document.getElementById('editServerId').value;
                const editTimeoutVal = document.getElementById('editServerTimeout').value;
                const data = {
                    name: document.getElementById('editServerName').value,
                    url: document.getElementById('editServerUrl').value,
                    description: document.getElementById('editServerDescription').value,
                    tool_prefix: document.getElementById('editServerPrefix').value,
                    auth_type: document.getElementById('editServerAuthType').value,
                    enabled: document.getElementById('editServerEnabled').checked,
                    timeout: editTimeoutVal ? parseInt(editTimeoutVal) : null
                };

                const authToken = document.getElementById('editServerAuthToken').value;
                if (authToken) {
                    data.auth_token = authToken;
                }

                try {
                    const response = await fetch(`/admin/api/mcp-servers/${serverId}`, {
                        method: 'PATCH',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify(data)
                    });

                    if (response.ok) {
                        this.showEditModal = false;
                        await this.loadServers();
                    } else {
                        const error = await response.json();
                        showToast('Failed to update server: ' + (error.detail || error.error || 'Unknown error'), 'error');
                    }
                } catch (error) {
                    showToast(error.message, 'error');
                }
            },

            async copyToClipboard(text, button) {
                try {
                    await navigator.clipboard.writeText(text);
                    const originalHtml = button.innerHTML;
                    button.innerHTML = '<i data-lucide="check" class="w-4 h-4"></i>';
                    button.classList.add('text-green-600');
                    setTimeout(() => {
                        button.innerHTML = originalHtml;
                        button.classList.remove('text-green-600');
                        lucide.createIcons();
                    }, 2000);
                } catch (error) {
                    showToast('Failed to copy: ' + error.message, 'error');
                }
            },

            copyServerEndpoint(button) {
                const codeEl = button.previousElementSibling;
                const path = codeEl.getAttribute('data-path');
                const fullUrl = window.location.origin + path;
                this.copyToClipboard(fullUrl, button);
            }
        }
    }
</script>
{% endblock %}
