<!doctype html>
<html
  lang="en"
  x-data="{ darkMode: (() => { try { return JSON.parse(localStorage.getItem('darkMode') || 'false') } catch(e) { window.Admin?.logRestrictedContext?.(e); return false } })() }"
  x-bind:class="darkMode ? 'dark' : ''"
  x-init="$watch('darkMode', val => { try { localStorage.setItem('darkMode', val) } catch(e) { window.Admin?.logRestrictedContext?.(e); } })"
>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ContextForge - Gateway Administration</title>

    <!-- Security headers are set by middleware, not meta tags -->
    <!-- Favicon -->
    <link
      rel="icon"
      type="image/png"
      sizes="32x32"
      href="{{ root_path }}/static/favicon.ico"
    />
    <!-- Tailwind CSS -->
    {% if ui_airgapped %}
    <script src="{{ root_path }}/static/vendor/tailwindcss/tailwind.min.js"></script>
    {% else %}
    <!-- SRI intentionally omitted: Tailwind Play CDN is JIT and does not provide stable CORS/SRI semantics -->
    <script src="https://cdn.tailwindcss.com/3.4.17"></script>
    {% endif %}
    <script nonce="{{ csp_nonce(request) }}">
      if (window.tailwind && typeof window.tailwind === "object") {
        window.tailwind.config = {
          darkMode: "class",
        };
      }
    </script>
    <!-- HTMX is now bundled in the main JS bundle -->
    <script nonce="{{ csp_nonce(request) }}">
      // Configure HTMX to swap content on 4xx responses (for inline error display)
      document.addEventListener("htmx:beforeSwap", function (evt) {
        const xhr = evt.detail.xhr;
        if (!xhr || xhr.status < 400 || xhr.status >= 500) {
          return;
        }
        const triggerEl = evt.detail.elt;
        const requestEl = evt.detail.requestConfig?.elt;
        const isTeamForm =
          (triggerEl &&
            triggerEl.closest('[data-team-validation="true"]')) ||
          (requestEl &&
            requestEl.closest('[data-team-validation="true"]'));
        const hasRetarget = !!xhr.getResponseHeader("HX-Retarget");
        if (isTeamForm || hasRetarget) {
          evt.detail.shouldSwap = true;
          evt.detail.isError = false;
        }
      });

      // Configure HTMX to include credentials and JWT tokens
      document.addEventListener("htmx:configRequest", function (evt) {
        // Force include credentials for same-origin requests
        evt.detail.credentials = "same-origin"; // pragma: allowlist secret
        evt.detail.headers = evt.detail.headers || {};

        // Add JWT token from cookie if available
        const jwtToken = getCookie("jwt_token");
        if (jwtToken) {
          evt.detail.headers["{{ auth_header_name|default('Authorization') }}"] = "Bearer " + jwtToken;
        }

        const csrfToken = getCookie("mcpgateway_csrf_token");
        if (csrfToken) {
          evt.detail.headers["X-CSRF-Token"] = csrfToken;
        }
      });

      // Helper function to get cookie value
      function getCookie(name) {
        const value = "; " + document.cookie;
        const parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
        return "";
      }

      function isUnsafeHttpMethod(method) {
        const normalized = (method || "GET").toUpperCase();
        return normalized !== "GET" && normalized !== "HEAD" && normalized !== "OPTIONS" && normalized !== "TRACE";
      }

      function isSameOriginRequest(resource) {
        try {
          if (resource instanceof Request) {
            return new URL(resource.url, window.location.origin).origin === window.location.origin;
          }
          return new URL(String(resource), window.location.origin).origin === window.location.origin;
        } catch (e) {
          return false;
        }
      }

      // Ensure all same-origin fetch mutations carry the CSRF header.
      (function wrapFetchWithCsrf() {
        if (window.__mcpgatewayCsrfFetchWrapped || typeof window.fetch !== "function") {
          return;
        }
        const originalFetch = window.fetch.bind(window);
        window.fetch = function(resource, init = {}) {
          const requestInit = init ? { ...init } : {};
          const methodFromRequest = resource instanceof Request ? resource.method : null;
          const method = (requestInit.method || methodFromRequest || "GET").toUpperCase();
          if (isUnsafeHttpMethod(method) && isSameOriginRequest(resource)) {
            const csrfToken = getCookie("mcpgateway_csrf_token");
            const jwtToken = getCookie("jwt_token");
            if (csrfToken || jwtToken) {
              const nextHeaders = new Headers(requestInit.headers || (resource instanceof Request ? resource.headers : undefined));
              const authHeaderName = "{{ auth_header_name|default('Authorization') }}";
              if (jwtToken && !nextHeaders.has(authHeaderName)) {
                nextHeaders.set(authHeaderName, "Bearer " + jwtToken);
              }
              if (csrfToken) {
                nextHeaders.set("X-CSRF-Token", csrfToken);
              }
              requestInit.headers = nextHeaders;
            }
          }
          return originalFetch(resource, requestInit);
        };
        window.__mcpgatewayCsrfFetchWrapped = true;
      })();

      // Add CSRF token to same-origin non-GET forms as a hidden field.
      document.addEventListener("submit", function (event) {
        const form = event.target;
        if (!(form instanceof HTMLFormElement)) {
          return;
        }
        const method = (form.getAttribute("method") || "GET").toUpperCase();
        if (!isUnsafeHttpMethod(method)) {
          return;
        }
        const action = form.getAttribute("action") || window.location.href;
        if (!isSameOriginRequest(action)) {
          return;
        }
        const csrfToken = getCookie("mcpgateway_csrf_token");
        if (!csrfToken) {
          return;
        }
        let tokenInput = form.querySelector('input[name="csrf_token"]');
        if (!tokenInput) {
          tokenInput = document.createElement("input");
          tokenInput.type = "hidden";
          tokenInput.name = "csrf_token";
          form.appendChild(tokenInput);
        }
        tokenInput.value = csrfToken;
      });

      // Helper function to get pagination parameters from URL (namespaced per table)
      function getPaginationParams(tableName) {
        const urlParams = new URLSearchParams(window.location.search);
        const prefix = tableName + '_';
        return {
          page: Math.max(1, parseInt(urlParams.get(prefix + 'page'), 10) || 1),
          perPage: Math.max(1, parseInt(urlParams.get(prefix + 'size'), 10) || 10),
          includeInactive: urlParams.get(prefix + 'inactive')
        };
      }

      // Helper function to build table URL with pagination params (namespaced per table)
      // URL state takes precedence over checkbox state for shareability
      function buildTableUrl(tableName, baseUrl, additionalParams = {}) {
        const params = getPaginationParams(tableName);
        const urlParams = new URLSearchParams(window.location.search);
        const prefix = tableName + '_';
        const url = new URL(baseUrl, window.location.origin);
        url.searchParams.set('page', params.page);
        url.searchParams.set('per_page', params.perPage);

        // Add additional parameters, but URL state takes precedence for include_inactive
        for (const [key, value] of Object.entries(additionalParams)) {
          if (key === 'include_inactive' && params.includeInactive !== null) {
            // URL state overrides checkbox state for shareability
            url.searchParams.set('include_inactive', params.includeInactive);
          } else if (value !== null && value !== undefined && value !== '') {
            url.searchParams.set(key, value);
          }
        }

        // If include_inactive wasn't in additionalParams but is in URL, still use it
        if (!additionalParams.hasOwnProperty('include_inactive') && params.includeInactive !== null) {
          url.searchParams.set('include_inactive', params.includeInactive);
        }

        // Preserve namespaced search state for shareable URLs
        const namespacedQuery = urlParams.get(prefix + 'q');
        const namespacedTags = urlParams.get(prefix + 'tags');
        if (namespacedQuery) {
          url.searchParams.set('q', namespacedQuery);
        }
        if (namespacedTags) {
          url.searchParams.set('tags', namespacedTags);
        }

        return url.pathname + url.search;
      }

      // Sync checkbox state from URL on page load (for shareable links)
      function syncCheckboxFromUrl(tableName, checkboxId) {
        const params = getPaginationParams(tableName);
        const urlParams = new URLSearchParams(window.location.search);
        if (params.includeInactive !== null) {
          const checkbox = document.getElementById(checkboxId);
          if (checkbox) {
            checkbox.checked = params.includeInactive === 'true';
          }
        } else if (urlParams.has('include_inactive')) {
          const checkbox = document.getElementById(checkboxId);
          if (checkbox) {
            checkbox.checked = urlParams.get('include_inactive') === 'true';
          }
        }
      }

      // Update URL when checkbox is toggled (namespaced)
      // Also resets page to 1 since HTMX reloads from page 1 when filter changes
      // Preserves params from other tables to avoid mixing/overwriting
      function updateInactiveUrlState(tableName, checked) {
        const currentUrl = new URL(window.location.href);
        const newParams = new URLSearchParams(currentUrl.searchParams);
        const prefix = tableName + '_';

        // Update current table's params only
        newParams.set(prefix + 'inactive', checked.toString());
        newParams.set(prefix + 'page', '1');  // Reset to page 1 when filter changes

        const newUrl = currentUrl.pathname + '?' + newParams.toString() + currentUrl.hash;
        window.Admin?.safeReplaceState?.({}, '', newUrl);
      }
    </script>

    <!-- CodeMirror -->
    {% if ui_airgapped %}
    <script src="{{ root_path }}/static/vendor/codemirror/codemirror.min.js"></script>
    <script src="{{ root_path }}/static/vendor/codemirror/addon/mode/simple.min.js"></script>
    <script src="{{ root_path }}/static/vendor/codemirror/mode/javascript/javascript.min.js"></script>
    <script src="{{ root_path }}/static/vendor/codemirror/mode/python/python.min.js"></script>
    <script src="{{ root_path }}/static/vendor/codemirror/mode/shell/shell.min.js"></script>
    <script src="{{ root_path }}/static/vendor/codemirror/mode/go/go.min.js"></script>
    <script src="{{ root_path }}/static/vendor/codemirror/mode/rust/rust.min.js"></script>
    {% else %}
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/codemirror.min.js"
      integrity="{{ sri_hashes.codemirror_js }}"
      crossorigin="anonymous">
    </script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/addon/mode/simple.min.js"
      integrity="{{ sri_hashes.codemirror_addon_simple }}"
      crossorigin="anonymous">
    </script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/mode/javascript/javascript.min.js"
      integrity="{{ sri_hashes.codemirror_mode_javascript }}"
      crossorigin="anonymous">
    </script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/mode/python/python.min.js"
      integrity="{{ sri_hashes.codemirror_mode_python }}"
      crossorigin="anonymous">
    </script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/mode/shell/shell.min.js"
      integrity="{{ sri_hashes.codemirror_mode_shell }}"
      crossorigin="anonymous">
    </script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/mode/go/go.min.js"
      integrity="{{ sri_hashes.codemirror_mode_go }}"
      crossorigin="anonymous">
    </script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/mode/rust/rust.min.js"
      integrity="{{ sri_hashes.codemirror_mode_rust }}"
      crossorigin="anonymous">
    </script>
    {% endif %}
    <!-- Alpine.js (requires unsafe-eval for reactive system) -->
    {% if ui_airgapped %}
    <script
      src="{{ root_path }}/static/vendor/alpinejs/alpine.min.js"
      defer
    ></script>
    {% else %}
    <script
      src="https://cdn.jsdelivr.net/npm/alpinejs@3.15.12/dist/cdn.min.js"
      integrity="{{ sri_hashes.alpinejs }}"
      crossorigin="anonymous"
      defer
    ></script>
    {% endif %}
    {% if is_admin %}
    <!-- Chart.js -->
    {% if ui_airgapped %}
    <script src="{{ root_path }}/static/vendor/chartjs/chart.umd.min.js"></script>
    {% else %}
    <script
      src="https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js"
      integrity="{{ sri_hashes.chartjs }}"
      crossorigin="anonymous">
    </script>
    {% endif %}
    {% endif %}
    <!-- Markdown and Sanitization -->
    {% if ui_airgapped %}
    <script src="{{ root_path }}/static/vendor/marked/marked.min.js"></script>
    <script src="{{ root_path }}/static/vendor/dompurify/purify.min.js"></script>
    {% else %}
    <script
      src="https://cdn.jsdelivr.net/npm/marked@18.0.3/lib/marked.umd.js"
      integrity="{{ sri_hashes.marked }}"
      crossorigin="anonymous">
    </script>
    <script
      src="https://cdn.jsdelivr.net/npm/dompurify@3.4.2/dist/purify.min.js"
      integrity="{{ sri_hashes.dompurify }}"
      crossorigin="anonymous">
    </script>
    {% endif %}
    <!-- Configure HTMX to use CSP nonce for inline event handlers BEFORE bundle loads -->
    <!-- CRITICAL LOAD-ORDER DEPENDENCY: This script MUST execute before admin.js bundle loads.
         admin.js reads window.htmxConfig.inlineScriptNonce to configure HTMX.
         If script tags are reordered, HTMX will silently lose the nonce and all
         HTMX-generated inline scripts will be blocked by CSP. -->
    <script nonce="{{ csp_nonce(request) }}">
      // HTMX needs the nonce configured before it processes any elements
      // This allows hx-on:* attributes to work with strict CSP
      window.htmxConfig = window.htmxConfig || {};
      window.htmxConfig.inlineScriptNonce = "{{ csp_nonce(request) }}";
    </script>
    <script src="{{ root_path }}/static/{{ bundle_js }}"></script>
    {% if is_admin %}
    <script src="{{ root_path }}/static/gantt-chart.js?v=3"></script>
    <script src="{{ root_path }}/static/flame-graph.js?v=1"></script>
    {% endif %}
    <!-- CodeMirror CSS -->
    {% if ui_airgapped %}
    <link
      href="{{ root_path }}/static/vendor/codemirror/codemirror.min.css"
      rel="stylesheet"
    />
    <link
      href="{{ root_path }}/static/vendor/codemirror/theme/monokai.min.css"
      rel="stylesheet"
    />
    {% else %}
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/codemirror.min.css"
      rel="stylesheet"
      integrity="{{ sri_hashes.codemirror_css }}"
      crossorigin="anonymous"
    />
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.20/theme/monokai.min.css"
      rel="stylesheet"
      integrity="{{ sri_hashes.codemirror_theme_monokai }}"
      crossorigin="anonymous"
    />
    {% endif %}
    <!-- Font Awesome -->
    {% if ui_airgapped %}
    <link rel="stylesheet" href="{{ root_path }}/static/vendor/fontawesome/css/all.min.css" />
    {% else %}
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"
      integrity="{{ sri_hashes.fontawesome }}"
      crossorigin="anonymous"
    />
    {% endif %}
    <link href="{{ root_path }}/static/admin.css" rel="stylesheet" />
    <link href="{{ root_path }}/static/gantt-chart.css" rel="stylesheet" />
    <link href="{{ root_path }}/static/flame-graph.css" rel="stylesheet" />
    <style>
      /* HTMX indicator visibility for bulk import only */
      #bulk-import-indicator {
        display: none;
      }
      .htmx-request #bulk-import-indicator {
        display: flex !important;
      }

      /* Team management styles */
      .filter-btn.active {
        background-color: #4f46e5 !important;
        color: white !important;
        border-color: #4f46e5 !important;
      }

      .team-card {
        transition: all 0.2s ease-in-out;
      }

      .team-card:hover {
        transform: translateY(-1px);
      }

      .relationship-badge {
        font-weight: 600;
      }
    </style>
  </head>

  <body class="bg-gray-100 dark:bg-gray-900">
    {% set hidden_sections = ui_hidden_sections | default([]) %}
    {% set hidden_header_items = ui_hidden_header_items | default([]) %}
    <div class="flex h-screen overflow-hidden" x-data="{ sidebarOpen: true, sidebarCollapsed: false }" @resize.window="if (window.innerWidth >= 1024) sidebarOpen = true">

      <!-- Mobile sidebar backdrop -->
      <div
        x-show="sidebarOpen"
        @click="sidebarOpen = false"
        class="fixed inset-0 bg-gray-900/50 z-10 lg:hidden"
        x-transition:enter="transition-opacity ease-linear duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="transition-opacity ease-linear duration-300"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        style="display: none;"
      ></div>

      <!-- Sidebar -->
      <aside
        id="sidebar"
        class="relative z-20 shrink-0 max-lg:fixed max-lg:top-0 max-lg:left-0 max-lg:h-screen max-lg:shadow-[4px_0_6px_-1px_rgb(0_0_0/10%)] flex flex-col bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 transition-all duration-300"
        :class="{
          'w-64': !sidebarCollapsed,
          'w-16': sidebarCollapsed,
          '-translate-x-full lg:translate-x-0': !sidebarOpen,
          'translate-x-0': sidebarOpen
        }"
        x-show="sidebarOpen || window.innerWidth >= 1024"
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="-translate-x-full"
        x-transition:enter-end="translate-x-0"
        x-transition:leave="transition ease-in duration-300"
        x-transition:leave-start="translate-x-0"
        x-transition:leave-end="-translate-x-full"
      >
        <!-- Sidebar Header -->
        <div class="flex items-center h-16 px-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0"
             :class="sidebarCollapsed ? 'justify-center' : 'justify-between'">
          <a href="{{ root_path }}/admin" class="flex items-center" x-show="!sidebarCollapsed">
            <img src="{{ root_path }}/static/contextforge-logo.png" alt="ContextForge logo" class="h-8 dark:hidden" />
            <img src="{{ root_path }}/static/contextforge-logo-white.png" alt="ContextForge logo" class="h-8 hidden dark:block" />
          </a>
          <button @click="sidebarCollapsed = false" class="flex items-center justify-center" x-show="sidebarCollapsed" title="Expand sidebar">
            <img src="{{ root_path }}/static/contextforge-icon.png" alt="ContextForge icon" class="h-8 w-8 dark:hidden" />
            <img src="{{ root_path }}/static/contextforge-icon-white.png" alt="ContextForge icon" class="h-8 w-8 hidden dark:block" />
          </button>
          <button
            @click="sidebarCollapsed = !sidebarCollapsed"
            class="p-1.5 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 hidden lg:block"
            :title="sidebarCollapsed ? 'Expand sidebar' : 'Collapse sidebar'"
            x-show="!sidebarCollapsed"
          >
            <svg class="w-5 h-5 transition-transform" :class="{ 'rotate-180': sidebarCollapsed }" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 19l-7-7 7-7m8 14l-7-7 7-7"></path>
            </svg>
          </button>
        </div>

        <!-- Sidebar Navigation -->
        <nav class="flex-1 overflow-y-auto py-4 sidebar-scroll">
          <!-- Overview Section -->
          <div class="space-y-1 px-2 mb-4">
            {% if 'overview' not in hidden_sections %}
            <a href="#overview" id="tab-overview" data-testid="overview-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors active"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="overview">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">📊</span>
              <span x-show="!sidebarCollapsed">Overview</span>
            </a>
            {% endif %}
          </div>

          <!-- MCP Section -->
          <div class="sidebar-section" x-show="!sidebarCollapsed">
            <span class="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">MCP</span>
          </div>
          <div class="space-y-1 px-2">
            {% if 'gateways' not in hidden_sections %}
            <a href="#gateways" id="tab-gateways" data-testid="gateways-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="gateways">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🖥️</span>
              <span x-show="!sidebarCollapsed">MCP Servers</span>
            </a>
            {% endif %}
            {% if 'servers' not in hidden_sections %}
            <a href="#catalog" id="tab-catalog" data-testid="servers-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="catalog">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🔗</span>
              <span x-show="!sidebarCollapsed">Virtual Servers</span>
            </a>
            {% endif %}
            {% if 'tools' not in hidden_sections %}
            <a href="#tools" id="tab-tools" data-testid="tools-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="tools">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🛠️</span>
              <span x-show="!sidebarCollapsed">Tools</span>
            </a>
            {% if toolops_enabled %}
            <a href="#tool-ops" id="tab-tool-ops" data-testid="tool-ops-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="tool-ops">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">⚙️</span>
              <span x-show="!sidebarCollapsed">ToolOps</span>
            </a>
            {% endif %}
            {% endif %}
            {% if 'prompts' not in hidden_sections %}
            <a href="#prompts" id="tab-prompts"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="prompts">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">💬</span>
              <span x-show="!sidebarCollapsed">Prompts</span>
            </a>
            {% endif %}
            {% if 'resources' not in hidden_sections %}
            <a href="#resources" id="tab-resources"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="resources">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">📁</span>
              <span x-show="!sidebarCollapsed">Resources</span>
            </a>
            {% endif %}
            {% if 'roots' not in hidden_sections %}
            <a href="#roots" id="tab-roots"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="roots">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🌳</span>
              <span x-show="!sidebarCollapsed">Roots</span>
            </a>
            {% endif %}
            {% if 'mcp-registry' not in hidden_sections %}
            <a href="#mcp-registry" id="tab-mcp-registry" data-testid="mcp-registry-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="mcp-registry">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">📦</span>
              <span x-show="!sidebarCollapsed">MCP Registry</span>
            </a>
            {% endif %}
          </div>

          <!-- Agents Section -->
          {% if (a2a_enabled and 'agents' not in hidden_sections) or (grpc_enabled and 'grpc-services' not in hidden_sections) %}
          <div class="sidebar-section mt-4" x-show="!sidebarCollapsed">
            <span class="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Agents</span>
          </div>
          <div class="space-y-1 px-2">
            {% if a2a_enabled and 'agents' not in hidden_sections %}
            <a href="#a2a-agents" id="tab-a2a-agents" data-testid="a2a-agents-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="a2a-agents">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🤖</span>
              <span x-show="!sidebarCollapsed">Agents (A2A)</span>
            </a>
            {% endif %}
            {% if grpc_enabled and 'grpc-services' not in hidden_sections %}
            <a href="#grpc-services" id="tab-grpc-services" data-testid="grpc-services-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="grpc-services">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🔌</span>
              <span x-show="!sidebarCollapsed">gRPC Services</span>
            </a>
            {% endif %}
          </div>
          {% endif %}

          <!-- LLM Section -->
          {% if llmchat_enabled or 'settings' not in hidden_sections %}
          <div class="sidebar-section mt-4" x-show="!sidebarCollapsed">
            <span class="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">LLM</span>
          </div>
          <div class="space-y-1 px-2">
            {% if llmchat_enabled %}
            <a href="#llm-chat" id="tab-llm-chat" data-testid="llm-chat-tab"
              class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="llm-chat">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">👨‍💻</span>
              <span x-show="!sidebarCollapsed">LLM Chat</span>
            </a>
            {% endif %}
            {% if 'settings' not in hidden_sections %}
            <a href="#llm-settings" id="tab-llm-settings"
              class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="llm-settings">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">⚙️</span>
              <span x-show="!sidebarCollapsed">LLM Settings</span>
            </a>
            {% endif %}
          </div>
          {% endif %}

          {% if 'metrics' not in hidden_sections or performance_enabled or observability_enabled %}
          <!-- Monitoring Section -->
          <div class="sidebar-section mt-4" x-show="!sidebarCollapsed">
            <span class="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Monitoring</span>
          </div>
          <div class="space-y-1 px-2">
            {% if 'metrics' not in hidden_sections %}
            <a href="#metrics" id="tab-metrics"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="metrics">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">📊</span>
              <span x-show="!sidebarCollapsed">Metrics</span>
            </a>
            {% endif %}
            {% if performance_enabled and is_admin %}
            <a href="#performance" id="tab-performance" data-testid="performance-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="performance">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">⚡</span>
              <span x-show="!sidebarCollapsed">Performance</span>
            </a>
            {% endif %}
            {% if observability_enabled and is_admin %}
            <a href="#observability" id="tab-observability" data-testid="observability-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="observability">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🔍</span>
              <span x-show="!sidebarCollapsed">Observability</span>
            </a>
            {% endif %}
          </div>
          {% endif %}

          {% if 'plugins' not in hidden_sections %}
          <!-- Extensions Section -->
          <div class="sidebar-section mt-4" x-show="!sidebarCollapsed">
            <span class="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Extensions</span>
          </div>
          <div class="space-y-1 px-2">
            {% if 'plugins' not in hidden_sections %}
            <a href="#plugins" id="tab-plugins" data-testid="plugins-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="plugins">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🧩</span>
              <span x-show="!sidebarCollapsed">Plugins</span>
            </a>
            {% endif %}
          </div>
          {% endif %}

          <!-- Organization Section -->
          {% if email_auth_enabled and ('teams' not in hidden_sections or 'users' not in hidden_sections or 'tokens' not in hidden_sections) %}
          <div class="sidebar-section mt-4" x-show="!sidebarCollapsed">
            <span class="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Organization</span>
          </div>
          <div class="space-y-1 px-2">
            {% if 'teams' not in hidden_sections %}
            <a href="#teams" id="tab-teams" data-testid="teams-tab"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="teams">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">👥</span>
              <span x-show="!sidebarCollapsed">Teams</span>
            </a>
            {% endif %}
            {% if 'users' not in hidden_sections %}
            <a href="#users" id="tab-users"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="users">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">👤</span>
              <span x-show="!sidebarCollapsed">Users</span>
            </a>
            {% endif %}
            {% if 'tokens' not in hidden_sections %}
            <a href="#tokens" id="tab-tokens"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="tokens">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🎫</span>
              <span x-show="!sidebarCollapsed">API Tokens</span>
            </a>
            {% endif %}
          </div>
          {% endif %}

          {% if 'export-import' not in hidden_sections or 'logs' not in hidden_sections or 'version-info' not in hidden_sections or 'maintenance' not in hidden_sections %}
          <!-- Admin Section -->
          <div class="sidebar-section mt-4" x-show="!sidebarCollapsed">
            <span class="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Admin</span>
          </div>
          <div class="space-y-1 px-2">
            {% if 'export-import' not in hidden_sections %}
            <a href="#export-import" id="tab-export-import"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="export-import">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">📤</span>
              <span x-show="!sidebarCollapsed">Export/Import</span>
            </a>
            {% endif %}
            {% if 'logs' not in hidden_sections %}
            <a href="#logs" id="tab-logs"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="logs">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">📋</span>
              <span x-show="!sidebarCollapsed">System Logs</span>
            </a>
            {% endif %}
            {% if 'version-info' not in hidden_sections %}
            <a href="#version-info" id="tab-version-info"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="version-info">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">ℹ️</span>
              <span x-show="!sidebarCollapsed">Version Info</span>
            </a>
            {% endif %}
            {% if 'maintenance' not in hidden_sections %}
            <a href="#maintenance" id="tab-maintenance"
               class="sidebar-link group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors"
               :class="{ 'justify-center': sidebarCollapsed }"
               data-action-click="showTab" data-arg0="maintenance">
              <span class="sidebar-icon text-lg" :class="{ 'mr-3': !sidebarCollapsed }">🔧</span>
              <span x-show="!sidebarCollapsed">Maintenance</span>
            </a>
            {% endif %}
          </div>
          {% endif %}
        </nav>

        <!-- Sidebar Footer -->
        <div class="flex-shrink-0 border-t border-gray-200 dark:border-gray-700 p-4">
          <div class="flex items-center" :class="{ 'justify-center': sidebarCollapsed, 'justify-between': !sidebarCollapsed }">
            <!-- Dark mode toggle -->
            {% if 'theme_toggle' not in hidden_header_items %}
            <button
              @click="darkMode = !darkMode"
              class="p-2 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              :title="darkMode ? 'Switch to light mode' : 'Switch to dark mode'"
            >
              <span x-text="darkMode ? '☀️' : '🌙'" class="text-lg"></span>
            </button>
            {% endif %}
            <!-- Links (hidden when collapsed) -->
            <div x-show="!sidebarCollapsed" class="flex items-center space-x-2">
              <a href="https://ibm.github.io/mcp-context-forge/" target="_blank"
                 class="p-2 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                 title="Documentation">
                <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="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                </svg>
              </a>
              <a href="https://github.com/IBM/mcp-context-forge" target="_blank"
                 class="p-2 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                 title="GitHub">
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                  <path fill-rule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clip-rule="evenodd"></path>
                </svg>
              </a>
            </div>
          </div>
        </div>
      </aside>

      <!-- Main Content Area -->
      <div class="flex-1 flex flex-col overflow-hidden">
        <!-- Top Header Bar -->
        <header class="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
          <div class="flex items-center justify-between h-16 px-4">
            <!-- Left side: mobile menu button + title -->
            <div class="flex items-center">
              <!-- Mobile menu button -->
              <button
                @click="sidebarOpen = !sidebarOpen"
                class="p-2 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 lg:hidden mr-2"
              >
                <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="M4 6h16M4 12h16M4 18h16"></path>
                </svg>
              </button>
              <h1 class="text-lg font-semibold text-gray-800 dark:text-gray-200 hidden sm:block">Gateway Administration</h1>
            </div>

            <!-- Right side: team selector, user, logout -->
            <div class="flex items-center space-x-4">
              <button
                type="button"
                id="global-search-trigger"
                data-action-click="openGlobalSearchModal"
                class="inline-flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-md hover:border-gray-400 dark:hover:border-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                title="Search across tools, prompts, resources, servers, gateways, agents, and roots (Ctrl/Cmd+K)"
              >
                <span>Search</span>
                <span class="hidden sm:inline text-xs text-gray-500 dark:text-gray-400">Ctrl/Cmd+K</span>
              </button>

              <!-- Team Selector with Search and Infinite Scroll -->
              {% if email_auth_enabled and 'team_selector' not in hidden_header_items %}
              <div
                class="relative inline-block text-left"
                x-data="{
                  open: false,
                  selectedTeam: '',
                  selectedTeamName: 'All Teams',
                  init() {
                    const urlParams = new URLSearchParams(window.location.search);
                    const requestedTeamId = urlParams.get('team_id') || '';
                    this.selectedTeam = '';
                    this.selectedTeamName = 'All Teams';

                    if (requestedTeamId) {
                      // Keep team scope only when it exists in known visible teams.
                      const teams = (Array.isArray(window.USER_TEAMS_DATA) && window.USER_TEAMS_DATA.length > 0)
                        ? window.USER_TEAMS_DATA
                        : (Array.isArray(window.USER_TEAMS) ? window.USER_TEAMS : []);
                      const team = teams.find(t => t.id === requestedTeamId);

                      if (team) {
                        this.selectedTeam = requestedTeamId;
                        this.selectedTeamName = team.is_personal ? '👤 ' + team.name : '🏢 ' + team.name;
                      } else if (teams.length > 0) {
                        // Remove stale/invalid team_id from URL to avoid confusing stale team scope behavior.
                        const cleanUrl = new URL(window.location.href);
                        cleanUrl.searchParams.delete('team_id');
                        window.Admin?.safeReplaceState?.({}, '', cleanUrl);
                      }
                    }
                  },
                  loadTeams() {
                    if (this.open) { window.Admin?.loadTeamSelectorDropdown?.(); }
                  }
                }"
                @click.away="open = false"
              >
                <button
                  type="button"
                  @click="open = !open; $nextTick(() => loadTeams())"
                  id="team-selector-button"
                  aria-expanded="false"
                  aria-haspopup="true"
                  class="inline-flex justify-center items-center px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 border border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  <span x-text="selectedTeamName" class="mr-2">All Teams</span>
                  <svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                  </svg>
                </button>

                <div
                  x-show="open"
                  x-transition:enter="transition ease-out duration-100"
                  x-transition:enter-start="transform opacity-0 scale-95"
                  x-transition:enter-end="transform opacity-100 scale-100"
                  x-transition:leave="transition ease-in duration-75"
                  x-transition:leave-start="transform opacity-100 scale-100"
                  x-transition:leave-end="transform opacity-0 scale-95"
                  class="origin-top-right absolute right-0 mt-2 w-72 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 z-30"
                  role="menu"
                  aria-orientation="vertical"
                  aria-labelledby="team-selector-button"
                  style="display: none"
                >
                  <!-- Search Input -->
                  <div class="p-2 border-b border-gray-200 dark:border-gray-700">
                    <input
                      type="text"
                      id="team-selector-search"
                      placeholder="Search teams..."
                      class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                      data-action-input="searchTeamSelector"
                      @click.stop
                    />
                  </div>

                  <!-- All Teams Option -->
                  <div class="border-b border-gray-200 dark:border-gray-700">
                    <button
                      type="button"
                      @click="selectedTeam = ''; selectedTeamName = 'All Teams'; open = false; updateTeamContext('')"
                      class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                      role="menuitem"
                    >
                      🌐 All Teams
                    </button>
                  </div>

                  <!-- Teams List with Infinite Scroll -->
                  <div
                    id="team-selector-items"
                    class="max-h-48 overflow-y-auto"
                    role="none"
                  >
                    <div class="text-center py-4 text-sm text-gray-500 dark:text-gray-400">
                      Loading teams...
                    </div>
                  </div>
                </div>
              </div>
              {% endif %}

              <!-- User Email -->
              {% if 'user_identity' not in hidden_header_items %}
              <div class="text-sm text-gray-600 dark:text-gray-400 flex items-center hidden sm:flex">
                <svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" />
                </svg>
                {{ current_user }}
              </div>
              {% endif %}

              <!-- Logout -->
              {% if 'logout' not in hidden_header_items %}
              <form method="post" action="{{ root_path }}/admin/logout" class="inline" data-action-submit="confirmAction" data-arg0="Are you sure you want to logout?" data-prevent-default="false">
                <button
                  type="submit"
                  class="px-3 py-2 text-sm font-medium text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300 border border-red-300 dark:border-red-600 hover:border-red-500 dark:hover:border-red-400 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                >
                  Logout
                </button>
              </form>
              {% endif %}
            </div>
          </div>
        </header>

        <!-- Admin Non-Member Team Banner -->
        {% if admin_viewing_non_member_team %}
        <div class="bg-red-100 dark:bg-red-900/30 border-b border-red-300 dark:border-red-800">
          <div class="px-4 py-3">
            <div class="flex items-center">
              <svg class="h-5 w-5 text-red-600 dark:text-red-400 mr-3 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
              </svg>
              <p class="text-sm font-semibold text-red-800 dark:text-red-200">
                ⚠ Since you are not a member of this team, team content won't be visible. Defaulting to All Teams.
              </p>
            </div>
          </div>
        </div>
        {% endif %}

        <!-- Global notification container for flash messages -->
        <div id="global-notification" class="px-4 mt-4" style="display: none;">
          <!-- Notification content will be inserted here -->
        </div>

        <!-- Global Search Modal -->
        <div id="global-search-modal" class="fixed inset-0 z-40 hidden" aria-hidden="true">
          <div class="absolute inset-0 bg-black/40" data-action-click="closeGlobalSearchModal"></div>
          <div class="relative max-w-3xl mx-auto mt-24 px-4">
            <div class="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl overflow-hidden">
              <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                <input
                  type="text"
                  id="global-search-input"
                  placeholder="Search across servers, gateways, tools, resources, prompts, agents, and roots..."
                  class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                  autocomplete="off"
                />
              </div>
              <div id="global-search-results" class="max-h-[28rem] overflow-y-auto">
                <div class="p-4 text-sm text-gray-500 dark:text-gray-400">
                  Start typing to search all entities.
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Tab Panels Container -->
        <main data-scroll-container class="flex-1 overflow-y-auto bg-gray-100 dark:bg-gray-900 p-4 lg:p-6">

      {% if 'logs' not in hidden_sections %}
      <!-- Logs Panel -->
      <div id="logs-panel" class="tab-panel hidden">
          <div class="bg-white dark:bg-gray-800 shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <h2
                class="text-lg font-medium text-gray-900 dark:text-white mb-4"
              >
                📋 System Logs
              </h2>

              <!-- Quick Actions -->
              <div class="mb-4 flex gap-2 flex-wrap">
                <button
                  data-action-click="searchStructuredLogs"
                  class="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                >
                  🔍 Search Logs
                </button>
                <button
                  data-action-click="showCorrelationTrace"
                  class="px-3 py-2 bg-purple-600 text-white rounded hover:bg-purple-700"
                >
                  🔗 Trace Correlation ID
                </button>
                <button
                  data-action-click="showSecurityEvents"
                  class="px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700"
                >
                  🛡️ Security Events
                </button>
                <button
                  data-action-click="showAuditTrail"
                  class="px-3 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700"
                >
                  📝 Audit Trail
                </button>
                <button
                  data-action-click="showPerformanceMetrics"
                  class="px-3 py-2 bg-green-600 text-white rounded hover:bg-green-700"
                >
                  ⚡ Performance
                </button>
              </div>

              <!-- Performance Aggregation Controls (toggle visibility via JS) -->
              <div id="performance-aggregation-controls" class="mb-4 hidden">
                <label
                  for="performance-aggregation-select"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >
                  Performance aggregation level
                </label>
                <div class="mt-1 max-w-xs">
                  <select
                    id="performance-aggregation-select"
                    class="px-3 py-2 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                    data-action-change="handlePerformanceAggregationChange"
                  >
                    <option value="5m">5 minutes</option>
                    <option value="24h">24 hours</option>
                  </select>
                </div>
              </div>

              <!-- Log Filters -->
              <div id="log-filters" class="mb-4 grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Level</label
                  >
                  <select
                    id="log-level-filter"
                    class="mt-1 px-3 py-2 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                    data-action-change="searchStructuredLogs"
                  >
                    <option value="">All Levels</option>
                    <option value="DEBUG">Debug</option>
                    <option value="INFO">Info</option>
                    <option value="WARNING">Warning</option>
                    <option value="ERROR">Error</option>
                    <option value="CRITICAL">Critical</option>
                  </select>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Component</label
                  >
                  <select
                    id="log-component-filter"
                    class="mt-1 px-3 py-2 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                    data-action-change="searchStructuredLogs"
                  >
                    <option value="">All Components</option>
                    <option value="http_gateway">HTTP Gateway</option>
                    <option value="gateway_service">Gateway Service</option>
                    <option value="tool_service">Tool Service</option>
                    <option value="resource_service">Resource Service</option>
                    <option value="prompt_service">Prompt Service</option>
                    <option value="server_service">Server Service</option>
                    <option value="a2a_service">A2A Service</option>
                    <option value="auth">Authentication</option>
                  </select>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Search / Correlation ID</label
                  >
                  <input
                    type="text"
                    id="log-search"
                    placeholder="Search or paste correlation ID..."
                    class="mt-1 px-3 py-2 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                  />
                </div>
              </div>

              <!-- Log Stats -->
              <div
                id="log-stats"
                class="mb-4 p-3 bg-gray-100 dark:bg-gray-700 rounded text-gray-700 dark:text-gray-300"
              >
                <div class="flex items-center justify-center p-4">
                  <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  <span class="ml-2 text-gray-600 dark:text-gray-400">Loading logs...</span>
                </div>
              </div>

              <!-- Log Table -->
              <div class="overflow-x-auto">
                <table
                  class="min-w-full divide-y divide-gray-200 dark:divide-gray-700"
                >
                  <thead id="logs-thead" class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th
                        class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Time
                      </th>
                      <th
                        class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Level
                      </th>
                      <th
                        class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Component
                      </th>
                      <th
                        class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Message
                      </th>
                      <th
                        class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        User
                      </th>
                      <th
                        class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Duration
                      </th>
                      <th
                        class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Correlation ID
                      </th>
                    </tr>
                  </thead>
                  <tbody
                    id="logs-tbody"
                    class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700"
                  >
                    <!-- Logs will be inserted here -->
                  </tbody>
                </table>
              </div>

              <!-- Pagination -->
              <div class="mt-4 flex justify-between items-center">
                <div>
                  <span
                    id="log-count"
                    class="text-sm text-gray-600 dark:text-gray-300"
                    >0 logs</span
                  >
                </div>
                <div class="flex gap-2">
                  <button
                    data-action-click="previousLogPage"
                    id="prev-page"
                    class="px-3 py-1 bg-gray-300 dark:bg-gray-600 rounded disabled:opacity-50"
                    disabled
                  >
                    Previous
                  </button>
                  <button
                    data-action-click="nextLogPage"
                    id="next-page"
                    class="px-3 py-1 bg-gray-300 dark:bg-gray-600 rounded disabled:opacity-50"
                  >
                    Next
                  </button>
                </div>
              </div>
            </div>
          </div>
      </div>
      {% endif %}

      {% if 'export-import' not in hidden_sections %}
      <!-- Export/Import Panel -->
      <div id="export-import-panel" class="tab-panel hidden">
          <div class="bg-white dark:bg-gray-800 shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <h2
                class="text-lg font-medium text-gray-900 dark:text-white mb-6"
              >
                Configuration Export & Import
              </h2>

              <!-- Export Section -->
              <div class="mb-8">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📤 Export Configuration
                </h3>

                <!-- Export Options -->
                <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg mb-4">
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Entity Types
                      </label>
                      <div class="space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-tools"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Tools</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-gateways"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Gateways</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-servers"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Servers</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-prompts"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Prompts</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-resources"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Resources</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-roots"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Roots</span
                          >
                        </label>
                      </div>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Filter Options
                      </label>
                      <div class="space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-include-inactive"
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Include Inactive</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-include-dependencies"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Include Dependencies</span
                          >
                        </label>
                      </div>

                      <div class="mt-3">
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                        >
                          Filter by Tags
                        </label>
                        <input
                          type="text"
                          id="export-tags"
                          placeholder="production,api,staging"
                          class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                        />
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 mt-1"
                        >
                          Comma-separated tags
                        </p>
                      </div>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Export Actions
                      </label>
                      <div class="space-y-2">
                        <button
                          id="export-all-btn"
                          class="w-full bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium"
                        >
                          📥 Export All Configuration
                        </button>
                        <button
                          id="export-selected-btn"
                          class="w-full bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md text-sm font-medium"
                        >
                          📋 Export Selected Types
                        </button>
                      </div>

                      <div class="mt-4">
                        <div id="export-progress" class="hidden">
                          <div
                            class="text-sm text-gray-600 dark:text-gray-300 mb-1"
                          >
                            Exporting...
                          </div>
                          <div
                            class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2"
                          >
                            <div
                              id="export-progress-bar"
                              class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                              style="width: 0%"
                            ></div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Import Section -->
              <div class="mb-8">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📥 Import Configuration
                </h3>

                <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                  <!-- File Upload Area -->
                  <div class="mb-4">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Import File
                    </label>
                    <div
                      id="import-drop-zone"
                      class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:border-gray-400 dark:hover:border-gray-500 cursor-pointer"
                    >
                      <div class="space-y-2">
                        <svg
                          class="mx-auto h-12 w-12 text-gray-400"
                          stroke="currentColor"
                          fill="none"
                          viewBox="0 0 48 48"
                        >
                          <path
                            d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3-3m-3 3l3 3m-3-3V8"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                          />
                        </svg>
                        <div class="text-sm text-gray-600 dark:text-gray-300">
                          <span
                            class="font-medium text-blue-600 dark:text-blue-400"
                            >Click to upload</span
                          >
                          or drag and drop
                        </div>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                          JSON export files only
                        </p>
                      </div>
                      <input
                        type="file"
                        id="import-file-input"
                        class="hidden"
                        accept=".json,application/json"
                      />
                    </div>
                  </div>

                  <!-- Import Options -->
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Conflict Strategy
                      </label>
                      <select
                        id="import-conflict-strategy"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                      >
                        <option value="update">Update existing items</option>
                        <option value="skip">Skip conflicting items</option>
                        <option value="rename">Rename conflicting items</option>
                        <option value="fail">Fail on conflicts</option>
                      </select>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Options
                      </label>
                      <div class="space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="import-dry-run"
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Dry Run (validate only)</span
                          >
                        </label>
                      </div>

                      <div class="mt-2">
                        <input
                          type="password"
                          id="import-rekey-secret"
                          autocomplete="off"
                          placeholder="New encryption secret (optional)"
                          class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                        />
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 mt-1"
                        >
                          For cross-environment imports
                        </p>
                      </div>
                    </div>
                  </div>

                  <!-- Import Actions -->
                  <div class="flex space-x-4">
                    <button
                      id="import-preview-btn"
                      class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50"
                      disabled
                      data-action-click="previewImport"
                    >
                      📋 Selective Import
                    </button>
                    <button
                      id="import-validate-btn"
                      class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50"
                      disabled
                    >
                      🔍 Validate Import
                    </button>
                    <button
                      id="import-execute-btn"
                      class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50"
                      disabled
                    >
                      ⚡ Execute Import
                    </button>
                  </div>
                </div>
              </div>

              <!-- Import Status -->
              <div id="import-status-section" class="hidden">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📊 Import Status
                </h3>

                <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                  <div id="import-progress" class="mb-4">
                    <div
                      class="flex justify-between text-sm text-gray-600 dark:text-gray-300 mb-1"
                    >
                      <span>Progress</span>
                      <span id="import-progress-text">0%</span>
                    </div>
                    <div
                      class="w-full bg-gray-200 dark:bg-gray-600 rounded-full h-2"
                    >
                      <div
                        id="import-progress-bar"
                        class="bg-green-600 h-2 rounded-full transition-all duration-300"
                        style="width: 0%"
                      ></div>
                    </div>
                  </div>

                  <div
                    class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4 text-sm"
                  >
                    <div class="text-center">
                      <div
                        id="import-total"
                        class="text-lg font-bold text-gray-900 dark:text-white"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">Total</div>
                    </div>
                    <div class="text-center">
                      <div
                        id="import-created"
                        class="text-lg font-bold text-green-600"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">
                        Created
                      </div>
                    </div>
                    <div class="text-center">
                      <div
                        id="import-updated"
                        class="text-lg font-bold text-blue-600"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">
                        Updated
                      </div>
                    </div>
                    <div class="text-center">
                      <div
                        id="import-failed"
                        class="text-lg font-bold text-red-600"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">Failed</div>
                    </div>
                  </div>

                  <!-- Messages -->
                  <div id="import-messages" class="space-y-2">
                    <!-- Messages will be populated here -->
                  </div>
                </div>
              </div>

              <!-- Recent Imports -->
              <div class="mt-8">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📋 Recent Import Operations
                </h3>

                <div
                  class="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg"
                >
                  <div
                    id="recent-imports-list"
                    class="divide-y divide-gray-200 dark:divide-gray-600"
                  >
                    <!-- Recent imports will be loaded here -->
                  </div>
                </div>
              </div>
            </div>
          </div>
      </div>
      {% endif %}

      {% if 'version-info' not in hidden_sections %}
      <!-- Version Info Panel -->
      <div id="version-info-panel" class="tab-panel hidden"></div>
      {% endif %}

      {% if 'maintenance' not in hidden_sections %}
      <!-- Maintenance Panel (admin only) -->
      <div id="maintenance-panel" class="tab-panel hidden"></div>
      {% endif %}

      {% if 'plugins' not in hidden_sections %}
      <!-- Plugins Panel -->
      <div id="plugins-panel" class="tab-panel hidden"></div>
      {% endif %}

      <!-- Performance Panel -->
      {% if performance_enabled and is_admin %}
      <div id="performance-panel" class="tab-panel hidden"
           hx-get="{{ root_path }}/admin/performance/stats"
           hx-trigger="revealed once"
           hx-swap="innerHTML">
        <div class="flex justify-center items-center py-8">
          <svg class="animate-spin h-8 w-8 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span class="ml-3 text-gray-600 dark:text-gray-400">Loading performance dashboard...</span>
        </div>
      </div>
      {% endif %}

      <!-- Observability Panel -->
      {% if observability_enabled and is_admin %}
      <div id="observability-panel" class="tab-panel hidden"
           hx-get="{{ root_path }}/admin/observability/partial"
           hx-trigger="revealed once"
           hx-swap="innerHTML">
        <div class="flex justify-center items-center py-8">
          <svg class="animate-spin h-8 w-8 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span class="ml-3 text-gray-600 dark:text-gray-400">Loading observability dashboard...</span>
        </div>
      </div>
      {% endif %}
        {% if llmchat_enabled %}
        <!-- LLM Chat Panel -->
        <div id="llm-chat-panel" class="tab-panel hidden">
          <div class="mx-auto px-4">
            <!-- Compact Toolbar -->
            <div
              class="llm-chat-toolbar bg-gradient-to-r from-gray-50 to-gray-100 dark:from-gray-800 dark:to-gray-750 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm mb-4">
              <div class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                <!-- Left Section: Virtual Server Selector + LLM Config -->
                <div class="flex items-center gap-3 flex-1 min-w-0">
                  <!-- Virtual Server Dropdown -->
                  <div class="relative" x-data="{ serverDropdownOpen: false }">
                    <button @click="serverDropdownOpen = !serverDropdownOpen" @click.away="serverDropdownOpen = false"
                      id="llm-server-dropdown-btn"
                      class="inline-flex items-center px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all">
                      <svg class="w-4 h-4 mr-2 text-indigo-600 dark:text-indigo-400" fill="none" stroke="currentColor"
                        viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01" />
                      </svg>
                      <span id="selected-server-name"
                        class="text-sm font-medium text-gray-700 dark:text-gray-300 truncate max-w-[200px]">Select
                        Virtual Server</span>
                      <svg class="w-4 h-4 ml-2 text-gray-500" :class="{ 'rotate-180': serverDropdownOpen }" fill="none"
                        stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                      </svg>
                    </button>

                    <!-- Dropdown Menu -->
                    <div x-show="serverDropdownOpen" x-transition:enter="transition ease-out duration-100"
                      x-transition:enter-start="transform opacity-0 scale-95"
                      x-transition:enter-end="transform opacity-100 scale-100"
                      x-transition:leave="transition ease-in duration-75"
                      x-transition:leave-start="transform opacity-100 scale-100"
                      x-transition:leave-end="transform opacity-0 scale-95"
                      class="absolute left-0 mt-2 w-80 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-30 max-h-96 overflow-hidden flex flex-col"
                      style="display: none">
                      <!-- Dropdown Header -->
                      <div
                        class="px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-gray-800 dark:to-gray-750">
                        <div class="flex items-center justify-between">
                          <h3 class="text-sm font-semibold text-gray-900 dark:text-white">
                            Virtual Servers
                          </h3>
                          <button data-action-click="loadVirtualServersForChat" data-stop-propagation="true"
                            class="text-xs px-2 py-1 bg-indigo-600 hover:bg-indigo-700 text-white rounded transition-colors">
                            <svg class="w-3 h-3 inline-block mr-1" fill="none" stroke="currentColor"
                              viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                            </svg>
                            Refresh
                          </button>
                        </div>
                      </div>

                      <!-- Server List -->
                      <div id="llm-chat-servers-list" class="flex-1 overflow-y-auto p-2">
                        <div class="text-center text-gray-500 dark:text-gray-400 text-sm py-8">
                          <svg class="mx-auto h-12 w-12 text-gray-400 mb-3" fill="none" stroke="currentColor"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01" />
                          </svg>
                          Click Refresh to load servers
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- LLM Configuration Toggle -->
                  <div class="relative" x-data="{ configDropdownOpen: false }" @click.away="configDropdownOpen = false">
                    <button @click="configDropdownOpen = !configDropdownOpen" id="llm-config-toggle"
                      class="inline-flex items-center px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all">
                      <svg class="w-4 h-4 mr-2 text-indigo-600 dark:text-indigo-400" fill="none" stroke="currentColor"
                        viewBox="0 0 24 24">
                        <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>
                      <span class="text-sm font-medium text-gray-700 dark:text-gray-300 mr-2">LLM Configuration</span>
                      <svg class="w-4 h-4 ml-2 text-gray-500" :class="{ 'rotate-180': configDropdownOpen }" fill="none"
                        stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                      </svg>
                    </button>

                    <!-- Floating Configuration Panel -->
                    <div x-show="configDropdownOpen" @click.stop x-transition:enter="transition ease-out duration-100"
                      x-transition:enter-start="transform opacity-0 scale-95"
                      x-transition:enter-end="transform opacity-100 scale-100"
                      x-transition:leave="transition ease-in duration-75"
                      x-transition:leave-start="transform opacity-100 scale-100"
                      x-transition:leave-end="transform opacity-0 scale-95" id="llm-config-form"
                      class="absolute left-0 mt-2 w-[600px] bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-30 p-4"
                      style="display: none">
                      <form id="llm-chat-config-form" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <!-- Model Selection -->
                        <div>
                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">LLM
                            Model</label>
                          <select id="llm-model-select"
                            class="w-full rounded-lg border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-2 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300 transition-colors"
                            data-action-change="handleLLMModelChange">
                            <option value="">
                              Select Model (configure in Settings → LLM
                              Settings)
                            </option>
                          </select>
                          <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                            Models are configured in LLM Settings
                          </p>
                        </div>

                        <!-- Temperature -->
                        <div>
                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Temperature
                            (0-2)</label>
                          <input type="number" id="llm-temperature" min="0" max="2" step="0.1" value="0.7"
                            class="w-full rounded-lg border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-2 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300" />
                        </div>

                        <!-- Max Tokens -->
                        <div>
                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Max Tokens
                            (Optional)</label>
                          <input type="number" id="llm-max-tokens" min="1" step="1"
                            class="w-full rounded-lg border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-2 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                            placeholder="Leave empty for default" />
                        </div>

                        <div id="llm-config-status" class="hidden text-sm col-span-3"></div>
                      </form>
                    </div>
                  </div>

                  <!-- Status Badges Section -->
                  <div class="flex items-center gap-2">
                    <!-- Connection Status Badge -->
                    <span id="llm-connection-status"
                      class="hidden inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200">
                      <span class="w-1.5 h-1.5 bg-green-600 rounded-full mr-1 animate-pulse"></span>
                      Connected
                    </span>

                    <!-- Active Tools Badge -->
                    <span id="llm-active-tools-badge"
                      class="hidden relative group inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 cursor-default transition-all hover:bg-blue-200 dark:hover:bg-blue-800">
                      <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <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>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                      </svg>
                      <span id="llm-tool-count">0 tools</span>

                      <!-- Enhanced tooltip card -->
                      <div
                        class="absolute left-1/2 -translate-x-1/2 top-full mt-3 hidden group-hover:block w-80 z-30 animate-fade-in">
                        <div
                          class="bg-white dark:bg-gray-800 rounded-lg shadow-2xl border-2 border-blue-200 dark:border-blue-700 p-4">
                          <!-- Header -->
                          <div class="flex items-center gap-2 mb-3 pb-2 border-b border-gray-200 dark:border-gray-700">
                            <svg class="w-4 h-4 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor"
                              viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z">
                              </path>
                            </svg>
                            <h4 class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                              Available Tools
                            </h4>
                          </div>

                          <!-- Tools list container -->
                          <div id="llm-tool-list"
                            class="flex flex-wrap gap-2 max-h-64 overflow-y-auto custom-scrollbar">
                            <span class="text-xs text-gray-500 dark:text-gray-400">Loading tools...</span>
                          </div>
                        </div>

                        <!-- Arrow pointer -->
                        <svg
                          class="absolute left-1/2 -translate-x-1/2 bottom-full mb-0.5 w-4 h-3 text-white dark:text-gray-800 drop-shadow-lg"
                          viewBox="0 0 16 8" fill="currentColor">
                          <path d="M0 8 L8 0 L16 8 Z" />
                        </svg>
                      </div>
                    </span>

                    <!-- Selected LLM Model Badge -->
                    <span id="llm-model-badge"
                      class="hidden inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200">
                      <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z">
                        </path>
                      </svg>
                      <span id="llmchat-model-name">Model</span>
                    </span>
                  </div>
                </div>

                <!-- Right Section: Connection Buttons -->
                <div class="flex items-center gap-2">
                  <button type="button" id="llm-connect-btn" data-action-click="connectLLMChat"
                    class="inline-flex items-center justify-center px-4 py-2 bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white text-sm font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
                    disabled>
                    <svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M13 10V3L4 14h7v7l9-11h-7z" />
                    </svg>
                    Connect
                  </button>

                  <button type="button" id="llm-disconnect-btn" data-action-click="disconnectLLMChat"
                    class="hidden inline-flex items-center justify-center px-4 py-2 bg-gradient-to-r from-red-600 to-red-700 hover:from-red-700 hover:to-red-800 text-white text-sm font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 shadow-sm">
                    <svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                    </svg>
                    Disconnect
                  </button>
                </div>
              </div>
            </div>

            <!-- Chat Container -->
            <div
              class="bg-white dark:bg-gray-800 shadow-xl rounded-xl border border-gray-200 dark:border-gray-700 flex flex-col overflow-hidden h-[calc(100vh-12rem)]">
              <!-- Chat Messages Area -->
              <div id="chat-messages-container"
                class="flex flex-col flex-1 overflow-y-auto p-5 bg-gray-50 dark:bg-gray-900 space-y-4">
                <div id="chat-welcome-message" class="flex items-center justify-center h-full">
                  <div class="text-center max-w-md">
                    <div
                      class="mx-auto w-16 h-16 bg-indigo-100 dark:bg-indigo-900 rounded-full flex items-center justify-center mb-4">
                      <svg class="h-8 w-8 text-indigo-600 dark:text-indigo-400" fill="none" stroke="currentColor"
                        viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                      </svg>
                    </div>
                    <h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">
                      Start a Conversation
                    </h3>
                    <p class="text-sm text-gray-600 dark:text-gray-400 mb-6">
                      Select a virtual server from the toolbar and configure
                      your LLM settings to begin chatting
                    </p>
                    <div class="flex items-center justify-center space-x-2 text-xs text-gray-500 dark:text-gray-500">
                      <span class="w-2 h-2 bg-gray-300 dark:bg-gray-600 rounded-full"></span>
                      <span class="w-2 h-2 bg-gray-300 dark:bg-gray-600 rounded-full"></span>
                      <span class="w-2 h-2 bg-gray-300 dark:bg-gray-600 rounded-full"></span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Chat Input Area -->
              <div id="chat-input-container"
                class="hidden border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
                <form id="chat-input-form" data-action-submit="sendChatMessage" class="p-4">
                  <div class="flex items-end space-x-3">
                    <div class="flex-1 relative">
                      <textarea id="chat-input" rows="1"
                        placeholder="Type your message here... (Shift+Enter for new line)"
                        class="w-full rounded-lg border border-gray-300 dark:border-gray-600 shadow-sm px-4 py-3 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300 resize-none transition-all"
                        data-action-keydown="handleChatInputKeydown" data-action-input="autoResizeTextarea" disabled></textarea>
                      <div
                        class="absolute bottom-2 right-2 text-xs text-gray-400 dark:text-gray-500 pointer-events-none">
                        Press Enter to send
                      </div>
                    </div>
                    <button type="submit" id="chat-send-btn"
                      class="h-12 flex items-center justify-center px-5 py-3 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg disabled:shadow-none"
                      disabled>
                      <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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                      </svg>
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        {% endif %}

        {% if 'settings' not in hidden_sections %}
        <!-- LLM Settings Panel -->
      <div id="llm-settings-panel" class="tab-panel hidden">
        <div class="container mx-auto">
          <!-- Tab Navigation -->
          <div class="border-b border-gray-200 dark:border-gray-700 mb-6">
            <nav class="-mb-px flex space-x-8" aria-label="LLM Settings Tabs">
              <button
                data-action-click="switchLLMSettingsTab" data-arg0="providers"
                id="llm-settings-tab-providers"
                class="llm-settings-tab border-b-2 border-indigo-500 py-4 px-1 text-sm font-medium text-indigo-600 dark:text-indigo-400"
              >
                <svg class="h-5 w-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
                Providers
              </button>
              <button
                data-action-click="switchLLMSettingsTab" data-arg0="models"
                id="llm-settings-tab-models"
                class="llm-settings-tab border-b-2 border-transparent py-4 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300"
              >
                <svg class="h-5 w-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                </svg>
                Models
              </button>
              <button
                data-action-click="switchLLMSettingsTab" data-arg0="test"
                id="llm-settings-tab-test"
                class="llm-settings-tab border-b-2 border-transparent py-4 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300"
              >
                <svg class="h-5 w-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Test
              </button>
            </nav>
          </div>

          <!-- Providers Content -->
          <div id="llm-settings-content-providers" class="llm-settings-content">
            <div
              id="llm-providers-container"
              hx-get="{{ root_path }}/admin/llm/providers/html"
              hx-trigger="revealed once"
              hx-swap="innerHTML"
            >
              <div class="flex justify-center items-center py-12">
                <svg class="animate-spin h-8 w-8 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-3 text-gray-600 dark:text-gray-400">Loading LLM providers...</span>
              </div>
            </div>
          </div>

          <!-- Models Content -->
          <div id="llm-settings-content-models" class="llm-settings-content hidden">
            <div
              id="llm-models-container"
              hx-get="{{ root_path }}/admin/llm/models/html"
              hx-trigger="revealed once"
              hx-swap="innerHTML"
            >
              <div class="flex justify-center items-center py-12">
                <svg class="animate-spin h-8 w-8 text-green-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-3 text-gray-600 dark:text-gray-400">Loading LLM models...</span>
              </div>
            </div>
          </div>

          <!-- Test Content -->
          <div id="llm-settings-content-test" class="llm-settings-content hidden">
            <div
              id="llm-test-container"
              hx-get="{{ root_path }}/admin/llm/api-info/html"
              hx-trigger="revealed once"
              hx-swap="innerHTML"
            >
              <div class="flex justify-center items-center py-12">
                <svg class="animate-spin h-8 w-8 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-3 text-gray-600 dark:text-gray-400">Loading test panel...</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Add/Edit Provider Modal -->
        <div id="llm-provider-modal" class="fixed inset-0 z-40 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
          <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" data-action-click="closeLLMProviderModal"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
              <form id="llm-provider-form" data-action-submit="saveLLMProvider">
                <input type="hidden" id="llm-provider-id" name="provider_id" value="">
                <div class="bg-white dark:bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                  <h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white mb-4" id="llm-provider-modal-title">
                    Add LLM Provider
                  </h3>
                  <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                      <div>
                        <label for="llm-provider-name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Name *</label>
                        <input type="text" id="llm-provider-name" name="name" required class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm">
                      </div>
                      <div>
                        <label for="llm-provider-type" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Provider Type *</label>
                        <select id="llm-provider-type" name="provider_type" required data-action-change="onLLMProviderTypeChange" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm">
                          <option value="">Select provider type</option>
                          <option value="openai">OpenAI</option>
                          <option value="azure_openai">Azure OpenAI</option>
                          <option value="anthropic">Anthropic</option>
                          <option value="ollama">Ollama</option>
                          <option value="groq">Groq</option>
                          <option value="mistral">Mistral</option>
                          <option value="cohere">Cohere</option>
                          <option value="together">Together AI</option>
                          <option value="google_vertex">Google Vertex AI</option>
                          <option value="bedrock">AWS Bedrock</option>
                          <option value="watsonx">IBM watsonx</option>
                          <option value="openai_compatible">OpenAI Compatible</option>
                        </select>
                        <p id="llm-provider-type-description" class="mt-1 text-sm text-gray-500 dark:text-gray-400 hidden"></p>
                      </div>
                    </div>
                    <div>
                      <label for="llm-provider-description" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Description</label>
                      <textarea id="llm-provider-description" name="description" rows="2" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm"></textarea>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                      <div>
                        <label for="llm-provider-api-key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                          API Key
                          <span id="llm-provider-api-key-required" class="text-red-500 hidden">*</span>
                        </label>
                        <input type="password" id="llm-provider-api-key" name="api_key" autocomplete="off" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="Leave blank to keep existing">
                      </div>
                      <div>
                        <label for="llm-provider-api-base" class="block text-sm font-medium text-gray-700 dark:text-gray-300">API Base URL</label>
                        <input type="text" id="llm-provider-api-base" name="api_base" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="Auto-filled based on provider type">
                        <p class="mt-1 text-xs text-gray-400">Will be auto-filled when you select a provider type</p>
                      </div>
                    </div>
                    <div class="grid grid-cols-3 gap-4">
                      <div>
                        <label for="llm-provider-default-model" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Default Model</label>
                        <input type="text" id="llm-provider-default-model" name="default_model" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="gpt-4o">
                      </div>
                      <div>
                        <label for="llm-provider-temperature" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Temperature</label>
                        <input type="number" id="llm-provider-temperature" name="default_temperature" step="0.1" min="0" max="2" value="0.7" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm">
                      </div>
                      <div>
                        <label for="llm-provider-max-tokens" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Max Tokens</label>
                        <input type="number" id="llm-provider-max-tokens" name="default_max_tokens" min="1" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="4096">
                      </div>
                    </div>
                    <!-- Dynamic Provider-Specific Configuration Fields -->
                    <div id="llm-provider-specific-config" class="space-y-4 hidden">
                      <div class="border-t border-gray-200 dark:border-gray-600 pt-4">
                        <h4 class="text-sm font-medium text-gray-900 dark:text-white mb-3">Provider-Specific Configuration</h4>
                        <div id="llm-provider-config-fields" class="space-y-4">
                          <!-- Dynamic fields will be inserted here -->
                        </div>
                      </div>
                    </div>
                    <div class="flex items-center">
                      <input type="checkbox" id="llm-provider-enabled" name="enabled" checked class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600">
                      <label for="llm-provider-enabled" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">Enabled</label>
                    </div>
                  </div>
                </div>
                <div class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                  <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-indigo-600 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:ml-3 sm:w-auto sm:text-sm">
                    Save Provider
                  </button>
                  <button type="button" data-action-click="closeLLMProviderModal" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:bg-gray-600 dark:text-gray-200 dark:border-gray-500 dark:hover:bg-gray-500">
                    Cancel
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>

        <!-- Add/Edit Model Modal -->
        <div id="llm-model-modal" class="fixed inset-0 z-40 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
          <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" data-action-click="closeLLMModelModal"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg text-left overflow-visible shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
              <form id="llm-model-form" data-action-submit="saveLLMModel">
                <input type="hidden" id="llm-model-id" name="model_id" value="">
                <div class="bg-white dark:bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                  <h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white mb-4" id="llm-model-modal-title">
                    Add LLM Model
                  </h3>
                  <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                      <div>
                        <label for="llm-model-provider" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Provider *</label>
                        <select id="llm-model-provider" name="provider_id" required data-action-change="onModelProviderChange" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm">
                          <option value="">Select provider</option>
                        </select>
                      </div>
                      <div>
                        <label for="llm-model-model-id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Model ID *</label>
                        <div class="relative" id="llm-model-combobox-container">
                          <div class="flex mt-1">
                            <input type="text" id="llm-model-model-id" name="model_id" required autocomplete="off" role="combobox" aria-expanded="false" aria-controls="llm-model-dropdown" aria-autocomplete="list" class="px-3 py-2 block w-full rounded-l-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="Select provider first..." data-action-input="llmModelComboboxFilter" data-action-focus="llmModelComboboxOpen" data-action-click="llmModelComboboxOpen" data-action-blur="delayAction" data-arg0="llmModelComboboxClose" data-arg1="150" data-action-keydown="llmModelComboboxKeydown">
                            <button type="button" data-action-click="fetchModelsForModelModal" class="inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 rounded-r-md bg-gray-50 text-gray-500 hover:bg-gray-100 dark:bg-gray-600 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-500" title="Fetch available models">
                              <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                              </svg>
                            </button>
                          </div>
                          <ul id="llm-model-dropdown" role="listbox" class="hidden absolute z-50 mt-1 w-full max-h-48 overflow-y-auto bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg text-sm"></ul>
                        </div>
                        <p id="llm-model-fetch-status" class="mt-1 text-xs text-gray-400 hidden"></p>
                      </div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                      <div>
                        <label for="llm-model-name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Display Name *</label>
                        <input type="text" id="llm-model-name" name="model_name" required class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="GPT-4o">
                      </div>
                      <div>
                        <label for="llm-model-alias" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Alias</label>
                        <input type="text" id="llm-model-alias" name="model_alias" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="Optional alias">
                      </div>
                    </div>
                    <div>
                      <label for="llm-model-description" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Description</label>
                      <textarea id="llm-model-description" name="description" rows="2" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm"></textarea>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                      <div>
                        <label for="llm-model-context-window" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Context Window</label>
                        <input type="number" id="llm-model-context-window" name="context_window" min="1" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="128000">
                      </div>
                      <div>
                        <label for="llm-model-max-output" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Max Output Tokens</label>
                        <input type="number" id="llm-model-max-output" name="max_output_tokens" min="1" class="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm" placeholder="4096">
                      </div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                      <div class="space-y-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Capabilities</label>
                        <div class="space-y-2">
                          <label class="flex items-center">
                            <input type="checkbox" id="llm-model-supports-chat" name="supports_chat" checked class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600">
                            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Chat</span>
                          </label>
                          <label class="flex items-center">
                            <input type="checkbox" id="llm-model-supports-streaming" name="supports_streaming" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600">
                            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Streaming</span>
                          </label>
                          <label class="flex items-center">
                            <input type="checkbox" id="llm-model-supports-functions" name="supports_function_calling" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600">
                            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Function Calling</span>
                          </label>
                          <label class="flex items-center">
                            <input type="checkbox" id="llm-model-supports-vision" name="supports_vision" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600">
                            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Vision</span>
                          </label>
                        </div>
                      </div>
                      <div class="space-y-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Status</label>
                        <div class="space-y-2">
                          <label class="flex items-center">
                            <input type="checkbox" id="llm-model-enabled" name="enabled" checked class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600">
                            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Enabled</span>
                          </label>
                          <label class="flex items-center">
                            <input type="checkbox" id="llm-model-deprecated" name="deprecated" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600">
                            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Deprecated</span>
                          </label>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                  <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:ml-3 sm:w-auto sm:text-sm">
                    Save Model
                  </button>
                  <button type="button" data-action-click="closeLLMModelModal" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:bg-gray-600 dark:text-gray-200 dark:border-gray-500 dark:hover:bg-gray-500">
                    Cancel
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      {% if 'mcp-registry' not in hidden_sections %}
      <!-- MCP Registry Panel -->
      <div id="mcp-registry-panel" class="tab-panel hidden">
        <div class="container mx-auto">
          <!-- Server Grid (includes filters and overview) -->
          <div id="mcp-registry-servers">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading MCP Registry servers...</span>
            </div>
          </div>
        </div>

        <!-- API Key Modal -->
        <div
          id="api-key-modal"
          class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-40"
        >
          <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">
                API Key Required
              </h3>
              <p class="text-sm text-gray-500 mb-4">
                <span id="modal-server-name"></span> requires an API key to
                connect.
              </p>
              <form id="api-key-form" data-action-submit="submitApiKeyForm">
                <input type="hidden" id="modal-server-id" />
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    Server Name (optional)
                  </label>
                  <input
                    type="text"
                    id="modal-custom-name"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Custom name for this server"
                  />
                </div>
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    API Key <span class="text-red-500">*</span>
                  </label>
                  <input
                    type="password"
                    id="modal-api-key"
                    autocomplete="off"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Enter your API key"
                    required
                  />
                </div>
                <div class="flex justify-end gap-2">
                  <button
                    type="button"
                    data-action-click="closeApiKeyModal"
                    class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
                  >
                    Add Server
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      {% if 'servers' not in hidden_sections %}
      <!-- Catalog Panel (Virtual Servers) -->
      <div id="catalog-panel" class="tab-panel hidden">
        {% if not catalog_enabled %}
        <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 mb-6 dark:bg-yellow-800 dark:border-yellow-400 dark:text-yellow-200">
          <p class="font-bold">Catalog is currently disabled</p>
          <p class="text-sm">Set <code>MCPGATEWAY_CATALOG_ENABLED=true</code> to enable catalog-backed server operations.</p>
        </div>
        {% endif %}
        <div class="flex justify-between items-center mb-4">
          <div class="flex items-center space-x-10">
            <h2 class="text-2xl font-bold dark:text-gray-200">Virtual MCP Servers</h2>
            <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
              Virtual Servers let you combine Tools, Resources, and Prompts into
              an MCP Server with its own API key (see API Tokens).
            </p>
          </div>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-servers"
              class="mr-2 show-inactive-toggle"
              name="include_inactive"
              checked
              x-init="syncCheckboxFromUrl('servers', 'show-inactive-servers')"
              @change="updateInactiveUrlState('servers', $el.checked)"
              hx-get="{{ root_path }}/admin/servers/partial?page=1{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
              hx-vals="js:{include_inactive: document.getElementById('show-inactive-servers').checked, per_page: document.querySelector('#servers-pagination-controls select')?.value || 50, q: document.getElementById('servers-search-input')?.value || '', tags: document.getElementById('servers-tag-filter')?.value || ''}"
              hx-target="#servers-table"
              hx-swap="outerHTML"
              hx-indicator="#servers-loading"
              hx-trigger="change"
            />
            <label
              for="show-inactive-servers"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Unified Search & Filter Bar for Virtual Servers -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <div class="flex flex-col space-y-4">

            <!-- Search and Filter Row -->
            <div class="flex items-center space-x-2">
              <!-- Search Input -->
              <div class="relative">
                <input
                  type="text"
                  id="servers-search-input"
                  data-testid="search-input"
                  placeholder="Search servers..."
                  class="w-64 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-300 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  data-action-input="filterServerTable"
                />
              </div>

              <!-- Clear Button -->
              <button
                id="catalog-clear-search"
                data-action-click="clearSearch" data-arg0="catalog"
                class="px-2 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors">
                Clear
              </button>
              <span id="servers-filter-status" class="text-sm text-gray-500 dark:text-gray-400" aria-live="polite" role="status"></span>
            </div>

            <!-- Hidden tag filter (for internal JavaScript usage) -->
            <input type="hidden" id="servers-tag-filter" />

            <!-- Filter Status Badge (optional, if you want to show active filter count) -->
            <div class="mt-2">
              <span id="catalog-filter-count-badge" class="hidden text-xs text-gray-500 dark:text-gray-400">
                <!-- This will be populated by JavaScript -->
              </span>
            </div>

            <!-- Available Tags (optional) -->
            <div id="catalog-available-tags" class="mt-2 flex flex-wrap gap-1">
              <!-- Tag suggestions or results will be populated here by JavaScript -->
            </div>

          </div>
        </div>

        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div id="servers-table-wrapper" class="overflow-x-auto">
            <!-- Table will be loaded via HTMX -->
            <div id="servers-table"
                 x-init="$el.setAttribute('hx-get', buildTableUrl('servers', '{{ root_path }}/admin/servers/partial', {include_inactive: (document.getElementById('show-inactive-servers')?.checked ?? true).toString(){% if selected_team_id %}, team_id: '{{ selected_team_id }}'{% endif %}}))"
                 hx-trigger="load"
                 hx-swap="outerHTML"
                 hx-indicator="#servers-loading">

            </div>
          </div>

          <!-- Loading Indicator for HTMX -->
          <div id="servers-loading" class="htmx-indicator">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading servers...</span>
            </div>
          </div>

          <!-- Pagination Controls -->
          {# ---- compute safe pagination values first ---- #}
          {% set page = page if page is defined else 1 %}
          {% set per_page = per_page if per_page is defined else 50 %}
          {% set total_items = servers|length if servers is defined else 0 %}
          {% set total_pages = (total_items + per_page - 1) // per_page if total_items > 0 else 0 %}
          {% set has_prev = page > 1 %}
          {% set has_next = (page * per_page) < total_items %}

          {% set pagination = {
            'page': page,
            'per_page': per_page,
            'total_items': total_items,
            'total_pages': total_pages,
            'has_prev': has_prev,
            'has_next': has_next,
            'page_items': None
          } %}

          {# build the refresh URL for controls #}
          {% set controls_url = root_path + '/admin/servers/partial'
            + '?render=controls'
            + '&page=' + page|string
            + '&per_page=' + per_page|string
            + '&include_inactive=' + (include_inactive|default(false)|string|lower) %}

          <div id="servers-pagination-controls"
              hx-get="{{ controls_url }}"
              hx-trigger="refreshControls"
              hx-target="#servers-pagination-controls"
              hx-swap="outerHTML"
              hx-indicator="#servers-loading">

            {# helpers used by pagination_controls.html #}
            {% set base_url = root_path + '/admin/servers/partial' %}
            {% set hx_target = '#servers-table' %}
            {% set hx_swap = 'outerHTML' %}
            {% set hx_indicator = '#servers-loading' %}
            {% set table_name = 'servers' %}
            {% set query_params = {'include_inactive': include_inactive} %}
            {% include 'pagination_controls.html' %}
          </div>
        </div>

        <!-- Old table for reference (hidden) -->
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800" style="display: none;">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Icon
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    S. No.
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    UUID
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Description
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Tools
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Resources
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Prompts
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Tags
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Owner
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Team
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Visibility
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                data-testid="server-list"
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for server in servers %}
                <tr data-testid="server-item">
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if server.icon %}
                    <img
                      src="{{ server.icon }}"
                      alt="{{ server.name }} Icon"
                      class="h-8 w-8"
                    />
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-300">N/A</span>
                    {% endif %}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-300"
                  >
                    {{ loop.index }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-all text-sm font-medium text-gray-900 dark:text-gray-300 max-w-32"
                  >
                    {{ server.id }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-300"
                  >
                    {{ server.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300"
                  >
                    {{ server.description | decode_html }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-300"
                  >
                    {% if server.associatedTools %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300"
                    >
                      {{ server.associatedTools | length }} tool{{ 's' if
                      server.associatedTools | length != 1 else '' }}
                    </span>
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-400 text-xs"
                      >0 tools</span
                    >
                    {% endif %}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-300"
                  >
                    {% if server.associatedResources %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300"
                    >
                      {{ server.associatedResources | length }} resource{{ 's'
                      if server.associatedResources | length != 1 else '' }}
                    </span>
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-400 text-xs"
                      >0 resources</span
                    >
                    {% endif %}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-300"
                  >
                    {% if server.associatedPrompts %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300"
                    >
                      {{ server.associatedPrompts | length }} prompt{{ 's' if
                      server.associatedPrompts | length != 1 else '' }}
                    </span>
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-400 text-xs"
                      >0 prompts</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if server.tags %}
                      {% for tag in server.tags %}
                        <span
                          class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1"
                        >
                          {% if tag is mapping %}
                            {{ tag.id }}
                          {% else %}
                            {{ tag }}
                          {% endif %}
                        </span>
                      {% endfor %}
                    {% else %}
                      <span class="text-gray-500 dark:text-gray-300 text-xs">None</span>
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if server.ownerEmail %}
                    <span class="text-sm text-gray-900 dark:text-gray-100"
                      >{{ server.ownerEmail }}</span
                    >
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >N/A</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-2 py-4 whitespace-nowrap">
                    {% if server.team %}
                    <span class="text-sm text-gray-900 dark:text-gray-100" style="display: block; white-space: normal; word-spacing: 9999px;">
                      {{ server.team }}
                    </span>
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >N/A</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if server.visibility == 'private' %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800"
                      >Private</span
                    >
                    {% elif server.visibility == 'team' %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800"
                      >Team</span
                    >
                    {% elif server.visibility == 'public' %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800"
                      >Public</span
                    >
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >N/A</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="grid grid-cols-2 gap-x-2 gap-y-1 max-w-48">
                      <!-- Row 1: View | Edit -->
                      <button
                        data-action-click="viewServer" data-arg0="{{ server.id|tojson_attr }}"
                        class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-indigo-600 hover:text-indigo-900 hover:bg-indigo-50 dark:text-indigo-400 dark:hover:bg-indigo-900/20 transition-colors"
                        x-tooltip="'💡View server details and configuration'"
                      >
                        View
                      </button>
                      <button
                        data-action-click="editServer" data-arg0="{{ server.id|tojson_attr }}"
                        class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-green-600 hover:text-green-900 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/20 transition-colors"
                        x-tooltip="'💡Edit server settings and configuration'"
                      >
                        Edit
                      </button>

                      <!-- Row 2: Export Config -->
                      <button
                        data-action-click="showConfigSelectionModal" data-arg0="{{ server.id|tojson_attr }}" data-arg1="{{ server.name|tojson_attr }}"
                        class="col-span-2 flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-purple-600 hover:text-purple-900 hover:bg-purple-50 dark:text-purple-400 dark:hover:bg-purple-900/20 transition-colors"
                        x-tooltip="'💡Generate client configuration files for this server'"
                      >
                        Export Config
                      </button>

                      <!-- Row 3: Deactivate/Activate | Delete -->
                      <div class="col-span-2 flex flex-col space-y-1">
                        {% if server.enabled %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/servers/{{ server.id }}/state"
                          class="contents"
                          data-action-submit="handleToggleSubmit" data-arg0="servers"
                        >
                          <input type="hidden" name="activate" value="false" />
                          <button
                            type="submit"
                            x-tooltip="'💡Temporarily disable this item (can be re-activated)'"
                            class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-yellow-600 hover:text-yellow-900 hover:bg-yellow-50 dark:text-yellow-400 dark:hover:bg-yellow-900/20 transition-colors"
                          >
                            Deactivate
                          </button>
                        </form>
                        {% else %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/servers/{{ server.id }}/state"
                          class="contents"
                          data-action-submit="handleToggleSubmit" data-arg0="servers"
                        >
                          <input type="hidden" name="activate" value="true" />
                          <button
                            type="submit"
                            x-tooltip="'💡Re-enable an inactive item'"
                            class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-blue-600 hover:text-blue-900 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20 transition-colors"
                          >
                            Activate
                          </button>
                        </form>
                        {% endif %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/servers/{{ server.id }}/delete"
                          class="contents"
                          data-action-submit="handleDeleteSubmit" data-arg0="server" data-arg1="{{ server.name|tojson_attr }}" data-arg2="servers"
                        >
                          <button
                            type="submit"
                            x-tooltip="'💡Permanently delete this item – cannot be undone'"
                            class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-red-600 hover:text-red-900 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 transition-colors"
                          >
                            Delete
                          </button>
                        </form>
                      </div>
                    </div>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>
        {% if user_permissions.can_create_server %}
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Server
          </h3>
          <form
            method="POST"
            id="add-server-form"
            data-action-reset="clearAssociatedTools"
          >
            <div class="grid grid-cols-1 gap-7">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Custom UUID (optional)</label
                >
                <input
                  type="text"
                  name="id"
                  placeholder="Leave blank to auto-generate"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  Provide a custom UUID if you need to preserve an existing
                  server ID
                </p>
              </div>
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  for="server-name"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  id="server-name"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Icon URL</label
                >
                <input
                  type="url"
                  name="icon"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div
                  class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-300 dark:border-gray-700"
                >
                  <label
                    class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                    for="associatedGateways"
                  >
                    MCP Servers
                  </label>
                  <input
                    type="text"
                    id="searchGateways"
                    placeholder="Search for MCP servers..."
                    class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                  />
                  <div
                    id="associatedGateways"
                    class="max-h-60 overflow-y-auto rounded-md border border-gray-300 dark:border-gray-700 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                    hx-get="{{ root_path }}/admin/gateways/partial?page=1&per_page=50&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                    hx-trigger="load"
                    hx-swap="innerHTML"
                  >
                    <!-- Gateway checkboxes will be loaded here via HTMX -->
                    <div class="flex items-center justify-center p-4">
                      <span class="text-gray-500 dark:text-gray-400 text-sm">Loading MCP servers...</span>
                    </div>
                  </div>
                  <p
                    id="noGatewayMessage"
                    class="text-gray-700 dark:text-gray-300 mt-2"
                    style="display: none"
                  >
                    No MCP server found containing "<span id="searchQueryServers"></span>"
                  </p>
                  <div class="flex justify-end mt-3 gap-2">
                    <button
                      type="button"
                      id="selectAllGatewayBtn"
                      class="px-3 py-1 text-sm font-semibold text-green-600 border border-green-600 rounded-md hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-green-300 focus:ring-offset-1"
                      aria-label="Select all MCP servers"
                    >
                      Select All
                    </button>

                    <button
                      type="button"
                      id="clearAllGatewayBtn"
                      class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                      aria-label="Clear all selected MPC servers"
                    >
                      Clear All
                    </button>
                  </div>

                  <p class="text-sm text-gray-600 dark:text-gray-400 mt-2">
                    Choose an MCP server, then select the tools, resources, and prompts to configure your virtual server.
                  </p>

                  <!-- Selected pills -->
                  <div
                    id="selectedGatewayPills"
                    class="mt-4 flex flex-wrap gap-2"
                  ></div>

                  <!-- Warning message -->
                  <div
                    id="selectedGatewayWarning"
                    class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                    aria-live="polite"
                  ></div>
                </div>

                <div
                  class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-300 dark:border-gray-700"
                >
                  <div class="flex items-center justify-between mb-2">
                    <label
                      class="block text-sm font-semibold text-gray-700 dark:text-gray-300"
                      for="associatedTools"
                    >
                      Associated Tools
                    </label>
                    <button
                      type="button"
                      data-action-click="refreshToolsForSelectedGateways" data-arg0="this"
                      class="px-2 py-1 text-xs font-medium text-green-700 dark:text-green-400 border border-green-600 dark:border-green-500 rounded-md hover:bg-green-50 dark:hover:bg-green-900/20 transition-colors"
                      x-tooltip="'Re-fetch tools from selected MCP gateways and reload this list'"
                    >Refresh from MCPs</button>
                  </div>
                  <input
                    type="text"
                    id="searchTools"
                    placeholder="Search for tools..."
                    class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                  />
                  <div
                    id="associatedTools"
                    class="max-h-60 overflow-y-auto rounded-md border border-gray-300 dark:border-gray-700 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                    hx-get="{{ root_path }}/admin/tools/partial?page=1&per_page=50&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                    hx-trigger="load"
                    hx-swap="innerHTML"
                    hx-on:htmx:after-swap="window.Admin?.initToolSelect?.('associatedTools', 'selectedToolsPills', 'selectedToolsWarning', 6, 'selectAllToolsBtn', 'clearAllToolsBtn')"
                  >
                    <!-- Tools will be loaded via HTMX -->
                    <div class="text-center py-4 text-gray-500 dark:text-gray-400">
                      <svg class="animate-spin h-5 w-5 text-indigo-600 dark:text-indigo-400 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <span class="ml-2">Loading tools...</span>
                    </div>
                  </div>
                  <p
                    id="noToolsMessage"
                    class="text-gray-700 dark:text-gray-300 mt-2"
                    style="display: none"
                  >
                    No tool found containing "<span id="searchQueryTools"></span>"
                  </p>
                  <div class="flex justify-end mt-3 gap-2">
                    <button
                      type="button"
                      id="selectAllToolsBtn"
                      class="px-3 py-1 text-sm font-semibold text-green-600 border border-green-600 rounded-md hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-green-300 focus:ring-offset-1"
                      aria-label="Select all tools"
                    >
                      Select All
                    </button>

                    <button
                      type="button"
                      id="clearAllToolsBtn"
                      class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                      aria-label="Clear all selected tools"
                    >
                      Clear All
                    </button>
                  </div>

                  <!-- Selected pills -->
                  <div
                    id="selectedToolsPills"
                    class="mt-4 flex flex-wrap gap-2"
                  ></div>

                  <!-- Warning message -->
                  <div
                    id="selectedToolsWarning"
                    class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                    aria-live="polite"
                  ></div>
                </div>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                <label
                  class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                  for="associatedResources"
                >
                  Associated Resources
                </label>
                <input
                  type="text"
                  id="searchResources"
                  placeholder="Search for resources..."
                  class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                />
                <div
                  id="associatedResources"
                  class="max-h-60 overflow-y-auto rounded-md border border-gray-300 dark:border-gray-700 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                  hx-get="{{ root_path }}/admin/resources/partial?page=1&per_page=20&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                  hx-trigger="load"
                  hx-swap="innerHTML"
                  hx-on:htmx:after-swap="window.Admin?.initResourceSelect?.('associatedResources', 'selectedResourcesPills', 'selectedResourcesWarning', 6, 'selectAllResourcesBtn', 'clearAllResourcesBtn')"
                >
                  <!-- Resources will be loaded via HTMX -->
                  <div class="text-center py-4 text-gray-500 dark:text-gray-400">
                    <svg class="animate-spin h-5 w-5 text-blue-600 dark:text-blue-400 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                      <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <span class="ml-2">Loading resources...</span>
                  </div>
                </div>
                <p
                  id="noResourcesMessage"
                  class="text-gray-700 dark:text-gray-300 mt-2"
                  style="display: none"
                >
                  No resource found containing "<span id="searchResourcesQuery"></span>"
                </p>
                <div class="flex justify-end gap-3 mt-3">
                  <button
                    type="button"
                    id="selectAllResourcesBtn"
                    class="px-3 py-1 text-sm font-semibold text-blue-600 border border-blue-600 rounded-md hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-offset-1"
                    aria-label="Select all resources"
                  >
                    Select All
                  </button>
                  <button
                    type="button"
                    id="clearAllResourcesBtn"
                    class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                    aria-label="Clear all selected resources"
                  >
                    Clear All
                  </button>
                </div>
                <!-- Selected pills -->
                <div
                  id="selectedResourcesPills"
                  class="mt-4 flex flex-wrap gap-2"
                ></div>
                <!-- Warning message -->
                <div
                  id="selectedResourcesWarning"
                  class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                  aria-live="polite"
                ></div>
              </div>
              <div>
                <label
                  class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                  for="associatedPrompts"
                >
                  Associated Prompts
                </label>
                <input
                  type="text"
                  id="searchPrompts"
                  placeholder="Search for prompts..."
                  class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                />
                <div
                  id="associatedPrompts"
                  class="max-h-60 overflow-y-auto rounded-md border border-gray-300 dark:border-gray-700 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                  hx-get="{{ root_path }}/admin/prompts/partial?page=1&per_page=20&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                  hx-trigger="load"
                  hx-swap="innerHTML"
                  hx-on:htmx:after-swap="window.Admin?.initPromptSelect?.('associatedPrompts', 'selectedPromptsPills', 'selectedPromptsWarning', 6, 'selectAllPromptsBtn', 'clearAllPromptsBtn')"
                >
                  <!-- Prompts will be loaded via HTMX -->
                  <div class="text-center py-4 text-gray-500 dark:text-gray-400">
                    <svg class="animate-spin h-5 w-5 text-purple-600 dark:text-purple-400 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                      <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <span class="ml-2">Loading prompts...</span>
                  </div>
                </div>
                <p
                  id="noPromptsMessage"
                  class="text-gray-700 dark:text-gray-300 mt-2"
                  style="display: none"
                >
                  No prompt found containing "<span id="searchPromptsQuery"></span>"
                </p>
                <div class="flex justify-end gap-3 mt-3">
                  <button
                    type="button"
                    id="selectAllPromptsBtn"
                    class="px-3 py-1 text-sm font-semibold text-purple-600 border border-purple-600 rounded-md hover:bg-purple-50 focus:outline-none focus:ring-2 focus:ring-purple-300 focus:ring-offset-1"
                    aria-label="Select all prompts"
                  >
                    Select All
                  </button>
                  <button
                    type="button"
                    id="clearAllPromptsBtn"
                    class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                    aria-label="Clear all selected prompts"
                  >
                    Clear All
                  </button>
                </div>
                <!-- Selected pills -->
                <div
                  id="selectedPromptsPills"
                  class="mt-4 flex flex-wrap gap-2"
                ></div>
                <!-- Warning message -->
                <div
                  id="selectedPromptsWarning"
                  class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                  aria-live="polite"
                ></div>
                </div>
              </div>
            </div>
            <!-- 🔻 Error Display Span -->
            <span
              id="serverFormError"
              class="block text-sm font-semibold text-red-600 mt-2"
            ></span>

            <!-- 🔄 Optional Loading Indicator -->
            <div
              id="add-server-loading"
              class="hidden text-sm text-gray-500 mt-2"
            >
              Submitting...
            </div>

            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Tags</label
              >
              <input
                type="text"
                name="tags"
                placeholder="e.g., development,production,api-gateway (comma-separated)"
                class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
              />
              <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                Enter tags separated by commas. Tags help categorize and filter
                servers.
              </p>
            </div>
            <!-- Visibility options -->
            <div class="mt-4">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Visibility</label
              >
              <div class="flex gap-x-6 mt-2">
                <!-- Add gap-x-6 for more space between radio options -->

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="public"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="server-visibility-public"
                    checked
                  />
                  <label
                    for="server-visibility-public"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🌍Public</label
                  >
                </div>

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="team"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="server-visibility-team"
                  />
                  <label
                    for="server-visibility-team"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >👥Team</label
                  >
                </div>
                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="private"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="server-visibility-private"
                  />
                  <label
                    for="server-visibility-private"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🔒Private</label
                  >
                </div>
              </div>
            </div>

            {% if selected_team_id %}
            <!-- View Public toggle for team-scoped server creation -->
            <div class="mt-4" id="add-server-view-public-container">
              <div class="flex items-center">
                <input
                  type="checkbox"
                  id="add-server-view-public"
                  class="form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                />
                <label
                  for="add-server-view-public"
                  class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-400"
                  >View Public &mdash; Include publicly available MCP servers, tools, resources, and prompts</label
                >
              </div>
              <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                When enabled, public items from across the platform are shown alongside your team's items in the selectors below.
              </p>
            </div>
            {% endif %}

            <!-- OAuth 2.0 Configuration Section (RFC 9728) -->
            <div class="mt-6 border-t border-gray-200 dark:border-gray-700 pt-4">
              <div class="flex items-center mb-4">
                <input
                  type="checkbox"
                  name="oauth_enabled"
                  id="server-oauth-enabled"
                  class="form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                  data-action-change="toggleElementClass" data-arg0="server-oauth-config-section" data-arg1="hidden"
                />
                <label
                  for="server-oauth-enabled"
                  class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Enable OAuth 2.0 for MCP Client Authentication</label
                >
              </div>
              <p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
                When enabled, MCP clients can authenticate using browser-based OAuth/SSO per RFC 9728.
              </p>

              <!-- OAuth Configuration Fields (hidden by default) -->
              <div id="server-oauth-config-section" class="hidden space-y-4 pl-6 border-l-2 border-indigo-200 dark:border-indigo-800">
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                    for="server-oauth-authorization-server"
                    >Authorization Server URL</label
                  >
                  <input
                    type="url"
                    name="oauth_authorization_server"
                    id="server-oauth-authorization-server"
                    placeholder="https://idp.example.com"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                  <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    The OAuth 2.0 authorization server URL (e.g., your Identity Provider)
                  </p>
                </div>
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                    for="server-oauth-scopes"
                    >Scopes (space-separated)</label
                  >
                  <input
                    type="text"
                    name="oauth_scopes"
                    id="server-oauth-scopes"
                    placeholder="openid profile email"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                  <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    OAuth scopes to request (e.g., openid profile email)
                  </p>
                </div>
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                    for="server-oauth-token-endpoint"
                    >Token Endpoint URL (optional)</label
                  >
                  <input
                    type="url"
                    name="oauth_token_endpoint"
                    id="server-oauth-token-endpoint"
                    placeholder="https://idp.example.com/oauth/token"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                  <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Leave blank to use standard discovery from authorization server
                  </p>
                </div>
              </div>
            </div>

            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Creates a new Virtual Server by combining Tools, Resources & Prompts from global catalogs.'"
                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Server
              </button>
            </div>
          </form>
        </div>
        {% endif %}
      </div>



      {% endif %}
      {% if 'tools' not in hidden_sections %}
      <!-- Tools Panel -->
      <div id="tools-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <div>
            <h2 class="text-2xl font-bold dark:text-gray-200">MCP Tools</h2>
            <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
              This is the global catalog of MCP Tools available. You can also
              add custom tools from REST APIs. Create a Virtual Server using one
              of these tools.
            </p>
            <div class="mt-2 text-xs text-gray-500 dark:text-gray-400">
              <strong>Annotation badges:</strong>
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 ml-1"
                >📖 Read-Only</span
              >
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800 ml-1"
                >⚠️ Destructive</span
              >
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800 ml-1"
                >🔄 Idempotent</span
              >
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800 ml-1"
                >🌐 External Access</span
              >
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <input
              type="checkbox"
              id="show-inactive-tools"
              class="mr-2 show-inactive-toggle"
              name="include_inactive"
              x-init="syncCheckboxFromUrl('tools', 'show-inactive-tools')"
              @change="updateInactiveUrlState('tools', $el.checked)"
              hx-get="{{ root_path }}/admin/tools/partial?page=1{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
              hx-vals="js:{include_inactive: document.getElementById('show-inactive-tools').checked, per_page: document.querySelector('#tools-pagination-controls select')?.value || 50, q: document.getElementById('tools-search-input')?.value || '', tags: document.getElementById('tools-tag-filter')?.value || ''}"
              hx-target="#tools-table"
              hx-swap="outerHTML"
              hx-indicator="#tools-loading"
              hx-trigger="change"
            />
            <label
              for="show-inactive-tools"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Unified Search & Filter Bar for Tools -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <div class="flex flex-col space-y-4">
            <!-- Search Row -->
            <div class="flex items-center space-x-2">
              <div class="relative">
                <input
                  type="text"
                  id="tools-search-input"
                  placeholder="Search tools..."
                  class="w-80 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-300 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <button
                id="tools-clear-search"
                data-action-click="clearSearch" data-arg0="tools"
                class="px-2 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors">
                Clear
              </button>
              <span id="tools-filter-status" class="text-sm text-gray-500 dark:text-gray-400" aria-live="polite" role="status"></span>
            </div>

            <!-- Hidden tag filter for functionality -->
            <input type="hidden" id="tools-tag-filter" />
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div id="tools-table-wrapper" class="overflow-x-auto">
            <!-- Table will be loaded via HTMX -->
            <div id="tools-table"
                 x-init="$el.setAttribute('hx-get', buildTableUrl('tools', '{{ root_path }}/admin/tools/partial', {include_inactive: (document.getElementById('show-inactive-tools')?.checked ?? false).toString(){% if selected_team_id %}, team_id: '{{ selected_team_id }}'{% endif %}}))"
                 hx-trigger="load"
                 hx-swap="outerHTML"
                 hx-indicator="#tools-loading">

            </div>
          </div>

          <!-- Loading Indicator for HTMX -->
          <div id="tools-loading" class="htmx-indicator">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading tools...</span>
            </div>
          </div>

          <!-- Pagination Controls -->
          {# ---- compute safe pagination values first ---- #}
          {% set page = page if page is defined else 1 %}
          {% set per_page = per_page if per_page is defined else 50 %}
          {% set total_items = tools|length if tools is defined else 0 %}
          {% set total_pages = (total_items + per_page - 1) // per_page if total_items > 0 else 0 %}
          {% set has_prev = page > 1 %}
          {% set has_next = (page * per_page) < total_items %}

          {% set pagination = {
            'page': page,
            'per_page': per_page,
            'total_items': total_items,
            'total_pages': total_pages,
            'has_prev': has_prev,
            'has_next': has_next,
            'page_items': None
          } %}

          {# build the refresh URL for controls #}
          {% set controls_url = root_path + '/admin/tools/partial'
            + '?render=controls'
            + '&page=' + page|string
            + '&per_page=' + per_page|string
            + '&include_inactive=' + (include_inactive|default(false)|string|lower) %}

          <div id="tools-pagination-controls"
              hx-get="{{ controls_url }}"
              hx-trigger="refreshControls"
              hx-target="#tools-pagination-controls"
              hx-swap="outerHTML"
              hx-indicator="#tools-loading">

            {# helpers used by pagination_controls.html #}
            {% set base_url = root_path + '/admin/tools/partial' %}
            {% set hx_target = '#tools-table' %}
            {% set hx_swap = 'outerHTML' %}
            {% set hx_indicator = '#tools-loading' %}
            {% set table_name = 'tools' %}
            {% set query_params = {'include_inactive': include_inactive} %}
            {% include 'pagination_controls.html' %}
          </div>
        </div>
        {% if user_permissions.can_create_tool %}
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <div class="flex justify-between items-center mb-4">
            <div>
              <h3 class="text-lg font-bold dark:text-gray-200">
                Add New Tool from REST API
              </h3>
              <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                Convert existing REST API to an MCP Tool
              </p>
            </div>

            <!-- Bulk Import Dropdown -->
            <div class="relative">
              <button
                id="bulk-import-dropdown-btn"
                data-action-click="toggleBulkImportDropdown"
                class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                <svg
                  class="w-4 h-4 mr-2 text-green-600"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                  ></path>
                </svg>
                Bulk Import
                <svg
                  class="w-4 h-4 ml-1"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M19 9l-7 7-7-7"
                  ></path>
                </svg>
              </button>

              <!-- Dropdown Menu -->
              <div
                id="bulk-import-dropdown"
                class="hidden absolute right-0 mt-2 w-96 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg z-30"
              >
                <div class="p-4">
                  <!-- Information Section -->
                  <div class="mb-4">
                    <h4
                      class="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-2"
                    >
                      📥 Bulk Import Information
                    </h4>
                    <div
                      class="text-xs text-gray-600 dark:text-gray-400 space-y-1"
                    >
                      <p>
                        Import multiple tools from a JSON array. The system
                        automatically fixes common formatting issues like tool
                        name spaces and tag formats.
                      </p>
                      <p><strong>Maximum:</strong> 200 tools per import</p>
                      <div
                        class="mt-3 p-3 bg-gray-50 dark:bg-gray-700 rounded border"
                      >
                        <div class="flex justify-between items-center mb-2">
                          <strong class="text-xs">Sample JSON Template:</strong>
                          <button
                            data-action-click="downloadSampleJSON"
                            class="text-blue-600 hover:text-blue-800 dark:text-blue-400 text-xs underline"
                          >
                            📥 Download Sample
                          </button>
                        </div>
                        <pre
                          class="text-xs overflow-x-auto"
                        ><code id="sample-json">[
  {
    "name": "weather-api",
    "displayName": "Weather API Tool",
    "url": "https://api.openweathermap.org/data/2.5/weather",
    "integration_type": "REST",
    "request_type": "GET",
    "description": "Get current weather data for any location",
    "auth_type": "bearer",
    "auth_value": "your-openweather-api-key-here",
    "headers": {
      "Accept": "application/json",
      "User-Agent": "ContextForge/1.0"
    },
    "input_schema": {
      "type": "object",
      "properties": {
        "q": {"type": "string", "description": "City name"},
        "units": {"type": "string", "description": "Temperature units"}
      },
      "required": ["q"]
    },
    "jsonpath_filter": "$.main",
    "tags": ["weather", "api", "external"]
  }
]</code></pre>
                        <div class="mt-3 text-xs space-y-1">
                          <p>
                            <strong>Auth Types:</strong> basic, bearer,
                            authheaders, oauth, or none
                          </p>
                          <p>
                            <strong>Required Fields:</strong> name, url,
                            integration_type, request_type
                          </p>
                          <p>
                            <strong>Optional Fields:</strong> displayName,
                            description, auth_type, auth_value, headers,
                            input_schema, jsonpath_filter, tags
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- Import Method Selection -->
                  <div class="mb-4">
                    <h5
                      class="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Choose Import Method:
                    </h5>
                    <div class="flex space-x-4">
                      <label class="flex items-center">
                        <input
                          type="radio"
                          name="dropdown-import-method"
                          value="file"
                          checked
                          data-action-change="toggleDropdownImportMethod" data-arg0="file"
                          class="mr-2"
                        />
                        <span class="text-xs text-gray-600 dark:text-gray-400"
                          >Upload File</span
                        >
                      </label>
                      <label class="flex items-center">
                        <input
                          type="radio"
                          name="dropdown-import-method"
                          value="paste"
                          data-action-change="toggleDropdownImportMethod" data-arg0="paste"
                          class="mr-2"
                        />
                        <span class="text-xs text-gray-600 dark:text-gray-400"
                          >Paste JSON</span
                        >
                      </label>
                    </div>
                  </div>

                  <!-- File Upload Section -->
                  <div id="dropdown-file-section" class="mb-4">
                    <label
                      class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Upload JSON File
                    </label>
                    <div
                      class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-3 text-center"
                    >
                      <input
                        type="file"
                        id="dropdown-file-input"
                        accept=".json"
                        data-action-change="handleDropdownFileSelect" data-arg0="this"
                        class="hidden"
                      />
                      <div
                        id="dropdown-file-drop-zone"
                        data-action-click="clickElement" data-arg0="dropdown-file-input"
                        class="cursor-pointer"
                      >
                        <svg
                          class="mx-auto h-8 w-8 text-gray-400"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                          ></path>
                        </svg>
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 mt-1"
                        >
                          Click to upload JSON file
                        </p>
                      </div>
                      <div
                        id="dropdown-file-info"
                        class="hidden mt-2 text-xs text-green-600 dark:text-green-400"
                      ></div>
                    </div>
                  </div>

                  <!-- JSON Paste Section -->
                  <div id="dropdown-paste-section" class="hidden mb-4">
                    <label
                      class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Paste JSON Data
                    </label>
                    <textarea
                      id="dropdown-json-textarea"
                      rows="6"
                      placeholder="[{&quot;name&quot;: &quot;example_tool&quot;, &quot;url&quot;: &quot;https://api.example.com&quot;, &quot;description&quot;: &quot;Example tool&quot;}]"
                      data-action-input="validateDropdownJson"
                      class="w-full text-xs border border-gray-300 dark:border-gray-600 rounded-md p-2 dark:bg-gray-700 dark:text-gray-300"
                    ></textarea>
                    <div id="dropdown-json-status" class="mt-1 text-xs"></div>
                  </div>

                  <!-- Preview Section -->
                  <div id="dropdown-preview" class="hidden mb-4">
                    <h5
                      class="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Import Preview
                    </h5>
                    <div class="bg-gray-50 dark:bg-gray-700 rounded-md p-2">
                      <div class="text-xs text-gray-600 dark:text-gray-400">
                        <span id="dropdown-preview-count">0</span> tools ready
                        for import
                      </div>
                    </div>
                  </div>

                  <!-- Import Results Section -->
                  <div id="dropdown-results" class="hidden mb-4">
                    <h5
                      class="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      📊 Import Results
                    </h5>
                    <div class="grid grid-cols-3 gap-2 mb-2">
                      <div class="bg-white dark:bg-gray-800 rounded p-2 text-center border">
                        <div id="dropdown-stats-total" class="text-sm font-bold text-blue-600 dark:text-blue-400">0</div>
                        <div class="text-xs text-gray-500">Total</div>
                      </div>
                      <div class="bg-white dark:bg-gray-800 rounded p-2 text-center border">
                        <div id="dropdown-stats-success" class="text-sm font-bold text-green-600 dark:text-green-400">0</div>
                        <div class="text-xs text-gray-500">Success</div>
                      </div>
                      <div class="bg-white dark:bg-gray-800 rounded p-2 text-center border">
                        <div id="dropdown-stats-failed" class="text-sm font-bold text-red-600 dark:text-red-400">0</div>
                        <div class="text-xs text-gray-500">Failed</div>
                      </div>
                    </div>
                  </div>

                  <!-- Status Messages -->
                  <div id="dropdown-status" class="hidden mb-4 text-xs"></div>

                  <!-- Action Buttons -->
                  <div class="flex justify-between items-center">
                    <button
                      data-action-click="resetDropdownImport"
                      class="text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                    >
                      Clear
                    </button>
                    <div class="space-x-2">
                      <button
                        data-action-click="toggleBulkImportDropdown"
                        class="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"
                      >
                        Cancel
                      </button>
                      <button
                        id="dropdown-import-btn"
                        data-action-click="submitDropdownImport"
                        disabled
                        class="px-3 py-1 text-xs bg-green-600 text-white rounded hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
                      >
                        Import Tools
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <form method="POST" id="add-tool-form">
            <div class="grid grid-cols-1 gap-7">
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  for="tool-name"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  id="tool-name"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
              </div>

              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Display Name (optional)</label
                >
                <input
                  type="text"
                  name="displayName"
                  placeholder="Custom display name for your UI"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>

              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  for="tool-url"
                  >URL</label
                >
                <input
                  type="url"
                  name="url"
                  required
                  id="tool-url"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="url" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">URL is required.</p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Integration Type</label
                >
                <select
                  id="integrationType"
                  name="integrationType"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  data-action-change="updateRequestTypeOptions"
                >
                  <option value="REST">REST</option>
                </select>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Request Type</label
                >
                <select
                  id="requestType"
                  name="requestType"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <!-- options will be filled by JS -->
                </select>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Headers (JSON)</label
                >
                <textarea
                  name="headers"
                  id="headers-editor"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Input Schema (JSON)</label
                >
                <div class="mb-2">
                  <label class="mr-4 dark:text-gray-300">
                    <input
                      type="radio"
                      name="schema_input_mode"
                      value="ui"
                      checked
                    />
                    Schema Builder
                  </label>
                  <label class="dark:text-gray-300">
                    <input type="radio" name="schema_input_mode" value="json" />
                    JSON Input
                  </label>
                </div>
                <div id="ui-builder" class="border p-4 mb-4">
                  <div id="parameters-container"></div>
                  <button
                    type="button"
                    id="add-parameter-btn"
                    class="mt-2 inline-flex justify-center py-1 px-2 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700"
                  >
                    Add New Parameter
                  </button>
                  <!-- Advanced: Add Passthrough Section -->
                    <button
                      type="button"
                      id="add-passthrough-btn"
                      class="mt-2 inline-flex justify-center py-1 px-2 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700"
                    >
                      Advanced: Add Passthrough
                    </button>
                    <fieldset id="passthrough-container" class="mt-2 border p-4 rounded-lg" style="display:none;">
                      <!-- Passthrough fields will be dynamically added here -->
                    </fieldset>
                </div>
                <div id="json-input-container" style="display: none">
                  <textarea
                    name="input_schema"
                    id="schema-editor"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  ></textarea>
                </div>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Output Schema (JSON)</label
                >
                <textarea
                  name="output_schema"
                  id="output-schema-editor"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="{&quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: {}}"
                ></textarea>
                <p class="mt-1 text-xs text-gray-500 dark:text-indigo-300">
                  Optional JSON Schema for validating structured tool output. Leave empty if not needed.
                </p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Json Path Filter</label
                >
                <input
                  type="text"
                  name="jsonpath_filter"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <!-- Authentication Section -->
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Authentication Type</label
                >
                <select
                  name="auth_type"
                  id="auth-type"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <option value="">None</option>
                  <option value="basic">Basic</option>
                  <option value="bearer">Bearer Token</option>
                  <option value="authheaders">Custom Headers</option>
                  <option value="oauth">OAuth 2.0</option>
                </select>
              </div>
              <div id="auth-basic-fields" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Username</label
                  >
                  <input
                    type="text"
                    name="auth_username"
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Password</label
                  >
                  <input
                    type="password"
                    name="auth_password"
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>
              <div id="auth-bearer-fields" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Token</label
                  >
                  <input
                    type="password"
                    name="auth_token"
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>
              <div id="auth-headers-fields" style="display: none">
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Custom Headers
                    </label>
                    <button
                      type="button"
                      data-action-click="addAuthHeader" data-arg0="auth-headers-container"
                      class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      <svg
                        class="w-4 h-4 mr-1"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                        ></path>
                      </svg>
                      Add Header
                    </button>
                  </div>
                  <div id="auth-headers-container" class="space-y-2">
                    <!-- Headers will be added dynamically here -->
                  </div>
                  <input
                    type="hidden"
                    name="auth_headers"
                    id="auth-headers-json"
                  />
                </div>
              </div>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Tags</label
              >
              <input
                type="text"
                name="tags"
                placeholder="e.g., api,data-processing,external (comma-separated)"
                class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
              />
              <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                Enter tags separated by commas. Tags help categorize and filter
                tools.
              </p>
            </div>
            <!-- Visibility options -->
            <div class="mt-4">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Visibility</label
              >
              <div class="flex gap-x-6 mt-2">
                <!-- Add gap-x-6 for more space between radio options -->

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="public"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="tool-visibility-public"
                    checked
                  />
                  <label
                    for="tool-visibility-public"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🌍Public</label
                  >
                </div>

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="team"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="tool-visibility-team"
                  />
                  <label
                    for="tool-visibility-team"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >👥Team</label
                  >
                </div>
                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="private"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="tool-visibility-private"
                  />
                  <label
                    for="tool-visibility-private"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🔒Private</label
                  >
                </div>
              </div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡  Registers a new Tool from an existing REST endpoint. Use Gateways to add MCP servers.'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Tool
              </button>
            </div>
          </form>
        </div>
        {% endif %}
      </div>
      {% if toolops_enabled %}
      <div id="tool-ops-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <div>
            <h2 class="text-2xl font-bold dark:text-gray-200">Tool Operations</h2>
              <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                Select tools and perform batch operations like enrichment and validation.
              </p>
          </div>
          </div>
          <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Left Column -->
            <div class="lg:col-span-2 bg-white border border-gray-200 rounded-lg shadow-sm">
              <!-- Search box and checkbox controls, which are static and not part of the HTMX swap -->
              <div class="p-4 flex items-center justify-between border-b border-gray-200">
                <input
                  type="text"
                  id="searchBox"
                  placeholder="Search tools..."
                  class="w-full mr-4 px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none"
                />
                <div class="flex items-center space-x-4">
                  <input
                    type="checkbox"
                    id="show-inactive-tools-toolops"
                    name="include_inactive"
                    class="mr-2 show-inactive-toggle"
                    hx-get="{{ root_path }}/admin/tool-ops/partial?page=1"
                    hx-vals="js:{include_inactive: document.getElementById('show-inactive-tools-toolops').checked}"
                    hx-trigger="change"
                    hx-target="#tool-ops-main-content-wrapper"
                    hx-swap="innerHTML"
                    hx-indicator="#tool-ops-loading-indicator"
                  />
                  <label
                    for="show-inactive-tools-toolops"
                    class="text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Show Inactive</label
                  >
                </div>
              </div>

              <!-- This div will be the target for the HTMX initial load and subsequent swaps -->
              <div id="tool-ops-main-content-wrapper" hx-get="{{ root_path }}/admin/tool-ops/partial" hx-trigger="load" hx-swap="innerHTML" hx-indicator="#tool-ops-loading-indicator">

              </div>

              <!-- Loading Indicator for HTMX -->
              <div id="tool-ops-loading-indicator" class="htmx-indicator">
                <div class="flex items-center justify-center p-4">
                  <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  <span class="ml-2 text-gray-600 dark:text-gray-400">Loading tools...</span>
                </div>
              </div>

            </div>

            <!-- Right Column -->
            <div class="space-y-6">
              <div class="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
                <div class="flex items-center justify-between mb-3">
                  <h3 class="text-sm font-medium text-gray-900">Selected Tools</h3>
                  <span id="selectedCount" class="text-xs px-2 py-1 rounded-full bg-indigo-100 text-indigo-800">0</span>
                </div>
                <div id="selectedList" class="flex flex-col gap-2 text-sm mb-4 text-gray-500">
                  No tools selected
                </div>
              </div>

              <div class="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
                <h3 class="text-sm font-medium text-gray-900 mb-4">Operations</h3>
                <div class="flex flex-col space-y-3">
                  <!-- <button class="w-full px-3 py-2 bg-green-600 text-white rounded-md text-sm hover:bg-green-700">Enrich Tools</button>
                  <button class="w-full px-3 py-2 bg-blue-600 text-white rounded-md text-sm hover:bg-blue-700">Tool Validation</button> -->
                  <div class="space-y-2">
                    <button
                      id="enrichToolsBtn"
                      class="w-full px-3 py-2 bg-teal-600 text-white rounded-md text-sm hover:bg-teal-700">
                      Enrich Tools
                    </button>

                    <button
                      id="validateToolsBtn"
                      class="w-full px-3 py-2 bg-purple-600 text-white rounded-md text-sm hover:bg-purple-700">
                      Generate Test Cases
                    </button>
                  </div>

                  <button
                      id="clearToolsBtn"
                      class="w-full px-3 py-2 bg-gray-600 text-white rounded-md text-sm hover:bg-gray-700">
                      Clear
                    </button>
                  </div>

                  <!-- Add a small output area to show response -->
                  <div id="toolOpsResponse" class="mt-3 text-sm text-gray-700"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      {% endif %}
      <div id="toolModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white p-6 rounded-lg shadow-lg w-96">
          <h3 class="text-lg font-semibold mb-3">Tool Details</h3>
          <div id="modalContent" class="text-sm text-gray-700 space-y-2"></div>
          <button id="closeModal" class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-md">Close</button>
        </div>
      </div>

      <!-- Bulk Import Modal -->
      <div id="bulk-import-modal" class="fixed inset-0 z-40 hidden">
        <div
          id="bulk-import-backdrop"
          class="absolute inset-0 bg-black/50"
        ></div>
        <div
          role="dialog"
          aria-modal="true"
          class="relative mx-auto my-12 w-full max-w-2xl rounded-xl bg-white p-0 shadow-xl dark:bg-gray-900"
        >
          <div
            class="flex items-center justify-between border-b px-5 py-3 dark:border-gray-700"
          >
            <h3 class="text-base font-semibold dark:text-gray-100">
              Bulk Import Tools
            </h3>
            <button
              id="close-bulk-import"
              data-close-bulk-import
              class="rounded p-1 text-gray-500 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
              aria-label="Close"
            >
              ✕
            </button>
          </div>

          <form
            id="bulk-import-form"
            enctype="multipart/form-data"
            class="space-y-4 p-5"
          >
            <p class="text-sm text-gray-600 dark:text-gray-400">
              Paste a JSON array or upload a <code>.json</code> file. Max {{
              bulk_import_max_tools }} tools.
            </p>

            <label
              class="block text-sm font-medium dark:text-gray-300"
              for="tools_json"
              >JSON Data</label
            >
            <textarea
              id="tools_json"
              name="tools_json"
              rows="8"
              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 font-mono text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300"
              placeholder="[{&quot;name&quot;:&quot;tool_name&quot;,&quot;url&quot;:&quot;https://...&quot;,&quot;integration_type&quot;:&quot;REST&quot;,&quot;request_type&quot;:&quot;GET&quot;}]"
            ></textarea>

            <div>
              <label
                class="block text-sm font-medium dark:text-gray-300"
                for="tools_file"
                >Or upload JSON file</label
              >
              <input
                id="tools_file"
                name="tools_file"
                type="file"
                accept="application/json,.json"
                class="mt-1 px-3 py-2 block w-full text-sm dark:text-gray-300"
              />
            </div>

            <div class="flex items-center gap-3 pt-1">
              <button
                type="submit"
                class="inline-flex justify-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                Import Tools
              </button>
              <span
                id="bulk-import-indicator"
                class="htmx-indicator flex items-center text-sm text-gray-500 dark:text-gray-400"
              >
                <svg
                  class="mr-2 h-4 w-4 animate-spin"
                  viewBox="0 0 24 24"
                  fill="none"
                >
                  <circle
                    class="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    stroke-width="4"
                  />
                  <path
                    class="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                  />
                </svg>
                Processing...
              </span>
            </div>

            <!-- Import Result Summary -->
            <div id="import-result" class="pt-2">
              <!-- Results will be populated here by JavaScript -->
            </div>

            <!-- Import Statistics Display -->
            <div id="import-statistics" class="hidden pt-4">
              <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">
                  📊 Import Summary
                </h4>
                <div class="grid grid-cols-3 gap-4 text-center">
                  <div class="bg-white dark:bg-gray-700 rounded-lg p-3 border">
                    <div id="stats-total" class="text-2xl font-bold text-blue-600 dark:text-blue-400">0</div>
                    <div class="text-xs text-gray-600 dark:text-gray-400">Total Tools</div>
                  </div>
                  <div class="bg-white dark:bg-gray-700 rounded-lg p-3 border">
                    <div id="stats-success" class="text-2xl font-bold text-green-600 dark:text-green-400">0</div>
                    <div class="text-xs text-gray-600 dark:text-gray-400">Successful</div>
                  </div>
                  <div class="bg-white dark:bg-gray-700 rounded-lg p-3 border">
                    <div id="stats-failed" class="text-2xl font-bold text-red-600 dark:text-red-400">0</div>
                    <div class="text-xs text-gray-600 dark:text-gray-400">Failed</div>
                  </div>
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>

      {% endif %}
      {% if 'resources' not in hidden_sections %}
      <!-- Resources Panel -->
      <div id="resources-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">MCP Resources</h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Resources are reusable data assets from MCP servers-like text, code,
            or media. You can also add custom resources that Tools and Prompts
            can reference by URI.
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-resources"
              class="mr-2 show-inactive-toggle"
              name="include_inactive"
              x-init="syncCheckboxFromUrl('resources', 'show-inactive-resources')"
              @change="updateInactiveUrlState('resources', $el.checked)"
              hx-get="{{ root_path }}/admin/resources/partial?page=1{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
              hx-vals="js:{include_inactive: document.getElementById('show-inactive-resources').checked, per_page: document.querySelector('#resources-pagination-controls select')?.value || 50, q: document.getElementById('resources-search-input')?.value || '', tags: document.getElementById('resources-tag-filter')?.value || ''}"
              hx-target="#resources-table"
              hx-swap="outerHTML"
              hx-indicator="#resources-loading"
              hx-trigger="change"
            />
            <label
              for="show-inactive-resources"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Unified Search & Filter Bar for Resources -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <div class="flex flex-col space-y-4">
            <!-- Search Row -->
            <div class="flex items-center space-x-2">
              <div class="relative">
                <input
                  type="text"
                  id="resources-search-input"
                  placeholder="Search resources..."
                  class="w-80 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-300 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <button
                id="resources-clear-search"
                data-action-click="clearSearch" data-arg0="resources"
                class="px-2 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors">
                Clear
              </button>
              <span id="resources-filter-status" class="text-sm text-gray-500 dark:text-gray-400" aria-live="polite" role="status"></span>
            </div>

            <!-- Hidden tag filter for functionality -->
            <input type="hidden" id="resources-tag-filter" />
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div id="resources-table-wrapper" class="overflow-x-auto">
            <!-- HTMX container: will be replaced by /admin/resources/partial -->
            <div id="resources-list-container"
              x-init="$el.setAttribute('hx-get', buildTableUrl('resources', '{{ root_path }}/admin/resources/partial', {include_inactive: (document.getElementById('show-inactive-resources')?.checked ?? false).toString(){% if selected_team_id %}, team_id: '{{ selected_team_id }}'{% endif %}}))"
              hx-trigger="load"
              hx-swap="outerHTML"
              hx-indicator="#resources-loading"
            >
              <!-- initial content will be swapped out by HTMX on load -->
            </div>
          </div>

          <!-- Loading Indicator for HTMX -->
          <div id="resources-loading" class="htmx-indicator">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading resources...</span>
            </div>
          </div>

          <!-- Placeholder for out-of-band pagination controls (injected by partial) -->
          <div id="resources-pagination-controls"></div>
        </div>

        {% if user_permissions.can_create_resource %}
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Resource
          </h3>
          <form method="POST" id="add-resource-form">
            <div class="grid grid-cols-1 gap-7">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >URI</label
                >
                <input
                  type="text"
                  name="uri"
                  id="resource-uri"
                  required
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  for="resource-name"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  id="resource-name"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >MIME Type</label
                >
                <input
                  type="text"
                  name="mimeType"
                  id="resource-mime-type"
                  aria-describedby="resource-mime-helper"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="text/plain"
                />
                <p id="resource-mime-helper" class="mt-1 text-xs text-gray-500 dark:text-gray-400 hidden">
                  For interactive MCP Apps use: text/html;profile=mcp-app
                </p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Content</label
                >
                <textarea
                  name="content"
                  id="resource-content-editor"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder=""
                ></textarea>
              </div>
              <div id="add-resources-loading" style="display: none">
                <div class="spinner"></div>
              </div>
              <div id="status-resources"></div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Tags</label
                >
                <input
                  type="text"
                  name="tags"
                  placeholder="e.g., documentation,api-spec,template (comma-separated)"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Enter tags separated by commas. Tags help categorize and
                  filter resources.
                </p>
              </div>
            </div>
            <!-- Visibility options -->
            <div class="mt-4">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Visibility</label
              >
              <div class="flex gap-x-6 mt-2">
                <!-- Add gap-x-6 for more space between radio options -->

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="public"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="resource-visibility-public"
                    checked
                  />
                  <label
                    for="resource-visibility-public"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🌍Public</label
                  >
                </div>

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="team"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="resource-visibility-team"
                  />
                  <label
                    for="resource-visibility-team"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >👥Team</label
                  >
                </div>
                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="private"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="resource-visibility-private"
                  />
                  <label
                    for="resource-visibility-private"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🔒Private</label
                  >
                </div>
              </div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Uploads or links a reusable data asset (file, URI, or text).'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Resource
              </button>
            </div>
          </form>
        </div>
        {% endif %}
      </div>

      {% endif %}
      {% if 'prompts' not in hidden_sections %}
      <!-- Prompts Panel -->
      <div id="prompts-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">MCP Prompts</h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Prompts define reusable message templates with parameters from MCP
            servers. You can also add custom prompts, useful for driving LLM
            interactions or Tool input.
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-prompts"
              class="mr-2 show-inactive-toggle"
              name="include_inactive"
              x-init="syncCheckboxFromUrl('prompts', 'show-inactive-prompts')"
              @change="updateInactiveUrlState('prompts', $el.checked)"
              hx-get="{{ root_path }}/admin/prompts/partial?page=1{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
              hx-vals="js:{include_inactive: document.getElementById('show-inactive-prompts').checked, per_page: document.querySelector('#prompts-pagination-controls select')?.value || 50, q: document.getElementById('prompts-search-input')?.value || '', tags: document.getElementById('prompts-tag-filter')?.value || ''}"
              hx-target="#prompts-table"
              hx-swap="outerHTML"
              hx-indicator="#prompts-loading"
              hx-trigger="change"
            />
            <label
              for="show-inactive-prompts"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Unified Search & Filter Bar for Prompts -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <div class="flex flex-col space-y-4">
            <!-- Search Row -->
            <div class="flex items-center space-x-2">
              <div class="relative">
                <input
                  type="text"
                  id="prompts-search-input"
                  placeholder="Search prompts..."
                  class="w-80 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-300 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <button
                id="prompts-clear-search"
                data-action-click="clearSearch" data-arg0="prompts"
                class="px-2 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors">
                Clear
              </button>
              <span id="prompts-filter-status" class="text-sm text-gray-500 dark:text-gray-400" aria-live="polite" role="status"></span>
            </div>

            <!-- Hidden tag filter for functionality -->
            <input type="hidden" id="prompts-tag-filter" />
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div id="prompts-table-wrapper" class="overflow-x-auto">
            <!-- HTMX container: will be replaced by /admin/prompts/partial -->
            <div id="prompts-list-container"
              x-init="$el.setAttribute('hx-get', buildTableUrl('prompts', '{{ root_path }}/admin/prompts/partial', {include_inactive: (document.getElementById('show-inactive-prompts')?.checked ?? false).toString(){% if selected_team_id %}, team_id: '{{ selected_team_id }}'{% endif %}}))"
              hx-trigger="load, refreshUsers"
              hx-swap="outerHTML"
              hx-indicator="#prompts-loading"
            >

            </div>
          </div>

          <!-- Loading Indicator for HTMX -->
          <div id="prompts-loading" class="htmx-indicator">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading prompts...</span>
            </div>
          </div>

          <!-- Placeholder for out-of-band pagination controls (injected by partial) -->
          <div id="prompts-pagination-controls"></div>
        </div>


        {% if user_permissions.can_create_prompt %}
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Prompt
          </h3>
          <form
            method="POST"
            action="{{ root_path }}/admin/prompts"
            id="add-prompt-form"
          >
            <div class="grid grid-cols-1 gap-7">
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  for="prompt-name"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  id="prompt-name"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Prompt name is required.</p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Display Name</label
                >
                <input
                  type="text"
                  name="display_name"
                  placeholder="Custom display name for your UI"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Template</label
                >
                <textarea
                  name="template"
                  id="prompt-template-editor"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 bg-gray-200 dark:bg-gray-800 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="Hello {{ name }}, welcome to {{ company }}! How can I help you with {{ topic }} today?"
                >
Hello &#123;&#123; name &#125;&#125;, welcome to &#123;&#123; company &#125;&#125;! How can I help you with &#123;&#123; topic &#125;&#125; today?</textarea
                >
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Arguments (JSON)</label
                >
                <textarea
                  name="arguments"
                  id="prompt-args-editor"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="[{'name':'name','description':'Customer name','required':true}]"
                >
[
  {
    "name": "name",
    "description": "Customer's name",
    "required": true
  },
  {
    "name": "company",
    "description": "Company name",
    "required": true
  },
  {
    "name": "topic",
    "description": "Topic they need help with",
    "required": false
  }
]</textarea
                >
              </div>
            </div>
            <div id="add-prompts-loading" style="display: none">
              <div class="spinner"></div>
            </div>
            <div id="status-prompts"></div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Tags</label
              >
              <input
                type="text"
                name="tags"
                placeholder="e.g., greeting,template,conversation (comma-separated)"
                class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
              />
              <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                Enter tags separated by commas. Tags help categorize and filter
                prompts.
              </p>
            </div>
            <!-- Visibility options -->
            <div class="mt-4">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Visibility</label
              >
              <div class="flex gap-x-6 mt-2">
                <!-- Add gap-x-6 for more space between radio options -->

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="public"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="prompt-visibility-public"
                    checked
                  />
                  <label
                    for="prompt-visibility-public"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🌍Public</label
                  >
                </div>

                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="team"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="prompt-visibility-team"
                  />
                  <label
                    for="prompt-visibility-team"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >👥Team</label
                  >
                </div>
                <div class="flex items-center">
                  <input
                    type="radio"
                    name="visibility"
                    value="private"
                    class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    id="prompt-visibility-private"
                  />
                  <label
                    for="prompt-visibility-private"
                    class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                    >🔒Private</label
                  >
                </div>
              </div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Creates a reusable message template with parameters.'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Prompt
              </button>
            </div>
          </form>
        </div>
        {% endif %}
      </div>

      {% endif %}
      <!-- Overview Panel -->
      {% if 'overview' not in hidden_sections %}
      <div id="overview-panel" class="tab-panel"
           hx-get="{{ root_path }}/admin/overview/partial"
           hx-trigger="load"
           hx-swap="innerHTML">
        <div class="flex items-center justify-center py-12">
          <div class="animate-pulse flex items-center space-x-2 text-gray-400 dark:text-gray-500">
            <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span>Loading overview...</span>
          </div>
        </div>
      </div>
      {% endif %}

      {% if 'gateways' not in hidden_sections %}
      <!-- Gateways Panel -->
      <div id="gateways-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            MCP Servers & Federated Gateways (MCP Registry)
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Register external MCP Servers (SSE/HTTP) to retrieve their
            tools/resources/prompts.
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-gateways"
              class="mr-2 show-inactive-toggle"
              name="include_inactive"
              checked
              x-init="syncCheckboxFromUrl('gateways', 'show-inactive-gateways')"
              @change="updateInactiveUrlState('gateways', $el.checked)"
              hx-get="{{ root_path }}/admin/gateways/partial?page=1{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
              hx-vals="js:{include_inactive: document.getElementById('show-inactive-gateways').checked, per_page: document.querySelector('#gateways-pagination-controls select')?.value || 50, q: document.getElementById('gateways-search-input')?.value || '', tags: document.getElementById('gateways-tag-filter')?.value || ''}"
              hx-target="#gateways-table"
              hx-swap="outerHTML"
              hx-indicator="#gateways-loading"
              hx-trigger="change"
            />
            <label
              for="show-inactive-gateways"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Unified Search & Filter Bar for MCP Servers -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <div class="flex flex-col space-y-4">
            <!-- Search Row -->
            <div class="flex items-center space-x-2">
              <div class="relative">
                <input
                  type="text"
                  id="gateways-search-input"
                  placeholder="Search gateways..."
                  class="w-64 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-300 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <button
                id="gateways-clear-search"
                data-action-click="clearSearch" data-arg0="gateways"
                class="px-2 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors">
                Clear
              </button>
              <span id="gateways-filter-status" class="text-sm text-gray-500 dark:text-gray-400" aria-live="polite" role="status"></span>
            </div>

            <!-- Hidden tag filter for functionality -->
            <input type="hidden" id="gateways-tag-filter" />
          </div>
        </div>

        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div id="gateways-table-wrapper" class="overflow-x-auto">
            <!-- Table will be loaded via HTMX -->
            <div id="gateways-table"
                 x-init="$el.setAttribute('hx-get', buildTableUrl('gateways', '{{ root_path }}/admin/gateways/partial', {include_inactive: (document.getElementById('show-inactive-gateways')?.checked ?? true).toString(){% if selected_team_id %}, team_id: '{{ selected_team_id }}'{% endif %}}))"
                 hx-trigger="load"
                 hx-swap="outerHTML"
                 hx-indicator="#gateways-loading">

            </div>
          </div>

          <!-- Loading Indicator for HTMX -->
          <div id="gateways-loading" class="htmx-indicator">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading gateways...</span>
            </div>
          </div>

          <!-- Pagination Controls -->
          {# ---- compute safe pagination values first ---- #}
          {% set page = page if page is defined else 1 %}
          {% set per_page = per_page if per_page is defined else 50 %}
          {% set total_items = gateways|length if gateways is defined else 0 %}
          {% set total_pages = (total_items + per_page - 1) // per_page if total_items > 0 else 0 %}
          {% set has_prev = page > 1 %}
          {% set has_next = (page * per_page) < total_items %}

          {% set pagination = {
            'page': page,
            'per_page': per_page,
            'total_items': total_items,
            'total_pages': total_pages,
            'has_prev': has_prev,
            'has_next': has_next,
            'page_items': None
          } %}

          {# build the refresh URL for controls #}
          {% set controls_url = root_path + '/admin/gateways/partial'
            + '?render=controls'
            + '&page=' + page|string
            + '&per_page=' + per_page|string
            + '&include_inactive=' + (include_inactive|default(false)|string|lower) %}

          <div id="gateways-pagination-controls"
              hx-get="{{ controls_url }}"
              hx-trigger="refreshControls"
              hx-target="#gateways-pagination-controls"
              hx-swap="outerHTML"
              hx-indicator="#gateways-loading">

            {# helpers used by pagination_controls.html #}
            {% set base_url = root_path + '/admin/gateways/partial' %}
            {% set hx_target = '#gateways-table' %}
            {% set hx_swap = 'outerHTML' %}
            {% set hx_indicator = '#gateways-loading' %}
            {% set table_name = 'gateways' %}
            {% set query_params = {'include_inactive': include_inactive} %}
            {% include 'pagination_controls.html' %}
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800" style="display: none;">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    S. No.
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider w-24"
                  >
                    URL
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Tags
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Status
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Last Seen
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Owner
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Team
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Visibility
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for gateway in gateways %}
                <tr id="gateway-row-{{ gateway.id }}">
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ loop.index }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ gateway.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400"
                  >
                    {{ gateway.url }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm">
                    {% if gateway.tags %} {% for tag in gateway.tags %}
                    <span
                      class="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full mr-1 mb-1"
                      >{% if tag is mapping %}{{ tag.id }}{% else %}{{ tag }}{% endif %}</span
                    >
                    {% endfor %} {% else %}
                    <span class="text-gray-400">No tags</span>
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% set enabled = gateway.enabled %} {% set reachable =
                    gateway.reachable %} {% if enabled and reachable %} {% set
                    bg_class = "bg-green-100 text-green-800" %} {% elif enabled
                    and not reachable %} {% set bg_class = "bg-yellow-100
                    text-yellow-800" %} {% else %} {% set bg_class = "bg-red-100
                    text-red-800" %} {% endif %}

                    <!-- Wrapper for tooltip -->
                    <div class="relative group inline-block">
                      <span
                        class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full {{ bg_class }}"
                      >
                        {% if enabled %} {% if reachable %}
                        <!-- Active icon (green check) -->
                        Active
                        <svg
                          class="ml-1 h-4 w-4 text-green-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-4.586l5.293-5.293-1.414-1.414L9 11.586 7.121 9.707 5.707 11.121 9 14.414z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% else %}
                        <!-- Offline icon (yellow warning) -->
                        Offline
                        <svg
                          class="ml-1 h-4 w-4 text-yellow-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-10h2v4h-2V8zm0 6h2v2h-2v-2z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% endif %} {% else %}
                        <!-- Inactive icon (red error) -->
                        Inactive
                        <svg
                          class="ml-1 h-4 w-4 text-red-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M6.293 6.293a1 1 0 011.414 0L10 8.586l2.293-2.293a1 1 0 111.414 1.414L11.414 10l2.293 2.293a1 1 0 11-1.414 1.414L10 11.414l-2.293 2.293a1 1 0 11-1.414-1.414L8.586 10 6.293 7.707a1 1 0 010-1.414z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% endif %}
                      </span>
                      <div
                        class="absolute left-full top-1/2 -translate-y-1/2 ml-2 hidden group-hover:block bg-gray-800 text-white text-xs rounded py-1 px-2 z-30 whitespace-nowrap shadow"
                      >
                        {% if not enabled %} 💡Gateway is Manually Deactivated
                        {% elif not reachable %} 💡Gateway is Not Reachable {%
                        else %} 💡Everything stable. {% endif %}
                      </div>
                    </div>
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400"
                  >
                    {{ gateway.lastSeen.strftime('%Y-%m-%d %H:%M:%S') if
                    gateway.lastSeen else 'Never' }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400"
                  >
                    {{ gateway.ownerEmail }}
                  </td>
                  <td class="px-2 py-4 whitespace-nowrap">
                    {% if gateway.team %}
                    <span class="text-sm text-gray-900 dark:text-gray-100" style="display: block; white-space: normal; word-spacing: 9999px;">
                      {{ gateway.team }}
                    </span>
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >N/A</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if gateway.visibility == 'private' %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800"
                      >Private</span
                    >
                    {% elif gateway.visibility == 'team' %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800"
                      >Team</span
                    >
                    {% elif gateway.visibility == 'public' %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800"
                      >Public</span
                    >
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >N/A</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-3 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="grid grid-cols-2 gap-x-2 gap-y-1 max-w-48">
                      <!-- Row 1: Test -->
                      <button
                        data-action-click="testGateway" data-arg0="{{ gateway.url|tojson_attr }}"
                        class="col-span-2 flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-purple-600 hover:text-purple-900 hover:bg-purple-50 dark:text-purple-400 dark:hover:bg-purple-900/20 transition-colors"
                        x-tooltip="'💡Test connection to this MCP Server'"
                      >
                        Test
                      </button>

                      {% if gateway.authType == 'oauth' %}
                      <!-- Row 2: OAuth Authorize | Fetch Tools -->
                      <a
                        href="{{ root_path }}/oauth/authorize/{{ gateway.id }}"
                        class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-indigo-600 hover:text-indigo-900 hover:bg-indigo-50 dark:text-indigo-400 dark:hover:bg-indigo-900/20 transition-colors"
                        x-tooltip="'🔐 Authorize Users for OAuth'"
                      >
                        🔐 Authorize
                      </a>
                      <button
                        data-action-click="fetchToolsForGateway" data-arg0="{{ gateway.id|tojson_attr }}" data-arg1="{{ gateway.name|tojson_attr }}"
                        class="flex items-center justify-center px-1 py-1 text-xs font-medium rounded-md text-green-600 hover:text-green-900 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/20 transition-colors"
                        x-tooltip="'🔧 Fetch Tools from MCP Server'"
                        id="fetch-tools-{{ gateway.id }}"
                      >
                        🔧 Fetch Tools
                      </button>

                      <!-- Row 3: View | Edit -->
                      <button
                        data-action-click="viewGateway" data-arg0="{{ gateway.id|tojson_attr }}"
                        class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-indigo-600 hover:text-indigo-900 hover:bg-indigo-50 dark:text-indigo-400 dark:hover:bg-indigo-900/20 transition-colors"
                        x-tooltip="'💡View gateway details and configuration'"
                      >
                        View
                      </button>
                      <button
                        data-action-click="editGateway" data-arg0="{{ gateway.id|tojson_attr }}"
                        class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-green-600 hover:text-green-900 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/20 transition-colors"
                        x-tooltip="'💡Edit gateway settings and configuration'"
                      >
                        Edit
                      </button>
                      {% else %}
                      <!-- Row 2: View | Edit (for non-OAuth) -->
                      <button
                        data-action-click="viewGateway" data-arg0="{{ gateway.id|tojson_attr }}"
                        class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-indigo-600 hover:text-indigo-900 hover:bg-indigo-50 dark:text-indigo-400 dark:hover:bg-indigo-900/20 transition-colors"
                        x-tooltip="'💡View gateway details and configuration'"
                      >
                        View
                      </button>
                      <button
                        data-action-click="editGateway" data-arg0="{{ gateway.id|tojson_attr }}"
                        class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-green-600 hover:text-green-900 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/20 transition-colors"
                        x-tooltip="'💡Edit gateway settings and configuration'"
                      >
                        Edit
                      </button>
                      {% endif %}

                      <!-- Row 4: Deactivate/Activate | Delete -->
                      <div class="col-span-2 flex flex-col space-y-1">
                        {% if gateway.enabled %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/gateways/{{ gateway.id }}/state"
                          class="contents"
                          data-action-submit="handleToggleSubmit" data-arg0="gateways"
                        >
                          <input type="hidden" name="activate" value="false" />
                          <button
                            type="submit"
                            x-tooltip="'💡Temporarily disable this item (can be re-activated)'"
                            class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-yellow-600 hover:text-yellow-900 hover:bg-yellow-50 dark:text-yellow-400 dark:hover:bg-yellow-900/20 transition-colors"
                          >
                            Deactivate
                          </button>
                        </form>
                        {% else %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/gateways/{{ gateway.id }}/state"
                          class="contents"
                          data-action-submit="handleToggleSubmit" data-arg0="gateways"
                        >
                          <input type="hidden" name="activate" value="true" />
                          <button
                            type="submit"
                            x-tooltip="'💡Re-enable an inactive item'"
                            class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-blue-600 hover:text-blue-900 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20 transition-colors"
                          >
                            Activate
                          </button>
                        </form>
                        {% endif %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/gateways/{{ gateway.id }}/delete"
                          class="contents"
                          data-action-submit="handleSubmitWithConfirmation" data-arg0="gateways"
                        >
                          <button
                            type="submit"
                            x-tooltip="'💡Permanently delete this item – cannot be undone'"
                            class="flex items-center justify-center px-2 py-1 text-xs font-medium rounded-md text-red-600 hover:text-red-900 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 transition-colors"
                          >
                            Delete
                          </button>
                        </form>
                      </div>
                    </div>

                    <!-- Debug: Show gateway data for troubleshooting -->
                    <!-- Gateway ID: {{ gateway.id }} -->
                    <!-- Auth Type: {{ gateway.auth_type }} -->
                    <!-- OAuth Config: {{ gateway.oauth_config }} -->
                    <!-- Grant Type: {{ gateway.oauth_config.grant_type if gateway.oauth_config else 'None' }} -->
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>

        {% if user_permissions.can_create_gateway %}
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800 mt-8">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New MCP Server or Gateway
          </h3>
          <form method="POST" id="add-gateway-form">
            <div class="grid grid-cols-1 gap-7">
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  for="mcp-server-name"
                  >MCP Server Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  id="mcp-server-name"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">MCP Server Name is required.</p>
              </div>
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  for="mcp-server-url"
                  >MCP Server URL</label
                >
                <input
                  type="url"
                  name="url"
                  required
                  id="mcp-server-url"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="url" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">MCP Server URL is required.</p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Tags</label
                >
                <input
                  type="text"
                  name="tags"
                  placeholder="e.g., production,external,api-gateway (comma-separated)"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p class="mt-1 text-sm text-gray-500">
                  Separate multiple tags with commas. Tags will be automatically
                  normalized (lowercase, spaces→hyphens).
                </p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >
                  Visibility
                </label>
                <div class="mt-1 flex space-x-6">

                  <div class="flex items-center">
                    <input
                      type="radio"
                      name="visibility"
                      value="public"
                      class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                      id="gateway-visibility-public"
                      checked
                    />
                    <label
                      for="gateway-visibility-public"
                      class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                      >🌍Public</label
                    >
                  </div>

                  <div class="flex items-center">
                    <input
                      type="radio"
                      name="visibility"
                      value="team"
                      id="gateway-visibility-team"
                      class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <label
                      for="gateway-visibility-team"
                      class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                      >👥Team</label
                    >
                  </div>
                  <div class="flex items-center">
                    <input
                      type="radio"
                      name="visibility"
                      value="private"
                      id="gateway-visibility-private"
                      class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <label
                      for="gateway-visibility-private"
                      class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                      >🔒Private</label
                    >
                  </div>
                </div>
              </div>

              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Transport Type</label
                >
                <select
                  name="transport"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <option value="SSE" selected>SSE</option>
                  <option value="STREAMABLEHTTP">Streamable HTTP</option>
                </select>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Authentication Type</label
                >
                <select
                  name="auth_type"
                  id="auth-type-gw"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <option value="">None</option>
                  <option value="basic">Basic</option>
                  <option value="bearer">Bearer Token</option>
                  <option value="authheaders">Custom Headers</option>
                  <option value="oauth">OAuth 2.0</option>
                  <option value="query_param">Query Parameter (INSECURE)</option>
                </select>
              </div>
              <div id="auth-query_param-fields-gw" style="display: none">
                <div class="p-3 mb-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-700 rounded-md">
                  <p class="text-xs text-amber-700 dark:text-amber-400">
                    <strong>Security Warning:</strong> API keys in URLs may appear in proxy logs, browser history, and server access logs.
                    Only use when the upstream server requires this authentication method.
                  </p>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Query Parameter Name</label
                  >
                  <input
                    type="text"
                    name="auth_query_param_key"
                    placeholder="e.g., tavilyApiKey"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
                <div class="mt-2">
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >API Key Value</label
                  >
                  <div class="relative">
                    <input
                      type="password"
                      name="auth_query_param_value"
                      id="auth-query-param-value-gw"
                      autocomplete="off"
                      data-sensitive-label="API key"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                  </div>
                </div>
              </div>
              <div id="auth-basic-fields-gw" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Username</label
                  >
                  <input
                    type="text"
                    name="auth_username"
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Password</label
                  >
                  <div class="relative">
                    <input
                      type="password"
                      name="auth_password"
                      id="auth-password-gw"
                      autocomplete="off"
                      data-sensitive-label="password"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                  </div>
                </div>
              </div>
              <div id="auth-bearer-fields-gw" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Token</label
                  >
                  <div class="relative">
                    <input
                      type="password"
                      name="auth_token"
                      id="auth-token-gw"
                      autocomplete="off"
                      data-sensitive-label="token"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                  </div>
                </div>
              </div>
              <div id="auth-headers-fields-gw" style="display: none">
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Custom Headers
                    </label>
                    <button
                      type="button"
                      data-action-click="addAuthHeader" data-arg0="auth-headers-container-gw"
                      class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      <svg
                        class="w-4 h-4 mr-1"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                        ></path>
                      </svg>
                      Add Header
                    </button>
                  </div>
                  <div id="auth-headers-container-gw" class="space-y-2">
                    <!-- Headers will be added dynamically here -->
                  </div>
                  <input
                    type="hidden"
                    name="auth_headers"
                    id="auth-headers-json-gw"
                  />
                </div>
              </div>

              <!-- OAuth Configuration Fields -->
              <div id="auth-oauth-fields-gw" style="display: none">
                <div class="space-y-4">
                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Grant Type
                    </label>
                    <select
                      name="oauth_grant_type"
                      id="oauth-grant-type-gw"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    >
                      <option value="authorization_code" selected>
                        Authorization Code (User Delegation)
                      </option>
                      <option value="client_credentials">
                        Client Credentials (Machine-to-Machine)
                      </option>
                      <option value="password">
                        Resource Owner Password Credentials (Keycloak/Legacy)
                      </option>
                    </select>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Issuer URL
                    </label>
                    <div class="mt-1 flex gap-2">
                      <input
                        type="url"
                        name="oauth_issuer"
                        class="px-1.5 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="http://localhost:3003 or https://oauth.example.com"
                      />
                      <button
                        type="button"
                        data-action-click="discoverOAuthEndpoints" data-arg0="this"
                        class="shrink-0 px-3 py-1.5 text-sm font-medium rounded-md border border-indigo-500 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900 transition-colors"
                        title="Auto-discover token &amp; authorization endpoints from issuer metadata"
                      >🔍 Discover</button>
                    </div>
                    <p class="mt-1 text-sm text-gray-500">
                      The OAuth Authorization Server issuer URL. Required for DCR (Dynamic Client Registration).
                    </p>
                  <div class="oauth-discover-status mt-1 hidden"></div>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Client ID <span class="text-gray-500">(optional for DCR)</span>
                    </label>
                    <input
                      type="text"
                      name="oauth_client_id"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Leave empty for auto-registration via DCR"
                    />
                    <p class="mt-1 text-sm text-blue-600">
                      💡 Leave empty if the server supports DCR - credentials will be auto-registered
                    </p>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Client Secret <span class="text-gray-500">(optional for DCR)</span>
                    </label>
                    <input
                      type="password"
                      name="oauth_client_secret"
                      autocomplete="off"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Leave empty for auto-registration via DCR"
                    />
                    <p class="mt-1 text-sm text-blue-600">
                      💡 Leave empty if the server supports DCR - credentials will be auto-registered
                    </p>
                  </div>

                  <div id="oauth-username-field-gw" style="display: none;">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Username <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                    </label>
                    <input
                      type="text"
                      name="oauth_username"
                      id="oauth-username-gw"
                      autocomplete="off"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="systemadmin@system.com"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      Required for Resource Owner Password Credentials grant type (Keycloak).
                    </p>
                  </div>

                  <div id="oauth-password-field-gw" style="display: none;">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Password <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                    </label>
                    <input
                      type="password"
                      name="oauth_password"
                      id="oauth-password-gw"
                      autocomplete="off"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Enter password"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      Required for Resource Owner Password Credentials grant type (Keycloak).
                    </p>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Token URL
                    </label>
                    <input
                      type="url"
                      name="oauth_token_url"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="https://oauth.example.com/token"
                    />
                  </div>

                  <div id="oauth-auth-code-fields-gw">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Authorization URL
                      </label>
                      <input
                        type="url"
                        name="oauth_authorization_url"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="https://oauth.example.com/authorize"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        The OAuth provider's authorization endpoint URL
                      </p>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Redirect URI
                      </label>
                      <input
                        type="url"
                        name="oauth_redirect_uri"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="https://gateway.example.com/oauth/callback"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        This must match the redirect URI configured in your
                        OAuth application
                      </p>
                      <p class="mt-1 text-sm text-blue-600 font-medium">
                        💡 Use:
                        <code class="bg-blue-100 px-1 rounded"
                          >{{ request.base_url }}oauth/callback</code
                        >
                      </p>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Token Management
                      </label>
                      <div class="mt-2 space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            name="oauth_store_tokens"
                            checked
                            class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                          />
                          <span
                            class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                          >
                            Store access tokens for reuse
                          </span>
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            name="oauth_auto_refresh"
                            checked
                            class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                          />
                          <span
                            class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                          >
                            Automatically refresh expired tokens
                          </span>
                        </label>
                      </div>
                      <p class="mt-1 text-sm text-gray-500">
                        Token management options for Authorization Code flow
                      </p>
                    </div>

                    <div
                      class="bg-blue-50 border border-blue-200 rounded-md p-4 dark:bg-blue-900/20 dark:border-blue-800"
                    >
                      <div class="flex">
                        <div class="flex-shrink-0">
                          <svg
                            class="h-5 w-5 text-blue-400"
                            viewBox="0 0 20 20"
                            fill="currentColor"
                          >
                            <path
                              fill-rule="evenodd"
                              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                              clip-rule="evenodd"
                            />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <h3
                            class="text-sm font-medium text-blue-800 dark:text-blue-200"
                          >
                            Authorization Code Flow Setup
                          </h3>
                          <div
                            class="mt-2 text-sm text-blue-700 dark:text-blue-300"
                          >
                            <p>After creating this gateway, you'll need to:</p>
                            <ol class="list-decimal list-inside mt-1 space-y-1">
                              <li>
                                Click the "🔐 Authorize" button in the gateway
                                list
                              </li>
                              <li>
                                Complete the OAuth consent flow with your
                                provider
                              </li>
                              <li>
                                Return to the admin panel to see authorization
                                status
                              </li>
                            </ol>
                            <p class="mt-2 font-medium">
                              Note: The gateway will be created but tools won't
                              work until OAuth authorization is completed.
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Scopes
                    </label>
                    <input
                      type="text"
                      name="oauth_scopes"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="repo read:user (space-separated)"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      Space-separated list of OAuth scopes (e.g., "repo
                      read:user")
                    </p>
                  </div>
                </div>
              </div>

              <div class="mt-4">
                <label class="flex items-center">
                  <input
                    type="checkbox"
                    name="one_time_auth"
                    id="single-use-auth-gw"
                    class="form-checkbox h-5 w-5 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 dark:bg-gray-800 dark:border-gray-600"
                    x-tooltip="'💡This will not store the server credentials, Some features may not work.'"
                    data-action-change="toggleOneTimeAuthHint" data-arg0="single-use-auth-hint-gw"
                  />
                  <span
                    class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Use one-time authentication
                  </span>
                </label>
                <p
                  id="single-use-auth-hint-gw"
                  style="display: none"
                  class="mt-2 text-sm text-gray-700 dark:text-gray-300 bg-indigo-50 dark:bg-indigo-900/30 border border-indigo-200 dark:border-indigo-700 rounded-md p-2"
                >
                  ⚠️ NOTE: Authentication won't be stored in the gateway. Configure Passthrough headers for reuse. Health checks will be disabled.
                </p>
              </div>

              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Passthrough Headers</label
                >
                <small class="text-gray-500 dark:text-gray-400 block mb-2">
                  List of headers to pass through from client requests
                  (comma-separated, e.g., "Authorization, X-Tenant-Id,
                  X-Trace-Id"). Leave empty to use global defaults.
                </small>
                <input
                  type="text"
                  name="passthrough_headers"
                  placeholder="Authorization, X-Tenant-Id, X-Trace-Id"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div id="add-gateway-loading" style="display: none">
                <div class="spinner"></div>
              </div>
              <div id="status-gateways"></div>
            </div>
            <div class="mb-4">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >
                Upload CA certificate
              </label>
              <input
                type="file"
                id="upload-ca-certificate"
                name="ca_certificates[]"
                class="hidden"
                data-action-change="validateCACertFiles"
                accept=".pem,.crt,.cer,.cert,application/x-x509-ca-certificate"
                multiple
              />
              <div
                id="ca-certificate-upload-drop-zone"
                class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:border-gray-400 dark:hover:border-gray-500 cursor-pointer"
              >
                <div class="space-y-2">
                  <svg
                    class="mx-auto h-12 w-12 text-gray-400"
                    stroke="currentColor"
                    fill="none"
                    viewBox="0 0 48 48"
                  >
                    <path
                      d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3-3m-3 3l3 3m-3-3V8"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </svg>
                  <div class="text-sm text-gray-600 dark:text-gray-300">
                    <span
                      class="font-medium text-blue-600 dark:text-blue-400"
                      >Click to upload</span
                    >
                    or drag and drop
                  </div>
                  <p class="text-xs text-gray-500 dark:text-gray-400">
                    Public certificate files only (.pem, .crt, .cer, .cert)
                  </p>
                </div>
              </div>
              <div id="ca-certificate-feedback" class="mt-2 text-sm"></div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Registers an external MCP server and imports its catalogs - Tools, Prompts, Resources, etc.'"
                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Gateway
              </button>
            </div>
          </form>
        </div>
        {% endif %}
      </div>

      {% endif %}
      <!-- Teams Panel -->
      {% if email_auth_enabled and 'teams' not in hidden_sections %}
      <div id="teams-panel" class="tab-panel hidden">
          <!-- Header with Create Team Button -->
          <div class="flex justify-between items-center mb-8">
            <div>
              <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-200">
                👥 My Teams
              </h2>
              <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                Teams you own, are a member of, and can join
              </p>
            </div>
            {% if user_permissions.can_create_team %}
            <button
              id="create-team-btn"
              data-action-click="openCreateTeamModal"
              class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              <svg
                class="-ml-1 mr-2 h-5 w-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                />
              </svg>
              Create New Team
            </button>
            {% endif %}
          </div>

          <!-- Search/Filter Bar -->
          <div class="mb-6">
            <div class="flex flex-col sm:flex-row gap-4">
              <div class="flex-1">
                <input
                  type="text"
                  id="team-search"
                  placeholder="Find teams..."
                  class="block w-full px-3 py-2 border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  data-action-input="serverSideTeamSearch"
                />
              </div>
              <div class="flex gap-2">
                <button
                  data-action-click="filterByRelationship" data-arg0="all"
                  class="filter-btn active px-3 py-2 text-sm font-medium rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"
                  data-filter="all"
                >
                  All Teams
                </button>
                <button
                  data-action-click="filterByRelationship" data-arg0="owner"
                  class="filter-btn px-3 py-2 text-sm font-medium rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"
                  data-filter="owner"
                >
                  I Own
                </button>
                <button
                  data-action-click="filterByRelationship" data-arg0="member"
                  class="filter-btn px-3 py-2 text-sm font-medium rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"
                  data-filter="member"
                >
                  I'm a Member
                </button>
                <button
                  data-action-click="filterByRelationship" data-arg0="public"
                  class="filter-btn px-3 py-2 text-sm font-medium rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"
                  data-filter="public"
                >
                  Can Join
                </button>
              </div>
            </div>
          </div>

          <!-- Loading indicator -->
          <div id="teams-loading" class="htmx-indicator">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading teams...</span>
            </div>
          </div>

          <!-- Teams List - loaded via initializeTeamManagement() when tab is shown -->
          <div id="unified-teams-list" class="space-y-4">
            <div class="flex items-center justify-center p-4">
              <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-2 text-gray-600 dark:text-gray-400">Loading teams...</span>
            </div>
          </div>

          <!-- Pagination controls placeholder (will be swapped OOB) -->
          <div id="teams-pagination-controls" class="mt-4"></div>
      </div>
      {% endif %}

      <!-- User Management Panel -->
      {% if email_auth_enabled and 'users' not in hidden_sections %}
      <div id="users-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">User Management</h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Manage user accounts and permissions
          </p>
        </div>

        <!-- Create User Form -->
         {% if user_permissions.can_create_user %}
        <div class="bg-white shadow rounded-lg mb-6 dark:bg-gray-800">
          <div class="px-4 py-5 sm:p-6">
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              Create New User
            </h3>
            <!-- User Creation Messages -->
            <div id="user-creation-messages" class="mb-4"></div>

            <form
              id="create-user-form"
              hx-post="{{ root_path }}/admin/users"
              hx-target="#user-creation-messages"
              hx-swap="innerHTML"
              class="space-y-4"
            >
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Email Address *
                  </label>
                  <input
                    type="email"
                    name="email"
                    required
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full border-gray-300 rounded-md shadow-sm bg-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-300"
                    placeholder="user@example.com"
                  />
                </div>
                <div class="relative">
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Full Name *
                  </label>
                  <input
                    type="text"
                    name="full_name"
                    required
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full border-gray-300 rounded-md shadow-sm bg-gray-200 dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                    placeholder="John Smith"
                  />
                </div>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Password *
                  </label>
                  <input
                    type="password"
                    id="new_user_password"
                    name="password"
                    required
                    minlength="8"
                    autocomplete="new-password"
                    data-action-input="validateNewUserPassword"
                    class="mt-1 px-3 py-2 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600 dark:text-gray-300"
                    placeholder="Strong password"
                  />
                  <!-- Password policy guidance (visible below password field) -->
                  <div class="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-md dark:bg-blue-900 dark:border-blue-800">
                    <div class="flex">
                      <div class="flex-shrink-0">
                        <svg class="h-5 w-5 text-blue-600 dark:text-blue-300" fill="currentColor" viewBox="0 0 20 20" aria-hidden="true"><path d="M18 10A8 8 0 11 2 10a8 8 0 0116 0zm-9-1h2v5H9V9zm0-3h2v2H9V6z"/></svg>
                      </div>
                      <div class="ml-3 text-sm text-blue-800 dark:text-blue-100">
                        <div class="font-semibold">Password Requirements</div>
                        <ul class="mt-2 space-y-1">
                          <li id="req-length" class="flex items-start">
                            <i class="fas fa-circle text-gray-400 mr-2"></i>
                            At least {{ password_min_length or 8 }} characters long
                          </li>
                          {% if password_require_uppercase %}
                          <li id="req-uppercase" class="flex items-start">
                            <i class="fas fa-circle text-gray-400 mr-2"></i>
                            Contains uppercase letters (A-Z)
                          </li>
                          {% endif %}
                          {% if password_require_lowercase %}
                          <li id="req-lowercase" class="flex items-start">
                            <i class="fas fa-circle text-gray-400 mr-2"></i>
                            Contains lowercase letters (a-z)
                          </li>
                          {% endif %}
                          {% if password_require_numbers %}
                          <li id="req-numbers" class="flex items-start">
                            <i class="fas fa-circle text-gray-400 mr-2"></i>
                            Contains numbers (0-9)
                          </li>
                          {% endif %}
                          {% if password_require_special %}
                          <li id="req-special" class="flex items-start">
                            <i class="fas fa-circle text-gray-400 mr-2"></i>
                            Contains special characters (e.g. !@#$%^&amp;*()_+[]{}:;"'&lt;&gt;?,.-)
                          </li>
                          {% endif %}
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
                <script nonce="{{ csp_nonce(request) }}">
                  // Validate the Create User password box and update requirement icons
                  (function(){
                    const minLen = {{ password_min_length | tojson }} || 8;
                    const REQ_UPPER = {{ password_require_uppercase | tojson }};
                    const REQ_LOWER = {{ password_require_lowercase | tojson }};
                    const REQ_NUMS = {{ password_require_numbers | tojson }};
                    const REQ_SPEC = {{ password_require_special | tojson }};

                    // Helper to update icons if element exists
                    function updateRequirement(id, met) {
                      const element = document.getElementById(id);
                      if (!element) return;
                      const icon = element.querySelector('i');
                      if (!icon) return;
                      if (met) {
                        icon.className = 'fas fa-check-circle text-green-500 mr-2';
                        element.classList.remove('text-blue-600');
                        element.classList.add('text-green-600');
                      } else {
                        icon.className = 'fas fa-circle text-gray-400 mr-2';
                        element.classList.remove('text-green-600');
                        element.classList.add('text-blue-600');
                      }
                    }
                    window.validateNewUserPassword = function() {
                      const password = document.getElementById('new_user_password')?.value || '';
                      // length
                      const lengthMet = password.length >= minLen;
                      const uppercaseMet = /[A-Z]/.test(password);
                      const lowercaseMet = /[a-z]/.test(password);
                      const numbersMet = /[0-9]/.test(password);
                      const specialMet = /[!@#$%^&*()_+\-\[\]{};':"\\|,.<>\/?]/.test(password);

                      // Update indicators only if elements exist (they may be conditionally rendered)
                      updateRequirement('req-length', lengthMet);
                      if (REQ_UPPER) updateRequirement('req-uppercase', uppercaseMet);
                      if (REQ_LOWER) updateRequirement('req-lowercase', lowercaseMet);
                      if (REQ_NUMS) updateRequirement('req-numbers', numbersMet);
                      if (REQ_SPEC) updateRequirement('req-special', specialMet);

                      // Determine whether submission is allowed
                      const allRequirementsMet = lengthMet && (!REQ_UPPER || uppercaseMet) && (!REQ_LOWER || lowercaseMet) && (!REQ_NUMS || numbersMet) && (!REQ_SPEC || specialMet);
                      const submitBtn = document.getElementById('create_user_submit');
                      if (submitBtn) {
                        submitBtn.disabled = !allRequirementsMet;
                        if (submitBtn.disabled) {
                          submitBtn.classList.add('opacity-60', 'cursor-not-allowed');
                        } else {
                          submitBtn.classList.remove('opacity-60', 'cursor-not-allowed');
                        }
                      }
                    };

                    document.addEventListener('DOMContentLoaded', function(){
                      // initialize state
                      window.validateNewUserPassword();
                    });
                  })();
                </script>
                <div class="flex items-center">
                  <input
                    type="checkbox"
                    name="is_admin"
                    id="is_admin"
                    class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                  />
                  <label
                    for="is_admin"
                    class="ml-2 block text-sm text-gray-900 dark:text-gray-300"
                  >
                    Administrator privileges
                  </label>
                </div>
              </div>
              <div class="flex justify-end">
                <button
                  type="submit"
                  id="create_user_submit"
                  class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  Create User
                </button>
              </div>
            </form>
          </div>
        </div>
        {% endif %}

        <!-- Users List -->
        <div class="bg-white shadow rounded-lg dark:bg-gray-800">
          <div class="px-4 py-5 sm:p-6">
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              System Users
            </h3>

            <!-- Loading indicator -->
            <div id="users-loading" class="htmx-indicator">
              <div class="flex items-center justify-center p-4">
                <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-2 text-gray-600 dark:text-gray-400">Loading users...</span>
              </div>
            </div>

            <!-- Users list container -->
            <div
              id="users-list-container"
              hx-get="{{ root_path }}/admin/users/partial?page=1&per_page=50"
              hx-trigger="load, refreshUsers"
              hx-swap="outerHTML"
              hx-indicator="#users-loading"
            >
              <!-- Content will be loaded via HTMX -->
            </div>

            <!-- Pagination controls container -->
            <div id="users-pagination-controls"></div>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- API Tokens Panel -->
      {% if email_auth_enabled and 'tokens' not in hidden_sections %}
      <div id="tokens-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            API Token Management
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Create and manage personal API tokens with scoped access controls
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-tokens"
              class="mr-2 show-inactive-toggle"
              name="include_inactive"
              x-init="syncCheckboxFromUrl('tokens', 'show-inactive-tokens')"
              @change="updateInactiveUrlState('tokens', $el.checked)"
              hx-get="{{ root_path }}/admin/tokens/partial?page=1{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
              hx-vals="js:{include_inactive: document.getElementById('show-inactive-tokens').checked, per_page: document.querySelector('#tokens-pagination-controls select')?.value || 50}"
              hx-target="#tokens-table"
              hx-swap="innerHTML"
              hx-indicator="#tokens-loading"
              hx-trigger="change"
            />
            <label
              for="show-inactive-tokens"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Create Token Form -->
         {% if user_permissions.can_create_token %}
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
            Create New API Token
          </h3>
          <form id="create-token-form" class="space-y-7">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  for="api-token-name"
                >
                  Token Name *
                </label>
                <input
                  type="text"
                  name="name"
                  required
                  id="api-token-name"
                  maxlength="255"
                  class="mt-1 px-3 py-2 block w-full border border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                  placeholder="Production API Access"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Token Name is required.</p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >
                  Expires In (Days)
                  {% if require_token_expiration %}
                  <span class="text-red-500">*</span>
                  {% endif %}
                </label>
                <input
                  type="number"
                  name="expires_in_days"
                  min="1"
                  max="365"
                  value="30"
                  {% if require_token_expiration %}required{% endif %}
                  {% if require_token_expiration %}
                  data-action-input="clearCustomValidity"
                  {% endif %}
                  class="mt-1 px-3 py-2 block w-full border border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                  placeholder="30"
                />
                {% if require_token_expiration %}
                <p class="mt-1 text-xs text-red-600 dark:text-red-400 font-medium">
                  Token expiration is required by server policy (REQUIRE_TOKEN_EXPIRATION=true).
                </p>
                {% else %}
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Leave empty for tokens that never expire
                </p>
                {% endif %}
              </div>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >
                Description
              </label>
              <textarea
                name="description"
                rows="2"
                class="mt-1 px-3 py-2 block w-full border border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                placeholder="Brief description of token usage"
              ></textarea>
            </div>

            <!-- Team Scoping Info/Warning -->
            <div id="team-scoping-warning" class="hidden">
                <div class="bg-yellow-50 dark:bg-yellow-900 border border-yellow-300 dark:border-yellow-700 rounded-md p-4">
                    <div class="flex">
                        <div class="flex-shrink-0">
                        </div>
                        <div class="ml-3 flex-1">
                            <!-- Token Scope Section -->
                            <div class="space-y-2">
                                <div class="flex items-center">
                                    <h3 class="text-sm font-bold text-yellow-800 dark:text-yellow-200">
                                        ⚠️ <span class="font-semibold">Token Scope</span>
                                    </h3>
                                </div>
                                <div class="mt-1 text-sm text-yellow-700 dark:text-yellow-300">
                                    <p class="mb-1">
                                        Tokens created without selecting a team are <span class="font-semibold">not scoped to any team</span>.
                                        Admin users retain full access; non-admin users can only see <span class="font-semibold">public resources</span>.
                                    </p>
                                    <p class="mb-1"><span class="font-semibold">✅ This token CAN access:</span></p>
                                    <ul class="list-disc list-inside ml-4 space-y-1">
                                        <li>Public servers (virtual servers marked as public)</li>
                                        <li>Public tools, resources, and prompts</li>
                                        <li>All resources (admin users only)</li>
                                    </ul>
                                    <p class="mt-2 mb-1"><span class="font-semibold">❌ Non-admin tokens CANNOT access:</span></p>
                                    <ul class="list-disc list-inside ml-4 space-y-1">
                                        <li>Your own private or team-scoped resources</li>
                                        <li>Team-scoped servers, tools, resources, and prompts</li>
                                    </ul>
                                </div>
                            </div>

                            <!-- Tip Section  -->
                            <div class="mt-4 bg-yellow-50 dark:bg-yellow-900 p-2 rounded-md border border-yellow-200 dark:border-yellow-600 flex items-center">
                                <span class="text-yellow-600 dark:text-yellow-400 text-lg">💡</span>
                                <p class="ml-2 text-sm font-semibold text-yellow-700 dark:text-yellow-300">
                                    For team-level access, select a specific team from the header above before creating a token.
                                </p>
                            </div>
                            <p class="mt-2 text-xs text-yellow-700 dark:text-yellow-300 ml-8">
                                The header team selector is global. It filters tools, servers, prompts, and other tabs to that team context.
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Info when a specific team is selected -->
            <div id="team-scoping-info" class="hidden">
                <div class="bg-blue-50 dark:bg-blue-900 border border-blue-300 dark:border-blue-700 rounded-md p-3">
                    <div class="flex items-center">
                        <svg class="h-5 w-5 text-blue-600 dark:text-blue-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"/>
                        </svg>
                        <p class="text-sm font-medium text-blue-800 dark:text-blue-200">
                            <span class="font-semibold">Team-level scoping enabled.</span> This token will be scoped to: <span id="selected-team-name" class="font-bold"></span>
                        </p>
                    </div>
                    <p class="text-xs text-blue-700 dark:text-blue-300 mt-2 ml-7">
                        Token can access all resources (public, team, and private) within this team.
                    </p>
                </div>
            </div>


            <!-- Token Scoping -->
            <div class="border-t pt-4">
              <h4
                class="text-md font-medium text-gray-900 dark:text-white mb-3"
              >
                Token Scoping (Optional)
              </h4>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Server ID (Limit to specific server)
                  </label>
                  <input
                    type="text"
                    name="server_id"
                    class="mt-1 px-3 py-2 block w-full border border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                    placeholder="server-abc-123"
                  />
                </div>
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    IP Restrictions (CIDR format)
                  </label>
                  <input
                    type="text"
                    name="ip_restrictions"
                    class="mt-1 px-3 py-2 block w-full border border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                    placeholder="192.168.1.0/24"
                  />
                </div>
              </div>
              <div class="mt-4">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >
                  Permissions (comma-separated)
                </label>
                <input
                  type="text"
                  name="permissions"
                  class="mt-1 px-3 py-2 block w-full border border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-700 dark:text-gray-300"
                  placeholder="tools.read, resources.read, tools.execute"
                />
              </div>
            </div>

            <div class="flex justify-end">
              <button
                type="submit"
                class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                Create Token
              </button>
            </div>
            <!-- Inline error/status display for token creation; populated by createToken() on failure -->
            <div id="token-creation-messages" class="mt-3" role="alert" aria-live="polite"></div>
          </form>
        </div>
        {% endif %}

        <!-- Tokens List -->
        <div class="bg-white shadow rounded-lg dark:bg-gray-800">
          <div class="px-4 py-5 sm:p-6">
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              Your API Tokens
            </h3>

            <!-- Search Bar -->
            <div class="flex items-center space-x-2 mb-4">
              <div class="relative">
                <input
                  type="text"
                  id="tokens-search-input"
                  placeholder="Search tokens by name..."
                  class="w-80 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-300 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <button
                id="tokens-clear-search"
                data-action-click="clearSearch" data-arg0="tokens"
                class="px-2 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors">
                Clear
              </button>
            </div>

            <!-- Tokens table loaded via HTMX -->
            <div id="tokens-table"
                 x-init="$el.setAttribute('hx-get', buildTableUrl('tokens', '{{ root_path }}/admin/tokens/partial', {include_inactive: (document.getElementById('show-inactive-tokens')?.checked ?? false).toString(){% if selected_team_id %}, team_id: '{{ selected_team_id }}'{% endif %}}))"
                 hx-trigger="load, refreshTokens"
                 hx-swap="innerHTML"
                 hx-indicator="#tokens-loading">
              <!-- Loading placeholder -->
              <div class="flex items-center justify-center p-4">
                <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-2 text-gray-600 dark:text-gray-400">Loading tokens...</span>
              </div>
            </div>

            <!-- Loading Indicator for HTMX -->
            <div id="tokens-loading" class="htmx-indicator">
              <div class="flex items-center justify-center p-4">
                <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-2 text-gray-600 dark:text-gray-400">Loading tokens...</span>
              </div>
            </div>

            <!-- Pagination Controls -->
            {# ---- compute safe pagination values ---- #}
            {% set page = page if page is defined else 1 %}
            {% set per_page = per_page if per_page is defined else 50 %}
            {% set total_items = 0 %}
            {% set total_pages = 0 %}
            {% set has_prev = page > 1 %}
            {% set has_next = false %}

            {% set pagination = {
              'page': page,
              'per_page': per_page,
              'total_items': total_items,
              'total_pages': total_pages,
              'has_prev': has_prev,
              'has_next': has_next,
              'page_items': None
            } %}

            {# build the refresh URL for controls #}
            {% set controls_url = root_path + '/admin/tokens/partial'
              + '?render=controls'
              + '&page=' + page|string
              + '&per_page=' + per_page|string
              + '&include_inactive=' + (include_inactive|default(false)|string|lower)
              + ('&team_id=' + selected_team_id if selected_team_id else '')
              + ('&q=' + q if q else '') %}

            <div id="tokens-pagination-controls"
                hx-get="{{ controls_url }}"
                hx-trigger="refreshControls"
                hx-target="#tokens-pagination-controls"
                hx-swap="outerHTML"
                hx-indicator="#tokens-loading">

              {# helpers used by pagination_controls.html #}
              {% set base_url = root_path + '/admin/tokens/partial' %}
              {% set hx_target = '#tokens-table' %}
              {% set hx_swap = 'outerHTML' %}
              {% set hx_indicator = '#tokens-loading' %}
              {% set table_name = 'tokens' %}
              {% set query_params = {'include_inactive': include_inactive} %}
              {% if selected_team_id %}{% set _ = query_params.update({'team_id': selected_team_id}) %}{% endif %}
              {% if q %}{% set _ = query_params.update({'q': q}) %}{% endif %}
              {% include 'pagination_controls.html' %}
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- A2A Agents Panel -->
      {% if a2a_enabled and 'agents' not in hidden_sections %}
       <div id="a2a-agents-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            A2A Agents Catalog
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Manage Agent-to-Agent compatible agents that can be integrated as
            tools
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-a2a-agents"
              class="mr-2 show-inactive-toggle"
              name="include_inactive"
              x-init="syncCheckboxFromUrl('agents', 'show-inactive-a2a-agents')"
              @change="updateInactiveUrlState('agents', $el.checked)"
              hx-get="{{ root_path }}/admin/a2a/partial?page=1{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
              hx-vals="js:{include_inactive: document.getElementById('show-inactive-a2a-agents').checked, per_page: document.querySelector('#agents-pagination-controls select')?.value || 50, q: document.getElementById('a2a-agents-search-input')?.value || '', tags: document.getElementById('a2a-agents-tag-filter')?.value || ''}"
              hx-target="#agents-table"
              hx-swap="outerHTML"
              hx-indicator="#agents-loading"
              hx-trigger="change"
            />
            <label
              for="show-inactive-a2a-agents"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Unified Search & Filter Bar for A2A Agents -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <div class="flex flex-col space-y-4">
            <!-- Search Row -->
            <div class="flex items-center space-x-2">
              <div class="relative">
                <input
                  type="text"
                  id="a2a-agents-search-input"
                  placeholder="Search agents..."
                  class="w-80 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-300 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <button
                id="a2a-agents-clear-search"
                data-action-click="clearSearch" data-arg0="a2a-agents"
                class="px-2 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors">
                Clear
              </button>
              <span id="agents-filter-status" class="text-sm text-gray-500 dark:text-gray-400" aria-live="polite" role="status"></span>
            </div>

            <!-- Hidden tag filter for functionality -->
            <input type="hidden" id="a2a-agents-tag-filter" />
          </div>
        </div>

                <!-- A2A Agents List -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="p-0">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4"
            >
              Registered A2A Agents
            </h3>
            <div id="agents-table-wrapper" class="overflow-x-auto">
              <!-- Table will be loaded via HTMX -->
              <div id="agents-table"
                   x-init="$el.setAttribute('hx-get', buildTableUrl('agents', '{{ root_path }}/admin/a2a/partial', {include_inactive: (document.getElementById('show-inactive-a2a-agents')?.checked ?? false).toString(){% if selected_team_id %}, team_id: '{{ selected_team_id }}'{% endif %}}))"
                   hx-trigger="load"
                   hx-swap="outerHTML"
                   hx-indicator="#agents-loading">
                <!-- Loading placeholder -->
                <div class="flex items-center justify-center p-8">
                  <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  <span class="ml-3 text-gray-600 dark:text-gray-400">Loading agents...</span>
                </div>
              </div>
            </div>

            <!-- Loading Indicator for HTMX -->
            <div id="agents-loading" class="htmx-indicator">
              <div class="flex items-center justify-center p-4">
                <svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="ml-2 text-gray-600 dark:text-gray-400">Loading agents...</span>
              </div>
            </div>

            <!-- Pagination Controls -->
            {# ---- compute safe pagination values first ---- #}
            {% set page = page if page is defined else 1 %}
            {% set per_page = per_page if per_page is defined else 50 %}
            {% set total_items = a2a_agents|length if a2a_agents is defined else 0 %}
            {% set total_pages = (total_items + per_page - 1) // per_page if total_items > 0 else 0 %}
            {% set has_prev = page > 1 %}
            {% set has_next = (page * per_page) < total_items %}

            {% set pagination = {
              'page': page,
              'per_page': per_page,
              'total_items': total_items,
              'total_pages': total_pages,
              'has_prev': has_prev,
              'has_next': has_next,
              'page_items': None
            } %}

            {# build the refresh URL for controls #}
            {% set controls_url = root_path + '/admin/a2a/partial'
              + '?render=controls'
              + '&page=' + page|string
              + '&per_page=' + per_page|string
              + '&include_inactive=' + (include_inactive|default(false)|string|lower) %}

            <div id="agents-pagination-controls"
                hx-get="{{ controls_url }}"
                hx-trigger="refreshControls"
                hx-target="#agents-pagination-controls"
                hx-swap="outerHTML"
                hx-indicator="#agents-loading">

              {# helpers used by pagination_controls.html #}
              {% set base_url = root_path + '/admin/a2a/partial' %}
              {% set hx_target = '#agents-table' %}
              {% set hx_swap = 'outerHTML' %}
              {% set hx_indicator = '#agents-loading' %}
              {% set table_name = 'agents' %}
              {% set query_params = {'include_inactive': include_inactive} %}
              {% include 'pagination_controls.html' %}
            </div>
          </div>
        </div>

        {% if user_permissions.can_create_agent %}
        <!-- A2A Agent Add Form -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800 mt-8">
          <h3 class="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">
            Add New A2A Agent
          </h3>
          <form method="POST" id="add-a2a-form">
            <div class="grid grid-cols-1 gap-7 sm:grid-cols-2">
              <!-- Agent Name -->
              <div class="relative">
                <label
                  for="a2a-agent-name"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Agent Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  id="a2a-agent-name"
                  placeholder="my-assistant-agent"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Agent Name is required.</p>
              </div>

              <!-- Endpoint URL -->
              <div class="relative">
                <label
                  for="a2a-agent-endpoint-url"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Endpoint URL</label
                >
                <input
                  type="url"
                  name="endpoint_url"
                  required
                  id="a2a-agent-endpoint-url"
                  placeholder="https://api.example.com/agent"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="url" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Endpoint URL is required.</p>
              </div>

              <!-- Agent Type -->
              <div>
                <label
                  for="a2a-agent-type"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Agent Type</label
                >
                <select
                  id="a2a-agent-type"
                  name="agent_type"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                >
                  <option value="generic">Generic</option>
                  <option value="openai">OpenAI</option>
                  <option value="anthropic">Anthropic</option>
                  <option value="custom">Custom</option>
                </select>
              </div>

              <!-- Authentication Type -->
              <div>
                <label
                  for="auth-type-a2a"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Authentication Type</label
                >
                <select
                  id="auth-type-a2a"
                  name="auth_type"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                >
                  <option value="">None</option>
                  <option value="basic">Basic</option>
                  <option value="bearer">Bearer Token</option>
                  <option value="authheaders">Custom Headers</option>
                  <option value="oauth">OAuth 2.0</option>
                  <option value="query_param">Query Parameter (INSECURE)</option>
                </select>
              </div>

              <div id="auth-basic-fields-a2a" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Username</label
                  >
                  <input
                    type="text"
                    name="auth_username"
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Password</label
                  >
                  <input
                    type="password"
                    name="auth_password"
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>

              <div id="auth-bearer-fields-a2a" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Token</label
                  >
                  <input
                    type="password"
                    name="auth_token"
                    autocomplete="off"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>

              <div id="auth-headers-fields-a2a" style="display: none">
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Custom Headers
                    </label>
                    <button
                      type="button"
                      data-action-click="addAuthHeader" data-arg0="auth-headers-container-a2a"
                      class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      <svg
                        class="w-4 h-4 mr-1"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                        ></path>
                      </svg>
                      Add Header
                    </button>
                  </div>
                  <div id="auth-headers-container-a2a" class="space-y-2">
                    <!-- Headers will be added dynamically here -->
                  </div>
                  <input
                    type="hidden"
                    name="auth_headers"
                    id="auth-headers-json-a2a"
                  />
                </div>
              </div>

              <!-- Query Parameter Auth Fields -->
              <div id="auth-query_param-fields-a2a" style="display: none">
                <div class="p-3 mb-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-700 rounded-md">
                  <p class="text-xs text-amber-700 dark:text-amber-400">
                    <strong>Security Warning:</strong> API keys in URLs may appear in proxy logs, browser history, and server access logs.
                    Consider using bearer tokens or headers instead (CWE-598).
                  </p>
                </div>
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Query Parameter Name
                  </label>
                  <input
                    type="text"
                    name="auth_query_param_key"
                    placeholder="e.g., api_key"
                    class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
                <div class="mt-3">
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Query Parameter Value
                  </label>
                  <div class="relative">
                    <input
                      type="password"
                      name="auth_query_param_value"
                      id="auth-query-param-value-a2a"
                      autocomplete="off"
                      data-sensitive-label="API key"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                  </div>
                </div>
              </div>

              <!-- OAuth Configuration Fields -->
              <div id="auth-oauth-fields-a2a" style="display: none">
                <div class="space-y-4">
                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Grant Type
                    </label>
                    <select
                      name="oauth_grant_type"
                      id="oauth-grant-type-a2a"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    >
                      <option value="authorization_code" selected>
                        Authorization Code (User Delegation)
                      </option>
                      <option value="client_credentials">
                        Client Credentials (Machine-to-Machine)
                      </option>
                      <option value="password">
                        Resource Owner Password Credentials (Keycloak/Legacy)
                      </option>
                    </select>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Issuer URL
                    </label>
                    <div class="mt-1 flex gap-2">
                      <input
                        type="url"
                        name="oauth_issuer"
                        class="px-1.5 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="http://localhost:3003 or https://oauth.example.com"
                      />
                      <button
                        type="button"
                        data-action-click="discoverOAuthEndpoints" data-arg0="this"
                        class="shrink-0 px-3 py-1.5 text-sm font-medium rounded-md border border-indigo-500 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900 transition-colors"
                        title="Auto-discover token &amp; authorization endpoints from issuer metadata"
                      >🔍 Discover</button>
                    </div>
                    <p class="mt-1 text-sm text-gray-500">
                      The OAuth Authorization Server issuer URL. Required for DCR (Dynamic Client Registration).
                    </p>
                  <div class="oauth-discover-status mt-1 hidden"></div>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Client ID <span class="text-gray-500">(optional for DCR)</span>
                    </label>
                    <input
                      type="text"
                      name="oauth_client_id"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Leave empty for auto-registration via DCR"
                    />
                    <p class="mt-1 text-sm text-blue-600">
                      💡 Leave empty if the server supports DCR - credentials will be auto-registered
                    </p>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Client Secret <span class="text-gray-500">(optional for DCR)</span>
                    </label>
                    <input
                      type="password"
                      name="oauth_client_secret"
                      autocomplete="off"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Leave empty for auto-registration via DCR"
                    />
                    <p class="mt-1 text-sm text-blue-600">
                      💡 Leave empty if the server supports DCR - credentials will be auto-registered
                    </p>
                  </div>

                  <div id="oauth-username-field-a2a" style="display: none;">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Username <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                    </label>
                    <input
                      type="text"
                      name="oauth_username"
                      id="oauth-username-a2a"
                      autocomplete="off"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="systemadmin@system.com"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      Required for Resource Owner Password Credentials grant type (Keycloak).
                    </p>
                  </div>

                  <div id="oauth-password-field-a2a" style="display: none;">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Password <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                    </label>
                    <input
                      type="password"
                      name="oauth_password"
                      id="oauth-password-a2a"
                      autocomplete="off"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Enter password"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      Required for Resource Owner Password Credentials grant type (Keycloak).
                    </p>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Token URL
                    </label>
                    <input
                      type="url"
                      name="oauth_token_url"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="https://oauth.example.com/token"
                    />
                  </div>

                  <div id="oauth-auth-code-fields-a2a">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Authorization URL
                      </label>
                      <input
                        type="url"
                        name="oauth_authorization_url"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="https://oauth.example.com/authorize"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        The OAuth provider's authorization endpoint URL
                      </p>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Redirect URI
                      </label>
                      <input
                        type="url"
                        name="oauth_redirect_uri"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="https://a2aagent.example.com/oauth/callback"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        This must match the redirect URI configured in your
                        OAuth application
                      </p>
                      <p class="mt-1 text-sm text-blue-600 font-medium">
                        💡 Use:
                        <code class="bg-blue-100 px-1 rounded"
                          >{{ request.base_url }}oauth/callback</code
                        >
                      </p>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Token Management
                      </label>
                      <div class="mt-2 space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            name="oauth_store_tokens"
                            checked
                            class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                          />
                          <span
                            class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                          >
                            Store access tokens for reuse
                          </span>
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            name="oauth_auto_refresh"
                            checked
                            class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                          />
                          <span
                            class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                          >
                            Automatically refresh expired tokens
                          </span>
                        </label>
                      </div>
                      <p class="mt-1 text-sm text-gray-500">
                        Token management options for Authorization Code flow
                      </p>
                    </div>

                    <div
                      class="bg-blue-50 border border-blue-200 rounded-md p-4 dark:bg-blue-900/20 dark:border-blue-800"
                    >
                      <div class="flex">
                        <div class="flex-shrink-0">
                          <svg
                            class="h-5 w-5 text-blue-400"
                            viewBox="0 0 20 20"
                            fill="currentColor"
                          >
                            <path
                              fill-rule="evenodd"
                              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                              clip-rule="evenodd"
                            />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <h3
                            class="text-sm font-medium text-blue-800 dark:text-blue-200"
                          >
                            Authorization Code Flow Setup
                          </h3>
                          <div
                            class="mt-2 text-sm text-blue-700 dark:text-blue-300"
                          >
                            <p>After creating this gateway, you'll need to:</p>
                            <ol class="list-decimal list-inside mt-1 space-y-1">
                              <li>
                                Click the "🔐 Authorize" button in the gateway
                                list
                              </li>
                              <li>
                                Complete the OAuth consent flow with your
                                provider
                              </li>
                              <li>
                                Return to the admin panel to see authorization
                                status
                              </li>
                            </ol>
                            <p class="mt-2 font-medium">
                              Note: The Agent will be created but tools won't
                              work until OAuth authorization is completed.
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Scopes
                    </label>
                    <input
                      type="text"
                      name="oauth_scopes"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="repo read:user (space-separated)"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      Space-separated list of OAuth scopes (e.g., "repo
                      read:user")
                    </p>
                  </div>
                </div>
              </div>

              <!-- Authentication Value -->
              <!-- Commenting the
              <div>
                <label
                  for="a2a-agent-auth-value"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Authentication Value</label
                >
                <input
                  type="password"
                  id="a2a-agent-auth-value"
                  name="auth_value"
                  placeholder="API key, token, etc."
                  autocomplete="off"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              -->
              <!-- Description -->
              <div class="sm:col-span-2">
                <label
                  for="a2a-agent-description"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  id="a2a-agent-description"
                  name="description"
                  rows="2"
                  placeholder="Description of the agent's capabilities"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>

              <!-- Tags -->
              <div>
                <label
                  for="a2a-agent-tags"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Tags</label
                >
                <input
                  type="text"
                  id="a2a-agent-tags"
                  name="tags"
                  placeholder="ai,assistant,production (comma-separated)"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>

              <!-- UAID (Universal Agent ID) Section -->
              <div class="sm:col-span-2 border-t border-gray-200 dark:border-gray-700 pt-6">
                <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                  Universal Agent ID (UAID) Settings
                </h4>

                <!-- Generate UAID Checkbox -->
                <div class="flex items-start mb-4">
                  <input
                    type="checkbox"
                    id="a2a-generate-uaid"
                    name="generate_uaid"
                    value="true"
                    class="h-4 w-4 mt-0.5 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-800 dark:border-gray-600"
                    data-action-change="toggleUAIDFieldsFromEvent" data-arg0="a2a"
                  />
                  <label for="a2a-generate-uaid" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">
                    Generate UAID for cross-gateway routing
                    <span class="text-xs text-gray-500 dark:text-gray-400 block mt-1">
                      Enables zero-config federation without manual peer setup. The UAID embeds endpoint URL, protocol, and registry for automatic discovery.
                    </span>
                  </label>
                </div>

                <!-- UAID Fields (shown when checkbox is checked) -->
                <div id="uaid-fields-a2a" style="display: none;" class="space-y-4 pl-6 border-l-2 border-indigo-200 dark:border-indigo-800">

                  <!-- UAID Registry -->
                  <div>
                    <label for="a2a-uaid-registry" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                      Registry Name
                    </label>
                    <input
                      type="text"
                      id="a2a-uaid-registry"
                      name="uaid_registry"
                      value="context-forge"
                      placeholder="context-forge"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      Registry identifier (e.g., "context-forge", "hol-registry")
                    </p>
                  </div>

                  <!-- UAID Protocol -->
                  <div>
                    <label for="a2a-uaid-protocol" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                      Protocol
                    </label>
                    <select
                      id="a2a-uaid-protocol"
                      name="uaid_protocol"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                    >
                      <option value="a2a" selected>A2A</option>
                      <option value="mcp">MCP</option>
                      <option value="rest">REST</option>
                      <option value="grpc">gRPC</option>
                    </select>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      Agent communication protocol
                    </p>
                  </div>

                  <!-- UAID Native ID Override -->
                  <div>
                    <label for="a2a-uaid-native-id-override" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                      Native ID Override (Optional)
                    </label>
                    <input
                      type="text"
                      id="a2a-uaid-native-id-override"
                      name="uaid_native_id_override"
                      placeholder="http://gateway.example.com:4445"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      Override the routing address in UAID. Leave empty to use endpoint URL. Use when gateway address differs from agent endpoint (e.g., gateway proxies to agent).
                    </p>
                  </div>

                  <!-- Info Box -->
                  <div class="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md">
                    <p class="text-xs text-blue-700 dark:text-blue-300">
                      <strong>ℹ️ About UAIDs:</strong> Universal Agent IDs enable cross-gateway routing without manual configuration.
                      The UAID embeds the endpoint URL, protocol, and registry info for automatic discovery.
                      <br/><br/>
                      <strong>Domain Allowlist:</strong> Set <code class="px-1 py-0.5 bg-blue-100 dark:bg-blue-800 rounded">UAID_ALLOWED_DOMAINS</code> in .env to control which domains can be used.
                    </p>
                  </div>

                </div>
              </div>

              <!-- Visibility -->
              <div class="sm:col-span-2">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Visibility</label
                >
                <div class="flex gap-x-6 mt-2">

                  <div class="flex items-center">
                    <input
                      type="radio"
                      name="visibility"
                      value="public"
                      id="a2a-visibility-public"
                      class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                      checked
                    />
                    <label
                      for="a2a-visibility-public"
                      class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                      >🌍 Public</label
                    >
                  </div>

                  <div class="flex items-center">
                    <input
                      type="radio"
                      name="visibility"
                      value="team"
                      id="a2a-visibility-team"
                      class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <label
                      for="a2a-visibility-team"
                      class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                      >👥 Team</label
                    >
                  </div>
                  <div class="flex items-center">
                    <input
                      type="radio"
                      name="visibility"
                      value="private"
                      id="a2a-visibility-private"
                      class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <label
                      for="a2a-visibility-private"
                      class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                      >🔒 Private</label
                    >
                  </div>
                </div>
              </div>

              <div class="sm:col-span-2 max-w-5xl">
                <label
                  for="passthrough_headers"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >
                  Passthrough Headers
                </label>
                <input
                  type="text"
                  name="passthrough_headers"
                  placeholder="Authorization, X-Tenant-Id, X-Trace-Id"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                        focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <small class="block mt-1 text-sm text-gray-500 dark:text-gray-400">
                  List of headers to pass through from client requests (comma-separated, e.g.,
                  "Authorization, X-Tenant-Id, X-Trace-Id").
                </small>
              </div>


              <!-- Error Display -->
              <span
                id="a2aFormError"
                class="sm:col-span-2 block text-sm font-semibold text-red-600 mt-2"
              ></span>

              <!-- Loading Indicator -->
              <div
                id="add-a2a-loading"
                class="hidden sm:col-span-2 text-sm text-gray-500 mt-2"
              >
                Submitting...
              </div>

              <!-- Submit -->
              <div class="sm:col-span-2 mt-6">
                <button
                  type="submit"
                  class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  Add A2A Agent
                </button>
              </div>
            </div>
          </form>
        </div>
        {% endif %}


      </div>
      {% endif %}

      <!-- gRPC Services Panel -->
      {% if grpc_enabled and 'grpc-services' not in hidden_sections %}
      <div id="grpc-services-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            gRPC Services Registry
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Manage gRPC services exposed as MCP tools via automatic reflection
          </p>
        </div>

        <!-- gRPC Service Add Form -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <h3 class="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">
            Register New gRPC Service
          </h3>
          <form method="POST" id="add-grpc-service-form">
            <div class="grid grid-cols-1 gap-7 sm:grid-cols-2">
              <!-- Service Name -->
              <div class="relative">
                <label
                  for="grpc-service-name"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Service Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  id="grpc-service-name"
                  placeholder="my-grpc-service"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Service Name is required.</p>
              </div>

              <!-- Target (host:port) -->
              <div>
                <label
                  for="grpc-service-target"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >gRPC Target (host:port)</label
                >
                <input
                  type="text"
                  id="grpc-service-target"
                  name="target"
                  required
                  placeholder="localhost:50051"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>

              <!-- Description -->
              <div class="sm:col-span-2">
                <label
                  for="grpc-service-description"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  id="grpc-service-description"
                  name="description"
                  rows="2"
                  placeholder="Optional description of the gRPC service"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>

              <!-- TLS Enabled -->
              <div class="flex items-center">
                <input
                  type="checkbox"
                  id="grpc-tls-enabled"
                  name="tls_enabled"
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                  data-action-change="toggleGrpcTlsFields"
                />
                <label
                  for="grpc-tls-enabled"
                  class="ml-2 block text-sm text-gray-900 dark:text-gray-400"
                  >Enable TLS</label
                >
              </div>

              <!-- Reflection Enabled -->
              <div class="flex items-center">
                <input
                  type="checkbox"
                  id="grpc-reflection-enabled"
                  name="reflection_enabled"
                  checked
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label
                  for="grpc-reflection-enabled"
                  class="ml-2 block text-sm text-gray-900 dark:text-gray-400"
                  >Enable Server Reflection</label
                >
              </div>

              <!-- TLS Certificate Path (hidden by default) -->
              <div id="grpc-tls-cert-field" class="hidden">
                <label
                  for="grpc-tls-cert-path"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >TLS Certificate Path</label
                >
                <input
                  type="text"
                  id="grpc-tls-cert-path"
                  name="tls_cert_path"
                  placeholder="/path/to/cert.pem"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>

              <!-- TLS Key Path (hidden by default) -->
              <div id="grpc-tls-key-field" class="hidden">
                <label
                  for="grpc-tls-key-path"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >TLS Key Path</label
                >
                <input
                  type="text"
                  id="grpc-tls-key-path"
                  name="tls_key_path"
                  placeholder="/path/to/key.pem"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>

              <!-- Team Selection -->
              {% if teams %}
              <div>
                <label
                  for="grpc-service-team-id"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Team</label
                >
                <select
                  id="grpc-service-team-id"
                  name="team_id"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                >
                  <option value="">No Team (Global)</option>
                  {% for team in teams %}
                  <option value="{{ team.id }}">{{ team.name }}</option>
                  {% endfor %}
                </select>
              </div>
              {% endif %}

              <!-- Visibility -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">Visibility</label>
                <div class="flex items-center space-x-4">

                  <div class="flex items-center">
                    <input type="radio" name="visibility" value="public" class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600" id="grpc-visibility-public" checked />
                    <label for="grpc-visibility-public" class="ml-2 text-sm text-gray-700 dark:text-gray-400">Public</label>
                  </div>

                  <div class="flex items-center">
                    <input type="radio" name="visibility" value="team" class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600" id="grpc-visibility-team" />
                    <label for="grpc-visibility-team" class="ml-2 text-sm text-gray-700 dark:text-gray-400">Team</label>
                  </div>
                  <div class="flex items-center">
                    <input type="radio" name="visibility" value="private" class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600" id="grpc-visibility-private" />
                    <label for="grpc-visibility-private" class="ml-2 text-sm text-gray-700 dark:text-gray-400">Private</label>
                  </div>
                </div>
              </div>
            </div>

            <div class="mt-6">
              <button
                type="submit"
                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Register gRPC Service
              </button>
            </div>
            <!-- Loading Indicator -->
            <div
              id="add-grpc-loading"
              class="hidden text-sm text-gray-500 mt-2"
            >
              Submitting...
            </div>
          </form>
          <!-- Error Message Display -->
          <div id="grpcFormError" class="mt-4 text-red-600 dark:text-red-400 hidden"></div>
        </div>

        <!-- Registered gRPC Services List -->
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">
            Registered gRPC Services
          </h3>
          <div class="space-y-4" id="grpc-services-list">
            {% if grpc_services %}
              {% for service in grpc_services %}
              <div class="border border-gray-200 dark:border-gray-600 rounded-lg p-4 space-y-3">
                <div class="flex items-start justify-between">
                  <div class="flex-1">
                    <h4 class="text-lg font-medium text-gray-900 dark:text-gray-200">
                      {{ service.name }}
                    </h4>
                    <p class="text-sm text-gray-600 dark:text-gray-400">
                      {{ (service.description or "") | decode_html }}
                    </p>
                    <div class="mt-2 flex flex-wrap gap-2">
                      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {% if service.enabled %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}">
                        {% if service.enabled %}Active{% else %}Inactive{% endif %}
                      </span>
                      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {% if service.reachable %}bg-blue-100 text-blue-800{% else %}bg-yellow-100 text-yellow-800{% endif %}">
                        {% if service.reachable %}Reachable{% else %}Unreachable{% endif %}
                      </span>
                      {% if service.reflection_enabled %}
                      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                        Reflection Enabled
                      </span>
                      {% endif %}
                      {% if service.tls_enabled %}
                      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800">
                        TLS
                      </span>
                      {% endif %}
                    </div>
                    <div class="mt-2 text-sm text-gray-600 dark:text-gray-400">
                      <p><strong>Target:</strong> {{ service.target }}</p>
                      <p><strong>Services:</strong> {{ service.service_count }} | <strong>Methods:</strong> {{ service.method_count }}</p>
                      {% if service.last_reflection %}
                      <p><strong>Last Reflection:</strong> {{ service.last_reflection }}</p>
                      {% endif %}
                    </div>
                  </div>
                  <div class="flex flex-col space-y-2 ml-4">
                    <form action="{{ root_path }}/admin/grpc/{{ service.id }}/state?activate={{ 'false' if service.enabled else 'true' }}" method="POST" class="inline">
                      <button
                        type="submit"
                        class="px-3 py-1 text-sm font-medium rounded-md {% if service.enabled %}bg-yellow-100 text-yellow-800 hover:bg-yellow-200{% else %}bg-green-100 text-green-800 hover:bg-green-200{% endif %}"
                      >
                        {% if service.enabled %}Deactivate{% else %}Activate{% endif %}
                      </button>
                    </form>
                    <form action="{{ root_path }}/admin/grpc/{{ service.id }}/reflect" method="POST" class="inline">
                      <button
                        type="submit"
                        class="px-3 py-1 text-sm font-medium bg-blue-100 text-blue-800 rounded-md hover:bg-blue-200"
                      >
                        Re-Reflect
                      </button>
                    </form>
                    <button
                      data-action-click="viewGrpcMethods" data-arg0="{{ service.id|tojson_attr }}"
                      class="px-3 py-1 text-sm font-medium bg-purple-100 text-purple-800 rounded-md hover:bg-purple-200"
                    >
                      View Methods
                    </button>
                    <form action="{{ root_path }}/admin/grpc/{{ service.id }}/delete" method="POST" class="inline" data-action-submit="confirmAction" data-arg0="Are you sure you want to delete this gRPC service?" data-prevent-default="false">
                      <button
                        type="submit"
                        class="px-3 py-1 text-sm font-medium bg-red-100 text-red-800 rounded-md hover:bg-red-200"
                      >
                        Delete
                      </button>
                    </form>
                  </div>
                </div>
              </div>
              {% endfor %}
            {% else %}
              <p class="text-gray-500 dark:text-gray-400">No gRPC services registered yet.</p>
            {% endif %}
          </div>
        </div>
      </div>
      {% endif %}

      {% if 'roots' not in hidden_sections %}
      <!-- Roots Panel -->
      <div id="roots-panel" class="tab-panel hidden">
        <!-- List of roots ------------------------------------------------------->
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <!-- Consistent header -->
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-2xl font-bold dark:text-gray-200">
              Root Directories
            </h2>
          </div>

          <!-- Description -->
          <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
            Roots define the base folders accessible for file-based Resources.
            They enable MCP servers to browse local content.
          </p>

          <!-- Roots table -->
          <div id="roots-table-wrapper" class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-20"
                  >
                    Actions
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    ID
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    URI
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Name
                  </th>
                </tr>
              </thead>
              <tbody
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for root in roots %}
                <tr>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="relative"
                         x-data="window.Admin?.overflowMenu?.('roots-table-wrapper')"
                         @click.away="menuOpen = false"
                         @keydown.escape="menuOpen = false; $refs.trigger.focus()">
                      <button
                        type="button"
                        x-ref="trigger"
                        @click="menuOpen ? (menuOpen = false) : openMenu()"
                        class="p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-gray-200 dark:hover:bg-gray-700 transition-colors"
                        :aria-expanded="menuOpen"
                        aria-haspopup="menu"
                        aria-label="Actions"
                        x-tooltip="'Actions'"
                      >
                        <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                          <path d="M6 10a2 2 0 11-4 0 2 2 0 014 0zm6 0a2 2 0 11-4 0 2 2 0 014 0zm6 0a2 2 0 11-4 0 2 2 0 014 0z"/>
                        </svg>
                      </button>
                      <!-- Dropdown menu (fixed-positioned to escape overflow/scroll containers) -->
                      <div
                        x-ref="menu"
                        x-cloak
                        x-show="menuOpen"
                        x-transition:enter="transition ease-out duration-100"
                        x-transition:enter-start="opacity-0 scale-95"
                        x-transition:enter-end="opacity-100 scale-100"
                        x-transition:leave="transition ease-in duration-75"
                        x-transition:leave-start="opacity-100 scale-100"
                        x-transition:leave-end="opacity-0 scale-95"
                        class="fixed w-44 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-50 py-1"
                        :style="`top: ${menuTop}px; left: ${menuLeft}px; display: ${menuOpen ? 'block' : 'none'}`"
                        role="menu"
                        aria-orientation="vertical"
                        @keydown.arrow-down.prevent="navigate(1)"
                        @keydown.arrow-up.prevent="navigate(-1)"
                      >
                        <button
                          type="button"
                          role="menuitem"
                          tabindex="0"
                          @click="menuOpen = false; window.Admin?.viewRoot?.({{ root.uri|tojson_attr }})"
                          class="w-full flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                          x-tooltip="'💡View root directory details and configuration'"
                        >View</button>
                        <button
                          type="button"
                          role="menuitem"
                          tabindex="0"
                          @click="menuOpen = false; window.Admin?.editRoot?.({{ root.uri|tojson_attr }})"
                          class="w-full flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                          x-tooltip="'💡Edit root directory settings and configuration'"
                        >Edit</button>
                        <button
                          type="button"
                          role="menuitem"
                          tabindex="0"
                          @click="menuOpen = false; window.Admin?.exportRoot?.({{ root.uri|tojson_attr }})"
                          class="w-full flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                          x-tooltip="'💡Export root directory configuration'"
                        >Export</button>
                        <hr class="border-gray-200 dark:border-gray-600 my-1">
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/roots/{{ root.uri }}/delete"
                          class="contents"
                          @submit="menuOpen = false"
                          data-action-submit="handleSubmitWithConfirmation" data-arg0="roots"
                        >
                          <button
                            type="submit"
                            role="menuitem"
                            tabindex="0"
                            class="w-full flex items-center px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700"
                            x-tooltip="'💡Permanently delete this item – cannot be undone'"
                          >Delete</button>
                        </form>
                      </div>
                    </div>
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    {{ loop.index }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    {{ root.uri }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400"
                  >
                    {{ root.name }}
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>

        <!-- Add new root -------------------------------------------------------->
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Root
          </h3>
          <form
            method="POST"
            action="{{ root_path }}/admin/roots"
            id="add-root-form"
            data-action-submit="handleToggleSubmit" data-arg0="roots"
          >
            <div class="grid grid-cols-1 gap-7">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >URI</label
                >
                <input
                  type="text"
                  name="uri"
                  required
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="file:///path/to/directory"
                />
              </div>
              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="My Project"
                />
              </div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Registers a base directory that MCP servers can browse for files.'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Root
              </button>
            </div>
          </form>
        </div>
      </div>
      {% endif %}

      {% if 'metrics' not in hidden_sections %}
      <!-- Metrics Panel -->
      <div id="metrics-panel" class="tab-panel hidden">
        <!-- System Metrics Section (isolated from JavaScript clearing) -->
        <div id="system-metrics-section" class="bg-white shadow rounded-lg p-6 dark:bg-gray-800 mb-6">
          <h2 class="text-2xl font-bold dark:text-gray-200 mb-4">
            System Metrics
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
            Real-time system metrics showing counts across all entity types.
            Useful for capacity planning and system monitoring.
          </p>

          <!-- System Metrics Content (loaded via HTMX) -->
          <div
            hx-get="{{ root_path }}/admin/system/stats"
            hx-trigger="revealed once"
            hx-swap="outerHTML"
          >
            <div class="flex justify-center items-center py-8">
              <svg class="animate-spin h-8 w-8 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span class="ml-3 text-gray-600 dark:text-gray-400">Loading system metrics...</span>
            </div>
          </div>
        </div>

        <!-- KPI Section (between system metrics and top performers) -->
        <div id="kpi-metrics-section" class="mb-6"></div>

        <!-- Top Performers Section -->
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <h2 class="text-2xl font-bold dark:text-gray-200 mb-4">
            Top Performers
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mb-6">
            View the most frequently used tools, resources, prompts, and servers with paginated results.
          </p>

          <!-- Tab Navigation -->
          <div class="border-b border-gray-200 dark:border-gray-700 mb-4">
            <nav class="-mb-px flex space-x-8" aria-label="Top Performers Tabs">
              <button
                data-action-click="switchTopPerformersTab" data-arg0="tools"
                id="top-performers-tab-tools"
                class="top-performers-tab border-b-2 border-indigo-500 py-2 px-1 text-sm font-medium text-indigo-600 dark:text-indigo-400"
              >
                Tools
              </button>
              <button
                data-action-click="switchTopPerformersTab" data-arg0="resources"
                id="top-performers-tab-resources"
                class="top-performers-tab border-b-2 border-transparent py-2 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300"
              >
                Resources
              </button>
              <button
                data-action-click="switchTopPerformersTab" data-arg0="prompts"
                id="top-performers-tab-prompts"
                class="top-performers-tab border-b-2 border-transparent py-2 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300"
              >
                Prompts
              </button>
              <button
                data-action-click="switchTopPerformersTab" data-arg0="servers"
                id="top-performers-tab-servers"
                class="top-performers-tab border-b-2 border-transparent py-2 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300"
              >
                Servers
              </button>
            </nav>
          </div>

          <!-- Tab Content Panels -->
          <div id="top-performers-panel-tools" class="top-performers-panel">
            <div class="overflow-x-auto">
              <div id="top-tools-content-visible"
                   hx-get="{{ root_path }}/admin/metrics/partial?entity_type=tools&page=1&per_page=10"
                   hx-trigger="load"
                   hx-swap="outerHTML"
                   hx-indicator="#top-tools-loading-visible">
                <div class="text-center py-8 text-gray-500 dark:text-gray-400">
                  Loading top tools...
                </div>
              </div>
            </div>
            <div id="top-tools-loading-visible" class="htmx-indicator hidden">Loading...</div>
            <div id="top-tools-pagination-controls-visible"></div>
          </div>

          <div id="top-performers-panel-resources" class="top-performers-panel hidden">
            <div class="overflow-x-auto">
              <div id="top-resources-content-visible"
                   hx-get="{{ root_path }}/admin/metrics/partial?entity_type=resources&page=1&per_page=10"
                   hx-trigger="load"
                   hx-swap="outerHTML"
                   hx-indicator="#top-resources-loading-visible">
                <div class="text-center py-8 text-gray-500 dark:text-gray-400">
                  Loading top resources...
                </div>
              </div>
            </div>
            <div id="top-resources-loading-visible" class="htmx-indicator hidden">Loading...</div>
            <div id="top-resources-pagination-controls-visible"></div>
          </div>

          <div id="top-performers-panel-prompts" class="top-performers-panel hidden">
            <div class="overflow-x-auto">
              <div id="top-prompts-content-visible"
                   hx-get="{{ root_path }}/admin/metrics/partial?entity_type=prompts&page=1&per_page=10"
                   hx-trigger="load"
                   hx-swap="outerHTML"
                   hx-indicator="#top-prompts-loading-visible">
                <div class="text-center py-8 text-gray-500 dark:text-gray-400">
                  Loading top prompts...
                </div>
              </div>
            </div>
            <div id="top-prompts-loading-visible" class="htmx-indicator hidden">Loading...</div>
            <div id="top-prompts-pagination-controls-visible"></div>
          </div>

          <div id="top-performers-panel-servers" class="top-performers-panel hidden">
            <div class="overflow-x-auto">
              <div id="top-servers-content-visible"
                   hx-get="{{ root_path }}/admin/metrics/partial?entity_type=servers&page=1&per_page=10"
                   hx-trigger="load"
                   hx-swap="outerHTML"
                   hx-indicator="#top-servers-loading-visible">
                <div class="text-center py-8 text-gray-500 dark:text-gray-400">
                  Loading top servers...
                </div>
              </div>
            </div>
            <div id="top-servers-loading-visible" class="htmx-indicator hidden">Loading...</div>
            <div id="top-servers-pagination-controls-visible"></div>
          </div>

          <!-- Individual Metrics Grid (inside Top Performers section) -->
          <div id="individual-metrics-grid" class="mt-8"></div>
        </div>

        <!-- Aggregated Metrics Section (hidden - metrics now in Top Performers) -->
        <div id="aggregated-metrics-section" class="hidden">
          <div id="aggregated-metrics-content"></div>
          <canvas id="metricsChart"></canvas>
        </div>
      </div>
      {% endif %}

      <!-- Modals -->
      <!-- Tool Detail Modal -->
      <div id="tool-modal" class="fixed z-40 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Tool Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-900"
                id="tool-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="tool-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- New Modal: Test Case Generation -->
<div
id="testcase-gen-modal"
class="fixed z-40 inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center hidden"
>
<div
  class="bg-white dark:bg-gray-900 w-full max-w-md rounded-lg shadow-lg p-6"
>
  <h2 class="text-xl font-bold mb-4 text-gray-800 dark:text-gray-100">
    Generate Test Cases
  </h2>


  <form id="testcase-gen-form" class="space-y-4 text-gray-800 dark:text-gray-100">
    <!-- Number of Test Cases -->
    <div>
      <label
          id="gen-test-tool-id"
          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
        ></label>
      <label
        for="gen-testcase-count"
        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
      >
        Number of Test Cases
      </label>
      <input
        id="gen-testcase-count"
        name="testCases"
        type="number"
        min="1"
        class="mt-1 block w-full rounded-md shadow-sm p-2 bg-gray-200 dark:bg-gray-800"
        placeholder="e.g., 5"
        value="2"
        required
      />
    </div>

    <!-- Number of NL Variations -->
    <div>
      <label
        for="gen-nl-variation-count"
        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
      >
        Number of Agent test utterances
      </label>
      <input
        id="gen-nl-variation-count"
        name="nlVariations"
        type="number"
        min="1"
        class="mt-1 block w-full rounded-md shadow-sm p-2 bg-gray-200 dark:bg-gray-800"
        placeholder="e.g., 3"
        value="2"
        required
      />
    </div>

    <!-- Action Buttons -->
    <div class="flex justify-between mt-6">
      <button
        type="button"
        data-action-click="generateTestCases"
        id="generate-btn"
        class="w-1/2 mr-2 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
      >
        Generate
      </button>
      <button
          data-action-click="closeModal" data-arg0="testcase-gen-modal"
          class="w-1/2 ml-2 px-4 py-2 border border-blue-600 rounded bg-white text-gray-700 hover:bg-gray-200"
        >
          Close
        </button>
    </div>
  </form>
</div>
</div>

<div
id="bulk-testcase-gen-modal"
class="fixed z-40 inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center hidden"
>
<div
  class="bg-white dark:bg-gray-900 w-full max-w-md rounded-lg shadow-lg p-6"
>
  <h2 class="text-xl font-bold mb-4 text-gray-800 dark:text-gray-100">
    Generate Test Cases
  </h2>


  <form id="bulk-testcase-gen-form" class="space-y-4 text-gray-800 dark:text-gray-100">
    <!-- Number of Test Cases -->
    <div>
      <label
          id="gen-bulk-test-tool-id"
          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
        ></label>
      <label
        for="gen-bulk-testcase-count"
        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
      >
        Number of Test Cases
      </label>
      <input
        id="gen-bulk-testcase-count"
        name="testCases"
        type="number"
        min="1"
        class="mt-1 block w-full rounded-md shadow-sm p-2 bg-gray-200 dark:bg-gray-800"
        placeholder="e.g., 5"
        value="2"
        required
      />
    </div>

    <!-- Number of NL Variations -->
    <div>
      <label
        for="gen-bulk-nl-variation-count"
        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
      >
        Number of Agent test utterances
      </label>
      <input
        id="gen-bulk-nl-variation-count"
        name="nlVariations"
        type="number"
        min="1"
        class="mt-1 block w-full rounded-md shadow-sm p-2 bg-gray-200 dark:bg-gray-800"
        placeholder="e.g., 3"
        value="2"
        required
      />
    </div>

    <!-- Action Buttons -->
    <div class="flex justify-between mt-6">
      <button
        type="button"
        data-action-click="generateBulkTestCases"
        id="bulk-generate-btn"
        class="w-1/2 mr-2 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
      >
        Generate
      </button>
      <button
        type="button"
        data-action-click="closeModal" data-arg0="bulk-testcase-gen-modal"
          class="w-1/2 ml-2 px-4 py-2 border border-blue-600 rounded bg-white text-gray-700 hover:bg-gray-200"
        >
          Close
        </button>
    </div>
  </form>
</div>
</div>

<!-- View Description Modal -->
<div
  id="description-view-modal"
  class="fixed z-40 inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center hidden"
>
  <div
    class="bg-white dark:bg-gray-900 w-full max-w-3xl rounded-lg shadow-lg p-6"
  >
    <h2 class="text-xl font-bold mb-4 text-gray-800 dark:text-gray-100">
      View Descriptions
    </h2>

    <form id="description-view-form" class="space-y-4 text-gray-800 dark:text-gray-100">
      <!-- Old Description -->
      <div>
        <label
          for="view-old-description"
          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
        >
          Original Description
        </label>
        <textarea
          id="view-old-description"
          name="oldDescription"
          rows="5"
          readonly
          class="mt-1 block w-full rounded-md shadow-sm p-2 bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
          placeholder="Old description will appear here"
        ></textarea>
      </div>

      <!-- New Description -->
      <div>
        <label
          for="view-new-description"
          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
        >
          Enriched Description
        </label>
        <textarea
          id="view-new-description"
          name="newDescription"
          rows="5"
          readonly
          class="mt-1 block w-full rounded-md shadow-sm p-2 bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
          placeholder="Enriched description will appear here"
        ></textarea>
      </div>

      <!-- Close Button -->
      <div class="flex justify-center mt-6">
        <button
          data-action-click="closeModal" data-arg0="description-view-modal"
          type="button"
          id="close-description-view"
          class="w-1/2 px-4 py-2 border border-blue-600 rounded bg-white text-gray-700 hover:bg-gray-200"
        >
          Close
        </button>
      </div>
    </form>
  </div>
</div>

      <div id="tool-validation-modal" class="fixed inset-0 hidden z-40 overflow-y-auto bg-black bg-opacity-50">
    <div
      class="relative bg-white dark:bg-gray-900 w-full max-w-3xl mx-auto my-10 rounded-lg shadow-lg p-6"
    >
      <div class="flex justify-between items-center mb-4">
        <h2
          id="tool-validation-modal-title"
          class="text-lg font-semibold text-gray-900 dark:text-gray-100"
        >
          Test Tool
        </h2>
        <button
          data-action-click="closeModal" data-arg0="tool-validation-modal"
          class="text-gray-500 hover:text-gray-800 dark:hover:text-gray-200"
        >
          ✕
        </button>
      </div>

      <p
        id="tool-validation-modal-description"
        class="text-sm text-gray-600 dark:text-gray-400 mb-4"
      ></p>

      <div
        id="tool-validation-form-fields"
        class="space-y-4 max-h-[70vh] overflow-y-auto"
      ></div>
      <button
                type="button"
                data-action-click="closeModal" data-arg0="tool-validation-modal" data-arg1="tool-validation-result"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
    </div>

      </div>

      <!-- Tool Test Modal -->
      <div
        id="tool-test-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <!-- Increased max width (sm:max-w-2xl) for a larger modal -->
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3
                id="tool-test-modal-title"
                class="text-lg font-medium text-gray-900 dark:text-gray-100"
              >
                Test Tool
              </h3>
              <!-- New container to show the tool's description -->
              <div
                id="tool-test-modal-description"
                class="mb-4 text-gray-700 dark:text-gray-400"
              ></div>
              <form id="tool-test-form">
                <div
                  id="tool-test-form-fields"
                  class="space-y-4 text-gray-700 dark:text-gray-400"
                >
                  <!-- Fields will be dynamically inserted here based on the tool's input schema -->
                </div>
                <div class="mt-4 border-t pt-4">
                  <div>
                    <label
                      for="test-passthrough-headers"
                      class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                    >
                      Passthrough Headers (Optional)
                    </label>
                    <small class="text-gray-500 dark:text-gray-400 block mb-2">
                      Additional headers to send with the request (format:
                      "Header-Name: Value", one per line)
                    </small>
                    <textarea
                      id="test-passthrough-headers"
                      name="passthrough_headers"
                      rows="3"
                      placeholder="Authorization: Bearer your-token&#10;X-Tenant-Id: tenant-123&#10;X-Trace-Id: trace-456"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
                    ></textarea>
                  </div>
                </div>
                <div class="mt-4">
                  <button
                    type="button"
                    data-action-click="runToolTest"
                    class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
                  >
                    Run Tool
                  </button>
                </div>
                <div id="tool-test-loading" style="display: none">
                  <div class="spinner"></div>
                </div>
              </form>
              <!-- The result area now uses a fixed height for a larger view -->
              <div
                id="tool-test-result"
                class="mt-4 bg-gray-100 p-2 rounded overflow-auto dark:bg-gray-900 dark:text-gray-300"
                style="height: 400px"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="tool-test-modal" data-arg1="tool-test-result"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Tool Edit Modal -->
      <div
        id="tool-edit-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Tool
              </h3>
              <div class="mt-4">
                <form id="edit-tool-form" method="POST">
                  <div class="grid grid-cols-1 gap-7">
                    <input type="hidden" name="name" id="edit-tool-name" />

                    <div class="relative">
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        for="edit-tool-custom-name"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="customName"
                        required
                        id="edit-tool-custom-name"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Display Name</label
                      >
                      <input
                        type="text"
                        name="displayName"
                        id="edit-tool-display-name"
                        placeholder="Custom display name for your UI"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>

                    <div class="relative">
                      <label
                        for="edit-tool-url"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >URL</label
                      >
                      <input
                        type="url"
                        name="url"
                        required
                        id="edit-tool-url"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p data-error-message-for="url" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">URL is required.</p>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-tool-description"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Integration Type</label
                      >
                      <select
                        name="integrationType"
                        id="edit-tool-type"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        data-action-change="handleEditIntegrationTypeChange"
                      >
                        <option value="REST">REST</option>
                        <option value="MCP">MCP</option>
                      </select>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Request Type</label
                      >
                      <select
                        name="requestType"
                        id="edit-tool-request-type"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></select>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Headers (JSON)</label
                      >
                      <textarea
                        name="headers"
                        id="edit-tool-headers"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Input Schema (JSON)</label
                      >
                      <textarea
                        name="input_schema"
                        id="edit-tool-schema"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Output Schema (JSON)</label
                      >
                      <textarea
                        name="output_schema"
                        id="edit-tool-output-schema"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="{&quot;type&quot;: &quot;object&quot;, &quot;properties&quot;}"
                      ></textarea>
                      <p class="mt-1 text-xs text-gray-500 dark:text-indigo-300">
                        Optional JSON Schema for validating structured tool output. Per MCP spec, servers should return structured results that conform to this schema.
                      </p>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Annotations (JSON)</label
                      >
                      <textarea
                        name="annotations"
                        id="edit-tool-annotations"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm text-gray-900 placeholder-gray-600 dark:placeholder-gray-400 bg-white dark:bg-gray-800"
                        placeholder="Annotations are generally provided by the MCP servers"
                      ></textarea>
                      <p
                        class="mt-1 text-xs text-gray-500 dark:text-indigo-300"
                      >
                        Annotations like readOnlyHint, destructiveHint are
                        generally provided by the MCP server.
                      </p>
                    </div>
                    <!-- Authentication Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Authentication Type</label
                      >
                      <select
                        name="auth_type"
                        id="edit-auth-type"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      >
                        <option value="">None</option>
                        <option value="basic">Basic</option>
                        <option value="bearer">Bearer Token</option>
                        <option value="authheaders">Custom Headers</option>
                      </select>
                    </div>
                    <div id="edit-auth-basic-fields" style="display: none">
                      <div class="relative">
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >Username</label
                        >
                        <input
                          type="text"
                          name="auth_username"
                          id="edit-auth-username"
                          autocomplete="off"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                      <div>
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >Password</label
                        >
                        <input
                          type="password"
                          name="auth_password"
                          id="edit-auth-password"
                          autocomplete="off"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          placeholder="********"
                        />
                      </div>
                    </div>
                    <div id="edit-auth-bearer-fields" style="display: none">
                      <div>
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >Token</label
                        >
                        <input
                          type="password"
                          name="auth_token"
                          id="edit-auth-token"
                          autocomplete="off"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          placeholder="********"
                        />
                      </div>
                    </div>
                  </div>
                  <div id="edit-auth-headers-fields" style="display: none">
                    <div class="space-y-3">
                      <div class="flex items-center justify-between">
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >
                          Custom Headers
                        </label>
                        <button
                          type="button"
                          data-action-click="addAuthHeader" data-arg0="edit-auth-headers-container"
                          class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                        >
                          <svg
                            class="w-4 h-4 mr-1"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                            ></path>
                          </svg>
                          Add Header
                        </button>
                      </div>
                      <div id="edit-auth-headers-container" class="space-y-2">
                        <!-- Headers will be added dynamically here -->
                      </div>
                      <input
                        type="hidden"
                        name="auth_headers"
                        id="edit-auth-headers-json"
                      />
                    </div>
                  </div>
                  <!-- Tags Section -->
                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >Tags</label
                    >
                    <input
                      type="text"
                      name="tags"
                      id="edit-tool-tags"
                      placeholder="e.g., api,data-processing,external (comma-separated)"
                      class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      Enter tags separated by commas. Tags help categorize and
                      filter tools.
                    </p>
                  </div>
                  <!-- Visibility options -->
                  <div id="edit-tool-visibility" class="mt-4">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                      >Visibility</label
                    >
                    <div class="flex gap-x-6 mt-2">
                      <!-- Add gap-x-6 for more space between radio options -->

                      <div class="flex items-center">
                        <input
                          type="radio"
                          name="visibility"
                          value="public"
                          class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                          id="edit-tool-visibility-public"
                        />
                        <label
                          for="edit-tool-visibility-public"
                          class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                          >🌍Public</label
                        >
                      </div>

                      <div class="flex items-center">
                        <input
                          type="radio"
                          name="visibility"
                          value="team"
                          class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                          id="edit-tool-visibility-team"
                        />
                        <label
                          for="edit-tool-visibility-team"
                          class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                          >👥Team</label
                        >
                      </div>
                      <div class="flex items-center">
                        <input
                          type="radio"
                          name="visibility"
                          value="private"
                          class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                          id="edit-tool-visibility-private"
                        />
                        <label
                          for="edit-tool-visibility-private"
                          class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                          >🔒Private</label
                        >
                      </div>
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      data-action-click="closeModal" data-arg0="tool-edit-modal"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Resource Detail Modal -->
      <div
        id="resource-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Resource Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-400"
                id="resource-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="resource-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- RESOURCE TESING MODAL --------------------------->

      <!-- Resource Test Modal -->
      <div
        id="resource-test-modal"
        class="fixed z-40 inset-0 hidden overflow-y-auto"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <!-- Overlay -->
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>

          <!-- Modal Panel -->
          <div
            class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-900 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">

              <!-- Title -->
              <h3
                id="resource-test-modal-title"
                class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4"
              ></h3>

              <!-- Dynamic Fields -->
              <form id="resource-test-form">
                <div
                  id="resource-test-form-fields"
                  class="space-y-4 text-gray-700 dark:text-gray-400"
                ></div>

                <!-- Test Button -->
                <button
                  type="button"
                  data-action-click="runResourceTest"
                  class="mt-4 inline-flex items-center px-3 py-2 border border-transparent
                        text-sm leading-4 font-medium rounded-md text-white
                        bg-indigo-600 hover:bg-indigo-700 focus:outline-none
                        focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  Test Resource
                </button>

                <!-- Test Result -->
                <div class="mt-6 border-t pt-4">
                  <h4
                    class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-2"
                  >
                    Result
                  </h4>

                  <div
                    id="resource-test-result"
                    class="bg-gray-50 dark:bg-gray-800 p-3 rounded-md border
                          border-gray-200 dark:border-gray-700 text-gray-700
                          dark:text-gray-300 text-sm whitespace-pre-wrap"
                  >
                    <!-- JSON content injected here -->
                  </div>
                </div>
              </form>
            </div>

            <!-- Footer -->
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="resource-test-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border
                      border-gray-300 shadow-sm px-4 py-2 bg-white text-base
                      font-medium text-gray-700 hover:bg-gray-50
                      dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600
                      focus:outline-none focus:ring-2 focus:ring-offset-2
                      focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>



      <!-- RESOURCE TESING MODAL --------------------------->

      <!-- Resource Edit Modal -->
      <div
        id="resource-edit-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Resource
              </h3>
              <div class="mt-4">
                <form id="edit-resource-form" method="POST">
                  <div class="grid grid-cols-1 gap-7">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >URI</label
                      >
                      <!-- URI is read-only -->
                      <input
                        type="text"
                        name="uri"
                        required
                        id="edit-resource-uri"
                        readonly
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div class="relative">
                      <label
                        class="block text-sm font-medium text-gray-700"
                        for="edit-resource-name"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-resource-name"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-resource-description"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >MIME Type</label
                      >
                      <input
                        type="text"
                        name="mimeType"
                        id="edit-resource-mime-type"
                        aria-describedby="edit-resource-mime-helper"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p id="edit-resource-mime-helper" class="mt-1 text-xs text-gray-500 dark:text-gray-400 hidden">
                        For interactive MCP Apps use: text/html;profile=mcp-app
                      </p>
                    </div>
                    <!-- Removing Content form Edit Form -->
                    <!-- Remove required attribute to avoid browser validation issues -->

                    <!--
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Content</label
                      >

                      <textarea
                        name="content"
                        id="edit-resource-content"
                        class="mt-1 px-1.5 block w-full h-48 rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                      ></textarea>
                    </div>
                    -->

                    <!-- Tags Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-resource-tags"
                        placeholder="e.g., data,content,media (comma-separated)"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter tags separated by commas. Tags help categorize and
                        filter resources.
                      </p>
                    </div>
                    <!-- Visibility options -->
                    <div id="edit-resource-visibility" class="mt-4">
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        >Visibility</label
                      >
                      <div class="flex gap-x-6 mt-2">

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="public"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-resource-visibility-public"
                          />
                          <label
                            for="edit-resource-visibility-public"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🌍Public</label
                          >
                        </div>

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="team"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-resource-visibility-team"
                          />
                          <label
                            for="edit-resource-visibility-team"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >👥Team</label
                          >
                        </div>
                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="private"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-resource-visibility-private"
                          />
                          <label
                            for="edit-resource-visibility-private"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🔒Private</label
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      data-action-click="closeModal" data-arg0="resource-edit-modal"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Prompt Detail Modal -->
      <div id="prompt-modal" class="fixed z-40 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Prompt Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-900"
                id="prompt-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="prompt-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Prompt Edit Modal -->
      <div
        id="prompt-edit-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Prompt
              </h3>
              <div class="mt-4">
                <form id="edit-prompt-form" method="POST">
                  <div class="grid grid-cols-1 gap-7">
                    <input type="hidden" name="name" id="edit-prompt-name" />
                    <div class="relative">
                      <label
                        for="edit-prompt-custom-name"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="customName"
                        required
                        id="edit-prompt-custom-name"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Technical Name</label
                      >
                      <input
                        type="text"
                        id="edit-prompt-technical-name"
                        readonly
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-200 dark:border-gray-700 shadow-sm bg-gray-50 dark:bg-gray-800 text-gray-600 dark:text-gray-300 font-mono"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Display Name</label
                      >
                      <input
                        type="text"
                        name="displayName"
                        id="edit-prompt-display-name"
                        placeholder="Custom display name for your UI"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-prompt-description"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Template</label
                      >
                      <textarea
                        name="template"
                        id="edit-prompt-template"
                        class="mt-1 px-3 py-2 block w-full h-48 rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Arguments (JSON)</label
                      >
                      <textarea
                        name="arguments"
                        id="edit-prompt-arguments"
                        class="mt-1 px-3 py- block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <!-- Tags Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-prompt-tags"
                        placeholder="e.g., greeting,template,conversation (comma-separated)"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter tags separated by commas. Tags help categorize and
                        filter prompts.
                      </p>
                    </div>
                    <!-- Visibility options -->
                    <div id="edit-prompt-visibility" class="mt-4">
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        >Visibility</label
                      >
                      <div class="flex gap-x-6 mt-2">

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="public"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-prompt-visibility-public"
                          />
                          <label
                            for="edit-prompt-visibility-public"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🌍Public</label
                          >
                        </div>

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="team"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-prompt-visibility-team"
                          />
                          <label
                            for="edit-prompt-visibility-team"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >👥Team</label
                          >
                        </div>
                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="private"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-prompt-visibility-private"
                          />
                          <label
                            for="edit-prompt-visibility-private"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🔒Private</label
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      data-action-click="closeModal" data-arg0="prompt-edit-modal"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Prompt Test Modal -->
      <div
        id="prompt-test-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <!-- Increased max width (sm:max-w-2xl) for a larger modal -->
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3
                id="prompt-test-modal-title"
                class="text-lg font-medium text-gray-900 dark:text-gray-100"
              >
                Test Prompt
              </h3>
              <!-- Container to show the prompt's description -->
              <div
                id="prompt-test-modal-description"
                class="mb-4 text-gray-700 dark:text-gray-400"
              ></div>
              <form id="prompt-test-form">
                <div
                  id="prompt-test-form-fields"
                  class="space-y-4 text-gray-700 dark:text-gray-400"
                >
                  <!-- Fields will be dynamically inserted here based on the prompt's arguments -->
                </div>

                <!-- Test Result Section -->
                <div class="mt-6 border-t pt-4">
                  <div class="flex justify-between items-center mb-3">
                    <h4
                      class="text-sm font-medium text-gray-900 dark:text-gray-100"
                    >
                      Rendered Prompt
                    </h4>
                    <button
                      type="button"
                      data-action-click="runPromptTest"
                      class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Render Prompt
                    </button>
                  </div>
                  <div id="prompt-test-loading" class="hidden text-center py-4">
                    <div class="inline-flex items-center">
                      <svg
                        class="animate-spin -ml-1 mr-3 h-5 w-5 text-gray-500"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="none"
                        viewBox="0 0 24 24"
                      >
                        <circle
                          class="opacity-25"
                          cx="12"
                          cy="12"
                          r="10"
                          stroke="currentColor"
                          stroke-width="4"
                        ></circle>
                        <path
                          class="opacity-75"
                          fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                        ></path>
                      </svg>
                      Rendering prompt...
                    </div>
                  </div>
                  <div
                    id="prompt-test-result"
                    class="mt-2 bg-gray-50 dark:bg-gray-800 p-3 rounded-md border"
                  >
                    <div
                      class="text-gray-500 dark:text-gray-400 text-sm italic"
                    >
                      Click "Render Prompt" to see the rendered output
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="prompt-test-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Gateway Detail Modal -->
      <div id="gateway-modal" class="fixed z-40 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Gateway Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-400"
                id="gateway-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="gateway-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Test Gateway Modal -->
      <div
        id="gateway-test-modal"
        class="fixed z-40 inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center hidden"
      >
        <div
          class="bg-white dark:bg-gray-900 w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-lg shadow-lg p-6"
        >
          <h2 class="text-xl font-bold mb-4 text-gray-800 dark:text-gray-100">
            Test Gateway Connectivity
          </h2>
          <form
            id="gateway-test-form"
            class="space-y-4 text-gray-800 dark:text-gray-100"
            novalidate
          >
            <div class="relative">
              <label
                for="gateway-test-url"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Server URL</label
              >
              <input
                required
                name="url"
                type="text"
                id="gateway-test-url"
                class="mt-1 px-3 py-2 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
              />
              <p
                data-error-message-for="url"
                class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible"
                >Server URL is required.</p
              >
            </div>
            <div>
              <label
                for="gateway-test-method"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Method</label
              >
              <select
                required
                name="method"
                id="gateway-test-method"
                class="mt-1 px-3 py-2 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
              >
                <option>GET</option>
                <option>POST</option>
                <option>PUT</option>
                <option>DELETE</option>
                <option>PATCH</option>
              </select>
            </div>
            <div>
              <label
                for="gateway-test-path"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Path</label
              >
              <input
                id="gateway-test-path"
                name="path"
                type="text"
                placeholder="/health"
                class="mt-1 px-3 py-2 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
              />
            </div>
            <div>
              <label
                for="gateway-test-headers"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Headers (JSON)</label
              >
              <textarea
                id="gateway-test-headers"
                class="mt-1 px-3 py-2 block w-full rounded-md shadow-sm p-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-300 placeholder-gray-600 dark:placeholder-gray-400"
                placeholder="Enter request headers as JSON"
              ></textarea>
            </div>

            <div>
              <label
                for="gateway-test-content-type"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Content-Type</label
              >
              <select
                id="gateway-test-content-type"
                name="content_type"
                class="mt-1 px-3 py-2 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
                data-action-change="updateBodyLabel"
              >
                <option value="application/json">application/json</option>
                <option value="application/x-www-form-urlencoded">application/x-www-form-urlencoded</option>
              </select>
            </div>

            <div>
              <label
                for="gateway-test-body"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                id="gateway-test-body-label"
                >Body (JSON)</label
              >
              <textarea
                id="gateway-test-body"
                name="body"
                class="mt-1 px-3 py-2 block w-full rounded-md shadow-sm p-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-300 placeholder-gray-600 dark:placeholder-gray-400"
                placeholder="Enter request body as JSON"
              ></textarea>
            </div>

            <div class="flex">
              <button
                type="submit"
                id="gateway-test-submit"
                class="w-full text-center px-3 py-1 bg-indigo-600 text-white rounded hover:bg-indigo-700"
              >
                Test
              </button>
              <p class="p-1"></p>
              <button
                id="gateway-test-close"
                type="button"
                class="w-full text-center px-3 py-1 border border-blue-600 rounded bg-white text-gray-700 hover:bg-gray-200"
              >
                Close
              </button>
            </div>

            <div
              id="gateway-test-loading"
              class="mt-4 hidden flex items-center justify-center"
            >
              <div
                class="spinner border-t-4 border-blue-600 w-6 h-6 rounded-full animate-spin"
              ></div>
            </div>

            <div id="gateway-test-result" class="hidden">
              <label class="block text-sm font-medium text-gray-700"
                >Response</label
              >
              <div
                id="gateway-test-response-json"
                class="bg-gray-100 p-2 rounded overflow-auto text-sm text-gray-800 max-h-64"
              ></div>
            </div>
          </form>
        </div>
      </div>

      <!-- Gateway Edit Modal -->
      <div
        id="gateway-edit-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Gateway
              </h3>
              <div class="mt-4">
                <form id="edit-gateway-form" method="POST">
                  <div class="grid grid-cols-1 gap-7">
                    <div class="relative">
                      <label
                        for="edit-gateway-name"
                        class="block text-sm font-medium text-gray-700"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-gateway-name"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
                    </div>
                    <div class="relative">
                      <label
                        for="edit-gateway-url"
                        class="block text-sm font-medium text-gray-700"
                        >URL</label
                      >
                      <input
                        type="url"
                        name="url"
                        required
                        id="edit-gateway-url"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p data-error-message-for="url" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">URL is required.</p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-gateway-description"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-gateway-tags"
                        placeholder="e.g., production,external,api-gateway (comma-separated)"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        Separate multiple tags with commas. Tags will be
                        automatically normalized.
                      </p>
                    </div>

                    <!-- Visibility options -->
                    <div id="edit-gateway-visibility" class="mt-4">
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        >Visibility</label
                      >
                      <div class="flex gap-x-6 mt-2">
                        <!-- Add gap-x-6 for more space between radio options -->

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="public"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-gateway-visibility-public"
                          />
                          <label
                            for="edit-gateway-visibility-public"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🌍Public</label
                          >
                        </div>

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="team"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-gateway-visibility-team"
                          />
                          <label
                            for="edit-gateway-visibility-team"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >👥Team</label
                          >
                        </div>
                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="private"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-gateway-visibility-private"
                          />
                          <label
                            for="edit-gateway-visibility-private"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🔒Private</label
                          >
                        </div>
                      </div>
                    </div>

                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Transport Type</label
                      >
                      <select
                        name="transport"
                        id="edit-gateway-transport"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      >
                        <option value="SSE" selected>SSE</option>
                        <option value="STREAMABLEHTTP">Streamable HTTP</option>
                      </select>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Authentication Type</label
                      >
                      <select
                        name="auth_type"
                        id="auth-type-gw-edit"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      >
                        <option value="">None</option>
                        <option value="basic">Basic</option>
                        <option value="bearer">Bearer Token</option>
                        <option value="authheaders">Custom Headers</option>
                        <option value="oauth">OAuth 2.0</option>
                        <option value="query_param">Query Parameter (INSECURE)</option>
                      </select>
                    </div>
                    <div id="auth-query_param-fields-gw-edit" style="display: none">
                      <div class="p-3 mb-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-700 rounded-md">
                        <p class="text-xs text-amber-700 dark:text-amber-400">
                          <strong>Security Warning:</strong> API keys in URLs may appear in proxy logs, browser history, and server access logs.
                          Only use when the upstream server requires this authentication method.
                        </p>
                      </div>
                      <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >Query Parameter Name</label
                        >
                        <input
                          type="text"
                          name="auth_query_param_key"
                          placeholder="e.g., tavilyApiKey"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                      <div class="mt-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >API Key Value</label
                        >
                        <div class="relative">
                          <input
                            type="password"
                            name="auth_query_param_value"
                            id="auth-query-param-value-gw-edit"
                            autocomplete="off"
                            data-sensitive-label="API key"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          />
                        </div>
                      </div>
                    </div>
                    <div id="auth-basic-fields-gw-edit" style="display: none">
                      <div>
                        <label class="block text-sm font-medium text-gray-700"
                          >Username</label
                        >
                        <input
                          type="text"
                          name="auth_username"
                          autocomplete="off"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Password</label
                      >
                      <div class="relative">
                        <input
                          type="password"
                          name="auth_password"
                          id="auth-password-gw-edit"
                          autocomplete="off"
                          data-sensitive-label="password"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                    </div>
                  </div>
                  <div id="auth-bearer-fields-gw-edit" style="display: none">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Token</label
                      >
                      <div class="relative">
                        <input
                          type="password"
                          name="auth_token"
                          id="auth-token-gw-edit"
                          autocomplete="off"
                          data-sensitive-label="token"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                    </div>
                  </div>
                    <div id="auth-headers-fields-gw-edit" style="display: none">
                      <div class="space-y-3">
                        <div class="flex items-center justify-between">
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Custom Headers
                          </label>
                          <button
                            type="button"
                            data-action-click="addAuthHeader" data-arg0="auth-headers-container-gw-edit"
                            class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                          >
                            <svg
                              class="w-4 h-4 mr-1"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                              ></path>
                            </svg>
                            Add Header
                          </button>
                        </div>
                        <div
                          id="auth-headers-container-gw-edit"
                          class="space-y-2"
                        >
                          <!-- Headers will be added dynamically here -->
                        </div>
                        <input
                          type="hidden"
                          name="auth_headers"
                          id="auth-headers-json-gw-edit"
                        />
                      </div>
                    </div>

                    <!-- OAuth Configuration Fields -->
                    <div id="auth-oauth-fields-gw-edit" style="display: none">
                      <div class="space-y-4">
                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Grant Type
                          </label>
                          <select
                            name="oauth_grant_type"
                            id="oauth-grant-type-gw-edit"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          >
                            <option value="authorization_code" selected>
                              Authorization Code (User Delegation)
                            </option>
                            <option value="client_credentials">
                              Client Credentials (Machine-to-Machine)
                            </option>
                            <option value="password">
                              Resource Owner Password Credentials (Keycloak/Legacy)
                            </option>
                          </select>
                        </div>

                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Issuer URL
                          </label>
                          <div class="mt-1 flex gap-2">
                            <input
                              type="url"
                              name="oauth_issuer"
                              id="oauth-issuer-gw-edit"
                              class="px-1.5 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="http://localhost:3003 or https://oauth.example.com"
                            />
                            <button
                              type="button"
                              data-action-click="discoverOAuthEndpoints" data-arg0="this"
                              class="shrink-0 px-3 py-1.5 text-sm font-medium rounded-md border border-indigo-500 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900 transition-colors"
                              title="Auto-discover token &amp; authorization endpoints from issuer metadata"
                            >🔍 Discover</button>
                          </div>
                          <p class="mt-1 text-sm text-gray-500">
                            The OAuth Authorization Server issuer URL. Required for DCR.
                          </p>
                        <div class="oauth-discover-status mt-1 hidden"></div>
                        </div>

                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Client ID <span class="text-gray-500">(optional for DCR)</span>
                          </label>
                          <input
                            type="text"
                            name="oauth_client_id"
                            id="oauth-client-id-gw-edit"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Leave empty for auto-registration via DCR"
                          />
                          <p class="mt-1 text-sm text-blue-600">
                            💡 Leave empty if the server supports DCR - credentials will be auto-registered
                          </p>
                        </div>

                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Client Secret <span class="text-gray-500">(optional for DCR)</span>
                          </label>
                          <input
                            type="password"
                            name="oauth_client_secret"
                            id="oauth-client-secret-gw-edit"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Leave empty for auto-registration via DCR"
                          />
                          <p class="mt-1 text-sm text-gray-500">
                            Leave blank to retain the current secret (when editing).
                          </p>
                          <p class="mt-1 text-sm text-blue-600">
                            💡 Leave empty if the server supports DCR - credentials will be auto-registered
                          </p>
                        </div>

                        <div id="oauth-username-field-gw-edit" style="display: none;">
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Username <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                          </label>
                          <input
                            type="text"
                            name="oauth_username"
                            id="oauth-username-gw-edit"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="systemadmin@system.com"
                          />
                          <p class="mt-1 text-sm text-gray-500">
                            Required for Resource Owner Password Credentials grant type (Keycloak).
                          </p>
                        </div>

                        <div id="oauth-password-field-gw-edit" style="display: none;">
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Password <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                          </label>
                          <input
                            type="password"
                            name="oauth_password"
                            id="oauth-password-gw-edit"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Enter password"
                          />
                          <p class="mt-1 text-sm text-gray-500">
                            Required for Resource Owner Password Credentials grant type (Keycloak).
                          </p>
                        </div>

                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Token URL
                          </label>
                          <input
                            type="url"
                            name="oauth_token_url"
                            id="oauth-token-url-gw-edit"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="https://oauth.example.com/token"
                          />
                        </div>

                        <div
                          id="oauth-auth-code-fields-gw-edit"
                        >
                          <div>
                            <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                            >
                              Authorization URL
                            </label>
                            <input
                              type="url"
                              name="oauth_authorization_url"
                              id="oauth-authorization-url-gw-edit"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="https://oauth.example.com/authorize"
                            />
                            <p class="mt-1 text-sm text-gray-500">
                              The OAuth provider's authorization endpoint URL
                            </p>
                          </div>

                          <div>
                            <label
                              class="mt-1 block text-sm font-medium text-gray-700 dark:text-gray-300"
                            >
                              Redirect URI
                            </label>
                            <input
                              type="url"
                              name="oauth_redirect_uri"
                              id="oauth-redirect-uri-gw-edit"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="https://gateway.example.com/oauth/callback"
                            />
                            <p class="mt-1 text-sm text-gray-500">
                              This must match the redirect URI configured in
                              your OAuth application
                            </p>
                            <p class="mt-1 text-sm text-blue-600 font-medium">
                              💡 Use:
                              <code class="bg-blue-100 px-1 rounded"
                                >{{ request.base_url }}oauth/callback</code
                              >
                            </p>
                          </div>

                          <div>
                            <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                            >
                              Scopes
                            </label>
                            <input
                              type="text"
                              name="oauth_scopes"
                              id="oauth-scopes-gw-edit"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="repo read:user (space-separated)"
                            />
                            <p class="mt-1 text-sm text-gray-500">
                              Space-separated list of OAuth scopes (e.g., "repo
                              read:user")
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="mt-4">
                      <label class="flex items-center">
                        <input
                          type="checkbox"
                          name="one_time_auth"
                          id="single-use-auth-gw-edit"
                          class="form-checkbox h-5 w-5 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 dark:bg-gray-800 dark:border-gray-600"
                          x-tooltip="'💡This will not store the server credentials, Some features may not work.'"
                          data-action-change="toggleOneTimeAuthHint" data-arg0="single-use-auth-hint-gw-edit"
                        />
                        <span
                          class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300"
                        >
                          Use one-time authentication
                        </span>
                      </label>
                      <p
                        id="single-use-auth-hint-gw-edit"
                        style="display: none"
                        class="mt-2 text-sm text-gray-700 dark:text-gray-300 bg-indigo-50 dark:bg-indigo-900/30 border border-indigo-200 dark:border-indigo-700 rounded-md p-2"
                      >
                        ⚠️ NOTE: Authentication won't be stored in the gateway. Configure Passthrough headers for reuse. Health checks will be disabled.
                      </p>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        >Passthrough Headers</label
                      >
                      <small
                        class="text-gray-500 dark:text-gray-400 block mb-2"
                      >
                        List of headers to pass through from client requests
                        (comma-separated, e.g., "Authorization, X-Tenant-Id,
                        X-Trace-Id"). Leave empty to use global defaults.
                      </small>
                      <input
                        type="text"
                        name="passthrough_headers"
                        id="edit-gateway-passthrough-headers"
                        placeholder="Authorization, X-Tenant-Id, X-Trace-Id"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      data-action-click="closeModal" data-arg0="gateway-edit-modal"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- A2A Agent Edit Modal -->
       <div id="a2a-edit-modal" class="fixed z-40 inset-0 overflow-y-auto hidden">
          <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
              <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <div
              class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
            >
              <div class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                  Edit A2A Agent
                </h3>
                <div class="mt-4">
                  <form id="edit-a2a-agent-form" method="POST">
                    <div class="grid grid-cols-1 gap-7">
                      <!-- Agent Name -->
                      <div class="relative">
                        <label for="a2a-agent-name-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                          Agent Name
                        </label>
                        <input
                          type="text"
                          id="a2a-agent-name-edit"
                          name="name"
                          required
                          placeholder="my-assistant-agent"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                        <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Agent Name is required.</p>
                      </div>

                      <!-- Endpoint URL -->
                      <div class="relative">
                        <label for="a2a-agent-endpoint-url-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                          Endpoint URL
                        </label>
                        <input
                          type="url"
                          id="a2a-agent-endpoint-url-edit"
                          name="endpoint_url"
                          required
                          placeholder="https://api.example.com/agent"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                        <p data-error-message-for="url" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Endpoint URL is required.</p>
                      </div>

                      <!-- Agent Type -->
                      <div>
                        <label for="a2a-agent-type-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                          Agent Type
                        </label>
                        <select
                          id="a2a-agent-type-edit"
                          name="agent_type"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                        >
                          <option value="generic">Generic</option>
                          <option value="openai">OpenAI</option>
                          <option value="anthropic">Anthropic</option>
                          <option value="custom">Custom</option>
                        </select>
                      </div>

                      <!-- Authentication Type -->
                      <div>
                        <label for="auth-type-a2a-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                          Authentication Type
                        </label>
                        <select
                          id="auth-type-a2a-edit"
                          name="auth_type"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                        >
                          <option value="">None</option>
                          <option value="basic">Basic</option>
                          <option value="bearer">Bearer Token</option>
                          <option value="authheaders">Custom Headers</option>
                          <option value="oauth">OAuth 2.0</option>
                          <option value="query_param">Query Parameter (INSECURE)</option>
                        </select>
                      </div>

                      <!-- Basic Auth -->
                      <div id="auth-basic-fields-a2a-edit" style="display: none">
                        <div>
                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Username</label>
                          <input
                            type="text"
                            name="auth_username"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                  focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                          />
                        </div>
                        <div>
                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Password</label>
                          <input
                            type="password"
                            name="auth_password"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                  focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                          />
                        </div>
                      </div>

                      <!-- Bearer Token -->
                      <div id="auth-bearer-fields-a2a-edit" style="display: none">
                        <div>
                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Token</label>
                          <input
                            type="password"
                            name="auth_token"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                  focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                          />
                        </div>
                      </div>

                      <!-- Custom Headers -->
                      <div id="auth-headers-fields-a2a-edit" style="display: none">
                        <div class="space-y-3">
                          <div class="flex items-center justify-between">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Custom Headers</label>
                            <button
                              type="button"
                              data-action-click="addAuthHeader" data-arg0="auth-headers-container-a2a-edit"
                              class="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md
                                    text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                            >
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                              </svg>
                              Add Header
                            </button>
                          </div>
                          <div id="auth-headers-container-a2a-edit" class="space-y-2"></div>
                          <input type="hidden" name="auth_headers" id="auth-headers-json-a2a-edit" />
                        </div>
                      </div>

                      <!-- Query Parameter Auth Fields -->
                      <div id="auth-query_param-fields-a2a-edit" style="display: none">
                        <div class="p-3 mb-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-700 rounded-md">
                          <p class="text-xs text-amber-700 dark:text-amber-400">
                            <strong>Security Warning:</strong> API keys in URLs may appear in proxy logs, browser history, and server access logs.
                            Consider using bearer tokens or headers instead (CWE-598).
                          </p>
                        </div>
                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Query Parameter Name
                          </label>
                          <input
                            type="text"
                            name="auth_query_param_key"
                            id="auth-query-param-key-a2a-edit"
                            placeholder="e.g., api_key"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          />
                        </div>
                        <div class="mt-3">
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Query Parameter Value
                          </label>
                          <div class="relative">
                            <input
                              type="password"
                              name="auth_query_param_value"
                              id="auth-query-param-value-a2a-edit"
                              autocomplete="off"
                              data-sensitive-label="API key"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            />
                          </div>
                        </div>
                      </div>

                      <!-- OAuth Fields -->
                      <div id="auth-oauth-fields-a2a-edit" style="display: none">
                        <div class="space-y-4">
                          <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Grant Type
                          </label>
                          <select
                            name="oauth_grant_type"
                            id="oauth-grant-type-a2a-edit"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          >
                            <option value="authorization_code" selected>
                            Authorization Code (User Delegation)
                            </option>
                            <option value="client_credentials">
                            Client Credentials (Machine-to-Machine)
                            </option>
                            <option value="password">
                            Resource Owner Password Credentials (Keycloak/Legacy)
                            </option>
                          </select>
                          </div>

                          <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Issuer URL
                          </label>
                          <div class="mt-1 flex gap-2">
                            <input
                              type="url"
                              name="oauth_issuer"
                              id="oauth-issuer-a2a-edit"
                              class="px-1.5 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="http://localhost:3003 or https://oauth.example.com"
                            />
                            <button
                              type="button"
                              data-action-click="discoverOAuthEndpoints" data-arg0="this"
                              class="shrink-0 px-3 py-1.5 text-sm font-medium rounded-md border border-indigo-500 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900 transition-colors"
                              title="Auto-discover token &amp; authorization endpoints from issuer metadata"
                            >🔍 Discover</button>
                          </div>

                          <!--
                          <p class="mt-1 text-sm text-gray-500">
                            The OAuth Authorization Server issuer URL. Required for DCR (Dynamic Client Registration).
                          </p>
                          <div class="oauth-discover-status mt-1 hidden"></div>
                          -->

                          </div>

                          <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Client ID <span class="text-gray-500">(optional for DCR)</span>
                          </label>
                          <input
                            type="text"
                            name="oauth_client_id"
                            id="oauth-client-id-a2a-edit"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Leave empty for auto-registration via DCR"
                          />

                          <!--
                          <p class="mt-1 text-sm text-blue-600">
                            💡 Leave empty if the server supports DCR - credentials will be auto-registered
                          </p>
                          -->

                          </div>

                          <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Client Secret <span class="text-gray-500">(optional for DCR)</span>
                          </label>
                          <input
                            type="password"
                            name="oauth_client_secret"
                            id="oauth-client-secret-a2a-edit"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Leave empty for auto-registration via DCR"
                          />

                          <!--
                          <p class="mt-1 text-sm text-blue-600">
                            💡 Leave empty if the server supports DCR - credentials will be auto-registered
                          </p>
                          -->

                          </div>

                          <div id="oauth-username-field-a2a-edit" style="display: none;">
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Username <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                          </label>
                          <input
                            type="text"
                            name="oauth_username"
                            id="oauth-username-a2a-edit"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="systemadmin@system.com"
                          />

                          <!--
                          <p class="mt-1 text-sm text-gray-500">
                            Required for Resource Owner Password Credentials grant type (Keycloak).
                          </p>
                          -->

                          </div>

                          <div id="oauth-password-field-a2a-edit" style="display: none;">
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Password <span class="text-red-500">*</span> <span class="text-gray-500">(for password grant)</span>
                          </label>
                          <input
                            type="password"
                            name="oauth_password"
                            id="oauth-password-a2a-edit"
                            autocomplete="off"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Enter password"
                          />

                          <!--
                          <p class="mt-1 text-sm text-gray-500">
                            Required for Resource Owner Password Credentials grant type (Keycloak).
                          </p>
                          -->

                          </div>

                          <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Token URL
                          </label>
                          <input
                            type="url"
                            name="oauth_token_url"
                            id="oauth-token-url-a2a-edit"
                            class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="https://oauth.example.com/token"
                          />
                          </div>

                          <div id="oauth-auth-code-fields-a2a-edit">
                            <div>
                              <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                              >
                              Authorization URL
                              </label>
                              <input
                              type="url"
                              name="oauth_authorization_url"
                              id="oauth-authorization-url-a2a-edit"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="https://oauth.example.com/authorize"
                              />
                              <p class="mt-1 text-sm text-gray-500">
                              The OAuth provider's authorization endpoint URL
                              </p>
                            </div>

                            <div>
                              <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                              >
                              Redirect URI
                              </label>
                              <input
                              type="url"
                              name="oauth_redirect_uri"
                              id="oauth-redirect-uri-a2a-edit"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="https://a2aagent.example.com/oauth/callback"
                              />
                              <p class="mt-1 text-sm text-gray-500">
                              This must match the redirect URI configured in your
                              OAuth application
                              </p>
                              <p class="mt-1 text-sm text-blue-600 font-medium">
                              💡 Use:
                              <code class="bg-blue-100 px-1 rounded"
                                >{{ request.base_url }}oauth/callback</code
                              >
                              </p>
                            </div>
                          </div>

                          <div>
                            <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                            >
                              Scopes
                            </label>
                            <input
                              type="text"
                              name="oauth_scopes"
                              id="oauth-scopes-a2a-edit"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="repo read:user (space-separated)"
                            />
                            <p class="mt-1 text-sm text-gray-500">
                              Space-separated list of OAuth scopes (e.g., "repo
                              read:user")
                            </p>
                          </div>
                        </div>
                      </div>

                      <!-- Description -->
                      <div>
                        <label for="a2a-agent-description-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                          Description
                        </label>
                        <textarea
                          id="a2a-agent-description-edit"
                          name="description"
                          rows="2"
                          placeholder="Description of the agent's capabilities"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        ></textarea>
                      </div>

                      <!-- Tags -->
                      <div>
                        <label for="a2a-agent-tags-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                          Tags
                        </label>
                        <input
                          type="text"
                          id="a2a-agent-tags-edit"
                          name="tags"
                          placeholder="ai,assistant,production (comma-separated)"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm
                                focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>

                      <!-- UAID (Universal Agent ID) Section -->
                      <div class="border-t border-gray-200 dark:border-gray-700 pt-6">
                        <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                          Universal Agent ID (UAID) Settings
                        </h4>

                        <!-- Generate UAID Checkbox -->
                        <div class="flex items-start mb-4">
                          <input
                            type="checkbox"
                            id="a2a-generate-uaid-edit"
                            name="generate_uaid"
                            value="true"
                            class="h-4 w-4 mt-0.5 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded dark:bg-gray-800 dark:border-gray-600"
                            data-action-change="toggleUAIDFields" data-arg0="a2a-edit"
                          />
                          <label for="a2a-generate-uaid-edit" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">
                            Generate UAID for cross-gateway routing
                            <span class="text-xs text-gray-500 dark:text-gray-400 block mt-1">
                              Enables zero-config federation without manual peer setup. The UAID embeds endpoint URL, protocol, and registry for automatic discovery.
                            </span>
                          </label>
                        </div>

                        <!-- UAID Fields (shown when checkbox is checked) -->
                        <div id="uaid-fields-a2a-edit" style="display: none;" class="space-y-4 pl-6 border-l-2 border-indigo-200 dark:border-indigo-800">

                          <!-- UAID Registry -->
                          <div>
                            <label for="a2a-uaid-registry-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                              Registry Name
                            </label>
                            <input
                              type="text"
                              id="a2a-uaid-registry-edit"
                              name="uaid_registry"
                              value="context-forge"
                              placeholder="context-forge"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            />
                            <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                              Registry identifier (e.g., "context-forge", "hol-registry")
                            </p>
                          </div>

                          <!-- UAID Protocol -->
                          <div>
                            <label for="a2a-uaid-protocol-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                              Protocol
                            </label>
                            <select
                              id="a2a-uaid-protocol-edit"
                              name="uaid_protocol"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
                            >
                              <option value="a2a" selected>A2A</option>
                              <option value="mcp">MCP</option>
                              <option value="rest">REST</option>
                              <option value="grpc">gRPC</option>
                            </select>
                            <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                              Agent communication protocol
                            </p>
                          </div>

                          <!-- UAID Native ID Override -->
                          <div>
                            <label for="a2a-uaid-native-id-override-edit" class="block text-sm font-medium text-gray-700 dark:text-gray-400">
                              Native ID Override (Optional)
                            </label>
                            <input
                              type="text"
                              id="a2a-uaid-native-id-override-edit"
                              name="uaid_native_id_override"
                              placeholder="http://gateway.example.com:4445"
                              class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            />
                            <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                              Override the routing address in UAID. Leave empty to use endpoint URL. Use when gateway address differs from agent endpoint (e.g., gateway proxies to agent).
                            </p>
                          </div>

                          <!-- Info Box -->
                          <div class="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md">
                            <p class="text-xs text-blue-700 dark:text-blue-300">
                              <strong>ℹ️ About UAIDs:</strong> Universal Agent IDs enable cross-gateway routing without manual configuration.
                              The UAID embeds the endpoint URL, protocol, and registry info for automatic discovery.
                              <br/><br/>
                              <strong>Domain Allowlist:</strong> Set <code class="px-1 py-0.5 bg-blue-100 dark:bg-blue-800 rounded">UAID_ALLOWED_DOMAINS</code> in .env to control which domains can be used.
                            </p>
                          </div>

                        </div>
                      </div>

                      <!-- Visibility -->
                      <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400">Visibility</label>
                        <div class="flex gap-x-6 mt-2">

                          <div class="flex items-center">
                            <input
                              type="radio"
                              name="visibility"
                              value="public"
                              id="edit-a2a-visibility-public"
                              class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                              checked
                            />
                            <label for="edit-a2a-visibility-public" class="ml-2 text-sm text-gray-700 dark:text-gray-400">🌍 Public</label>
                          </div>

                          <div class="flex items-center">
                            <input
                              type="radio"
                              name="visibility"
                              value="team"
                              id="edit-a2a-visibility-team"
                              class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            />
                            <label for="edit-a2a-visibility-team" class="ml-2 text-sm text-gray-700 dark:text-gray-400">👥 Team</label>
                          </div>
                          <div class="flex items-center">
                            <input
                              type="radio"
                              name="visibility"
                              value="private"
                              id="edit-a2a-visibility-private"
                              class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            />
                            <label for="edit-a2a-visibility-private" class="ml-2 text-sm text-gray-700 dark:text-gray-400">🔒 Private</label>
                          </div>
                        </div>
                      </div>

                      <div>
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                          >Passthrough Headers</label
                        >
                        <small
                          class="text-gray-500 dark:text-gray-400 block mb-2"
                        >
                          List of headers to pass through from client requests
                          (comma-separated, e.g., "Authorization, X-Tenant-Id,
                          X-Trace-Id"). Leave empty to use global defaults.
                        </small>
                        <input
                          type="text"
                          name="passthrough_headers"
                          id="edit-a2a-agent-passthrough-headers"
                          placeholder="Authorization, X-Tenant-Id, X-Trace-Id"
                          class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>

                      <!-- Hidden Config Fields -->
                      <input type="hidden" name="capabilities" id="a2a-agent-capabilities-edit" value="{}" />
                      <input type="hidden" name="config" id="a2a-agent-config-edit" value="{}" />

                      <!-- Footer Buttons -->
                      <div class="mt-6 flex justify-end space-x-3">
                        <button
                          type="button"
                          data-action-click="closeModal" data-arg0="a2a-edit-modal"
                          class="px-4 py-2 border rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 dark:text-gray-300"
                        >
                          Cancel
                        </button>
                        <button
                          type="submit"
                          class="px-4 py-2 rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
                        >
                          Save Changes
                        </button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
       </div>



      <!-- Server Detail Modal -->
      <div id="server-modal" class="fixed z-40 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Server Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-900"
                id="server-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="server-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Server Edit Modal -->
      <div
        id="server-edit-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Server
              </h3>
              <div class="mt-4">
                <form id="edit-server-form" method="POST">
                  <div class="grid grid-cols-1 gap-7">
                    <!-- Existing fields -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >UUID</label
                      >
                      <input
                        type="text"
                        name="id"
                        id="edit-server-id"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                        Changing UUID will create a new server endpoint. Use
                        with caution.
                      </p>
                    </div>
                    <div class="relative">
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-server-name"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p data-error-message-for="name" class="absolute top-full left-0 mt-1 text-xs text-red-500 invisible">Name is required.</p>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-server-description"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Icon URL</label
                      >
                      <input
                        type="url"
                        name="icon"
                        id="edit-server-icon"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>

                    <!-- Tags Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-server-tags"
                        placeholder="e.g., api,data-processing,external (comma-separated)"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter tags separated by commas. Tags help categorize and
                        filter servers.
                      </p>
                    </div>

                    <!-- Visibility options -->
                    <div id="edit-server-visibility" class="mt-4">
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        >Visibility</label
                      >
                      <div class="flex gap-x-6 mt-2">
                        <!-- Add gap-x-6 for more space between radio options -->

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="public"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-server-visibility-public"
                          />
                          <label
                            for="edit-server-visibility-public"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🌍Public</label
                          >
                        </div>

                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="team"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-server-visibility-team"
                          />
                          <label
                            for="edit-server-visibility-team"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >👥Team</label
                          >
                        </div>
                        <div class="flex items-center">
                          <input
                            type="radio"
                            name="visibility"
                            value="private"
                            class="form-radio h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                            id="edit-server-visibility-private"
                          />
                          <label
                            for="edit-server-visibility-private"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🔒Private</label
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                  {% if selected_team_id %}
                  <!-- View Public toggle for team-scoped server editing -->
                  <div class="mt-4" id="edit-server-view-public-container">
                    <div class="flex items-center">
                      <input
                        type="checkbox"
                        id="edit-server-view-public"
                        class="form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                      />
                      <label
                        for="edit-server-view-public"
                        class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-400"
                        >View Public &mdash; Include publicly available MCP servers, tools, resources, and prompts</label
                      >
                    </div>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      When enabled, public items from across the platform are shown alongside your team's items in the selectors below.
                    </p>
                  </div>
                  {% endif %}
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
                    <div
                      class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-600"
                    >
                    <label
                    class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                    for="associatedEditGateways"
                  >
                    MCP Servers
                  </label>
                  <input
                    type="text"
                    id="searchEditGateways"
                    placeholder="Search for MCP servers..."
                    class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                  />
                  <div
                    id="associatedEditGateways"
                    class="max-h-60 overflow-y-auto rounded-md border border-gray-300 dark:border-gray-700 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                    hx-get="{{ root_path }}/admin/gateways/partial?page=1&per_page=50&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                    hx-trigger="load"
                    hx-swap="innerHTML"
                  >
                    <!-- Gateway checkboxes will be loaded here via HTMX -->
                    <div class="flex items-center justify-center p-4">
                      <span class="text-gray-500 dark:text-gray-400 text-sm">Loading MCP servers...</span>
                    </div>
                  </div>
                  <p
                    id="noEditGatewayMessage"
                    class="text-gray-700 dark:text-gray-300 mt-2"
                    style="display: none"
                  >
                    No MCP server found containing "<span id="searchQueryEditServers"></span>"
                  </p>
                  <div class="flex justify-end mt-3 gap-2">
                    <button
                      type="button"
                      id="selectAllEditGatewayBtn"
                      class="px-3 py-1 text-sm font-semibold text-green-600 border border-green-600 rounded-md hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-green-300 focus:ring-offset-1"
                      aria-label="Select all MCP servers"
                    >
                      Select All
                    </button>

                    <button
                      type="button"
                      id="clearAllEditGatewayBtn"
                      class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                      aria-label="Clear all selected MCP servers"
                    >
                      Clear All
                    </button>
                  </div>

                  <p class="text-sm text-gray-600 dark:text-gray-400 mt-2">
                    Choose an MCP server, then select the tools, resources, and prompts to configure your virtual server.
                  </p>

                  <!-- Selected pills -->
                  <div
                    id="selectedEditGatewayPills"
                    class="mt-4 flex flex-wrap gap-2"
                  ></div>

                  <!-- Warning message -->
                  <div
                    id="selectedEditGatewayWarning"
                    class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                    aria-live="polite"
                  ></div>
                    </div>
                    <div
                      class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-600"
                    >
                      <div class="flex items-center justify-between mb-2">
                        <label
                          for="edit-server-tools"
                          class="block text-sm font-semibold text-gray-700 dark:text-gray-300"
                        >
                          Associated Tools
                        </label>
                        <button
                          type="button"
                          data-action-click="refreshToolsForSelectedGateways" data-arg0="this"
                          class="px-2 py-1 text-xs font-medium text-green-700 dark:text-green-400 border border-green-600 dark:border-green-500 rounded-md hover:bg-green-50 dark:hover:bg-green-900/20 transition-colors"
                          x-tooltip="'Re-fetch tools from selected MCP gateways and reload this list'"
                        >Refresh from MCPs</button>
                      </div>
                       <input
                        type="text"
                        id="searchEditTools"
                        placeholder="Search for tools..."
                        class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                      />
                      <div
                        id="edit-server-tools"
                        class="max-h-60 overflow-y-auto rounded-md border border-gray-600 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                        hx-get="{{ root_path }}/admin/tools/partial?page=1&per_page=20&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                        hx-trigger="load"
                        hx-swap="innerHTML"
                        hx-on:htmx:after-swap="window.Admin?.initToolSelect?.('edit-server-tools', 'selectedEditToolsPills', 'selectedEditToolsWarning', 6, 'selectAllEditToolsBtn', 'clearAllEditToolsBtn')"
                      >
                        <!-- Tools will be loaded via HTMX -->
                        <div class="text-center py-4 text-gray-500 dark:text-gray-400">
                          <svg class="animate-spin h-5 w-5 text-indigo-600 dark:text-indigo-400 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span class="ml-2">Loading tools...</span>
                        </div>
                      </div>
                      <p
                        id="noEditToolsMessage"
                        class="text-gray-700 dark:text-gray-300 mt-2"
                        style="display: none"
                      >
                        No tool found containing "<span id="searchQueryEditTools"></span>"
                      </p>
                      <div class="flex justify-end gap-3 mt-3">
                        <button
                          type="button"
                          id="selectAllEditToolsBtn"
                          class="px-3 py-1 text-sm font-semibold text-green-600 border border-green-600 rounded-md hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-green-300 focus:ring-offset-1"
                          aria-label="Select all tools"
                        >
                          Select All
                        </button>

                        <button
                          type="button"
                          id="clearAllEditToolsBtn"
                          class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                          aria-label="Clear all selected tools"
                        >
                          Clear All
                        </button>
                      </div>

                      <!-- Selected pills -->
                      <div
                        id="selectedEditToolsPills"
                        class="mt-4 flex flex-wrap gap-2"
                      ></div>

                      <!-- Warning message -->
                      <div
                        id="selectedEditToolsWarning"
                        class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                        aria-live="polite"
                      ></div>
                    </div>
                  </div>
                <div class="mt-6">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div
                      class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-600"
                    >
                      <label
                        for="edit-server-resources"
                        class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Associated Resources
                      </label>
                      <input
                        type="text"
                        id="searchEditResources"
                        placeholder="Search for resources..."
                        class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                      />
                      <div
                        id="edit-server-resources"
                        class="max-h-60 overflow-y-auto rounded-md border border-gray-600 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                        hx-get="{{ root_path }}/admin/resources/partial?page=1&per_page=20&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                        hx-trigger="load"
                        hx-swap="innerHTML"
                        hx-on:htmx:after-swap="window.Admin?.initResourceSelect?.('edit-server-resources', 'selectedEditResourcesPills', 'selectedEditResourcesWarning', 6, 'selectAllEditResourcesBtn', 'clearAllEditResourcesBtn')"
                      >
                        <!-- Resources will be loaded via HTMX -->
                        <div class="text-center py-4 text-gray-500 dark:text-gray-400">
                          <svg class="animate-spin h-5 w-5 text-indigo-600 dark:text-indigo-400 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span class="ml-2">Loading resources...</span>
                        </div>
                      </div>
                      <p
                        id="noEditResourcesMessage"
                        class="text-gray-700 dark:text-gray-300 mt-2"
                        style="display: none"
                      >
                        No resource found containing "<span id="searchQueryEditResources"></span>"
                      </p>
                      <div class="flex justify-end gap-3 mt-3">
                        <button
                          type="button"
                          id="selectAllEditResourcesBtn"
                          class="px-3 py-1 text-sm font-semibold text-blue-600 border border-blue-600 rounded-md hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-offset-1"
                          aria-label="Select all resources"
                        >
                          Select All
                        </button>
                        <button
                          type="button"
                          id="clearAllEditResourcesBtn"
                          class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                          aria-label="Clear all selected resources"
                        >
                          Clear All
                        </button>
                      </div>
                      <div
                        id="selectedEditResourcesPills"
                        class="mt-4 flex flex-wrap gap-2"
                      ></div>
                      <div
                        id="selectedEditResourcesWarning"
                        class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                        aria-live="polite"
                      ></div>
                    </div>
                    <div
                      class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-600"
                    >
                      <label
                        for="edit-server-prompts"
                        class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Associated Prompts
                      </label>
                      <input
                        type="text"
                        id="searchEditPrompts"
                        placeholder="Search for prompts..."
                        class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                      />
                      <div
                        id="edit-server-prompts"
                        class="max-h-60 overflow-y-auto rounded-md border border-gray-600 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                        hx-get="{{ root_path }}/admin/prompts/partial?page=1&per_page=20&render=selector{% if selected_team_id %}&team_id={{ selected_team_id }}{% endif %}"
                        hx-trigger="load"
                        hx-swap="innerHTML"
                        hx-on:htmx:after-swap="window.Admin?.initPromptSelect?.('edit-server-prompts', 'selectedEditPromptsPills', 'selectedEditPromptsWarning', 6, 'selectAllEditPromptsBtn', 'clearAllEditPromptsBtn')"
                      >
                        <!-- Prompts will be loaded via HTMX -->
                        <div class="text-center py-4 text-gray-500 dark:text-gray-400">
                          <svg class="animate-spin h-5 w-5 text-indigo-600 dark:text-indigo-400 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span class="ml-2">Loading prompts...</span>
                        </div>
                      </div>
                      <p
                        id="noEditPromptsMessage"
                        class="text-gray-700 dark:text-gray-300 mt-2"
                        style="display: none"
                      >
                        No prompt found containing "<span id="searchQueryEditPrompts"></span>"
                      </p>
                      <div class="flex justify-end gap-3 mt-3">
                        <button
                          type="button"
                          id="selectAllEditPromptsBtn"
                          class="px-3 py-1 text-sm font-semibold text-purple-600 border border-purple-600 rounded-md hover:bg-purple-50 focus:outline-none focus:ring-2 focus:ring-purple-300 focus:ring-offset-1"
                          aria-label="Select all prompts"
                        >
                          Select All
                        </button>
                        <button
                          type="button"
                          id="clearAllEditPromptsBtn"
                          class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                          aria-label="Clear all selected prompts"
                        >
                          Clear All
                        </button>
                      </div>
                      <div
                        id="selectedEditPromptsPills"
                        class="mt-4 flex flex-wrap gap-2"
                      ></div>
                      <div
                        id="selectedEditPromptsWarning"
                        class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                        aria-live="polite"
                      ></div>
                    </div>
                  </div>
                </div>

                <!-- OAuth 2.0 Configuration Section (RFC 9728) -->
                <div class="mt-6 border-t border-gray-200 dark:border-gray-700 pt-4">
                  <div class="flex items-center mb-4">
                    <input
                      type="checkbox"
                      name="oauth_enabled"
                      id="edit-server-oauth-enabled"
                      class="form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                      data-action-change="toggleElementClass" data-arg0="edit-server-oauth-config-section" data-arg1="hidden"
                    />
                    <label
                      for="edit-server-oauth-enabled"
                      class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-400"
                      >Enable OAuth 2.0 for MCP Client Authentication</label
                    >
                  </div>
                  <p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
                    When enabled, MCP clients can authenticate using browser-based OAuth/SSO per RFC 9728.
                  </p>

                  <!-- OAuth Configuration Fields (hidden by default) -->
                  <div id="edit-server-oauth-config-section" class="hidden space-y-4 pl-6 border-l-2 border-indigo-200 dark:border-indigo-800">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        for="edit-server-oauth-authorization-server"
                        >Authorization Server URL</label
                      >
                      <input
                        type="url"
                        name="oauth_authorization_server"
                        id="edit-server-oauth-authorization-server"
                        placeholder="https://idp.example.com"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        The OAuth 2.0 authorization server URL (e.g., your Identity Provider)
                      </p>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        for="edit-server-oauth-scopes"
                        >Scopes (space-separated)</label
                      >
                      <input
                        type="text"
                        name="oauth_scopes"
                        id="edit-server-oauth-scopes"
                        placeholder="openid profile email"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        OAuth scopes to request (e.g., openid profile email)
                      </p>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        for="edit-server-oauth-token-endpoint"
                        >Token Endpoint URL (optional)</label
                      >
                      <input
                        type="url"
                        name="oauth_token_endpoint"
                        id="edit-server-oauth-token-endpoint"
                        placeholder="https://idp.example.com/oauth/token"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Leave blank to use standard discovery from authorization server
                      </p>
                    </div>
                  </div>
                </div>

                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      data-action-click="closeModal" data-arg0="server-edit-modal"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Agent Detail Modal -->
      <div id="agent-modal" class="fixed z-40 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Agent Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-400"
                id="agent-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="agent-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- A2A Agent Test Modal -->
      <div
        id="a2a-test-modal"
        class="fixed z-40 inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center hidden"
      >
        <div
          class="bg-white dark:bg-gray-900 w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-lg shadow-lg p-6"
        >
          <h2 id="a2a-test-modal-title" class="text-xl font-bold mb-4 text-gray-800 dark:text-gray-100">
            Test A2A Agent
          </h2>
          <p id="a2a-test-modal-description" class="text-sm text-gray-600 dark:text-gray-400 mb-4"></p>

          <form id="a2a-test-form" class="space-y-4 text-gray-800 dark:text-gray-100" novalidate>
            <!-- Hidden field for agent ID -->
            <input type="hidden" id="a2a-test-agent-id" name="agent_id" />

            <div class="relative">
              <label
                for="a2a-test-query"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >Query</label>
              <textarea
                required
                name="query"
                id="a2a-test-query"
                rows="4"
                class="mt-1 px-3 py-2 block w-full rounded-md shadow-sm p-2 bg-gray-200 dark:bg-gray-800"
                placeholder="Enter your query (e.g., calc: 5*10+2 or weather: Dallas)"
                aria-describedby="a2a-test-query-help"
              >Hello from ContextForge Admin UI test!</textarea>
              <p id="a2a-test-query-help" class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                Enter the message/query to send to the A2A agent
              </p>
            </div>

            <div class="flex gap-2">
              <button
                type="submit"
                id="a2a-test-submit"
                class="flex-1 text-center px-3 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700"
              >
                Test Agent
              </button>
              <button
                id="a2a-test-close"
                type="button"
                class="flex-1 text-center px-3 py-2 border border-blue-600 rounded bg-white text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300"
              >
                Close
              </button>
            </div>

            <div
              id="a2a-test-loading"
              class="mt-4 hidden flex items-center justify-center"
            >
              <div
                class="spinner border-t-4 border-blue-600 w-6 h-6 rounded-full animate-spin"
                role="status"
                aria-label="Testing agent, please wait"
              ></div>
            </div>

            <div id="a2a-test-result" class="hidden mt-4">
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Response</label>
              <div
                id="a2a-test-response-json"
                class="bg-gray-100 dark:bg-gray-800 p-2 rounded overflow-auto text-sm text-gray-800 dark:text-gray-100 max-h-64"
              ></div>
            </div>
          </form>
        </div>
      </div>

      <!-- Config Selection Modal -->
      <div
        id="config-selection-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3
                class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4"
              >
                Export Configuration for <span id="server-name-display"></span>
              </h3>
              <p class="text-sm text-gray-600 dark:text-gray-400 mb-6">
                Choose the configuration format for your MCP client:
              </p>

              <div class="space-y-3">
                <button
                  id="stdio-config-btn"
                  data-action-click="generateAndShowConfig" data-arg0="stdio"
                  class="w-full flex items-center p-4 text-left border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <span class="text-2xl mr-3">▶️</span>
                  <div>
                    <div class="font-medium text-gray-900 dark:text-gray-100">
                      Stdio (Claude Desktop, CLI)
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      For Claude Desktop, CLI tools, and stdio-based MCP clients
                    </div>
                  </div>
                </button>

                <button
                  id="sse-config-btn"
                  data-action-click="generateAndShowConfig" data-arg0="sse"
                  class="w-full flex items-center p-4 text-left border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <span class="text-2xl mr-3">🌐</span>
                  <div>
                    <div class="font-medium text-gray-900 dark:text-gray-100">
                      SSE (LangChain, LlamaIndex)
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      For frameworks supporting Server-Sent Events transport
                    </div>
                  </div>
                </button>

                <button
                  id="http-config-btn"
                  data-action-click="generateAndShowConfig" data-arg0="http"
                  class="w-full flex items-center p-4 text-left border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <span class="text-2xl mr-3">🔗</span>
                  <div>
                    <div class="font-medium text-gray-900 dark:text-gray-100">
                      HTTP (REST clients)
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      For REST clients and HTTP-based MCP integrations
                    </div>
                  </div>
                </button>
              </div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="config-selection-modal"
                class="w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Config Display Modal -->
      <div
        id="config-display-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-3xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <div class="flex items-center justify-between mb-4">
                <h3
                  class="text-lg font-medium text-gray-900 dark:text-gray-100"
                >
                  <span id="config-display-title">Client Configuration</span>
                </h3>
                <button
                  data-action-click="copyConfigToClipboard"
                  class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  📋 Copy to Clipboard
                </button>
              </div>

              <div class="mb-4">
                <p class="text-sm text-gray-600 dark:text-gray-400 mb-2">
                  <span id="config-description"></span>
                </p>
                <div
                  class="bg-gray-100 dark:bg-gray-800 rounded p-2 text-xs text-gray-600 dark:text-gray-400"
                >
                  <strong>Usage:</strong> <span id="config-usage"></span>
                </div>
              </div>

              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                >
                  Configuration JSON:
                </label>
                <div class="relative">
                  <textarea
                    id="config-content"
                    readonly
                    class="w-full h-80 p-3 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:text-gray-200 font-mono text-sm"
                    style="tab-size: 2"
                  ></textarea>
                </div>
              </div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                data-action-click="downloadConfig"
                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:ml-3 sm:w-auto sm:text-sm"
              >
                💾 Download JSON
              </button>
              <button
                data-action-click="goBackToSelection"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                ← Back
              </button>
              <button
                type="button"
                data-action-click="closeModal" data-arg0="config-display-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Root Details Modal -->
      <div
        id="root-details-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Root Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-400"
                id="root-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                data-action-click="closeModal" data-arg0="root-details-modal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Root Edit Modal -->
      <div
        id="root-edit-modal"
        class="fixed z-40 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity pointer-events-none" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="relative z-20 inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Root
              </h3>
              <div class="mt-4">
                <form id="edit-root-form" method="POST">
                  <div class="grid grid-cols-1 gap-7">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >URI</label
                      >
                      <!-- URI is read-only -->
                      <input
                        type="text"
                        name="uri"
                        required
                        id="edit-root-uri"
                        readonly
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div class="relative">
                      <label
                        class="block text-sm font-medium text-gray-700"
                        for="edit-root-name"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-root-name"
                        class="mt-1 px-3 py-2 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      data-action-click="closeModal" data-arg0="root-edit-modal"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    <!-- Scripts -->
    <script defer nonce="{{ csp_nonce(request) }}">
      // User creation form event handler
      document.addEventListener('DOMContentLoaded', function() {
        const createUserForm = document.getElementById('create-user-form');
        if (createUserForm) {
          createUserForm.addEventListener('htmx:afterRequest', function(event) {
            const messagesDiv = document.getElementById('user-creation-messages');
            if (event.detail.successful) {
              this.reset();
              messagesDiv.innerHTML = '<div class="bg-green-50 border border-green-300 text-green-700 px-4 py-3 rounded dark:bg-green-800 dark:border-green-600 dark:text-green-200">✅ User created successfully!</div>';
              setTimeout(() => { messagesDiv.innerHTML = ''; }, 5000);
            } else {
              messagesDiv.innerHTML = '<div class="bg-red-50 border border-red-300 text-red-700 px-4 py-3 rounded dark:bg-red-800 dark:border-red-600 dark:text-red-200">❌ Failed to create user. Please check your input.</div>';
              setTimeout(() => { messagesDiv.innerHTML = ''; }, 5000);
            }
          });
        }

      });

      // Build mapping objects using your existing tools, resources, and prompts arrays
      window.Admin = window.Admin || {};
      window.Admin.toolMapping = {};
      {% for tool in tools %}
      window.Admin.toolMapping[{{ tool.id|tojson }}] = {{ tool.name|tojson }};
      {% endfor %}

      window.Admin.resourceMapping = {};
      {% for resource in resources %}
      window.Admin.resourceMapping[{{ resource.id|tojson }}] = {{ resource.name|tojson }};
      {% endfor %}

      window.Admin.promptMapping = {};
      {% for prompt in prompts %}
      window.Admin.promptMapping[{{ prompt.id|tojson }}] = {{ (prompt.displayName or prompt.originalName or prompt.name)|tojson }};
      {% endfor %}

      window.ROOT_PATH = {{ root_path | tojson }};
      window.ALLOW_PUBLIC_VISIBILITY = {{ allow_public_visibility | tojson }};
      window.GATEWAY_TOOL_NAME_SEPARATOR = {{ gateway_tool_name_separator | tojson }};
      window.MAX_NAME_LENGTH = {{ max_name_length | tojson }};
      window.USER_TEAMS = {{ user_teams | default([]) | tojson }};
      window.MCPGATEWAY_UI_TOOL_TEST_TIMEOUT = {{ mcpgateway_ui_tool_test_timeout | tojson }};
      window.CURRENT_USER = {{ current_user | tojson }};
      window.IS_ADMIN = {{ is_admin | tojson }};
      window.UI_HIDDEN_SECTIONS = {{ ui_hidden_sections | default([]) | tojson }};
      window.UI_HIDDEN_HEADER_ITEMS = {{ ui_hidden_header_items | default([]) | tojson }};
      window.UI_HIDDEN_TABS = {{ ui_hidden_tabs | default([]) | tojson }};

      // Display flash messages from URL parameters
      (function() {
        const urlParams = new URLSearchParams(window.location.search);
        const error = urlParams.get('error');
        const success = urlParams.get('success');
        const notificationDiv = document.getElementById('global-notification');

        if (error || success) {
          let messageHtml = '';
          if (error) {
            messageHtml = `<div class="bg-red-50 border border-red-300 text-red-700 px-4 py-3 rounded dark:bg-red-800 dark:border-red-600 dark:text-red-200">❌ ${decodeURIComponent(error)}</div>`;
          } else if (success) {
            messageHtml = `<div class="bg-green-50 border border-green-300 text-green-700 px-4 py-3 rounded dark:bg-green-800 dark:border-green-600 dark:text-green-200">✅ ${decodeURIComponent(success)}</div>`;
          }

          notificationDiv.innerHTML = messageHtml;
          notificationDiv.style.display = 'block';

          // Auto-dismiss after 5 seconds
          setTimeout(() => {
            notificationDiv.style.display = 'none';
            notificationDiv.innerHTML = '';

            // Clean up URL by removing the message parameters
            const cleanUrl = new URL(window.location);
            cleanUrl.searchParams.delete('error');
            cleanUrl.searchParams.delete('success');
            window.Admin?.safeReplaceState?.({}, '', cleanUrl);
          }, 5000);
        }
      })();

      // Tag filtering functionality is implemented in admin.js.


      // Team context switching functions
      function updateTeamContext(teamId) {
        // Prevent double-invocation if user clicks rapidly
        if (window.__teamSwitchingInProgress) {
          console.log('Team switch already in progress, ignoring');
          return;
        }
        window.__teamSwitchingInProgress = true;

        try {
          const url = new URL(window.location.href);

          if (teamId && teamId !== '') {
            url.searchParams.set('team_id', teamId);
          } else {
            url.searchParams.delete('team_id');
          }

          // Use assign so browser navigates and we get a brand-new initial render
          // (pushState + DOM replacements is the root cause of the stack overflow).
          window.location.assign(url.toString());
        } finally {
          // We leave the guard in place for a short time — navigation should occur immediately.
          // If navigation fails for some reason the guard is cleared after a short timeout.
          setTimeout(() => {
            window.__teamSwitchingInProgress = false;
          }, 2000);
        }
      }

      function createTagsSpan(tags) {
        if (!tags || tags.length === 0) {
          return '<span class="text-gray-500 dark:text-gray-300 text-xs">None</span>';
        }
        return tags.map(tag => `<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1">${escapeHtml(tag)}</span>`).join('');
      }

      {% if is_admin %}
      function closeInviteUserModal() {
        document.getElementById('invite-user-modal').classList.add('hidden');
        document.getElementById('invite-user-form').reset();
      }

      function toggleEmailInput(selectedUser) {
        const emailInput = document.getElementById('invite-email');
        if (selectedUser) {
          emailInput.value = selectedUser;
          emailInput.disabled = true;
          emailInput.required = false;
        } else {
          emailInput.value = '';
          emailInput.disabled = false;
          emailInput.required = true;
        }
      }

      function submitUserInvitation(event) {
        event.preventDefault();

        const formData = new FormData(event.target);
        const inviteData = {
          email: formData.get('email'),
          team_id: formData.get('team_id'),
          role: formData.get('role')
        };

        console.log('Submitting invitation:', inviteData);

        // Get the selected user's email (either from dropdown or email input)
        const selectedUser = formData.get('existing_user');
        const emailInput = formData.get('email');
        const finalEmail = selectedUser || emailInput;

        if (!finalEmail) {
          alert('Please select an existing user or enter an email address');
          return;
        }

        if (!inviteData.team_id) {
          alert('Please select a team');
          return;
        }

        // Prepare form data for the API
        const apiFormData = new FormData();
        apiFormData.append('user_email', finalEmail);
        apiFormData.append('role', inviteData.role);

        // Make API call to add team member
        fetch(`${window.ROOT_PATH}/admin/teams/${inviteData.team_id}/add-member`, {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + (getCookie('jwt_token') || '')
          },
          body: apiFormData
        })
        .then(response => {
          if (response.ok) {
            return response.text(); // API returns HTML
          } else {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
        })
        .then(html => {
          // Check if HTML contains success message
          if (html.includes('added successfully')) {
            alert('Member added successfully!');
            closeInviteUserModal();
            // Trigger page refresh for teams tab if it's visible
            if (document.getElementById('teams-list')) {
              htmx.trigger(document.getElementById('teams-list'), 'load');
            }
          } else if (html.includes('text-red-500')) {
            // Extract error message from HTML
            const errorMatch = html.match(/>([^<]+)</);
            const errorMsg = errorMatch ? errorMatch[1] : 'Unknown error';
            alert('Error adding member: ' + errorMsg);
          } else {
            alert('Member added successfully!');
            closeInviteUserModal();
          }
        })
        .catch(error => {
          console.error('Error sending invitation:', error);
          alert('Error adding member: ' + error.message);
        });
      }

      function openRoleAssignmentModal() {
        console.log('Opening role assignment modal...');

        // Populate teams dropdown
        const teamSelect = document.getElementById('assign-team');
        teamSelect.innerHTML = '<option value="">Select a team...</option>';

        // Try to get teams data from multiple sources
        let teamsData = [];

        // Method 1: Direct access to global data (most reliable)
        if (window.USER_TEAMS_DATA && Array.isArray(window.USER_TEAMS_DATA)) {
          teamsData = window.USER_TEAMS_DATA;
          console.log('Found teams in window.USER_TEAMS_DATA for role assignment:', teamsData.length);
        }
        // Method 2: Alpine.js component (backup)
        else {
          console.log('Trying Alpine.js component for role assignment...');
          const teamSelector = document.querySelector('[x-data*="selectedTeam"]');
          if (teamSelector && teamSelector._x_dataStack && teamSelector._x_dataStack[0]) {
            const alpineData = teamSelector._x_dataStack[0];
            if (alpineData.teams && Array.isArray(alpineData.teams)) {
              teamsData = alpineData.teams;
              console.log('Found teams in Alpine.js for role assignment:', teamsData.length);
            }
          }
        }

        // Populate the dropdown with found teams
        if (teamsData.length > 0) {
          teamsData.forEach(team => {
            const option = document.createElement('option');
            option.value = team.id;
            option.textContent = team.name || `Team ${team.id}`;
            teamSelect.appendChild(option);
          });
          console.log(`Populated ${teamsData.length} teams in role assignment modal`);
        } else {
          console.warn('No teams data found for role assignment modal');
          // Add a message option to indicate the issue
          const option = document.createElement('option');
          option.value = '';
          option.textContent = 'No teams available';
          option.disabled = true;
          teamSelect.appendChild(option);
        }

        // Populate users dropdown - load from API
        const userSelect = document.getElementById('assign-user');
        userSelect.innerHTML = '<option value="">Select a user...</option>';

        // Load users from the database
        const headers = {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        };

        // Add authentication if available
        let token = null;
        try { token = localStorage.getItem('auth_token') || sessionStorage.getItem('auth_token'); } catch(e) { window.Admin?.logRestrictedContext?.(e); }
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }

        fetch(window.ROOT_PATH + '/admin/users?format=json', { headers })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
          })
          .then(data => {
            if (data.users && Array.isArray(data.users)) {
              // Only show active users
              const activeUsers = data.users.filter(user => user.is_active);
              activeUsers.forEach(user => {
                const option = document.createElement('option');
                option.value = user.email;
                option.textContent = `${user.full_name || user.email} (${user.email})`;
                userSelect.appendChild(option);
              });
              console.log(`Loaded ${activeUsers.length} active users`);
            }
          })
          .catch(error => {
            console.error('Error loading users:', error);
            // Add some mock users for development
            const mockUsers = [
              { email: 'admin@example.com', full_name: 'Platform Administrator' },
              { email: 'crivetimihai@gmail.com', full_name: 'Mihai Criveti' }
            ];
            mockUsers.forEach(user => {
              const option = document.createElement('option');
              option.value = user.email;
              option.textContent = `${user.full_name} (${user.email})`;
              userSelect.appendChild(option);
            });
          });

        // Show modal
        document.getElementById('role-assignment-modal').classList.remove('hidden');
      }

      function closeRoleAssignmentModal() {
        document.getElementById('role-assignment-modal').classList.add('hidden');
        document.getElementById('role-assignment-form').reset();
      }

      function submitRoleAssignment(event) {
        event.preventDefault();

        const formData = new FormData(event.target);
        const assignmentData = {
          user_email: formData.get('user_email'),
          team_id: formData.get('team_id'),
          role: formData.get('role')
        };

        console.log('Submitting role assignment:', assignmentData);

        // Validate required fields
        if (!assignmentData.user_email) {
          alert('Please select a user');
          return;
        }

        if (!assignmentData.team_id) {
          alert('Please select a team');
          return;
        }

        if (!assignmentData.role) {
          alert('Please select a role');
          return;
        }

        // Prepare form data for the API
        const apiFormData = new FormData();
        apiFormData.append('user_email', assignmentData.user_email);
        apiFormData.append('role', assignmentData.role);

        // Make API call to update team member role
        fetch(`${window.ROOT_PATH}/admin/teams/${assignmentData.team_id}/update-member-role`, {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + (getCookie('jwt_token') || '')
          },
          body: apiFormData
        })
        .then(response => {
          if (response.ok) {
            return response.text(); // API returns HTML
          } else {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
        })
        .then(html => {
          // Check if HTML contains success message
          if (html.includes('Role updated successfully')) {
            alert('Role assigned successfully!');
            closeRoleAssignmentModal();
            // Trigger page refresh for teams tab if it's visible
            if (document.getElementById('teams-list')) {
              htmx.trigger(document.getElementById('teams-list'), 'load');
            }
          } else if (html.includes('text-red-500')) {
            // Extract error message from HTML
            const errorMatch = html.match(/>([^<]+)</);
            const errorMsg = errorMatch ? errorMatch[1] : 'Unknown error';
            alert('Error assigning role: ' + errorMsg);
          } else {
            alert('Role assigned successfully!');
            closeRoleAssignmentModal();
          }
        })
        .catch(error => {
          console.error('Error assigning role:', error);
          alert('Error assigning role: ' + error.message);
        });
      }

      {% endif %}

      // Initialize tag suggestions when page loads - using functions from admin.js
      document.addEventListener('DOMContentLoaded', function() {
        ['tools', 'resources', 'prompts', 'servers', 'gateways', 'a2a-agents'].forEach(entityType => {
          // Use the corrected functions from admin.js
          if (typeof updateAvailableTags === 'function') {
            updateAvailableTags(entityType);
          }
        });

      });

      // Add search functionality for filtering tools
    </script>
    <script nonce="{{ csp_nonce(request) }}">
      function handleEditIntegrationTypeChange() {
        const typeSel = document.getElementById("edit-tool-type");
        const reqSel = document.getElementById("edit-tool-request-type");
        if (!typeSel || !reqSel) return;

        const isREST = typeSel.value === "REST";
        // For REST tools, enable HTTP verbs; for MCP, disable & clear to avoid bad values.
        reqSel.disabled = !isREST;
        if (!isREST) {
          reqSel.value = "";
        }
      }

      // When the Edit modal is shown, re-evaluate enable/disable based on prefilled value.
      (function () {
        const modal = document.getElementById("tool-edit-modal");
        if (!modal) return;

        const observer = new MutationObserver(() => {
          const isOpen = !modal.classList.contains("hidden");
          if (isOpen) {
            // Defer one tick so existing JS can prefill values first.
            setTimeout(handleEditIntegrationTypeChange, 0);
          }
        });
        observer.observe(modal, {
          attributes: true,
          attributeFilter: ["class"],
        });
      })();

      // Logs functionality
      let logStreamSource = null;
      // Note: currentLogPage is defined in admin.js
      const logsPerPage = 100;

      // Main search function for structured logs
      // Note: Structured logging functions are defined in admin.js which loads below:
      // - searchStructuredLogs() - Search logs with filters
      // - displayLogResults() - Display log table
      // - showCorrelationTrace() - Show correlation trace modal
      // - displayCorrelationTrace() - Display trace results
      // - Helper functions: getLevelClass(), formatDuration(), getDurationClass()
      //
      // Keeping all structured logging UI logic centralized in admin.js to avoid
      // duplication and maintenance issues. admin.js loads last and provides the
      // definitive implementations.

      // Note: showSecurityEvents, showAuditTrail, showPerformanceMetrics,
      // updateLogStats, and updateLogCount are also defined in admin.js which
      // is loaded below and overrides any inline definitions.
      // Keeping functions centralized in admin.js to avoid duplication and maintenance issues.

      function toggleLogStream() {
        const button = document.getElementById("stream-toggle");

        if (logStreamSource) {
          // Stop streaming
          logStreamSource.close();
          logStreamSource = null;
          button.textContent = "Start Live Stream";
          button.className =
            "px-3 py-2 bg-green-600 text-white rounded hover:bg-green-700";
        } else {
          // Start streaming
          const level = document.getElementById("log-level-filter").value;
          const entityType = document.getElementById("log-entity-filter").value;

          const params = new URLSearchParams();
          if (level) params.append("level", level);
          if (entityType) params.append("entity_type", entityType);

          // EventSource doesn't support custom headers, so we need to pass auth in query params
          // or rely on cookie-based auth
          const url = `${window.ROOT_PATH || ""}/admin/logs/stream?${params}`;
          logStreamSource = new EventSource(url, { withCredentials: true });

          logStreamSource.onmessage = (event) => {
            const data = JSON.parse(event.data);
            if (data.type === "log_entry") {
              prependLog(data.data);
            }
          };

          logStreamSource.onerror = (error) => {
            console.error("Stream error:", error);
            toggleLogStream(); // Stop on error
          };

          button.textContent = "Stop Live Stream";
          button.className =
            "px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700";
        }
      }

      function prependLog(log) {
        const tbody = document.getElementById("logs-tbody");
        const row = document.createElement("tr");
        row.className = "hover:bg-gray-50 dark:hover:bg-gray-700 animate-pulse";

        const timestamp = new Date(log.timestamp).toLocaleString();
        const levelClass = getLevelClass(log.level);
        const entity = log.entity_name || log.entity_id || "-";

        row.innerHTML = `
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
            ${timestamp}
          </td>
          <td class="px-6 py-4 whitespace-nowrap">
            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${levelClass}">
              ${log.level}
            </span>
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
            ${log.entity_type ? `${log.entity_type}: ${entity}` : entity}
          </td>
          <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100">
            ${escapeHtml(log.message)}
          </td>
        `;

        tbody.insertBefore(row, tbody.firstChild);

        // Remove animation after a moment
        setTimeout(() => row.classList.remove("animate-pulse"), 1000);

        // Limit displayed rows
        while (tbody.children.length > logsPerPage) {
          tbody.removeChild(tbody.lastChild);
        }
      }

      async function exportLogs(format) {
        const level = document.getElementById("log-level-filter").value;
        const entityType = document.getElementById("log-entity-filter").value;
        const search = document.getElementById("log-search").value;

        const params = new URLSearchParams({ format });
        if (level) params.append("level", level);
        if (entityType) params.append("entity_type", entityType);
        if (search) params.append("search", search);

        try {
          // Use the same auth approach as other admin endpoints
          const headers = {};
          const token = window.Admin?.getAuthToken?.();
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

          const response = await fetch(
            `${window.ROOT_PATH || ""}/admin/logs/export?${params}`,
            {
              headers: headers,
              credentials: "same-origin", // pragma: allowlist secret
            },
          );

          if (!response.ok) throw new Error(`HTTP ${response.status}`);

          const blob = await response.blob();
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = `logs_export.${format}`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        } catch (error) {
          console.error("Error exporting logs:", error);
          showErrorMessage("Failed to export logs");
        }
      }

      function showErrorMessage(message) {
        const toast = document.createElement("div");
        toast.className =
          "fixed top-4 right-4 bg-red-600 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-pulse";
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 5000);
      }

      function showSuccessMessage(message) {
        const toast = document.createElement("div");
        toast.className =
          "fixed top-4 right-4 bg-green-600 text-white px-6 py-3 rounded-lg shadow-lg z-50";
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 3000);
      }

      async function showLogFiles() {
        try {
          const headers = {};
          const token = window.Admin?.getAuthToken?.();
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

          const response = await fetch(
            `${window.ROOT_PATH || ""}/admin/logs/file`,
            {
              headers: headers,
              credentials: "same-origin", // pragma: allowlist secret
            },
          );

          if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.detail || `HTTP ${response.status}`);
          }

          const data = await response.json();

          if (data.files && data.files.length > 0) {
            // Create a modal to show available files
            const modal = document.createElement("div");
            modal.className =
              "fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-40";
            modal.innerHTML = `
              <div class="bg-white rounded-lg p-6 max-w-md w-full max-h-96 overflow-y-auto">
                <h3 class="text-lg font-bold mb-4">Available Log Files</h3>
                <p class="text-sm text-gray-600 mb-4">Directory: ${data.log_directory}</p>
                <ul class="space-y-2">
                  ${data.files
                    .map(
                      (file) => `
                    <li class="flex justify-between items-center p-2 hover:bg-gray-100 rounded">
                      <div>
                        <div class="font-medium">${file.name}</div>
                        <div class="text-xs text-gray-500">
                          ${(file.size / 1024).toFixed(1)} KB - ${new Date(file.modified).toLocaleString()}
                        </div>
                      </div>
                      <button data-action-click="downloadLogFile" data-arg0="${file.name}"
                              class="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700">
                        Download
                      </button>
                    </li>
                  `,
                    )
                    .join("")}
                </ul>
                <button data-action-click="removeClosestFixed"
                        class="mt-4 px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 w-full">
                  Close
                </button>
              </div>
            `;
            document.body.appendChild(modal);
          } else {
            showErrorMessage("No log files available");
          }
        } catch (error) {
          console.error("Error fetching log files:", error);
          showErrorMessage(error.message || "Failed to fetch log files");
        }
      }

      function escapeHtml(text) {
        const div = document.createElement("div");
        div.textContent = text;
        return div.innerHTML;
      }

      /**
       * Decode HTML entities back to their original characters.
       * Used when populating form fields to prevent double-encoding.
       * @param {string} html - The HTML-encoded string
       * @returns {string} Decoded string
       */
      function decodeHtml(html) {
          if (html === null || html === undefined) {
              return "";
          }
          const txt = document.createElement("textarea");
          txt.innerHTML = html;
          return txt.value;
      }

      // Add event listeners for log filters
      document.addEventListener("DOMContentLoaded", () => {
        const logFilters = [
          "log-level-filter",
          "log-component-filter",
          "log-search",
        ];
        logFilters.forEach((id) => {
          const element = document.getElementById(id);
          if (element) {
            element.addEventListener("change", () => {
              currentLogPage = 0;
              window.Admin?.refreshLogs?.();
            });

            // For search input, debounce
            if (id === "log-search") {
              let timeout;
              element.addEventListener("input", () => {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                  currentLogPage = 0;
                  window.Admin?.refreshLogs?.();
                }, 500);
              });
            }
          }
        });

        // Load logs when logs tab is clicked
        const logsTab = document.getElementById("tab-logs");
        if (logsTab) {
          logsTab.addEventListener("click", () => {
            setTimeout(() => window.Admin?.refreshLogs?.(), 100);
          });
        }

        // ================================
        // BULK IMPORT FUNCTIONALITY
        // ================================

        let bulkImportData = null;

        // Open bulk import modal - make it globally available
        window.openBulkImportModal = function () {
          console.log("openBulkImportModal called");
          const modal = document.getElementById("bulk-import-modal");
          console.log("Modal element:", modal);
          if (modal) {
            modal.classList.remove("hidden");
            resetBulkImportModal();
          } else {
            console.error("Modal element not found!");
          }
        };

        // Close bulk import modal
        window.closeBulkImportModal = function () {
          document.getElementById("bulk-import-modal").classList.add("hidden");
          resetBulkImportModal();
        };

        // Reset modal to initial state
        function resetBulkImportModal() {
          // Reset radio buttons
          document.querySelector(
            'input[name="import-method"][value="file"]',
          ).checked = true;
          toggleImportMethod("file");

          // Clear file input
          document.getElementById("bulk-import-file").value = "";
          document.getElementById("file-info").classList.add("hidden");

          // Clear JSON textarea
          document.getElementById("bulk-import-json").value = "";

          // Hide sections
          document.getElementById("import-preview").classList.add("hidden");
          document.getElementById("import-status").classList.add("hidden");
          document.getElementById("import-loading").classList.add("hidden");
          document.getElementById("import-statistics").classList.add("hidden");

          // Reset validation status
          document.getElementById("json-validation-status").textContent = "";
          document.getElementById("json-validation-status").className =
            "text-sm";

          // Disable submit button
          document.getElementById("import-submit-btn").disabled = true;

          // Reset global data
          bulkImportData = null;
        }

        // Toggle between file upload and JSON paste
        window.toggleImportMethod = function (method) {
          const fileSection = document.getElementById("file-upload-section");
          const pasteSection = document.getElementById("json-paste-section");

          if (method === "file") {
            fileSection.classList.remove("hidden");
            pasteSection.classList.add("hidden");
          } else {
            fileSection.classList.add("hidden");
            pasteSection.classList.remove("hidden");
          }

          // Clear preview when switching methods
          document.getElementById("import-preview").classList.add("hidden");
          document.getElementById("import-submit-btn").disabled = true;
          bulkImportData = null;
        };

        // Handle file selection
        window.handleFileSelect = function (input) {
          const file = input.files[0];
          if (!file) {
            document.getElementById("file-info").classList.add("hidden");
            return;
          }

          // Validate file type
          if (!file.name.toLowerCase().endsWith(".json")) {
            showImportError("Please select a JSON file.");
            input.value = "";
            return;
          }

          // Show file info
          document.getElementById("file-name").textContent = file.name;
          document.getElementById("file-size").textContent =
            `(${formatFileSize(file.size)})`;
          document.getElementById("file-info").classList.remove("hidden");

          // Read file content
          const reader = new FileReader();
          reader.onload = function (e) {
            try {
              const jsonData = JSON.parse(e.target.result);
              processImportData(jsonData);
            } catch (error) {
              showImportError(`Invalid JSON file: ${error.message}`);
              input.value = "";
              document.getElementById("file-info").classList.add("hidden");
            }
          };
          reader.onerror = function () {
            showImportError("Error reading file.");
            input.value = "";
            document.getElementById("file-info").classList.add("hidden");
          };
          reader.readAsText(file);
        };

        // Validate JSON input from textarea
        window.validateJsonInput = function () {
          const jsonText = document
            .getElementById("bulk-import-json")
            .value.trim();
          const statusElement = document.getElementById(
            "json-validation-status",
          );

          if (!jsonText) {
            statusElement.textContent = "Please enter JSON data";
            statusElement.className =
              "text-sm text-yellow-600 dark:text-yellow-400";
            return;
          }

          try {
            const jsonData = JSON.parse(jsonText);

            // Validate structure with helpful messages
            if (!Array.isArray(jsonData)) {
              statusElement.textContent =
                "✗ JSON must be an array of tool objects [{}], not a single object {}";
              statusElement.className =
                "text-sm text-red-600 dark:text-red-400";
              document.getElementById("import-preview").classList.add("hidden");
              document.getElementById("import-submit-btn").disabled = true;
              bulkImportData = null;
              return;
            }

            if (jsonData.length === 0) {
              statusElement.textContent =
                "✗ Array cannot be empty - add at least one tool";
              statusElement.className =
                "text-sm text-red-600 dark:text-red-400";
              document.getElementById("import-preview").classList.add("hidden");
              document.getElementById("import-submit-btn").disabled = true;
              bulkImportData = null;
              return;
            }

            // Success with helpful info
            const toolCount = jsonData.length;
            const toolsWithNames = jsonData.filter((tool) => tool && tool.name);

            if (toolsWithNames.length === toolCount) {
              statusElement.textContent = `✓ Valid JSON array with ${toolCount} tool(s) - names will be auto-fixed for compatibility`;
              statusElement.className =
                "text-sm text-green-600 dark:text-green-400";
            } else {
              statusElement.textContent = `⚠ Valid JSON but ${toolCount - toolsWithNames.length} tool(s) missing required name field`;
              statusElement.className =
                "text-sm text-yellow-600 dark:text-yellow-400";
            }

            processImportData(jsonData);
          } catch (error) {
            let helpText = "";
            if (error.message.includes("Unexpected")) {
              helpText = " (Check for missing commas, quotes, or brackets)";
            }
            statusElement.textContent = `✗ Invalid JSON: ${error.message}${helpText}`;
            statusElement.className = "text-sm text-red-600 dark:text-red-400";
            document.getElementById("import-preview").classList.add("hidden");
            document.getElementById("import-submit-btn").disabled = true;
            bulkImportData = null;
          }
        };

        // Process and validate import data
        function processImportData(data) {
          try {
            // Validate data structure
            if (!Array.isArray(data)) {
              throw new Error("Data must be an array of tool definitions");
            }

            if (data.length === 0) {
              throw new Error("Array cannot be empty");
            }

            if (data.length > 200) {
              throw new Error(
                `Too many tools (${data.length}). Maximum 200 allowed.`,
              );
            }

            // Auto-fix and validate each tool
            const errors = [];
            const fixedData = data.map((tool, index) => {
              if (!tool || typeof tool !== "object") {
                errors.push(`Item ${index + 1}: Must be an object`);
                return tool;
              }

              // Create a copy to avoid modifying original
              const fixedTool = { ...tool };

              // Fix tool name to meet validation requirements
              if (fixedTool.name) {
                const originalName = fixedTool.name;
                // Convert to valid format: start with letter, only letters/numbers/dots/underscores/hyphens
                fixedTool.name = String(originalName)
                  .trim()
                  .replace(/\s+/g, "_") // Replace spaces with underscores
                  .replace(/[^a-zA-Z0-9._-]/g, "") // Remove invalid characters
                  .replace(/^[^a-zA-Z]/, "tool_") // Ensure starts with letter
                  .toLowerCase();

                if (fixedTool.name !== originalName) {
                  console.log(
                    `Auto-fixed tool name: "${originalName}" -> "${fixedTool.name}"`,
                  );
                }
              }

              // Fix tags if present (tags must be an array, not a string)
              if (fixedTool.tags) {
                const originalTags = fixedTool.tags;
                if (typeof fixedTool.tags === "string") {
                  // Convert comma-separated string to array of strings
                  fixedTool.tags = fixedTool.tags
                    .split(",") // Split by comma
                    .map((tag) => tag.trim()) // Trim whitespace
                    .filter((tag) => tag.length >= 2) // Remove empty/too short tags
                    .map((tag) => tag.toLowerCase()) // Convert to lowercase
                    .map((tag) => tag.replace(/[^a-z0-9\-\:\.]/g, "")) // Remove invalid characters
                    .filter((tag) => tag.length >= 2); // Filter again after cleaning

                  if (
                    JSON.stringify(fixedTool.tags) !==
                    JSON.stringify(originalTags)
                  ) {
                    console.log(
                      `Auto-fixed tags: "${originalTags}" -> ${JSON.stringify(fixedTool.tags)}`,
                    );
                  }
                } else if (Array.isArray(fixedTool.tags)) {
                  // Clean up array of tags
                  fixedTool.tags = fixedTool.tags
                    .map((tag) => String(tag).trim().toLowerCase())
                    .map((tag) => tag.replace(/[^a-z0-9\-\:\.]/g, ""))
                    .filter((tag) => tag.length >= 2);

                  if (
                    JSON.stringify(fixedTool.tags) !==
                    JSON.stringify(originalTags)
                  ) {
                    console.log(
                      `Auto-fixed tags array: ${JSON.stringify(originalTags)} -> ${JSON.stringify(fixedTool.tags)}`,
                    );
                  }
                }
              }

              // Only name is strictly required
              const required = ["name"];
              const missing = required.filter(
                (field) =>
                  !fixedTool[field] ||
                  (typeof fixedTool[field] === "string" &&
                    fixedTool[field].trim() === ""),
              );
              if (missing.length > 0) {
                errors.push(
                  `Item ${index + 1}: Missing required fields: ${missing.join(", ")}`,
                );
              }

              // Warn about missing recommended fields but don't block import
              const recommended = ["url"];
              const missingRecommended = recommended.filter(
                (field) =>
                  !fixedTool[field] ||
                  (typeof fixedTool[field] === "string" &&
                    fixedTool[field].trim() === ""),
              );
              if (missingRecommended.length > 0) {
                console.warn(
                  `Item ${index + 1} (${fixedTool.name || "unnamed"}): Missing recommended fields: ${missingRecommended.join(", ")}`,
                );
              }

              return fixedTool;
            });

            if (errors.length > 0) {
              throw new Error(
                `Validation errors:\\n${errors.slice(0, 5).join("\\n")}${errors.length > 5 ? `\\n... and ${errors.length - 5} more errors` : ""}`,
              );
            }

            // Store the fixed data instead of original
            bulkImportData = fixedData;

            // Show preview
            showImportPreview(fixedData);

            // Enable submit button
            document.getElementById("import-submit-btn").disabled = false;

            // Clear any previous error messages
            document.getElementById("import-status").classList.add("hidden");
          } catch (error) {
            showImportError(error.message);
            bulkImportData = null;
            document.getElementById("import-submit-btn").disabled = true;
          }
        } // Show import preview
        function showImportPreview(data) {
          document.getElementById("preview-count").textContent = data.length;

          // Populate preview list
          const previewList = document.getElementById("preview-list");
          previewList.innerHTML = "";

          data.slice(0, 10).forEach((tool, index) => {
            const li = document.createElement("li");
            li.className = "flex justify-between";
            li.innerHTML = `
              <span class="truncate">${escapeHtml(tool.name || "Unnamed")}</span>
              <span class="ml-2 text-gray-500">${escapeHtml(tool.integrationType || "REST")}</span>
            `;
            previewList.appendChild(li);
          });

          if (data.length > 10) {
            const li = document.createElement("li");
            li.className = "text-gray-500 italic";
            li.textContent = `... and ${data.length - 10} more tools`;
            previewList.appendChild(li);
          }

          document.getElementById("import-preview").classList.remove("hidden");
        }

        // Toggle validation guide visibility
        window.toggleValidationGuide = function () {
          const guide = document.getElementById("validation-guide");
          const toggle = document.getElementById("validation-guide-toggle");

          if (guide.classList.contains("hidden")) {
            guide.classList.remove("hidden");
            toggle.textContent = "Hide Validation Rules";
          } else {
            guide.classList.add("hidden");
            toggle.textContent = "Show Validation Rules";
          }
        };

        // Toggle preview details
        window.togglePreviewDetails = function () {
          const details = document.getElementById("preview-details");
          const toggleText = document.getElementById("preview-toggle-text");

          if (details.classList.contains("hidden")) {
            details.classList.remove("hidden");
            toggleText.textContent = "Hide Details";
          } else {
            details.classList.add("hidden");
            toggleText.textContent = "Show Details";
          }
        };

        // Submit bulk import
        window.submitBulkImport = async function () {
          if (!bulkImportData) {
            showImportError("No valid data to import");
            return;
          }

          // Show loading
          document.getElementById("import-loading").classList.remove("hidden");
          document.getElementById("import-submit-btn").disabled = true;

          try {
            const response = await fetch(
              `${window.location.origin}/admin/tools/import`,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(bulkImportData),
              },
            );

            const result = await response.json();

            // Debug logging
            console.log("Response status:", response.status);
            console.log("Response ok:", response.ok);
            console.log("Result:", result);
            console.log("Result.success:", result.success);
            console.log("Result.created_count:", result.created_count);
            console.log("Result.failed_count:", result.failed_count);
            console.log("Result.errors:", result.errors);

            // Log individual errors for debugging
            if (result.errors && result.errors.length > 0) {
              console.log("Detailed errors:");
              result.errors.forEach((error, index) => {
                console.log(`Error ${index + 1}:`, error);
                if (error.error) {
                  console.log(`  Error message:`, error.error.message);
                  console.log(
                    `  Full error object:`,
                    JSON.stringify(error.error, null, 2),
                  );
                }
              });
            }

            // Hide loading
            document.getElementById("import-loading").classList.add("hidden");

            if (response.ok) {
              // Update statistics display
              updateImportStatistics(result);

              if (result.success) {
                // Complete success
                showImportSuccess(result);

                // Auto-close modal after success and refresh page
                setTimeout(() => {
                  closeBulkImportModal();
                  location.reload(); // Refresh to show new tools
                }, 3000);
              } else if (result.created_count > 0) {
                // Partial success - some tools imported successfully
                showImportSuccess(result);

                // Auto-close modal after partial success and refresh page
                setTimeout(() => {
                  closeBulkImportModal();
                  location.reload(); // Refresh to show new tools
                }, 5000); // Longer delay to see the message
              } else {
                // Complete failure
                showImportError(result.message || "All tools failed to import", result);
                document.getElementById("import-submit-btn").disabled = false;
              }
            } else {
              showImportError(result.message || "Import failed", result);
              document.getElementById("import-submit-btn").disabled = false;
            }
          } catch (error) {
            document.getElementById("import-loading").classList.add("hidden");
            showImportError(`Network error: ${error.message}`, null);
            document.getElementById("import-submit-btn").disabled = false;
          }
        };

        // Show import success message
        function showImportSuccess(result) {
          const statusDiv = document.getElementById("import-status");
          const isPartialSuccess = result.failed_count > 0;
          const bgColor = isPartialSuccess ? "yellow" : "green";
          const textColor = isPartialSuccess ? "yellow" : "green";
          const totalTools = (result.created_count || 0) + (result.failed_count || 0);

          statusDiv.innerHTML = `
            <div class="bg-${bgColor}-50 dark:bg-${bgColor}-900 border border-${bgColor}-200 dark:border-${bgColor}-800 rounded-md p-4">
              <div class="flex">
                <div class="flex-shrink-0">
                  <svg class="h-5 w-5 text-${textColor}-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                  </svg>
                </div>
                <div class="ml-3 w-full">
                  <h3 class="text-sm font-medium text-${textColor}-800 dark:text-${textColor}-200">
                    ${isPartialSuccess ? "Import Partially Completed" : "Import Completed Successfully"}
                  </h3>

                  <!-- Import Statistics -->
                  <div class="mt-3 grid grid-cols-3 gap-4 text-center">
                    <div class="bg-white dark:bg-gray-800 rounded-lg p-3 border">
                      <div class="text-lg font-bold text-blue-600 dark:text-blue-400">${totalTools}</div>
                      <div class="text-xs text-gray-600 dark:text-gray-400">Total Tools</div>
                    </div>
                    <div class="bg-white dark:bg-gray-800 rounded-lg p-3 border">
                      <div class="text-lg font-bold text-green-600 dark:text-green-400">${result.created_count || 0}</div>
                      <div class="text-xs text-gray-600 dark:text-gray-400">Successful</div>
                    </div>
                    <div class="bg-white dark:bg-gray-800 rounded-lg p-3 border">
                      <div class="text-lg font-bold text-red-600 dark:text-red-400">${result.failed_count || 0}</div>
                      <div class="text-xs text-gray-600 dark:text-gray-400">Failed</div>
                    </div>
                  </div>

                  <div class="mt-3 text-sm text-${textColor}-700 dark:text-${textColor}-300">
                    <p><strong>${result.created_count || 0}</strong> tools imported successfully out of <strong>${totalTools}</strong> total tools</p>
                    ${result.failed_count > 0 ? `<p class="text-red-600 dark:text-red-400"><strong>${result.failed_count}</strong> tools failed to import</p>` : ""}
                    ${
                      result.errors && result.errors.length > 0
                        ? `
                      <details class="mt-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
                        <summary class="cursor-pointer font-medium text-red-800 dark:text-red-200 hover:text-red-600 dark:hover:text-red-300">
                          📋 View Failed Tools (${result.errors.length})
                        </summary>
                        <div class="mt-3 max-h-64 overflow-y-auto">
                          <div class="space-y-2">
                            ${result.errors
                              .map(
                                (error, index) => `
                                <div class="bg-white dark:bg-gray-800 border border-red-200 dark:border-red-700 rounded p-2 text-xs">
                                  <div class="flex justify-between items-start">
                                    <div class="font-medium text-red-800 dark:text-red-200">
                                      ${index + 1}. ${escapeHtml(error.name || error.tool_name || "Unnamed Tool")}
                                    </div>
                                    <span class="text-red-600 dark:text-red-400 text-xs">❌</span>
                                  </div>
                                  <div class="mt-1 text-red-700 dark:text-red-300">
                                    <strong>Error:</strong> ${escapeHtml(error.error?.message || error.message || "Unknown error")}
                                  </div>
                                  ${error.url ? `<div class="mt-1 text-gray-600 dark:text-gray-400"><strong>URL:</strong> ${escapeHtml(error.url)}</div>` : ""}
                                </div>
                              `
                              )
                              .join("")}
                          </div>
                        </div>
                      </details>
                    `
                        : ""
                    }
                    <p class="mt-3 text-xs text-gray-600 dark:text-gray-400">Page will refresh automatically...</p>
                  </div>
                </div>
              </div>
            </div>
          `;
          statusDiv.classList.remove("hidden");
        }

        // Show import error message
        function showImportError(message, result = null) {
          const statusDiv = document.getElementById("import-status");

          let errorContent = `<p>${escapeHtml(message)}</p>`;

          // If we have detailed error information, show statistics
          if (result && (result.failed_count > 0 || result.errors)) {
            const totalTools = (result.created_count || 0) + (result.failed_count || 0);
            const successCount = result.created_count || 0;
            const failedCount = result.failed_count || 0;

            errorContent = `
              <div class="mb-3 grid grid-cols-3 gap-4 text-center">
                <div class="bg-white dark:bg-gray-800 rounded-lg p-3 border">
                  <div class="text-lg font-bold text-blue-600 dark:text-blue-400">${totalTools}</div>
                  <div class="text-xs text-gray-600 dark:text-gray-400">Total Tools</div>
                </div>
                <div class="bg-white dark:bg-gray-800 rounded-lg p-3 border">
                  <div class="text-lg font-bold text-green-600 dark:text-green-400">${successCount}</div>
                  <div class="text-xs text-gray-600 dark:text-gray-400">Successful</div>
                </div>
                <div class="bg-white dark:bg-gray-800 rounded-lg p-3 border">
                  <div class="text-lg font-bold text-red-600 dark:text-red-400">${failedCount}</div>
                  <div class="text-xs text-gray-600 dark:text-gray-400">Failed</div>
                </div>
              </div>
              <p>${escapeHtml(message)}</p>
            `;
          }

          statusDiv.innerHTML = `
            <div class="bg-red-50 dark:bg-red-900 border border-red-200 dark:border-red-800 rounded-md p-4">
              <div class="flex">
                <div class="flex-shrink-0">
                  <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                  </svg>
                </div>
                <div class="ml-3 w-full">
                  <h3 class="text-sm font-medium text-red-800 dark:text-red-200">
                    Import ${result && result.created_count > 0 ? 'Partially Failed' : 'Failed'}
                  </h3>
                  <div class="mt-2 text-sm text-red-700 dark:text-red-300">
                    ${errorContent}
                  </div>
                </div>
              </div>
            </div>
          `;
          statusDiv.classList.remove("hidden");
        }

        // Update import statistics display
        function updateImportStatistics(result) {
          const totalTools = (result.created_count || 0) + (result.failed_count || 0);
          const successCount = result.created_count || 0;
          const failedCount = result.failed_count || 0;

          document.getElementById("stats-total").textContent = totalTools;
          document.getElementById("stats-success").textContent = successCount;
          document.getElementById("stats-failed").textContent = failedCount;

          // Show the statistics section
          document.getElementById("import-statistics").classList.remove("hidden");
        }

        // Format file size
        function formatFileSize(bytes) {
          if (bytes === 0) return "0 Bytes";
          const k = 1024;
          const sizes = ["Bytes", "KB", "MB", "GB"];
          const i = Math.floor(Math.log(bytes) / Math.log(k));
          return (
            parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
          );
        }

        // Auto-trigger JSON validation when typing in textarea
        document.addEventListener("DOMContentLoaded", function () {
          const jsonTextarea = document.getElementById("bulk-import-json");
          if (jsonTextarea) {
            let validationTimeout;
            jsonTextarea.addEventListener("input", function () {
              clearTimeout(validationTimeout);
              validationTimeout = setTimeout(function () {
                if (jsonTextarea.value.trim()) {
                  validateJsonInput();
                }
              }, 1000); // Validate 1 second after user stops typing
            });
          }
        });

        // Dropdown Functions
        window.toggleBulkImportDropdown = function () {
          const dropdown = document.getElementById("bulk-import-dropdown");
          dropdown.classList.toggle("hidden");
        };

        window.toggleDropdownImportMethod = function (method) {
          const fileSection = document.getElementById("dropdown-file-section");
          const pasteSection = document.getElementById(
            "dropdown-paste-section",
          );

          if (method === "file") {
            fileSection.classList.remove("hidden");
            pasteSection.classList.add("hidden");
          } else {
            fileSection.classList.add("hidden");
            pasteSection.classList.remove("hidden");
          }
          resetDropdownImport();
        };

        window.handleDropdownFileSelect = function (input) {
          const fileInfo = document.getElementById("dropdown-file-info");
          const preview = document.getElementById("dropdown-preview");
          const status = document.getElementById("dropdown-status");

          if (!input.files[0]) {
            resetDropdownImport();
            return;
          }

          const file = input.files[0];
          fileInfo.textContent = `Selected: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
          fileInfo.classList.remove("hidden");

          const reader = new FileReader();
          reader.onload = function (e) {
            try {
              const data = JSON.parse(e.target.result);
              validateDropdownData(data);
            } catch (error) {
              showDropdownStatus("error", `Invalid JSON: ${error.message}`);
            }
          };
          reader.readAsText(file);
        };

        window.validateDropdownJson = function () {
          const textarea = document.getElementById("dropdown-json-textarea");
          const status = document.getElementById("dropdown-json-status");

          if (!textarea.value.trim()) {
            status.textContent = "";
            document.getElementById("dropdown-import-btn").disabled = true;
            document.getElementById("dropdown-preview").classList.add("hidden");
            return;
          }

          try {
            const data = JSON.parse(textarea.value);
            status.innerHTML =
              '<span class="text-green-600">✓ Valid JSON</span>';
            validateDropdownData(data);
          } catch (error) {
            status.innerHTML = `<span class="text-red-600">✗ Invalid JSON: ${escapeHtml(error.message)}</span>`;
            document.getElementById("dropdown-import-btn").disabled = true;
            document.getElementById("dropdown-preview").classList.add("hidden");
          }
        };

        window.validateDropdownData = function (data) {
          const preview = document.getElementById("dropdown-preview");
          const count = document.getElementById("dropdown-preview-count");
          const importBtn = document.getElementById("dropdown-import-btn");

          if (!Array.isArray(data)) {
            showDropdownStatus("error", "Data must be an array of tools");
            return;
          }

          if (data.length === 0) {
            showDropdownStatus("error", "Array cannot be empty");
            return;
          }

          if (data.length > 200) {
            showDropdownStatus(
              "error",
              "Cannot import more than 200 tools at once",
            );
            return;
          }

          count.textContent = data.length;
          preview.classList.remove("hidden");
          importBtn.disabled = false;
          showDropdownStatus(
            "success",
            `${data.length} tools ready for import`,
          );
        };

        window.showDropdownStatus = function (type, message) {
          const status = document.getElementById("dropdown-status");
          const colorClass = type === "error" ? "red" : type === "warning" ? "yellow" : "green";
          const content = message.includes('<div') ? message : escapeHtml(message);
          status.innerHTML = `<div class="text-${colorClass}-600 dark:text-${colorClass}-400 whitespace-pre-line text-xs">${content}</div>`;
          status.classList.remove("hidden");
        };

        window.showDropdownResults = function (total, success, failed) {
          document.getElementById("dropdown-stats-total").textContent = total;
          document.getElementById("dropdown-stats-success").textContent = success;
          document.getElementById("dropdown-stats-failed").textContent = failed;
          document.getElementById("dropdown-results").classList.remove("hidden");
        };

        window.showDropdownFailedTools = function (errors) {
          const failedToolsHtml = errors.map((error, index) =>
            `<div class="text-xs p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 rounded mb-1">
              <div class="font-medium text-red-800 dark:text-red-200">${index + 1}. ${escapeHtml(error.name || error.tool_name || "Unnamed Tool")}</div>
              <div class="text-red-600 dark:text-red-400 mt-1">${escapeHtml(error.error?.message || error.message || "Unknown error")}</div>
            </div>`
          ).join('');

          showDropdownStatus("error", `<div class="font-medium mb-2">Failed Tools (${errors.length}):</div><div class="max-h-32 overflow-y-auto">${failedToolsHtml}</div>`);
        };

        window.showDropdownActionButtons = function() {
          const actionButtonsHtml = `<div class="mt-3 flex justify-center space-x-2">
            <button data-action-click="toggleBulkImportDropdown" class="px-3 py-1 text-xs bg-gray-600 text-white rounded hover:bg-gray-700">
              Discard
            </button>
            <button data-action-click="executeBulkImportAndReload" class="px-3 py-1 text-xs bg-blue-600 text-white rounded hover:bg-blue-700">
              🔄 Execute Import
            </button>
          </div>`;

          const statusDiv = document.getElementById("dropdown-status");
          statusDiv.innerHTML += actionButtonsHtml;
        };

        window.resetDropdownImport = function () {
          document.getElementById("dropdown-file-input").value = "";
          document.getElementById("dropdown-json-textarea").value = "";
          document.getElementById("dropdown-file-info").classList.add("hidden");
          document.getElementById("dropdown-json-status").textContent = "";
          document.getElementById("dropdown-preview").classList.add("hidden");
          document.getElementById("dropdown-status").classList.add("hidden");
          document.getElementById("dropdown-results").classList.add("hidden");
          document.getElementById("dropdown-import-btn").disabled = true;
        };

        window.submitDropdownImport = async function () {
          const importBtn = document.getElementById("dropdown-import-btn");
          const status = document.getElementById("dropdown-status");

          let data;
          const fileInput = document.getElementById("dropdown-file-input");
          const textarea = document.getElementById("dropdown-json-textarea");

          if (fileInput.files[0]) {
            const reader = new FileReader();
            reader.onload = async function (e) {
              try {
                data = JSON.parse(e.target.result);
                await performDropdownImport(data);
              } catch (error) {
                showDropdownStatus(
                  "error",
                  `Failed to parse file: ${error.message}`,
                );
              }
            };
            reader.readAsText(fileInput.files[0]);
          } else if (textarea.value.trim()) {
            try {
              data = JSON.parse(textarea.value);
              await performDropdownImport(data);
            } catch (error) {
              showDropdownStatus("error", `Invalid JSON: ${error.message}`);
            }
          }
        };

        window.performDropdownImport = async function (data) {
          const importBtn = document.getElementById("dropdown-import-btn");
          const status = document.getElementById("dropdown-status");

          importBtn.disabled = true;
          importBtn.textContent = "Importing...";

          try {
            const response = await fetch(
              window.ROOT_PATH + "/admin/tools/import",
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(data),
              },
            );

            const result = await response.json();

            if (response.ok) {
              const totalTools = (result.created_count || result.imported || 0) + (result.failed_count || 0);
              const successCount = result.created_count || result.imported || 0;
              const failedCount = result.failed_count || 0;

              // Show statistics
              showDropdownResults(totalTools, successCount, failedCount);

              let statusMessage = `✅ Import completed: ${successCount}/${totalTools} tools imported successfully`;
              if (failedCount > 0) {
                statusMessage = `⚠️ Partial success: ${successCount}/${totalTools} tools imported, ${failedCount} failed`;
              }

              showDropdownStatus("success", statusMessage);

              // Show failed tools if any
              if (result.errors && result.errors.length > 0) {
                showDropdownFailedTools(result.errors);
              }

              // Show close/refresh buttons after import
              showDropdownActionButtons();
            } else {
              showDropdownStatus(
                "error",
                `❌ Import failed: ${result.detail || result.message || "Unknown error"}`,
              );
            }
          } catch (error) {
            showDropdownStatus("error", `❌ Network error: ${error.message}`);
          } finally {
            importBtn.disabled = false;
            importBtn.textContent = "Import Tools";
          }
        };

        // Close dropdown when clicking outside
        document.addEventListener("click", function (event) {
          const dropdown = document.getElementById("bulk-import-dropdown");
          const button = document.getElementById("bulk-import-dropdown-btn");

          if (
            dropdown &&
            !dropdown.contains(event.target) &&
            !button.contains(event.target)
          ) {
            dropdown.classList.add("hidden");
          }
        });
      });
    </script>

    <!-- Bulk Import Modal -->
    <div
      id="bulk-import-modal-2"
      class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-40"
    >
      <div
        class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white dark:bg-gray-800"
      >
        <div class="mt-3">
          <!-- Modal Header -->
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
              Bulk Import Tools
            </h3>
            <button
              data-action-click="closeBulkImportModal"
              class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              <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>

          <!-- Modal Content -->
          <div class="space-y-4">
            <!-- Instructions -->
            <div
              class="bg-blue-50 dark:bg-blue-900 border border-blue-200 dark:border-blue-800 rounded-md p-3"
            >
              <div class="flex">
                <div class="flex-shrink-0">
                  <svg
                    class="h-5 w-5 text-blue-400"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fill-rule="evenodd"
                      d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                      clip-rule="evenodd"
                    ></path>
                  </svg>
                </div>
                <div class="ml-3">
                  <h3
                    class="text-sm font-medium text-blue-800 dark:text-blue-200"
                  >
                    Import Instructions
                  </h3>
                  <div class="mt-2 text-sm text-blue-700 dark:text-blue-300">
                    <div class="mb-3">
                      <button
                        data-action-click="toggleValidationGuide"
                        class="inline-flex items-center text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-200"
                      >
                        <svg
                          class="w-3 h-3 mr-1"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                          ></path>
                        </svg>
                        <span id="validation-guide-toggle"
                          >Show Validation Rules</span
                        >
                      </button>
                    </div>

                    <div
                      id="validation-guide"
                      class="hidden bg-blue-50 dark:bg-blue-900 border border-blue-200 dark:border-blue-700 rounded-md p-3 mb-3 text-xs"
                    >
                      <h5
                        class="font-semibold mb-2 text-blue-800 dark:text-blue-200"
                      >
                        📋 JSON Validation Rules
                      </h5>
                      <div class="space-y-2">
                        <div>
                          <strong class="text-green-700 dark:text-green-300"
                            >✅ Required:</strong
                          >
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >name</code
                          >
                          - must start with letter, only
                          letters/numbers/dots/underscores/hyphens
                        </div>
                        <div>
                          <strong class="text-blue-700 dark:text-blue-300"
                            >🔹 Optional:</strong
                          >
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >url</code
                          >
                          (http/https/ws/wss only),
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >description</code
                          >,
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >tags</code
                          >
                          (array only)
                        </div>
                        <div>
                          <strong class="text-orange-700 dark:text-orange-300"
                            >⚠️ Case Sensitive:</strong
                          >
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >requestType</code
                          >
                          ("GET", "POST"),
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >integrationType</code
                          >
                          ("REST", "MCP")
                        </div>
                        <div>
                          <strong class="text-red-700 dark:text-red-300"
                            >❌ Not Allowed:</strong
                          >
                          Names starting with numbers, FTP URLs, tag strings
                          "tag1,tag2" (use ["tag1","tag2"])
                        </div>
                        <div
                          class="pt-1 border-t border-blue-200 dark:border-blue-700"
                        >
                          <strong class="text-purple-700 dark:text-purple-300"
                            >🔧 Auto-Fixed:</strong
                          >
                          Spaces in names, tag strings → arrays, case
                          normalization
                        </div>
                      </div>
                    </div>

                    <ul class="list-disc pl-5 space-y-1"></ul>
                  </div>
                </div>
              </div>
            </div>

            <!-- Input Method Selection -->
            <div class="space-y-3">
              <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100">
                Choose Import Method:
              </h4>

              <!-- Radio buttons for input method -->
              <div class="flex space-x-6">
                <label class="flex items-center">
                  <input
                    type="radio"
                    name="import-method"
                    value="file"
                    checked
                    data-action-change="toggleImportMethod"
                    class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                  />
                  <span class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                    >Upload JSON File</span
                  >
                </label>
                <label class="flex items-center">
                  <input
                    type="radio"
                    name="import-method"
                    value="paste"
                    data-action-change="toggleImportMethod"
                    class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                  />
                  <span class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                    >Paste JSON Data</span
                  >
                </label>
              </div>
            </div>

            <!-- File Upload Section -->
            <div id="file-upload-section" class="space-y-3">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >
                Select JSON File
              </label>
              <div
                class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md dark:border-gray-600"
              >
                <div class="space-y-1 text-center">
                  <svg
                    class="mx-auto h-12 w-12 text-gray-400"
                    stroke="currentColor"
                    fill="none"
                    viewBox="0 0 48 48"
                  >
                    <path
                      d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </svg>
                  <div class="flex text-sm text-gray-600 dark:text-gray-400">
                    <label
                      for="bulk-import-file"
                      class="relative cursor-pointer bg-white dark:bg-gray-800 rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500"
                    >
                      <span>Upload a file</span>
                      <input
                        id="bulk-import-file"
                        name="bulk-import-file"
                        type="file"
                        accept=".json"
                        data-action-change="handleFileSelect" data-arg0="this"
                        class="sr-only"
                      />
                    </label>
                    <p class="pl-1">or drag and drop</p>
                  </div>
                  <p class="text-xs text-gray-500 dark:text-gray-400">
                    JSON files only
                  </p>
                </div>
              </div>
              <!-- File info display -->
              <div id="file-info" class="hidden mt-2">
                <div
                  class="flex items-center space-x-2 text-sm text-gray-600 dark:text-gray-400"
                >
                  <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path
                      fill-rule="evenodd"
                      d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z"
                      clip-rule="evenodd"
                    ></path>
                  </svg>
                  <span id="file-name"></span>
                  <span id="file-size" class="text-xs text-gray-500"></span>
                </div>
              </div>
            </div>

            <!-- JSON Paste Section -->
            <div id="json-paste-section" class="space-y-3 hidden">
              <label
                for="bulk-import-json"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >
                Paste JSON Data
              </label>
              <textarea
                id="bulk-import-json"
                name="bulk-import-json"
                rows="12"
                placeholder="[&#10;  {&#10;    &quot;name&quot;: &quot;Books Search&quot;,&#10;    &quot;url&quot;: &quot;https://www.googleapis.com/books/v1/volumes&quot;,&#10;    &quot;description&quot;: &quot;Search Google Books&quot;,&#10;    &quot;integrationType&quot;: &quot;REST&quot;,&#10;    &quot;requestType&quot;: &quot;GET&quot;,&#10;    &quot;tags&quot;: [&quot;api&quot;, &quot;google&quot;, &quot;books&quot;]&#10;  },&#10;  {&#10;    &quot;name&quot;: &quot;JSON Placeholder Posts&quot;,&#10;    &quot;url&quot;: &quot;https://jsonplaceholder.typicode.com/posts&quot;,&#10;    &quot;integrationType&quot;: &quot;REST&quot;,&#10;    &quot;requestType&quot;: &quot;GET&quot;,&#10;    &quot;headers&quot;: {&quot;Accept&quot;: &quot;application/json&quot;}&#10;  }&#10;]"
                class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 mt-1 px-3 py-2 block w-full sm:text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-300"
              ></textarea>
              <div class="flex justify-between items-center">
                <button
                  type="button"
                  data-action-click="validateJsonInput"
                  class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-indigo-800 dark:text-indigo-200"
                >
                  <svg
                    class="w-4 h-4 mr-1"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                    ></path>
                  </svg>
                  Validate JSON
                </button>
                <span id="json-validation-status" class="text-sm"></span>
              </div>
            </div>

            <!-- Preview Section -->
            <div id="import-preview" class="hidden space-y-3">
              <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100">
                Import Preview
              </h4>
              <div class="bg-gray-50 dark:bg-gray-700 rounded-md p-3">
                <div class="flex items-center justify-between">
                  <span class="text-sm text-gray-700 dark:text-gray-300">
                    <span id="preview-count">0</span> tools ready for import
                  </span>
                  <button
                    type="button"
                    data-action-click="togglePreviewDetails"
                    class="text-sm text-indigo-600 hover:text-indigo-500 dark:text-indigo-400"
                  >
                    <span id="preview-toggle-text">Show Details</span>
                  </button>
                </div>
                <div
                  id="preview-details"
                  class="hidden mt-3 max-h-40 overflow-y-auto"
                >
                  <ul
                    id="preview-list"
                    class="text-xs text-gray-600 dark:text-gray-400 space-y-1"
                  >
                    <!-- Preview items will be populated here -->
                  </ul>
                </div>
              </div>
            </div>

            <!-- Status Messages -->
            <div id="import-status" class="hidden">
              <!-- Success/Error messages will be displayed here -->
            </div>

            <!-- Loading Indicator -->
            <div
              id="import-loading"
              class="hidden flex items-center justify-center py-4"
            >
              <div
                class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"
              ></div>
              <span class="ml-2 text-sm text-gray-600 dark:text-gray-400"
                >Processing import...</span
              >
            </div>

            <!-- Modal Actions -->
            <div
              class="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-600"
            >
              <button
                type="button"
                data-action-click="closeBulkImportModal"
                class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600"
              >
                Cancel
              </button>
              <button
                type="button"
                id="import-submit-btn"
                data-action-click="submitBulkImport"
                disabled
                class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <svg
                  class="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                  ></path>
                </svg>
                Import Tools
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- User Edit Modal -->
    <div id="user-edit-modal" class="fixed inset-0 z-40 hidden">
      <div
        class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
      >
        <div
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
          aria-hidden="true"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full sm:p-6"
        >
          <div id="user-edit-modal-content">
            <!-- Content will be loaded here -->
          </div>
        </div>
      </div>
    </div>

    <!-- Create Team Modal -->
    <div id="create-team-modal" class="fixed inset-0 z-40 hidden">
      <div
        class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
      >
        <div
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
          aria-hidden="true"
          data-action-click="closeCreateTeamModal"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full sm:p-6"
        >
          <div>
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                Create New Team
              </h3>
              <button
                data-action-click="closeCreateTeamModal"
                class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <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"
                  />
                </svg>
              </button>
            </div>

            <form
              id="create-team-form"
              hx-post="{{ root_path }}/admin/teams"
              hx-target="#create-team-error"
              hx-swap="innerHTML"
              data-team-validation="true"
            >
              <div id="create-team-error" class="mb-4"></div>
              <div class="space-y-4">
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                  >
                    Team Name <span class="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    name="name"
                    id="team-name"
                    required
                    maxlength="100"
                    class="block w-full px-3 py-2 border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    placeholder="Development Team"
                  />
                  <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Letters, numbers, spaces, underscores, periods, and dashes only
                  </p>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                  >
                    Description
                  </label>
                  <textarea
                    name="description"
                    id="team-description"
                    rows="3"
                    maxlength="500"
                    class="block w-full px-3 py-2 border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    placeholder="Brief description of the team's purpose..."
                  ></textarea>
                  <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Optional, maximum 500 characters
                  </p>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                  >
                    Team Visibility
                  </label>
                  <div class="space-y-2">
                    <label class="flex items-center">
                      <input
                        type="radio"
                        name="visibility"
                        value="private"
                        checked
                        class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600"
                      />
                      <div class="ml-3">
                        <div
                          class="text-sm font-medium text-gray-700 dark:text-gray-300"
                        >
                          Private
                        </div>
                        <div class="text-xs text-gray-500 dark:text-gray-400">
                          Only visible to members, invitation required to join
                        </div>
                      </div>
                    </label>
                    <label class="flex items-center">
                      <input
                        type="radio"
                        name="visibility"
                        value="public"
                        class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600"
                      />
                      <div class="ml-3">
                        <div
                          class="text-sm font-medium text-gray-700 dark:text-gray-300"
                        >
                          Public
                        </div>
                        <div class="text-xs text-gray-500 dark:text-gray-400">
                          Discoverable by all users, others can request to join
                        </div>
                      </div>
                    </label>
                  </div>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                  >
                    Maximum Members
                  </label>
                  <input
                    type="number"
                    name="max_members"
                    id="team-max-members"
                    min="1"
                    {% if not is_admin %}max="{{ max_members_per_team }}"{% endif %}
                    class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  />
                  <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    {% if is_admin %}
                    Optional. Leave empty to use global default ({{ max_members_per_team }}). Admins can set any limit.
                    {% else %}
                    Optional. Leave empty to use global default ({{ max_members_per_team }}).
                    {% endif %}
                  </p>
                </div>
              </div>

              <div class="mt-6 flex justify-end space-x-3">
                <button
                  type="button"
                  data-action-click="closeCreateTeamModal"
                  class="px-4 py-2 border border-gray-300 rounded-md shadow-sm bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  class="px-4 py-2 border border-transparent rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  Create Team
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- Team Edit Modal -->
    <div id="team-edit-modal" class="fixed inset-0 z-40 hidden">
      <div
        class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
      >
        <div
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
          aria-hidden="true"
          data-action-click="hideElement" data-arg0="team-edit-modal"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg px-4 pt-5 pb-4 text-left shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full sm:p-6"
          style="max-height: 90vh; overflow-y: auto"
        >
          <div id="team-edit-modal-content">
            <!-- Content will be loaded here -->
          </div>
        </div>
      </div>
    </div>

    <!-- Team Join Requests Modal -->
    <div id="team-join-requests-modal" class="fixed inset-0 z-40 hidden">
      <div
        class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
      >
        <div
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
          aria-hidden="true"
          data-action-click="hideElement" data-arg0="team-join-requests-modal"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full sm:p-6"
        >
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-medium text-gray-900 dark:text-white">
              Team Join Requests
            </h3>
            <button
              data-action-click="hideElement" data-arg0="team-join-requests-modal"
              class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              <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"
                />
              </svg>
            </button>
          </div>
          <div id="team-join-requests-modal-content">
            <!-- Content will be loaded here -->
          </div>
        </div>
      </div>
    </div>

    {% if is_admin %}
    <!-- User Invitation Modal -->
    <div id="invite-user-modal" class="fixed inset-0 z-40 hidden">
      <div
        class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
      >
        <div
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
          aria-hidden="true"
          data-action-click="closeInviteUserModal"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full sm:p-6"
        >
          <div>
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              Invite User to Team
            </h3>
            <form id="invite-user-form" data-action-submit="submitUserInvitation">
              <div class="mb-4">
                <label
                  for="invite-user-select"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Select Existing User</label
                >
                <select
                  id="invite-user-select"
                  name="existing_user"
                  class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white"
                  data-action-change="toggleEmailInput"
                >
                  <option value="">Select existing user...</option>
                </select>
              </div>
              <div class="mb-4">
                <div class="flex items-center mb-2">
                  <div
                    class="flex-1 border-t border-gray-300 dark:border-gray-600"
                  ></div>
                  <span class="px-3 text-sm text-gray-500 dark:text-gray-400"
                    >or</span
                  >
                  <div
                    class="flex-1 border-t border-gray-300 dark:border-gray-600"
                  ></div>
                </div>
                <label
                  for="invite-email"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Invite New User by Email</label
                >
                <input
                  type="email"
                  id="invite-email"
                  name="email"
                  autocomplete="off"
                  class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white"
                  placeholder="user@example.com"
                />
              </div>
              <div class="mb-4">
                <label
                  for="invite-team"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Select Team</label
                >
                <select
                  id="invite-team"
                  name="team_id"
                  required
                  class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white"
                >
                  <option value="">Select a team...</option>
                </select>
              </div>
              <div class="mb-4">
                <label
                  for="invite-role"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Role</label
                >
                <select
                  id="invite-role"
                  name="role"
                  required
                  class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white"
                >
                  <option value="member">Member</option>
                  <option value="admin">Admin</option>
                  <option value="owner">Owner</option>
                </select>
              </div>
              <div class="flex justify-end space-x-3">
                <button
                  type="button"
                  data-action-click="closeInviteUserModal"
                  class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-600 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  Send Invitation
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- Role Assignment Modal -->
    <div id="role-assignment-modal" class="fixed inset-0 z-40 hidden">
      <div
        class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
      >
        <div
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
          aria-hidden="true"
          data-action-click="closeRoleAssignmentModal"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="relative z-20 inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full sm:p-6"
        >
          <div>
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              Assign Role to User
            </h3>
            <form
              id="role-assignment-form"
              data-action-submit="submitRoleAssignment"
            >
              <div class="mb-4">
                <label
                  for="assign-user"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Select User</label
                >
                <select
                  id="assign-user"
                  name="user_email"
                  required
                  class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white"
                >
                  <option value="">Select a user...</option>
                </select>
              </div>
              <div class="mb-4">
                <label
                  for="assign-team"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Select Team</label
                >
                <select
                  id="assign-team"
                  name="team_id"
                  required
                  class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white"
                >
                  <option value="">Select a team...</option>
                </select>
              </div>
              <div class="mb-4">
                <label
                  for="assign-role"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >New Role</label
                >
                <select
                  id="assign-role"
                  name="role"
                  required
                  class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white"
                >
                  <option value="member">Member</option>
                  <option value="admin">Admin</option>
                  <option value="owner">Owner</option>
                </select>
              </div>
              <div class="flex justify-end space-x-3">
                <button
                  type="button"
                  data-action-click="closeRoleAssignmentModal"
                  class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-600 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  class="px-4 py-2 text-sm font-medium text-white bg-green-600 border border-transparent rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
                >
                  Assign Role
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    {% endif %}

    <script nonce="{{ csp_nonce(request) }}">
      // Safely inject teams data for Alpine.js
      window.USER_TEAMS_DATA = {{ user_teams | default([]) | tojson }};

      // Team Management Functions
      function openCreateTeamModal() {
        document.getElementById('create-team-modal').classList.remove('hidden');
        // Focus on team name field
        setTimeout(() => {
          document.getElementById('team-name').focus();
        }, 100);
      }

      function closeCreateTeamModal() {
        document.getElementById('create-team-modal').classList.add('hidden');
        document.getElementById('create-team-form').reset();
      }

      // Filter functions for team list are defined in admin.js (filterTeams, filterByRelationship)
      // to enable server-side search and pagination

      // Safe team action functions using data attributes
      function requestToJoinTeamSafe(button) {
        const teamId = button.getAttribute('data-team-id');
        const teamName = button.getAttribute('data-team-name');
        if (confirm(`Request to join "${teamName}"?`)) {
          // HTMX call to create join request
          htmx.ajax('POST', window.ROOT_PATH + '/admin/teams/' + teamId + '/join-request', {
            target: button.parentElement,
            swap: 'innerHTML'
          }).catch(error => {
            // Handle network errors with toast notification
            showToast('Failed to create join request. Please try again.', 'error');
          });
        }
      }

      function leaveTeamSafe(button) {
        const teamId = button.getAttribute('data-team-id');
        const teamName = button.getAttribute('data-team-name');
        if (confirm(`Leave team "${teamName}"? You will lose access to team resources.`)) {
          htmx.ajax('POST', window.ROOT_PATH + '/admin/teams/' + teamId + '/leave', {
            target: 'body',
            swap: 'none'
          });
          // Backend HX-Trigger handles refresh with proper delay for DB commit
        }
      }

      function editTeamSafe(button) {
        const teamId = button.getAttribute('data-team-id');
        // Clear stale modal content before fetching fresh data to prevent
        // race conditions with the delayed closeTeamEditModal timer.
        var mc = document.getElementById('team-edit-modal-content');
        if (mc) mc.innerHTML = '';
        // Load edit modal content via HTMX
        htmx.ajax('GET', window.ROOT_PATH + '/admin/teams/' + teamId + '/edit', {
          target: '#team-edit-modal-content',
          swap: 'innerHTML'
        }).then(() => {
          document.getElementById('team-edit-modal').classList.remove('hidden');
        });
      }

      function manageTeamMembersSafe(button) {
        const teamId = button.getAttribute('data-team-id');
        loadTeamMembersView(teamId);
      }

      function loadTeamMembersView(teamId) {
        var mc = document.getElementById('team-edit-modal-content');
        if (mc) mc.innerHTML = '';
        htmx.ajax('GET', window.ROOT_PATH + '/admin/teams/' + teamId + '/members', {
          target: '#team-edit-modal-content',
          swap: 'innerHTML'
        }).then(() => {
          document.getElementById('team-edit-modal').classList.remove('hidden');
        });
      }

      function loadAddMembersView(teamId) {
        var mc = document.getElementById('team-edit-modal-content');
        if (mc) mc.innerHTML = '';
        htmx.ajax('GET', window.ROOT_PATH + '/admin/teams/' + teamId + '/members/add', {
          target: '#team-edit-modal-content',
          swap: 'innerHTML'
        }).then(() => {
          document.getElementById('team-edit-modal').classList.remove('hidden');
        });
      }

      function deleteTeamSafe(button) {
        const teamId = button.getAttribute('data-team-id');
        const teamName = button.getAttribute('data-team-name');
        if (confirm(`Delete team "${teamName}"? This action cannot be undone.`)) {
          htmx.ajax('DELETE', window.ROOT_PATH + '/admin/teams/' + teamId, {
            target: 'body',
            swap: 'none'
          });
          // Backend HX-Trigger handles refresh with proper delay for DB commit
        }
      }

      function cancelJoinRequest(teamId, requestId) {
        if (confirm('Cancel your join request?')) {
          htmx.ajax('DELETE', window.ROOT_PATH + '/admin/teams/' + teamId + '/join-request/' + requestId, {
            target: 'body',
            swap: 'none'
          });
          // Backend HX-Trigger handles refresh with proper delay for DB commit
        }
      }

      function viewJoinRequestsSafe(button) {
        const teamId = button.getAttribute('data-team-id');
        // Load join requests modal content
        htmx.ajax('GET', window.ROOT_PATH + '/admin/teams/' + teamId + '/join-requests', {
          target: '#team-join-requests-modal-content',
          swap: 'innerHTML'
        }).then(() => {
          document.getElementById('team-join-requests-modal').classList.remove('hidden');
        });
      }

      function approveJoinRequest(teamId, requestId) {
        if (confirm('Approve this join request?')) {
          htmx.ajax('POST', window.ROOT_PATH + '/admin/teams/' + teamId + '/join-requests/' + requestId + '/approve', {
            target: '#team-join-requests-modal-content',
            swap: 'innerHTML'
          });
        }
      }

      function rejectJoinRequest(teamId, requestId) {
        if (confirm('Reject this join request?')) {
          htmx.ajax('POST', window.ROOT_PATH + '/admin/teams/' + teamId + '/join-requests/' + requestId + '/reject', {
            target: '#team-join-requests-modal-content',
            swap: 'innerHTML'
          });
        }
      }

      // Initialize team management when teams tab is shown
      function initializeTeamManagement() {
        // Load teams list using /teams/partial endpoint
        // Get current search and filter state
        const searchInput = document.getElementById('team-search');
        const searchQuery = searchInput ? searchInput.value.trim() : '';
        const activeFilterBtn = document.querySelector('.filter-btn.active');
        const relationship = activeFilterBtn ? activeFilterBtn.getAttribute('data-filter') : 'all';

        // Preserve current pagination state (use inline Admin.getPaginationParams)
        const paginationState = getPaginationParams('teams');
        const params = new URLSearchParams();
        params.set('page', paginationState.page);
        params.set('per_page', paginationState.perPage);
        if (searchQuery) {
          params.set('q', searchQuery);
        }
        if (relationship && relationship !== 'all') {
          params.set('relationship', relationship);
        }
        const url = window.ROOT_PATH + '/admin/teams/partial?' + params.toString();

        htmx.ajax('GET', url, {
          target: '#unified-teams-list',
          swap: 'innerHTML',
          indicator: '#teams-loading'
        });
      }

      // Set up event listener for teams tab
      document.addEventListener('DOMContentLoaded', function() {
        const teamsTab = document.getElementById('tab-teams');
        if (teamsTab) {
          teamsTab.addEventListener('click', function() {
            // Always refresh teams when tab is clicked
            setTimeout(initializeTeamManagement, 100);
          });
        }

        // Initialize if we're already on the teams tab (support both old and new hash)
        if (window.location.hash === '#teams' || window.location.hash === '#permissions') {
          setTimeout(initializeTeamManagement, 500);
        }

      });

      // Team member management functions are now in admin.js

      // Handle form submission success
      document.addEventListener('htmx:afterRequest', function(evt) {
        if (evt.detail.xhr.status === 201 && evt.detail.elt.id === 'create-team-form') {
          closeCreateTeamModal();
          // Show success message or refresh teams list
          initializeTeamManagement();
        }
      });

      // NOTE: Select All / Clear All handlers for Resources and Prompts are now handled
      // by Admin.initResourceSelect() and Admin.initPromptSelect() functions in admin.js.
      // Those functions properly fetch ALL IDs from the server and maintain state,
      // so items that load via pagination are also included in the selection.
      // The handlers are attached via HTMX's hx-on:htmx:after-swap attribute.

      // Download sample JSON for bulk import
      function downloadSampleJSON() {
        const sampleData = [
          {
            "name": "weather-api",
            "displayName": "Weather API Tool",
            "url": "https://api.openweathermap.org/data/2.5/weather",
            "integration_type": "REST",
            "request_type": "GET",
            "description": "Get current weather data for any location",
            "auth_type": "bearer",
            "auth_value": "your-openweather-api-key-here",
            "headers": {
              "Accept": "application/json",
              "User-Agent": "ContextForge/1.0"
            },
            "input_schema": {
              "type": "object",
              "properties": {
                "q": {"type": "string", "description": "City name, state code and country code divided by comma"},
                "units": {"type": "string", "description": "Temperature units", "enum": ["standard", "metric", "imperial"], "default": "metric"}
              },
              "required": ["q"]
            },
            "jsonpath_filter": "$.main",
            "tags": ["weather", "api", "external"]
          },
          {
            "name": "user-management",
            "displayName": "User Management API",
            "url": "https://api.mycompany.com/v1/users",
            "integration_type": "REST",
            "request_type": "POST",
            "description": "Create new user accounts in the system",
            "auth_type": "basic",
            "auth_value": "api-username:api-password",
            "headers": {
              "Content-Type": "application/json",
              "Accept": "application/json",
              "X-API-Version": "1.0"
            },
            "input_schema": {
              "type": "object",
              "properties": {
                "email": {"type": "string", "format": "email", "description": "User's email address"},
                "firstName": {"type": "string", "description": "User's first name"},
                "lastName": {"type": "string", "description": "User's last name"},
                "role": {"type": "string", "enum": ["user", "admin"], "default": "user"},
                "department": {"type": "string", "description": "User's department"}
              },
              "required": ["email", "firstName", "lastName"]
            },
            "tags": ["users", "crud", "internal"]
          },
          {
            "name": "slack-notify",
            "displayName": "Slack Notification Tool",
            "url": "https://hooks.slack.com/services/your/webhook/url",
            "integration_type": "REST",
            "request_type": "POST",
            "description": "Send notifications to Slack channels",
            "auth_type": "authheaders",
            "auth_value": "Authorization: Bearer xoxb-your-slack-token",
            "headers": {
              "Content-Type": "application/json"
            },
            "input_schema": {
              "type": "object",
              "properties": {
                "channel": {"type": "string", "description": "Slack channel (e.g., #general)"},
                "text": {"type": "string", "description": "Message text"},
                "username": {"type": "string", "description": "Bot username", "default": "ContextForge"}
              },
              "required": ["text"]
            },
            "tags": ["notifications", "slack", "communication"]
          }
        ];

        const blob = new Blob([JSON.stringify(sampleData, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'bulk-import-sample.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }

      // ---------------------------------------------------------------------------
      // OAuth endpoint discovery (RFC 8414 / OIDC Discovery)
      // Called by the 🔍 Discover buttons next to each Issuer URL field.
      // ---------------------------------------------------------------------------
      async function discoverOAuthEndpoints(btn) {
        // DOM layout:
        //   <div>                                  ← grandparent (section wrapper)
        //     <label>Issuer URL</label>
        //     <div class="mt-1 flex gap-2">        ← btn.parentElement
        //       <input name="oauth_issuer" />
        //       <button data-action-click="discoverOAuthEndpoints" data-arg0="this">
        //     </div>
        //     <p>...</p>
        //     <div class="oauth-discover-status">  ← status target
        //   </div>
        const section   = btn.parentElement.parentElement;
        const statusEl  = section.querySelector('.oauth-discover-status');
        const form      = btn.closest('form');

        const issuerInput = form
          ? form.querySelector('input[name="oauth_issuer"]')
          : section.querySelector('input[name="oauth_issuer"]');
        const issuer = issuerInput?.value?.trim();

        if (!issuer) {
          _oauthDiscoverStatus(statusEl, 'error', 'Please enter an Issuer URL first.');
          return;
        }

        btn.disabled    = true;
        btn.textContent = '⏳ Discovering…';
        _oauthDiscoverStatus(statusEl, 'info', 'Contacting issuer metadata endpoint…');

        try {
          const resp = await fetch(
            `${window.ROOT_PATH}/admin/gateways/discover-oauth`,
            {
              method:  'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': getCookie('mcpgateway_csrf_token') || '',
              },
              body:    JSON.stringify({ issuer }),
            }
          );
          const data = await resp.json();

          if (!data.success) {
            _oauthDiscoverStatus(statusEl, 'error',
              `Discovery failed: ${_escHtml(data.error || data.message || 'Unknown error')}. ` +
              'Please configure Token URL and Authorization URL manually.');
            return;
          }

          // Map discovered values → form field names
          const discovered = {
            oauth_token_url:         data.token_endpoint,
            oauth_authorization_url: data.authorization_endpoint,
          };

          let populated = 0;
          for (const [name, value] of Object.entries(discovered)) {
            if (!value) continue;
            const el = form
              ? form.querySelector(`input[name="${name}"]`)
              : document.querySelector(`input[name="${name}"]`);
            if (!el) continue;
            el.value              = value;
            el.dataset.discovered = 'true';
            el.readOnly           = true;
            el.title              = 'Auto-discovered — clear the Issuer URL field to edit manually';
            el.classList.add('bg-gray-50', 'text-gray-500', 'cursor-not-allowed');
            populated++;
          }

          const dcrBadge = data.dcr_available
            ? '<span class="ml-2 inline-flex items-center px-2 py-0.5 text-xs font-medium bg-green-100 text-green-700 rounded">DCR available</span>'
            : '<span class="ml-2 inline-flex items-center px-2 py-0.5 text-xs font-medium bg-gray-100 text-gray-500 rounded">No DCR</span>';

          _oauthDiscoverStatus(statusEl, 'success',
            `✅ Discovered ${populated} endpoint${populated !== 1 ? 's' : ''} from ` +
            `<code class="font-mono text-xs">${_escHtml(issuer)}</code>${dcrBadge}`);

        } catch (err) {
          _oauthDiscoverStatus(statusEl, 'error', `Network error: ${_escHtml(err.message)}`);
        } finally {
          btn.disabled    = false;
          btn.textContent = '🔍 Discover';
        }
      }

      function _oauthDiscoverStatus(el, type, html) {
        if (!el) return;
        const colours = { info: 'text-blue-600', success: 'text-green-600', error: 'text-red-600' };
        el.className = `oauth-discover-status mt-1 text-sm ${colours[type] || ''}`;
        el.innerHTML = html;
        el.classList.remove('hidden');
      }

      function _escHtml(str) {
        return String(str)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      }

      window.Admin = window.Admin || {};
      window.Admin.manageTeamMembersSafe = manageTeamMembersSafe;
      window.Admin.deleteTeamSafe = deleteTeamSafe;
      window.Admin.cancelJoinRequest = cancelJoinRequest;
      window.Admin.discoverOAuthEndpoints = discoverOAuthEndpoints;
      window.Admin.editTeamSafe = editTeamSafe;
      window.Admin.leaveTeamSafe = leaveTeamSafe;
      window.Admin.requestToJoinTeamSafe = requestToJoinTeamSafe;
      window.Admin.viewJoinRequestsSafe = viewJoinRequestsSafe;
      window.Admin.submitUserInvitation = submitUserInvitation;
      window.Admin.submitRoleAssignment = submitRoleAssignment;
      window.Admin.closeInviteUserModal = closeInviteUserModal;
      window.Admin.closeRoleAssignmentModal = closeRoleAssignmentModal;
      window.Admin.toggleEmailInput = toggleEmailInput;
      window.Admin.validateNewUserPassword = validateNewUserPassword;
      if (typeof openBulkImportModal !== 'undefined') window.Admin.openBulkImportModal = openBulkImportModal;
      if (typeof closeBulkImportModal !== 'undefined') window.Admin.closeBulkImportModal = closeBulkImportModal;
      if (typeof toggleImportMethod !== 'undefined') window.Admin.toggleImportMethod = toggleImportMethod;
      if (typeof handleFileSelect !== 'undefined') window.Admin.handleFileSelect = handleFileSelect;
      if (typeof validateJsonInput !== 'undefined') window.Admin.validateJsonInput = validateJsonInput;
      if (typeof toggleValidationGuide !== 'undefined') window.Admin.toggleValidationGuide = toggleValidationGuide;
      if (typeof togglePreviewDetails !== 'undefined') window.Admin.togglePreviewDetails = togglePreviewDetails;
      if (typeof submitBulkImport !== 'undefined') window.Admin.submitBulkImport = submitBulkImport;
      if (typeof toggleBulkImportDropdown !== 'undefined') window.Admin.toggleBulkImportDropdown = toggleBulkImportDropdown;
      if (typeof toggleDropdownImportMethod !== 'undefined') window.Admin.toggleDropdownImportMethod = toggleDropdownImportMethod;
      if (typeof handleDropdownFileSelect !== 'undefined') window.Admin.handleDropdownFileSelect = handleDropdownFileSelect;
      if (typeof validateDropdownJson !== 'undefined') window.Admin.validateDropdownJson = validateDropdownJson;
      if (typeof validateDropdownData !== 'undefined') window.Admin.validateDropdownData = validateDropdownData;
      if (typeof showDropdownStatus !== 'undefined') window.Admin.showDropdownStatus = showDropdownStatus;
      if (typeof showDropdownResults !== 'undefined') window.Admin.showDropdownResults = showDropdownResults;
      if (typeof showDropdownFailedTools !== 'undefined') window.Admin.showDropdownFailedTools = showDropdownFailedTools;
      if (typeof showDropdownActionButtons !== 'undefined') window.Admin.showDropdownActionButtons = showDropdownActionButtons;
      if (typeof resetDropdownImport !== 'undefined') window.Admin.resetDropdownImport = resetDropdownImport;
      if (typeof submitDropdownImport !== 'undefined') window.Admin.submitDropdownImport = submitDropdownImport;
      if (typeof performDropdownImport !== 'undefined') window.Admin.performDropdownImport = performDropdownImport;
      if (typeof downloadSampleJSON !== 'undefined') window.Admin.downloadSampleJSON = downloadSampleJSON;
      if (typeof openCreateTeamModal !== 'undefined') window.Admin.openCreateTeamModal = openCreateTeamModal;
      if (typeof closeCreateTeamModal !== 'undefined') window.Admin.closeCreateTeamModal = closeCreateTeamModal;
    </script>
        </main>
      </div>
    </div>
  </body>
</html>
