<!doctype html>
<html
  lang="en"
  x-data="{ darkMode: JSON.parse(localStorage.getItem('darkMode') || 'false') }"
  x-bind:class="darkMode ? 'dark' : ''"
  x-init="$watch('darkMode', val => localStorage.setItem('darkMode', val))"
>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Context Forge - 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"
    />
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
      tailwind.config = {
        darkMode: "class",
      };
    </script>
    <!-- HTMX for dynamic interactions -->
    <script src="https://unpkg.com/htmx.org@1.9.10"></script>
    <script>
      // 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";

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

      // 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();
      }
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/javascript/javascript.min.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"
      defer
    ></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="{{ root_path }}/static/admin.js"></script>
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/codemirror.min.css"
      rel="stylesheet"
    />
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/theme/monokai.min.css"
      rel="stylesheet"
    />
    <link href="{{ root_path }}/static/admin.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">
    <div class="w-full max-w-screen-2xl mx-auto px-4 py-8">
      <header
        id="sticky-header"
        class="sticky top-0 left-0 right-0 z-50 w-full"
        aria-hidden="false"
      >
        <!-- inner container kept identical to original layout so initial load is unchanged -->
        <div
          class="w-full max-w-screen-2xl mx-auto px-4 py-6 header-inner flex justify-between items-start"
        >
          <!-- LEFT SIDE (exact original content/placement) -->
          <div class="header-left">
            <h1
              class="text-3xl font-bold text-gray-800 dark:text-gray-200 leading-tight"
            >
              Context Forge - Gateway Administration
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-1 header-subtitle">
              AI Gateway and Registry supporting MCP, A2A and REST
              <span class="mx-2 text-gray-400">|</span>
              <a
                href="https://ibm.github.io/mcp-context-forge/"
                target="_blank"
                class="text-indigo-600 dark:text-indigo-500 hover:underline"
                >Docs</a
              >
              <span class="mx-2 text-gray-400">|</span>
              <a
                href="https://github.com/IBM/mcp-context-forge"
                target="_blank"
                class="text-indigo-600 dark:text-indigo-500 hover:underline"
                >⭐ GitHub</a
              >
              <span class="mx-2 text-gray-400">|</span>
              <button
                @click="darkMode = !darkMode"
                class="p-2 text-indigo-600 dark:text-indigo-500 hover:text-indigo-800 dark:hover:text-indigo-300"
              >
                <span x-text="darkMode ? '☀️' : '🌙'"></span>
              </button>
            </p>
          </div>

          <!-- RIGHT SIDE (exact original controls & markup; added lightweight classes for styling on compact) -->
          <div class="flex items-center space-x-4 header-right">
            <!-- Team Selector (preserved) -->
            {% if email_auth_enabled %}
            <div
              class="relative inline-block text-left mr-3"
              x-data="{
                open: false,
                selectedTeam: '',
                selectedTeamName: 'All Teams',
                teams: [],
                init() {
                  this.teams = window.USER_TEAMS_DATA || [];
                  const urlParams = new URLSearchParams(window.location.search);
                  this.selectedTeam = urlParams.get('team_id') || '';
                  if (this.selectedTeam) {
                    const team = this.teams.find(t => t.id === this.selectedTeam);
                    this.selectedTeamName = team ? (team.is_personal ? '👤 ' + team.name : '🏢 ' + team.name) : 'All Teams';
                  }
                }
              }"
            >
              <button
                type="button"
                @click="open = !open"
                id="team-selector-button"
                aria-expanded="false"
                aria-haspopup="true"
                class="inline-flex justify-center items-center px-3 py-1 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 header-team-btn"
              >
                <span x-text="selectedTeamName" class="mr-2">All Teams</span>
                <svg
                  class="ml-2 -mr-1 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"
                @click.away="open = false"
                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-64 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 divide-y divide-gray-100 dark:divide-gray-700 z-50"
                role="menu"
                aria-orientation="vertical"
                aria-labelledby="team-selector-button"
                style="display: none"
              >
                <div class="py-1" role="none">
                  <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>

                  <template x-for="team in teams" :key="team.id">
                    <button
                      @click="selectedTeam = team.id; selectedTeamName = (team.is_personal ? '👤 ' : '🏢 ') + team.name; open = false; updateTeamContext(team.id)"
                      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"
                      x-bind:class="selectedTeam === team.id ? 'bg-blue-50 dark:bg-blue-900' : ''"
                    >
                      <span
                        x-text="(team.is_personal ? '👤 ' : '🏢 ') + team.name"
                      ></span>
                      <span
                        class="text-xs text-gray-500 dark:text-gray-400 ml-2"
                        x-text="team.member_count + ' members'"
                      ></span>
                    </button>
                  </template>
                </div>
              </div>
            </div>
            {% endif %}

            <!-- User Email (preserved) -->
            <div
              class="text-sm text-gray-600 dark:text-gray-400 flex items-center header-user"
            >
              <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>

            <!-- Admin Menu (preserved) -->
            <div
              class="relative inline-block text-left"
              x-data="{ open: false }"
            >
              <div>
                <button
                  type="button"
                  @click="open = !open"
                  id="admin-menu-button"
                  aria-expanded="false"
                  aria-haspopup="true"
                  class="inline-flex justify-center items-center px-3 py-1 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-indigo-500 header-admin-btn"
                >
                  ⚙️ Admin
                  <svg
                    class="ml-2 -mr-1 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>

              <div
                x-show="open"
                @click.away="open = false"
                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-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 divide-y divide-gray-100 dark:divide-gray-700 z-50"
                role="menu"
                aria-orientation="vertical"
                aria-labelledby="admin-menu-button"
                style="display: none"
              >
                <div class="py-1" role="none">
                  {% if email_auth_enabled %}
                  <a
                    href="#users"
                    @click="open = false"
                    class="text-gray-700 dark:text-gray-300 block px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                    role="menuitem"
                    onclick="showTab('users')"
                    >👤 User Management</a
                  >
                  <a
                    href="#tokens"
                    @click="open = false"
                    class="text-gray-700 dark:text-gray-300 block px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                    role="menuitem"
                    onclick="showTab('tokens')"
                    >🎫 API Tokens</a
                  >
                  {% endif %}
                  <a
                    href="#roots"
                    @click="open = false"
                    class="text-gray-700 dark:text-gray-300 block px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                    role="menuitem"
                    onclick="showTab('roots')"
                    >📁 Roots Management</a
                  >
                  <a
                    href="#export-import"
                    @click="open = false"
                    class="text-gray-700 dark:text-gray-300 block px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                    role="menuitem"
                    onclick="showTab('export-import')"
                    >📤 Export/Import</a
                  >
                </div>

                <div class="py-1" role="none">
                  <a
                    href="#logs"
                    @click="open = false"
                    class="text-gray-700 dark:text-gray-300 block px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                    role="menuitem"
                    onclick="showTab('logs')"
                    >📋 System Logs</a
                  >
                  <a
                    href="#version-info"
                    @click="open = false"
                    class="text-gray-700 dark:text-gray-300 block px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                    role="menuitem"
                    onclick="showTab('version-info')"
                    >ℹ️ Version & Environment</a
                  >
                </div>
              </div>
            </div>

            <!-- Logout (preserved) -->
            <form
              method="post"
              action="{{ root_path }}/admin/logout"
              class="inline"
            >
              <button
                type="submit"
                class="px-3 py-1 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 header-logout-btn"
                onclick="return confirm('Are you sure you want to logout?')"
              >
                Logout
              </button>
            </form>
          </div>
        </div>
      </header>

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

      <!-- SENTINEL must be OUTSIDE the header so it scrolls out of view correctly -->
      <div id="header-sentinel" style="height: 1px"></div>

      <script>
        (function () {
          const header = document.getElementById("sticky-header");
          const sentinel = document.getElementById("header-sentinel");
          if (!header || !sentinel) return;

          let compactActive = false;

          const observer = new IntersectionObserver(
            ([entry]) => {
              // when sentinel is NOT intersecting the viewport => we've scrolled past it
              const shouldCompact = !entry.isIntersecting;
              if (shouldCompact !== compactActive) {
                header.classList.toggle("compact", shouldCompact);
                compactActive = shouldCompact;
              }
            },
            {
              rootMargin: "-80px 0px 0px 0px", // trigger when we've scrolled ~80px
              threshold: 0,
            },
          );

          observer.observe(sentinel);
        })();
      </script>

      <!-- Tabs -->
      <div class="mt-8 mb-4">
        <div class="border-b border-gray-200">
          <nav class="-mb-px flex space-x-4 md:space-x-6 lg:space-x-8">
            <a
              href="#gateways"
              id="tab-gateways"
              data-testid="gateways-tab"
              class="tab-link border-indigo-500 text-indigo-600 dark:text-indigo-500 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('gateways')"
            >
              🖥️ MCP Servers
            </a>
            <a
              href="#catalog"
              id="tab-catalog"
              data-testid="servers-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('catalog')"
            >
              🔗 Virtual Servers
            </a>
            <a
              href="#tools"
              id="tab-tools"
              data-testid="tools-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('tools')"
            >
              🛠️ Tools
            </a>
            <a
              href="#prompts"
              id="tab-prompts"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('prompts')"
            >
              💬 Prompts
            </a>
            <a
              href="#resources"
              id="tab-resources"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('resources')"
            >
              📁 Resources
            </a>
            {% if a2a_enabled %}
            <a
              href="#a2a-agents"
              id="tab-a2a-agents"
              data-testid="a2a-agents-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('a2a-agents')"
            >
              🤖 Agents (A2A)
            </a>
            {% endif %}
            {% if grpc_enabled %}
            <a
              href="#grpc-services"
              id="tab-grpc-services"
              data-testid="grpc-services-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('grpc-services')"
            >
              🔌 gRPC Services
            </a>
            {% endif %}
            <a
              href="#metrics"
              id="tab-metrics"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('metrics')"
            >
              📊 Metrics
            </a>
            <a
              href="#plugins"
              id="tab-plugins"
              data-testid="plugins-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('plugins')"
            >
              🔌 Plugins
            </a>
            <a
              href="#mcp-registry"
              id="tab-mcp-registry"
              data-testid="mcp-registry-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('mcp-registry')"
            >
              📦 MCP Registry
            </a>
            {% if llmchat_enabled %}
            <a
              href="#llm-chat" \
              id="tab-llm-chat"
              data-testid="llm-chat-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('llm-chat')">
              👨‍💻 LLM Chat
            </a>
            {% endif %}

            {% if email_auth_enabled %}
            <a
              href="#teams"
              id="tab-teams"
              data-testid="teams-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
              onclick="showTab('teams')"
            >
              👥 Teams
            </a>
            {% endif %}
          </nav>
        </div>
      </div>

      <!-- Logs Panel -->
      <div id="logs-panel" class="tab-panel hidden">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <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>

              <!-- Log Filters -->
              <div 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 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"
                  >
                    <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"
                    >Entity Type</label
                  >
                  <select
                    id="log-entity-filter"
                    class="mt-1 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"
                  >
                    <option value="">All Types</option>
                    <option value="tool">Tool</option>
                    <option value="resource">Resource</option>
                    <option value="server">Server</option>
                    <option value="gateway">Gateway</option>
                  </select>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Search</label
                  >
                  <input
                    type="text"
                    id="log-search"
                    placeholder="Search logs..."
                    class="mt-1 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>

              <!-- Action Buttons -->
              <div class="mb-4 flex gap-2">
                <button
                  onclick="refreshLogs()"
                  class="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                >
                  Refresh
                </button>
                <button
                  onclick="toggleLogStream()"
                  id="stream-toggle"
                  class="px-3 py-2 bg-green-600 text-white rounded hover:bg-green-700"
                >
                  Start Live Stream
                </button>
                <button
                  onclick="exportLogs('json')"
                  class="px-3 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
                >
                  Export JSON
                </button>
                <button
                  onclick="exportLogs('csv')"
                  class="px-3 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
                >
                  Export CSV
                </button>
                <button
                  onclick="showLogFiles()"
                  class="px-3 py-2 bg-purple-600 text-white rounded hover:bg-purple-700"
                >
                  Download Files
                </button>
              </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"
              >
                <span class="text-sm text-gray-600 dark:text-gray-300"
                  >Loading stats...</span
                >
              </div>

              <!-- Log Table -->
              <div class="overflow-x-auto">
                <table
                  class="min-w-full divide-y divide-gray-200 dark:divide-gray-700"
                >
                  <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"
                      >
                        Time
                      </th>
                      <th
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Level
                      </th>
                      <th
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Entity
                      </th>
                      <th
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Message
                      </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
                    onclick="previousLogPage()"
                    id="prev-page"
                    class="px-3 py-1 bg-gray-300 dark:bg-gray-600 rounded disabled:opacity-50"
                    disabled
                  >
                    Previous
                  </button>
                  <button
                    onclick="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>
      </div>

      <!-- Export/Import Panel -->
      <div id="export-import-panel" class="tab-panel hidden">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <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="text"
                          id="import-rekey-secret"
                          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
                      onclick="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>
      </div>
      <!-- Version Info Panel -->
      <div id="version-info-panel" class="tab-panel hidden"></div>

      <!-- Plugins Panel -->
      <div id="plugins-panel" class="tab-panel hidden"></div>

      {% if llmchat_enabled %}
      <!-- LLM Chat Panel -->
      <div id="llm-chat-panel" class="tab-panel hidden">
          <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
              <div class="flex flex-col lg:flex-row gap-6 h-[calc(100vh-12rem)]">

                  <!-- Left Column: Virtual Servers & Info -->
                  <div class="w-full lg:w-80 flex flex-col gap-4 overflow-hidden">

                      <!-- Virtual Servers Card -->
                      <div class="bg-white dark:bg-gray-800 shadow-lg rounded-xl border border-gray-200 dark:border-gray-700 flex flex-col overflow-hidden">
                          <div class="px-5 py-4 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">
                              <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                                  <svg class="w-5 h-5 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>
                                  Virtual Servers
                              </h3>
                              <button onclick="loadVirtualServersForChat()" class="mt-3 w-full px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
                                  <svg class="w-4 h-4 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 Servers
                              </button>
                          </div>

                          <div id="llm-chat-servers-list" class="flex-1 overflow-y-auto p-3">
                              <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>

                      <!-- Environment Info Card -->
                      <div id="llm-info-card" class="bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-900 dark:to-indigo-900 border border-blue-200 dark:border-blue-700 rounded-xl p-4 shadow-sm">
                          <div class="flex items-start">
                              <svg class="h-5 w-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" 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 class="ml-3 flex-1">
                                  <h3 class="text-sm font-semibold text-blue-900 dark:text-blue-200">Environment Variables</h3>
                                  <div class="mt-2 text-xs text-blue-800 dark:text-blue-300 space-y-1">
                                      <p>Configure LLM via environment:</p>
                                      <ul class="list-none mt-1 space-y-0.5 ml-2">
                                          <li>
                                              <button onclick="copyEnvVariables('azure')" class="text-blue-700 dark:text-blue-300 hover:text-blue-900 dark:hover:text-blue-100 underline hover:no-underline transition-colors">
                                                  Copy Azure OpenAI variables
                                              </button>
                                          </li>
                                          <li>
                                              <button onclick="copyEnvVariables('ollama')" class="text-blue-700 dark:text-blue-300 hover:text-blue-900 dark:hover:text-blue-100 underline hover:no-underline transition-colors">
                                                  Copy Ollama variables
                                              </button>
                                          </li>
                                          <li>
                                              <button onclick="copyEnvVariables('openai')" class="text-blue-700 dark:text-blue-300 hover:text-blue-900 dark:hover:text-blue-100 underline hover:no-underline transition-colors">
                                                  Copy OpenAI variables
                                              </button>
                                          </li>
                                      </ul>
                                  </div>
                              </div>
                          </div>
                      </div>
                  </div>

                  <!-- Right Column: Chat Interface -->
                  <div class="flex-1 bg-white dark:bg-gray-800 shadow-xl rounded-xl border border-gray-200 dark:border-gray-700 flex flex-col overflow-hidden">

                      <!-- LLM Configuration Header -->
                      <!-- <div id="llm-config-container" class="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-750"> -->
                        <div id="llm-config-container" class="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-750">

                          <button id="llm-config-toggle" onclick="toggleLLMConfig()" class="w-full px-5 py-3.5 flex items-center justify-between text-left dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                              <div class="flex items-center space-x-3">
                                  <div class="p-2 bg-indigo-100 dark:bg-indigo-900 rounded-lg">
                                      <svg class="w-5 h-5 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>
                                  </div>
                                  <div>
                                      <span class="font-semibold text-gray-900 dark:text-white">LLM Configuration</span>
                                      <span id="llm-connection-status" class="hidden ml-2 inline-flex items-center px-2.5 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.5 animate-pulse"></span>
                                          Connected
                                        </span>
                                        <span id="llm-active-tools-badge" class="hidden ml-2 relative group inline-flex items-center px-2.5 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-50 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>


                                  </div>
                              </div>
                              <svg id="llm-config-chevron" class="w-5 h-5 text-gray-500 dark:text-gray-400 transform transition-transform duration-200" 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>

                          <!-- Configuration Form -->
                          <div id="llm-config-form" class="hidden px-5 pb-5 max-h-96 overflow-y-auto dark:bg-gray-800">
                            <!-- <div id="llm-config-form" class="hidden px-4 pb-4 bg-white dark:bg-gray-800"> -->

                              <form id="llm-chat-config-form" class="space-y-4">
                                  <!-- Provider Selection -->
                                  <div>
                                      <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">LLM Provider</label>
                                      <select id="llm-provider" class="w-full rounded-lg border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-2.5 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300 transition-colors" onchange="handleLLMProviderChange()">
                                          <option value="">Select Provider</option>
                                          <option value="azure_openai">Azure OpenAI</option>
                                          <option value="openai">OpenAI</option>
                                          <option value="anthropic">Anthropic Claude</option>
                                          <option value="aws_bedrock">AWS Bedrock</option>
                                          <option value="ollama">Ollama</option>
                                      </select>
                                  </div>

                                  <!-- Azure OpenAI Fields -->
                                  <div id="azure-openai-fields" class="hidden space-y-3">
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">API Key</label>
                                          <input type="password" id="azure-api-key" 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="Enter API key">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Endpoint</label>
                                          <input type="url" id="azure-endpoint" 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="https://your-resource.openai.azure.com">
                                      </div>
                                      <div class="grid grid-cols-2 gap-3">
                                          <div>
                                              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Deployment</label>
                                              <input type="text" id="azure-deployment" 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="gpt-4">
                                          </div>
                                          <div>
                                              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">API Version</label>
                                              <input type="text" id="azure-api-version" value="2024-02-15-preview" 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>
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Temperature (0-1)</label>
                                          <input type="number" id="azure-temperature" min="0" max="1" 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>
                                  </div>

                                  <!-- OpenAI Fields -->
                                  <div id="openai-fields" class="hidden space-y-3">
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">API Key</label>
                                          <input type="password" id="openai-api-key" 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="sk-...">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Model</label>
                                          <input type="text" id="openai-model" value="gpt-4o-mini" 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="gpt-4o-mini">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Base URL (Optional)</label>
                                          <input type="url" id="openai-base-url" 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="https://api.openai.com/v1">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Temperature (0-2)</label>
                                          <input type="number" id="openai-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>
                                  </div>

                                  <!-- Anthropic Claude Fields -->
                                  <div id="anthropic-fields" class="hidden space-y-3">
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">API Key</label>
                                          <input type="password" id="anthropic-api-key" 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="sk-ant-...">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Model</label>
                                          <input type="text" id="anthropic-model" value="claude-3-5-sonnet-20241022" 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="claude-3-5-sonnet-20241022">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Temperature (0-1)</label>
                                          <input type="number" id="anthropic-temperature" min="0" max="1" 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>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Max Tokens</label>
                                          <input type="number" id="anthropic-max-tokens" value="4096" 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>
                                  </div>

                                  <!-- AWS Bedrock Fields -->
                                  <div id="aws-bedrock-fields" class="hidden space-y-3">
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Model ID</label>
                                          <input type="text" id="aws-bedrock-model-id" 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="anthropic.claude-v2">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">AWS Region</label>
                                          <input type="text" id="aws-bedrock-region" value="us-east-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="us-east-1">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">AWS Access Key (Optional)</label>
                                          <input type="password" id="aws-access-key-id" 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 to use default credential chain">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">AWS Secret Key (Optional)</label>
                                          <input type="password" id="aws-secret-access-key" 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 to use default credential chain">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Temperature (0-1)</label>
                                          <input type="number" id="aws-bedrock-temperature" min="0" max="1" 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>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Max Tokens</label>
                                          <input type="number" id="aws-bedrock-max-tokens" value="4096" 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>
                                  </div>

                                  <!-- Ollama Fields -->
                                  <div id="ollama-fields" class="hidden space-y-3">
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Model</label>
                                          <input type="text" id="ollama-model" 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="llama2">
                                      </div>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Base URL</label>
                                          <input type="url" id="ollama-base-url" value="http://localhost:11434" 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>
                                      <div>
                                          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Temperature (0-1)</label>
                                          <input type="number" id="ollama-temperature" min="0" max="1" 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>
                                  </div>

                                  <!-- Action Buttons -->
                                  <div class="flex space-x-3 pt-2">
                                      <button type="button" id="llm-connect-btn" onclick="connectLLMChat()"
                                          class="flex-1 inline-flex items-center justify-center px-4 py-1.5
                                                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" onclick="disconnectLLMChat()"
                                          class="hidden flex-1 inline-flex items-center justify-center px-4 py-1.5
                                                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 id="llm-config-status" class="hidden text-sm"></div>
                              </form>
                          </div>
                      </div>

                      <!-- Chat Messages Area -->
                      <div id="chat-messages-container" class="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 left panel 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" onsubmit="sendChatMessage(event)" 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"
                                          onkeydown="handleChatInputKeydown(event)"
                                          oninput="this.style.height = 'auto'; this.style.height = Math.min(this.scrollHeight, 120) + 'px'"
                                          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="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>
      </div>
      {% endif %}

      <!-- MCP Registry Panel -->
      <div id="mcp-registry-panel" class="tab-panel hidden">
        <div class="container mx-auto px-4 py-8">
          <!-- Server Grid (includes filters and overview) -->
          <div id="mcp-registry-servers">
            <div class="text-center py-8">
              <div
                class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 dark:border-gray-100"
              ></div>
              <p class="mt-2 text-gray-600 dark:text-gray-400">
                Loading MCP Registry servers...
              </p>
            </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-50"
        >
          <div
            class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white"
          >
            <div class="mt-3">
              <h3 class="text-lg font-medium text-gray-900 mb-4">
                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" onsubmit="submitApiKeyForm(event)">
                <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"
                    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"
                    onclick="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>

      <!-- Catalog Panel (Virtual Servers) -->
      <div id="catalog-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">
              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 space-x-4">
            <input
              type="text"
              id="search-servers"
              data-testid="search-input"
              placeholder="Search servers..."
              class="mt-1 block w-full rounded-md 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"
              oninput="filterServerTable(this.value)"
            />
            <button
              onclick="clearTagFilter('catalog')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div id="catalog-available-tags" class="mt-1 flex flex-wrap gap-1">
              <!-- Tag suggestions 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 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 }}
                  </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"
                      >{{ tag }}</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">
                      {{ server.team.replace(' ', '<br />')|safe }}
                    </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
                        onclick="viewServer('{{ server.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="'💡View server details and configuration'"
                      >
                        View
                      </button>
                      <button
                        onclick="editServer('{{ server.id }}')"
                        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
                        onclick="showConfigSelectionModal('{{ server.id }}', '{{ server.name }}')"
                        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.isActive %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/servers/{{ server.id }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, '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 }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, '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"
                          onsubmit="return handleSubmitWithConfirmation(event, '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>
        <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"
            onreset="document.getElementById('associatedTools').selectedIndex = -1;"
          >
            <div class="grid grid-cols-1 gap-6">
              <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 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>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 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 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 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="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="associatedTools"
                >
                  Associated Tools
                </label>
                <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"
                >
                  {% for tool in tools %}
                  <label
                    class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-indigo-50 dark:hover:bg-indigo-900 rounded-md p-1 tool-item"
                  >
                    <input
                      type="checkbox"
                      name="associatedTools"
                      value="{{ tool.id }}"
                      class="tool-checkbox form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <span class="select-none"
                      >{{ tool.displayName or tool.customName or tool.name
                      }}</span
                    >
                  </label>
                  {% endfor %}
                  <p
                    id="noToolsMessage"
                    class="text-gray-700 dark:text-gray-300"
                    style="display: none"
                  >
                    No tool found containing "<span id="searchQuery"></span>"
                  </p>
                </div>
                <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>
                <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"
                >
                  {% for resource in resources %}
                  <label
                    class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-blue-50 dark:hover:bg-blue-900 rounded-md p-1 resource-item"
                  >
                    <input
                      type="checkbox"
                      name="associatedResources"
                      value="{{ resource.id }}"
                      class="form-checkbox h-5 w-5 text-blue-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <div class="flex-1 min-w-0">
                      <span class="select-none font-medium"
                        >{{ resource.name }}</span
                      >
                      <div
                        class="text-xs text-gray-500 dark:text-gray-400 truncate"
                      >
                        {{ resource.description or resource.uri }}
                      </div>
                    </div>
                  </label>
                  {% endfor %}
                  <p
                    id="noResourcesMessage"
                    class="text-gray-700 dark:text-gray-300"
                    style="display: none"
                  >
                    No resource found containing "<span
                      id="searchResourcesQuery"
                    ></span
                    >"
                  </p>
                </div>
                <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>
              </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"
                >
                  {% for prompt in prompts %}
                  <label
                    class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-purple-50 dark:hover:bg-purple-900 rounded-md p-1 prompt-item"
                  >
                    <input
                      type="checkbox"
                      name="associatedPrompts"
                      value="{{ prompt.id }}"
                      class="form-checkbox h-5 w-5 text-purple-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <div class="flex-1 min-w-0">
                      <span class="select-none font-medium"
                        >{{ prompt.name }}</span
                      >
                      <div
                        class="text-xs text-gray-500 dark:text-gray-400 truncate"
                      >
                        {{ prompt.description or "No description" }}
                      </div>
                    </div>
                  </label>
                  {% endfor %}
                  <p
                    id="noPromptsMessage"
                    class="text-gray-700 dark:text-gray-300"
                    style="display: none"
                  >
                    No prompt found containing "<span
                      id="searchPromptsQuery"
                    ></span
                    >"
                  </p>
                </div>
                <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>
              </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 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>
            <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>
      </div>

      <!-- 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"
              onchange="toggleInactiveItems('tools')"
            />
            <label
              for="show-inactive-tools"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Tag Filtering for Tools -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex items-center space-x-4">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Filter by Tags:</label
            >
            <input
              type="text"
              id="tools-tag-filter"
              placeholder="Enter tags (comma-separated)"
              class="flex-1 rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-1 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
              oninput="filterEntitiesByTags('tools', this.value)"
            />
            <button
              onclick="clearTagFilter('tools')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div id="tools-available-tags" class="mt-1 flex flex-wrap gap-1">
              <!-- Tag suggestions 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 class="overflow-x-auto">
            <!-- Table will be loaded via HTMX -->
            <div id="tools-table"
                 hx-get="{{ root_path }}/admin/tools/partial?page=1&per_page=50&include_inactive={{ include_inactive|default(false)|string|lower }}"
                 hx-trigger="load"
                 hx-swap="outerHTML"
                 hx-indicator="#tools-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 tools...</span>
              </div>
            </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 = (pagination.page if pagination is defined else (page if page is defined else 1)) %}
          {% set per_page = (pagination.per_page if pagination is defined else (per_page if per_page is defined else 50)) %}
          {% set total_items = (pagination.total_items if pagination is defined else (total_items if total_items is defined else (tools|length if tools is defined else 0))) %}
          {% set total_pages = (pagination.total_pages if pagination is defined else ((total_items + per_page - 1) // per_page)) %}
          {% 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
          } %}

          {# 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_indicator = '#tools-loading' %}
            {% set query_params = {'include_inactive': include_inactive} %}

            {% include 'pagination_controls.html' %}
          </div>
        </div>
        <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"
                onclick="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-50"
              >
                <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
                            onclick="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": "MCP-Gateway/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
                          onchange="toggleDropdownImportMethod('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"
                          onchange="toggleDropdownImportMethod('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"
                        onchange="handleDropdownFileSelect(this)"
                        class="hidden"
                      />
                      <div
                        id="dropdown-file-drop-zone"
                        onclick="document.getElementById('dropdown-file-input').click()"
                        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;}]"
                      oninput="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>

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

                  <!-- Action Buttons -->
                  <div class="flex justify-between items-center">
                    <button
                      onclick="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
                        onclick="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"
                        onclick="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-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 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"
                  >Display Name (optional)</label
                >
                <input
                  type="text"
                  name="displayName"
                  placeholder="Custom display name for your UI"
                  class="mt-1 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"
                  >URL</label
                >
                <input
                  type="url"
                  name="url"
                  required
                  class="mt-1 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 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 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"
                  onchange="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 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 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 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 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 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 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"
                    class="mt-1 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"
                    class="mt-1 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"
                    class="mt-1 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"
                      onclick="addAuthHeader('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 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>
      </div>

      <!-- Bulk Import Modal -->
      <div id="bulk-import-modal" class="fixed inset-0 z-[60] 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 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 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>

            <div id="import-result" class="pt-2"></div>
          </form>
        </div>
      </div>

      <!-- 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"
              onchange="toggleInactiveItems('resources')"
            />
            <label
              for="show-inactive-resources"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Tag Filtering for Resources -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex items-center space-x-4">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Filter by Tags:</label
            >
            <input
              type="text"
              id="resources-tag-filter"
              placeholder="Enter tags (comma-separated)"
              class="flex-1 rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-1 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
              oninput="filterEntitiesByTags('resources', this.value)"
            />
            <button
              onclick="clearTagFilter('resources')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div
              id="resources-available-tags"
              class="mt-1 flex flex-wrap gap-1"
            >
              <!-- Tag suggestions 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 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"
                  >
                    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>
                  <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"
                  >
                    MIME Type
                  </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"
                  >
                    Status
                  </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
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for resource in resources %}
                <tr>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.id }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.uri }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.description or "N/A" }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-500"
                  >
                    {{ resource.mimeType or "N/A" }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if resource.tags %} {% for tag in resource.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"
                      >{{ tag }}</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 resource.ownerEmail %}
                    <span class="text-sm text-gray-900 dark:text-gray-100"
                      >{{ resource.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 resource.team %}
                    <span class="text-sm text-gray-900 dark:text-gray-100">
                      {{ resource.team.replace(' ', '<br />')|safe }}
                    </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 resource.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 resource.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 resource.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">
                    <span
                      class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {% if resource.isActive %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}"
                    >
                      {{ "Active" if resource.isActive else "Inactive" }}
                    </span>
                  </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
                        onclick="viewResource('{{ resource.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="'💡View resource details and configuration'"
                      >
                        View
                      </button>
                      <button
                        onclick="editResource('{{ resource.id }}')"
                        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 resource settings and configuration'"
                      >
                        Edit
                      </button>

                      <!-- Row 2: Deactivate/Activate | Delete -->
                      <div class="col-span-2 flex flex-col space-y-1">
                        {% if resource.isActive %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/resources/{{ resource.id }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, 'resources')"
                        >
                          <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/resources/{{ resource.id }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, 'resources')"
                        >
                          <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/resources/{{ resource.id }}/delete"
                          class="contents"
                          onsubmit="return handleSubmitWithConfirmation(event, 'resources')"
                        >
                          <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>

        <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-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >URI</label
                >
                <input
                  type="text"
                  name="uri"
                  required
                  class="mt-1 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"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 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 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"
                  class="mt-1 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"
                />
              </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 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 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>
      </div>

      <!-- 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"
              onchange="toggleInactiveItems('prompts')"
            />
            <label
              for="show-inactive-prompts"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Tag Filtering for Prompts -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex items-center space-x-4">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Filter by Tags:</label
            >
            <input
              type="text"
              id="prompts-tag-filter"
              placeholder="Enter tags (comma-separated)"
              class="flex-1 rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-1 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
              oninput="filterEntitiesByTags('prompts', this.value)"
            />
            <button
              onclick="clearTagFilter('prompts')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div id="prompts-available-tags" class="mt-1 flex flex-wrap gap-1">
              <!-- Tag suggestions 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 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"
                  >
                    ID
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Description
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Arguments
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Tags
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Owner
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Team
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Visibility
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Status
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 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 prompt in prompts %}
                <tr>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ prompt.id }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ prompt.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300"
                  >
                    {{ prompt.description }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal text-sm text-gray-500 dark:text-gray-300"
                  >
                    {% for arg in prompt.arguments %}{{ arg.name }}{% if not
                    loop.last %}, {% endif %}{% endfor %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if prompt.tags %} {% for tag in prompt.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"
                      >{{ tag }}</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 prompt.ownerEmail %}
                    <span class="text-sm text-gray-900 dark:text-gray-100"
                      >{{ prompt.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 prompt.team %}
                    <span class="text-sm text-gray-900 dark:text-gray-100">
                      {{ prompt.team.replace(' ', '<br />')|safe }}
                    </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 prompt.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 prompt.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 prompt.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">
                    <span
                      class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {% if prompt.isActive %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}"
                    >
                      {{ "Active" if prompt.isActive else "Inactive" }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="grid grid-cols-2 gap-x-6 gap-y-0 max-w-48">
                      <!-- Row 1: Test -->
                      <button
                        onclick="testPrompt('{{ prompt.id }}')"
                        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 this prompt with sample arguments to see how it renders'"
                      >
                        Test
                      </button>

                      <!-- Row 2: View | Edit -->
                      <button
                        onclick="viewPrompt('{{ prompt.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="'💡View prompt details and configuration'"
                      >
                        View
                      </button>
                      <button
                        onclick="editPrompt('{{prompt.id }}')"
                        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 prompt settings and configuration'"
                      >
                        Edit
                      </button>

                      <!-- Row 3: Deactivate/Activate | Delete -->
                      <div class="col-span-2 flex flex-col space-y-1">
                        {% if prompt.isActive %}
                        <form
                          method="POST"
                          action="{{ root_path }}/admin/prompts/{{ prompt.id }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, 'prompts')"
                        >
                          <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/prompts/{{ prompt.id }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, 'prompts')"
                        >
                          <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/prompts/{{ prompt.id }}/delete"
                          class="contents"
                          onsubmit="return handleSubmitWithConfirmation(event, 'prompts')"
                        >
                          <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>

        <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-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 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 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 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 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 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>
      </div>

      <!-- 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"
              onchange="toggleInactiveItems('gateways')"
            />
            <label
              for="show-inactive-gateways"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Gateway Filter Section -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex flex-wrap gap-4 items-center">
            <div class="flex-1 min-w-64">
              <label
                for="gateway-tag-filter"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Filter by Tags:</label
              >
              <input
                type="text"
                id="gateway-tag-filter"
                placeholder="e.g., production,external (comma-separated)"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                oninput="filterEntitiesByTags('gateways', this.value)"
              />
            </div>
            <div id="gateway-available-tags" class="flex flex-wrap gap-2">
              <!-- Available tags will be populated by JavaScript -->
            </div>
            <button
              onclick="clearTagFilter('gateways')"
              class="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-600 dark:text-gray-300 dark:border-gray-500 dark:hover:bg-gray-500"
            >
              Clear Filter
            </button>
          </div>
        </div>

        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <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"
                  >
                    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>
                  <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"
                      >{{ tag }}</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-10 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-2 py-4 whitespace-nowrap">
                    {% if gateway.team %}
                    <span class="text-sm text-gray-900 dark:text-gray-100">
                      {{ gateway.team.replace(' ', '<br />')|safe }}
                    </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
                        onclick="testGateway('{{ gateway.url }}')"
                        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
                        onclick="fetchToolsForGateway('{{ gateway.id }}', '{{ gateway.name }}')"
                        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
                        onclick="viewGateway('{{ 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="'💡View gateway details and configuration'"
                      >
                        View
                      </button>
                      <button
                        onclick="editGateway('{{ gateway.id }}')"
                        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
                        onclick="viewGateway('{{ 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="'💡View gateway details and configuration'"
                      >
                        View
                      </button>
                      <button
                        onclick="editGateway('{{ gateway.id }}')"
                        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 }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, '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 }}/toggle"
                          class="contents"
                          onsubmit="return handleToggleSubmit(event, '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"
                          onsubmit="return handleSubmitWithConfirmation(event, '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>

        <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 MCP Server or Gateway
          </h3>
          <form method="POST" id="add-gateway-form">
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >MCP Server Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 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"
                  >MCP Server URL</label
                >
                <input
                  type="url"
                  name="url"
                  required
                  class="mt-1 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 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 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"
                      checked
                    />
                    <label
                      for="edit-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"
                    />
                    <label
                      for="edit-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"
                    />
                    <label
                      for="edit-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 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 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-gw" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Username</label
                  >
                  <input
                    type="text"
                    name="auth_username"
                    class="mt-1 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"
                    class="mt-1 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-gw" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Token</label
                  >
                  <input
                    type="password"
                    name="auth_token"
                    class="mt-1 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-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"
                      onclick="addAuthHeader('auth-headers-container-gw')"
                      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-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 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>
                    <input
                      type="url"
                      name="oauth_issuer"
                      class="mt-1 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"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      The OAuth Authorization Server issuer URL. Required for DCR (Dynamic Client Registration).
                    </p>
                  </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 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"
                      class="mt-1 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"
                      class="mt-1 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"
                      class="mt-1 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 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 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 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 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>
                <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 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="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>
      </div>

      <!-- Teams Panel -->
      {% if email_auth_enabled %}
      <div id="teams-panel" class="tab-panel hidden">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <!-- 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>
            <button
              id="create-team-btn"
              onclick="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>
          </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 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"
                  oninput="filterTeams(this.value)"
                />
              </div>
              <div class="flex gap-2">
                <button
                  onclick="filterByRelationship('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
                  onclick="filterByRelationship('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
                  onclick="filterByRelationship('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
                  onclick="filterByRelationship('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>

          <!-- Teams List -->
          <div id="unified-teams-list" class="space-y-4">
            <div class="text-center py-8">
              <div class="animate-pulse text-gray-500 dark:text-gray-400">
                Loading teams...
              </div>
              <div class="text-xs text-gray-400 dark:text-gray-500 mt-2">
                Note: Team management requires email authentication
              </div>
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- User Management Panel -->
      {% if email_auth_enabled %}
      <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 -->
        <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="#users-list"
              hx-swap="afterbegin"
              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
                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm bg-gray-300 dark:bg-gray-700 dark:border-gray-600"
                    placeholder="user@example.com"
                  />
                </div>
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Full Name *
                  </label>
                  <input
                    type="text"
                    name="full_name"
                    required
                    class="mt-1 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"
                    name="password"
                    required
                    minlength="8"
                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600"
                    placeholder="Strong password"
                  />
                </div>
                <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"
                  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>

        <!-- 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>
            <div
              id="users-list"
              hx-get="{{ root_path }}/admin/users"
              hx-trigger="load"
            >
              <p class="text-gray-500 dark:text-gray-400">
                <span class="animate-pulse">Loading users...</span>
                <br /><small class="text-xs"
                  >Note: User management requires email authentication</small
                >
              </p>
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- API Tokens Panel -->
      {% if email_auth_enabled %}
      <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>

        <!-- Create Token Form -->
        <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-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"
                >
                  Token Name *
                </label>
                <input
                  type="text"
                  name="name"
                  required
                  maxlength="255"
                  class="mt-1 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"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >
                  Expires In (Days)
                </label>
                <input
                  type="number"
                  name="expires_in_days"
                  min="1"
                  max="365"
                  value="30"
                  class="mt-1 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"
                />
              </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 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">
                            <!-- Public Access Token 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">Public Access Token</span>
                                    </h3>
                                </div>
                                <div class="mt-1 text-sm text-yellow-700 dark:text-yellow-300">
                                    <p class="mb-1">
                                        You are currently viewing <span class="font-semibold">"All Teams"</span>. Tokens created in this context will have <span class="font-semibold">public-only access</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>
                                    </ul>
                                    <p class="mt-2 mb-1"><span class="font-semibold">❌ This token CANNOT access:</span></p>
                                    <ul class="list-disc list-inside ml-4 space-y-1">
                                        <li>Team-scoped or private 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">
                                    To create a token with full Team Access, select a specific team from the header above.
                                </p>
                            </div>
                        </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 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 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 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>
          </form>
        </div>

        <!-- 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>
            <div id="tokens-list">
              <p class="text-gray-500 dark:text-gray-400">Loading tokens...</p>
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- A2A Agents Panel -->
      {% if a2a_enabled %}
      <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"
              onchange="toggleInactiveItems('a2a-agents')"
            />
            <label
              for="show-inactive-a2a-agents"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- A2A Agent Filter Section -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex flex-wrap gap-4 items-center">
            <div class="flex-1 min-w-64">
              <label
                for="a2a-agent-tag-filter"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Filter by Tags:</label
              >
              <input
                type="text"
                id="a2a-agent-tag-filter"
                placeholder="e.g., ai,assistant (comma-separated)"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                oninput="filterEntitiesByTags('a2a-agents', this.value)"
              />
            </div>
            <div id="a2a-agent-available-tags" class="flex flex-wrap gap-2">
              <!-- Available tags will be populated by JavaScript -->
            </div>
            <button
              onclick="clearTagFilter('a2a-agents')"
              class="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-600 dark:text-gray-300 dark:border-gray-500 dark:hover:bg-gray-500"
            >
              Clear Filter
            </button>
          </div>
        </div>

        <!-- A2A Agent 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">
            Add New A2A Agent
          </h3>
          <form method="POST" id="add-a2a-form">
            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <!-- Agent Name -->
              <div>
                <label
                  for="a2a-agent-name"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Agent Name</label
                >
                <input
                  type="text"
                  id="a2a-agent-name"
                  name="name"
                  required
                  placeholder="my-assistant-agent"
                  class="mt-1 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>

              <!-- Endpoint URL -->
              <div>
                <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"
                  id="a2a-agent-endpoint-url"
                  name="endpoint_url"
                  required
                  placeholder="https://api.example.com/agent"
                  class="mt-1 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>

              <!-- 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 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="a2a-agent-auth-type"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Authentication Type</label
                >
                <select
                  id="a2a-agent-auth-type"
                  name="auth_type"
                  class="mt-1 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="api_key">API Key</option>
                  <option value="bearer">Bearer Token</option>
                  <option value="oauth">OAuth</option>
                </select>
              </div>

              <!-- Authentication Value -->
              <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."
                  class="mt-1 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 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 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>

              <!-- 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>

              <!-- 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>

        <!-- A2A Agents List -->
        <div class="bg-white shadow rounded-lg dark:bg-gray-800">
          <div class="p-6">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4"
            >
              Registered A2A Agents
            </h3>
            <div class="space-y-4">
              {% if a2a_agents %} {% for agent in a2a_agents %}
              <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"
                    >
                      {{ agent.name }}
                    </h4>
                    <p class="text-sm text-gray-600 dark:text-gray-400">
                      {{ agent.description or "" }}
                    </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 agent.enabled %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}"
                      >
                        {% if agent.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 agent.reachable %}bg-green-100 text-green-800{% else %}bg-yellow-100 text-yellow-800{% endif %}"
                      >
                        {% if agent.reachable %}Reachable{% else %}Unreachable{%
                        endif %}
                      </span>
                      <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                      >
                        {{ agent.agentType }}
                      </span>
                      <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800"
                      >
                        Auth: {{ agent.authType or "None" }}
                      </span>
                    </div>
                    <div class="mt-2 text-xs text-gray-500 dark:text-gray-400">
                      <div>Endpoint: {{ agent.endpointUrl }}</div>
                      <div>
                        Executions: {{ agent.metrics.totalExecutions }} |
                        Success Rate: {% if agent.metrics.totalExecutions %}{{
                        "%.1f"|format(100 - agent.metrics.failureRate) }}%{%
                        else %}N/A{% endif %}
                      </div>
                      <div>
                        Created: {{ agent.createdAt.strftime('%Y-%m-%d
                        %H:%M:%S') }}
                      </div>
                      {% if agent.lastInteraction %}
                      <div>
                        Last Interaction: {{
                        agent.lastInteraction.strftime('%Y-%m-%d %H:%M:%S') }}
                      </div>
                      {% endif %}
                    </div>
                    {% if agent.tags %}
                    <div class="mt-2 flex flex-wrap gap-1">
                      {% for tag in agent.tags %}
                      <span
                        class="inline-flex items-center px-2 py-1 rounded text-xs bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300"
                        >{{ tag }}</span
                      >
                      {% endfor %}
                    </div>
                    {% endif %}
                    <!-- Test result placeholder -->
                    <div
                      id="test-result-{{ agent.id }}"
                      class="mt-2 p-2 rounded-md bg-gray-50 dark:bg-gray-700 hidden"
                    ></div>
                  </div>
                  <div class="flex space-x-2">
                    <!--- Adding a2a-agents VIEW HERE -->
                    <button
                      onclick="viewAgent('{{ agent.id }}')"
                      class="px-3 py-1 text-sm font-medium text-indigo-700 bg-indigo-100 hover:bg-indigo-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                      x-tooltip="'💡View Agent A2A details and configuration'"
                    >
                      View
                    </button>
                    <!--- Adding a2a-agents EDIT HERE -->
                    <button
                      class="px-3 py-1 text-sm font-medium text-green-700 bg-green-100 hover:bg-green-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
                      x-tooltip="'Edit Agent A2A details and configuration'"
                    >
                      Edit
                    </button>
                    <button
                      onclick="testA2AAgent('{{ agent.id }}', '{{ agent.name }}', '{{ agent.endpointUrl }}')"
                      class="px-3 py-1 text-sm font-medium text-blue-700 bg-blue-100 hover:bg-blue-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    >
                      Test
                    </button>
                    <form
                      method="post"
                      action="{{ root_path }}/admin/a2a/{{ agent.id }}/toggle"
                      class="inline"
                    >
                      <input
                        type="hidden"
                        name="activate"
                        value="{% if agent.enabled %}false{% else %}true{% endif %}"
                      />
                      <button
                        type="submit"
                        class="px-3 py-1 text-sm font-medium {% if agent.enabled %}text-red-700 bg-red-100 hover:bg-red-200{% else %}text-green-700 bg-green-100 hover:bg-green-200{% endif %} rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                      >
                        {% if agent.enabled %}Deactivate{% else %}Activate{%
                        endif %}
                      </button>
                    </form>
                    <form
                      method="post"
                      action="{{ root_path }}/admin/a2a/{{ agent.id }}/delete"
                      class="inline"
                      onsubmit="return confirm('Are you sure you want to delete this A2A agent?')"
                    >
                      <button
                        type="submit"
                        class="px-3 py-1 text-sm font-medium text-red-700 bg-red-100 hover:bg-red-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                      >
                        Delete
                      </button>
                    </form>
                  </div>
                </div>
              </div>
              {% endfor %} {% else %}
              <div class="text-center py-8">
                <p class="text-gray-500 dark:text-gray-400">
                  No A2A agents registered yet.
                </p>
              </div>
              {% endif %}
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- gRPC Services Panel -->
      {% if grpc_enabled %}
      <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 action="{{ root_path }}/grpc" method="POST" id="add-grpc-service-form">
            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <!-- Service Name -->
              <div>
                <label
                  for="grpc-service-name"
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Service Name</label
                >
                <input
                  type="text"
                  id="grpc-service-name"
                  name="name"
                  required
                  placeholder="my-grpc-service"
                  class="mt-1 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>

              <!-- 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 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 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"
                  onchange="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 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 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 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 %}
            </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>
          </form>
        </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 "" }}
                    </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 }}/grpc/{{ service.id }}/toggle" 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 }}/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
                      onclick="viewGrpcMethods('{{ service.id }}')"
                      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 }}/grpc/{{ service.id }}/delete" method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this gRPC service?')">
                      <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 %}

      <!-- 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 class="flex items-center">
              <input
                type="checkbox"
                id="show-inactive-roots"
                class="mr-2"
                onchange="toggleInactiveItems('roots')"
              />
              <label
                for="show-inactive-roots"
                class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >
                Show Inactive
              </label>
            </div>
          </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 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"
                  >
                    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>
                  <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
                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 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>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="grid grid-cols-2 gap-1 max-w-48">
                      <!-- Row 1: View | Edit -->
                      <button
                        onclick="viewRoot('{{ root.uri }}')"
                        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 virtual server details and configuration'"
                      >
                        View
                      </button>
                      <button
                        onclick="editRoot('{{ root.uri }}')"
                        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 virtual server settings and configuration'"
                      >
                        Edit
                      </button>

                      <!-- Row 2: Export -->
                      <button
                        onclick="exportRoot('{{ root.uri }}')"
                        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="'💡Export virtual server configuration'"
                      >
                        Export
                      </button>

                      <!-- Row 3: Deactivate | Delete -->
                      <button
                        onclick="deactivateRoot('{{ root.uri }}')"
                        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"
                        x-tooltip="'💡Temporarily disable this virtual server (can be re-activated)'"
                      >
                        Deactivate
                      </button>
                      <form
                        method="POST"
                        action="{{ root_path }}/admin/roots/{{ root.uri }}/delete"
                        class="contents"
                        onsubmit="return handleSubmitWithConfirmation(event, 'roots')"
                      >
                        <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>
                  </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"
            onsubmit="return handleToggleSubmit(event, 'roots')"
          >
            <div class="grid grid-cols-1 gap-6">
              <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 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>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  class="mt-1 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>

      <!-- 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>

        <!-- Aggregated Metrics Section (managed by JavaScript) -->
        <div id="aggregated-metrics-section" class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h2 class="text-2xl font-bold dark:text-gray-200 mb-4">
            Aggregated Metrics
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Metrics provide visibility into Tool, Resource, Prompt, and Server
            usage across your Gateway-helpful for debugging and optimization.
          </p>

          <!-- Refresh button (also auto-refreshes when the tab is selected) -->
          <button
            onclick="loadAggregatedMetrics()"
            class="mb-4 px-4 py-2 bg-indigo-600 text-white rounded"
          >
            Refresh Metrics
          </button>

          <!-- Aggregated Metrics Table -->
          <div
            id="aggregated-metrics-content"
            class="overflow-auto mb-6 bg-gray-100"
          ></div>

          <!-- Overall Bar Chart for Total Executions -->
          <canvas
            id="metricsChart"
            width="400"
            height="200"
            class="bg-white"
          ></canvas>

          <hr class="my-6" />

          <!-- Expandable sections for top items -->
          <details id="top-tools-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Tools by Executions
            </summary>
            <div id="top-tools-content" class="mt-4"></div>
          </details>

          <details id="top-resources-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Resources by Executions
            </summary>
            <div id="top-resources-content" class="mt-4"></div>
          </details>

          <details id="top-servers-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Servers by Executions
            </summary>
            <div id="top-servers-content" class="mt-4"></div>
          </details>

          <details id="top-prompts-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Prompts by Executions
            </summary>
            <div id="top-prompts-content" class="mt-4"></div>
          </details>
        </div>
      </div>

      <!-- Modals -->
      <!-- Tool Detail Modal -->
      <div id="tool-modal" class="fixed z-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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"
                onclick="closeModal('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>

      <!-- Tool Test Modal -->
      <div
        id="tool-test-modal"
        class="fixed z-10 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" 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="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"
                    onclick="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"
                onclick="closeModal('tool-test-modal', '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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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-6">
                    <input type="hidden" name="name" id="edit-tool-name" />

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="customName"
                        required
                        id="edit-tool-custom-name"
                        class="mt-1 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"
                        >Display Name</label
                      >
                      <input
                        type="text"
                        name="displayName"
                        id="edit-tool-display-name"
                        placeholder="Custom display name for your UI"
                        class="mt-1 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"
                        >URL</label
                      >
                      <input
                        type="url"
                        name="url"
                        required
                        id="edit-tool-url"
                        class="mt-1 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"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-tool-description"
                        class="mt-1 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 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"
                        onchange="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 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 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 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 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 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 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>
                        <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"
                          class="mt-1 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"
                          class="mt-1 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"
                          class="mt-1 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"
                          onclick="addAuthHeader('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 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"
                      onclick="closeModal('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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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"
                onclick="closeModal('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 Edit Modal -->
      <div
        id="resource-edit-modal"
        class="fixed z-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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-6">
                    <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 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"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-resource-name"
                        class="mt-1 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"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-resource-description"
                        class="mt-1 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"
                        class="mt-1 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"
                        >Content</label
                      >
                      <!-- Remove required attribute to avoid browser validation issues -->
                      <textarea
                        name="content"
                        id="edit-resource-content"
                        class="mt-1 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 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"
                      onclick="closeModal('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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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-400"
                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"
                onclick="closeModal('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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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-6">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-prompt-name"
                        class="mt-1 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"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-prompt-description"
                        class="mt-1 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 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 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 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"
                      onclick="closeModal('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-10 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" 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="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"
                      onclick="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"
                onclick="closeModal('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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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"
                onclick="closeModal('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-50 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"
          >
            <div>
              <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 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
              />
            </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 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 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 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-body"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Body (JSON)</label
              >
              <textarea
                id="gateway-test-body"
                class="mt-1 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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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-6">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-gateway-name"
                        class="mt-1 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"
                        >URL</label
                      >
                      <input
                        type="url"
                        name="url"
                        required
                        id="edit-gateway-url"
                        class="mt-1 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"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-gateway-description"
                        class="mt-1 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 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 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 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>
                      </select>
                    </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"
                          class="mt-1 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
                        >
                        <input
                          type="password"
                          name="auth_password"
                          class="mt-1 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 id="auth-bearer-fields-gw-edit" style="display: none">
                      <div>
                        <label class="block text-sm font-medium text-gray-700"
                          >Token</label
                        >
                        <input
                          type="password"
                          name="auth_token"
                          class="mt-1 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 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"
                            onclick="addAuthHeader('auth-headers-container-gw-edit')"
                            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-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 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>
                          <input
                            type="url"
                            name="oauth_issuer"
                            id="oauth-issuer-gw-edit"
                            class="mt-1 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"
                          />
                          <p class="mt-1 text-sm text-gray-500">
                            The OAuth Authorization Server issuer URL. Required for DCR.
                          </p>
                        </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 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"
                            class="mt-1 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-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"
                            class="mt-1 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-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"
                            class="mt-1 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 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 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="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 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"
                                >http://localhost:4444/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 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>
                      <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 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"
                      onclick="closeModal('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>

      <!-- Server Detail Modal -->
      <div id="server-modal" class="fixed z-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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"
                onclick="closeModal('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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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-6">
                    <!-- 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 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>
                      <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 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>
                    <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 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 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 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-visibility-public"
                          />
                          <label
                            for="edit-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-visibility-team"
                          />
                          <label
                            for="edit-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-visibility-private"
                          />
                          <label
                            for="edit-visibility-private"
                            class="ml-2 text-sm text-gray-700 dark:text-gray-400"
                            >🔒Private</label
                          >
                        </div>
                      </div>
                    </div>

                    <div
                      class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-600"
                    >
                      <label
                        for="edit-server-tools"
                        class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Associated Tools
                      </label>
                      <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"
                      >
                        {% for tool in tools %}
                        <label
                          class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-indigo-50 dark:hover:bg-indigo-900 rounded-md p-1"
                        >
                          <input
                            type="checkbox"
                            name="associatedTools"
                            value="{{ tool.id }}"
                            class="tool-checkbox form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                          />
                          <span class="select-none"
                            >{{ tool.displayName or tool.customName or tool.name
                            }}</span
                          >
                        </label>
                        {% endfor %}
                      </div>
                      <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
                      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>
                      <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"
                      >
                        {% for resource in resources %}
                        <label
                          class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-blue-50 dark:hover:bg-blue-900 rounded-md p-1"
                        >
                          <input
                            type="checkbox"
                            name="associatedResources"
                            value="{{ resource.id }}"
                            class="resource-checkbox form-checkbox h-5 w-5 text-blue-600 dark:bg-gray-800 dark:border-gray-600"
                          />
                          <span class="select-none">{{ resource.name }}</span>
                        </label>
                        {% endfor %}
                      </div>
                      <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>
                      <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"
                      >
                        {% for prompt in prompts %}
                        <label
                          class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-purple-50 dark:hover:bg-purple-900 rounded-md p-1"
                        >
                          <input
                            type="checkbox"
                            name="associatedPrompts"
                            value="{{ prompt.id }}"
                            class="prompt-checkbox form-checkbox h-5 w-5 text-purple-600 dark:bg-gray-800 dark:border-gray-600"
                          />
                          <span class="select-none">{{ prompt.name }}</span>
                        </label>
                        {% endfor %}
                      </div>
                      <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
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      onclick="closeModal('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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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"
                onclick="closeModal('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>

      <!-- Config Selection Modal -->
      <div
        id="config-selection-modal"
        class="fixed z-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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"
                  onclick="generateAndShowConfig('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"
                  onclick="generateAndShowConfig('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"
                  onclick="generateAndShowConfig('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"
                onclick="closeModal('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-10 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" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="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
                  onclick="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
                onclick="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
                onclick="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"
                onclick="closeModal('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>
    </div>
    <!-- Scripts -->
    <script>
      // 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.toolMapping = {};
      {% for tool in tools %}
      window.toolMapping["{{ tool.id }}"] = "{{ tool.name }}";
      {% endfor %}

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

      window.promptMapping = {};
      {% for prompt in prompts %}
      window.promptMapping["{{ prompt.id }}"] = "{{ prompt.name }}";
      {% endfor %}

      window.ROOT_PATH = {{ root_path | 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 }};

      // 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.history.replaceState({}, '', cleanUrl);
          }, 5000);
        }
      })();

      // Tag filtering functionality moved to admin.js
      function clearTagFilter(entityType) {
        const input = document.getElementById(entityType + '-tag-filter');
        input.value = '';
        // Use the corrected filterEntitiesByTags function from admin.js
        if (typeof filterEntitiesByTags === 'function') {
          filterEntitiesByTags(entityType, '');
        }
      }


      // Team context switching functions
      function updateTeamContext(teamId) {
        // Prevent double-invocation if user clicks rapidly
        if (window.__teamSwitchingInProgress) {
          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 reloadAllResourceSections(teamId) {
        // delegate to the implementation in admin.js
        if (window.reloadAllResourceSections) {
          return window.reloadAllResourceSections(teamId);
        } else {
          console.warn('reloadAllResourceSections implementation not available.');
        }
      }

      function updateSectionHeaders(teamId) {
        const sections = ['tools', 'resources', 'prompts', 'servers', 'gateways'];

        sections.forEach(section => {
          const header = document.querySelector('#' + section + '-section h2');
          if (header) {
            // Remove existing team badge
            const existingBadge = header.querySelector('.team-badge');
            if (existingBadge) {
              existingBadge.remove();
            }

            // Add team badge if team is selected
            if (teamId && teamId !== '') {
              const teamName = getTeamNameById(teamId);
              if (teamName) {
                const badge = document.createElement('span');
                badge.className = 'team-badge inline-flex items-center px-2 py-1 ml-2 text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 rounded-full';
                badge.textContent = teamName;
                header.appendChild(badge);
              }
            }
          }
        });
      }

      function updateSectionDisplay(sectionType, items) {
        const tbody = document.querySelector('#' + sectionType + '-section tbody');
        if (!tbody) return;

        // Clear existing rows
        tbody.innerHTML = '';

        // Add new rows
        items.forEach(item => {
          const row = createRowElement(sectionType, item);
          tbody.appendChild(row);
        });
      }

      function createRowElement(sectionType, item) {
        const row = document.createElement('tr');

        // Create row content based on section type
        if (sectionType === 'tools') {
          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.id)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.name || item.customName || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${escapeHtml(item.description || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${escapeHtml(item.url || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createTagsSpan(item.tags)}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createStatusSpan(item.isActive)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">${createActionButtons(sectionType, item)}</td>
          `;
        } else if (sectionType === 'resources') {
          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.id)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.name || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${escapeHtml(item.description || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${escapeHtml(item.uri || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createTagsSpan(item.tags)}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createStatusSpan(item.isActive)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">${createActionButtons(sectionType, item)}</td>
          `;
        } else if (sectionType === 'prompts') {
          const argsText = item.arguments ? item.arguments.map(arg => escapeHtml(arg.name)).join(', ') : '';
          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.id)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.name || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${escapeHtml(item.description || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${argsText}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createTagsSpan(item.tags)}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createStatusSpan(item.isActive)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">${createActionButtons(sectionType, item)}</td>
          `;
        } else if (sectionType === 'servers') {
          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.id)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.name || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${escapeHtml(item.description || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createTagsSpan(item.tags)}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createStatusSpan(item.isActive)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">${createActionButtons(sectionType, item)}</td>
          `;
        } else if (sectionType === 'gateways') {
          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.id)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${escapeHtml(item.name || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${escapeHtml(item.host || '')}:${escapeHtml(item.port || '')}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createTagsSpan(item.tags)}</td>
            <td class="px-6 py-4 whitespace-nowrap">${createStatusSpan(item.isActive)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">${createActionButtons(sectionType, item)}</td>
          `;
        }

        return row;
      }

      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('');
      }

      function createStatusSpan(isActive) {
        if (isActive) {
          return '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Active</span>';
        } else {
          return '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Inactive</span>';
        }
      }

      function createActionButtons(sectionType, item) {
        const activeButton = item.isActive ?
          `<form method="POST" action="${window.ROOT_PATH}/admin/${sectionType}/${item.id}/toggle" class="inline mr-2" onsubmit="return handleToggleSubmit(event, '${sectionType}')">
            <input type="hidden" name="activate" value="false" />
            <button type="submit" class="text-yellow-600 hover:text-yellow-900">Deactivate</button>
          </form>` :
          `<form method="POST" action="${window.ROOT_PATH}/admin/${sectionType}/${item.id}/toggle" class="inline mr-2" onsubmit="return handleToggleSubmit(event, '${sectionType}')">
            <input type="hidden" name="activate" value="true" />
            <button type="submit" class="text-blue-600 hover:text-blue-900">Activate</button>
          </form>`;

        let buttons = activeButton;

        // Add specific buttons based on section type
        if (sectionType === 'tools') {
          buttons += `<button onclick="invokeTool('${item.name}')" class="text-indigo-600 dark:text-indigo-500 hover:text-indigo-900 mr-2">Invoke</button>`;
        } else if (sectionType === 'prompts') {
          buttons += `<button onclick="viewPrompt('${item.id}')" class="text-indigo-600 dark:text-indigo-500 hover:text-indigo-900 mr-2">View</button>`;
        } else if (sectionType === 'servers') {
          buttons += `<button onclick="viewServer('${item.id}')" class="text-indigo-600 dark:text-indigo-500 hover:text-indigo-900 mr-2">View</button>`;
        }

        // Show Edit/Delete buttons - check ownership, admin status, and team owner permissions
        const itemOwner = item.owner_email || item.ownerEmail;
        const isDirectOwner = itemOwner === window.CURRENT_USER;
        const isPlatformAdmin = window.IS_ADMIN;

        // Check if user is team owner for team-scoped resources
        // Note: Check both team_id (snake_case) and teamId (camelCase from model_dump(by_alias=True))
        let isTeamOwner = false;
        const itemTeamId = item.team_id || item.teamId;
        if (item.visibility === 'team' && itemTeamId && window.USER_TEAMS) {
          const userTeam = window.USER_TEAMS.find(t => t.id === itemTeamId);
          isTeamOwner = userTeam && userTeam.role === 'owner';
        }

        // User can edit if: platform admin, direct owner, or team owner for team resources
        const canEdit = isPlatformAdmin || isDirectOwner || isTeamOwner;

        // Edit button
        const editDisabled = canEdit ? '' : 'disabled';
        const editTitle = canEdit ? '' : 'title="You can only edit resources you own or resources in teams you manage"';
        const editClass = canEdit ? 'text-green-600 hover:text-green-900' : 'text-gray-400 cursor-not-allowed';
        const editOnclick = canEdit ? `onclick="edit${sectionType.charAt(0).toUpperCase() + sectionType.slice(1, -1)}('${item.id}')"` : 'onclick="return false;"';
        buttons += `<button ${editDisabled} ${editTitle} ${editOnclick} class="${editClass} mr-2">Edit</button>`;

        // Delete button
        const deleteDisabled = canEdit ? '' : 'disabled';
        const deleteTitle = canEdit ? '' : 'title="You can only delete resources you own or resources in teams you manage"';
        const deleteClass = canEdit ? 'text-red-600 hover:text-red-900' : 'text-gray-400 cursor-not-allowed';
        const deleteOnclick = canEdit ? `onclick="delete${sectionType.charAt(0).toUpperCase() + sectionType.slice(1, -1)}('${item.id}')"` : 'onclick="return false;"';
        buttons += `<button ${deleteDisabled} ${deleteTitle} ${deleteOnclick} class="${deleteClass}">Delete</button>`;

        return buttons;
      }



      // Permission Management Functions
      function refreshVisibilityRules() {
        console.log('Refreshing visibility rules...');
        const tableBody = document.getElementById('visibility-rules-table');

        if (tableBody) {
          tableBody.innerHTML = '<tr><td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500 dark:text-gray-400">Resource visibility management is available in the main admin panels (Tools, Resources, Prompts, Servers, Gateways). Use the individual panels to modify resource visibility settings.</td></tr>';
        }
      }

      function displayVisibilityRules(rules) {
        const tableBody = document.getElementById('visibility-rules-table');

        if (rules.length === 0) {
          tableBody.innerHTML = '<tr><td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500 dark:text-gray-400">No resources found</td></tr>';
          return;
        }

        tableBody.innerHTML = '';
        rules.forEach(rule => {
          const row = document.createElement('tr');
          const teamName = rule.team_id ? getTeamNameById(rule.team_id) || rule.team_id : 'None';

          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">${rule.name}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300 capitalize">${rule.type}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${teamName}</td>
            <td class="px-6 py-4 whitespace-nowrap">
              <select class="text-xs px-2 py-1 rounded ${getVisibilityBadgeClass(rule.visibility)}" onchange="updateResourceVisibility('${rule.type}', '${rule.id}', this.value)">
                <option value="private" ${rule.visibility === 'private' ? 'selected' : ''}>Private</option>
                <option value="team" ${rule.visibility === 'team' ? 'selected' : ''}>Team</option>
                <option value="public" ${rule.visibility === 'public' ? 'selected' : ''}>Public</option>
              </select>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
              <button onclick="editResourcePermissions('${rule.type}', '${rule.id}')" class="text-indigo-600 hover:text-indigo-900 mr-2">Edit</button>
            </td>
          `;
          tableBody.appendChild(row);
        });
      }

      function getVisibilityBadgeClass(visibility) {
        switch(visibility) {
          case 'private': return 'bg-red-100 text-red-800';
          case 'team': return 'bg-blue-100 text-blue-800';
          case 'public': return 'bg-green-100 text-green-800';
          default: return 'bg-gray-100 text-gray-800';
        }
      }

      function updateResourceVisibility(type, id, visibility) {
        console.log(`Updating ${type} ${id} visibility to ${visibility}`);
        // TODO: Make API call to update resource visibility
        alert(`Visibility update logged. ${type} ${id} → ${visibility}`);
      }

      function editResourcePermissions(type, id) {
        console.log(`Editing permissions for ${type} ${id}`);
        alert(`Permission editing for ${type} resources coming soon`);
      }

      function bulkUpdateVisibility() {
        const visibility = prompt('Enter visibility level (private, team, public):');
        if (!visibility || !['private', 'team', 'public'].includes(visibility.toLowerCase())) {
          alert('Invalid visibility level. Please enter: private, team, or public');
          return;
        }

        if (!confirm(`Are you sure you want to set ALL resources to ${visibility}? This will affect all tools, resources, prompts, servers, and gateways.`)) {
          return;
        }

        console.log('Bulk updating all resources to visibility:', visibility);

        // TODO: Implement actual bulk update API call
        alert(`Bulk visibility update to "${visibility}" logged to console. API integration pending.`);

        // Refresh the rules table to show changes
        setTimeout(refreshVisibilityRules, 1000);
      }

      function openInviteUserModal() {
        console.log('Opening invite user modal...');

        // Populate existing users dropdown
        const userSelect = document.getElementById('invite-user-select');
        userSelect.innerHTML = '<option value="">Select existing user...</option>';

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

        // Add authentication if available
        const token = localStorage.getItem('auth_token') || sessionStorage.getItem('auth_token');
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }

        fetch(window.ROOT_PATH + '/admin/users?format=json', { headers })
          .then(response => {
            if (response.ok) {
              return response.json();
            }
            throw new Error(`HTTP ${response.status}`);
          })
          .then(data => {
            if (data.users && Array.isArray(data.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);
              });
            }
          })
          .catch(error => {
            console.warn('Could not load users:', error);
          });

        // Populate teams dropdown
        const teamSelect = document.getElementById('invite-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:', teamsData.length);
        }
        // Method 2: Alpine.js component (backup)
        else {
          console.log('Trying Alpine.js component...');
          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:', 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 invite modal`);
        } else {
          console.warn('No teams data found for invite 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);
        }

        // Show modal
        document.getElementById('invite-user-modal').classList.remove('hidden');
      }

      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
        const token = localStorage.getItem('auth_token') || sessionStorage.getItem('auth_token');
        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);
        });
      }

      function exportPermissions() {
        console.log('Exporting permissions...');

        // Collect all current permission data
        const sections = ['tools', 'resources', 'prompts', 'servers', 'gateways'];
        let exportData = {
          export_date: new Date().toISOString(),
          permissions: []
        };

        // Load and export current permissions
        Promise.all(
          sections.map(section =>
            fetch(window.ROOT_PATH + '/admin/sections/' + section)
              .then(response => response.json())
              .catch(error => ({ [section]: [] }))
          )
        ).then(results => {
          results.forEach((data, index) => {
            const section = sections[index];
            if (data[section]) {
              data[section].forEach(item => {
                exportData.permissions.push({
                  id: item.id,
                  name: item.name,
                  type: section.slice(0, -1),
                  team_id: item.team_id || null,
                  visibility: item.visibility || 'private',
                  owner_email: item.owner_email || null
                });
              });
            }
          });

          // Create and download JSON file
          const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `permissions-export-${new Date().toISOString().split('T')[0]}.json`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);

          alert('Permissions exported successfully!');
        });
      }

      function auditPermissions() {
        console.log('Auditing permissions...');

        const sections = ['tools', 'resources', 'prompts', 'servers', 'gateways'];
        let auditResults = {
          total_resources: 0,
          private_resources: 0,
          team_resources: 0,
          public_resources: 0,
          unassigned_resources: 0,
          resource_breakdown: {}
        };

        Promise.all(
          sections.map(section =>
            fetch(window.ROOT_PATH + '/admin/sections/' + section)
              .then(response => response.json())
              .catch(error => ({ [section]: [] }))
          )
        ).then(results => {
          results.forEach((data, index) => {
            const section = sections[index];
            const sectionType = section.slice(0, -1);
            auditResults.resource_breakdown[sectionType] = {
              total: 0,
              private: 0,
              team: 0,
              public: 0,
              unassigned: 0
            };

            if (data[section]) {
              data[section].forEach(item => {
                auditResults.total_resources++;
                auditResults.resource_breakdown[sectionType].total++;

                const visibility = item.visibility || 'private';
                auditResults[visibility + '_resources']++;
                auditResults.resource_breakdown[sectionType][visibility]++;

                if (!item.team_id && !item.owner_email) {
                  auditResults.unassigned_resources++;
                  auditResults.resource_breakdown[sectionType].unassigned++;
                }
              });
            }
          });

          // Display audit results
          let auditHtml = `
            <div style="background: white; padding: 20px; border-radius: 8px; max-width: 600px; margin: 20px auto; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
              <h3 style="margin-bottom: 15px; color: #333;">🔍 Permission Audit Results</h3>
              <p><strong>Total Resources:</strong> ${auditResults.total_resources}</p>
              <p><strong>Private:</strong> ${auditResults.private_resources} | <strong>Team:</strong> ${auditResults.team_resources} | <strong>Public:</strong> ${auditResults.public_resources}</p>
              <p><strong>Unassigned:</strong> ${auditResults.unassigned_resources}</p>
              <hr style="margin: 15px 0;">
              <h4>Breakdown by Type:</h4>
          `;

          Object.entries(auditResults.resource_breakdown).forEach(([type, stats]) => {
            auditHtml += `<p><strong>${type}:</strong> ${stats.total} (Private: ${stats.private}, Team: ${stats.team}, Public: ${stats.public})</p>`;
          });

          auditHtml += `</div>`;

          const auditWindow = window.open('', '_blank', 'width=650,height=500');
          auditWindow.document.write(`
            <html><head><title>Permission Audit</title></head><body>
            ${auditHtml}
            <div style="text-align: center; margin-top: 20px;">
              <button onclick="window.print()" style="padding: 10px 20px; background: #4F46E5; color: white; border: none; border-radius: 4px; cursor: pointer;">Print Report</button>
              <button onclick="window.close()" style="padding: 10px 20px; background: #6B7280; color: white; border: none; border-radius: 4px; cursor: pointer; margin-left: 10px;">Close</button>
            </div>
            </body></html>
          `);
        });
      }

      function makeAllResourcesPrivate() {
        if (confirm('Are you sure you want to make all resources private? This will affect all users and restrict access to resource owners only.')) {
          console.log('Making all resources private...');

          // TODO: Implement actual API call to update all resources to private
          alert('All resources set to private visibility. API integration pending - change logged to console.');

          // Refresh the visibility rules to show changes
          setTimeout(refreshVisibilityRules, 1000);
        }
      }

      function makeTeamResourcesVisible() {
        const teamSelector = document.querySelector('[x-data*="selectedTeam"]');
        let currentTeam = null;

        if (teamSelector && teamSelector._x_dataStack && teamSelector._x_dataStack[0].selectedTeam) {
          currentTeam = teamSelector._x_dataStack[0].selectedTeam;
        }

        if (!currentTeam) {
          alert('Please select a team first using the team selector in the header.');
          return;
        }

        if (confirm(`Make all resources visible to team "${teamSelector._x_dataStack[0].selectedTeamName}"? This will set team visibility for all resources.`)) {
          console.log(`Making all resources visible to team: ${currentTeam}`);

          // TODO: Implement actual API call to update resources to team visibility
          alert(`All resources set to team visibility for selected team. API integration pending - change logged to console.`);

          // Refresh the visibility rules to show changes
          setTimeout(refreshVisibilityRules, 1000);
        }
      }


      // Cleaned up - old functions removed

      // addTagToFilter function moved to admin.js

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

      });

      // Add search functionality for filtering tools
    </script>
    <script>
      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;
      let currentLogPage = 0;
      const logsPerPage = 100;

      async function refreshLogs() {
        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({
          limit: logsPerPage,
          offset: currentLogPage * logsPerPage,
          order: "desc",
        });

        if (level) params.append("level", level);
        if (entityType) params.append("entity_type", entityType);
        if (search) params.append("search", search);

        try {
          const headers = {};
          const token = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

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

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

          const data = await response.json();
          displayLogs(data.logs);
          updateLogStats(data.stats);
          updateLogCount(data.total);
        } catch (error) {
          console.error("Error fetching logs:", error);
          showErrorMessage("Failed to fetch logs");
        }
      }

      function displayLogs(logs) {
        const tbody = document.getElementById("logs-tbody");
        tbody.innerHTML = "";

        logs.forEach((log) => {
          const row = document.createElement("tr");
          row.className = "hover:bg-gray-50 dark:hover:bg-gray-700";

          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.appendChild(row);
        });
      }

      function getLevelClass(level) {
        switch (level) {
          case "debug":
            return "bg-gray-100 text-gray-800";
          case "info":
            return "bg-blue-100 text-blue-800";
          case "warning":
            return "bg-yellow-100 text-yellow-800";
          case "error":
            return "bg-red-100 text-red-800";
          case "critical":
            return "bg-red-600 text-white";
          default:
            return "bg-gray-100 text-gray-800";
        }
      }

      function updateLogStats(stats) {
        if (!stats) return;

        const statsDiv = document.getElementById("log-stats");
        const levelDist = stats.level_distribution || {};
        const entityDist = stats.entity_distribution || {};

        let html = `
          <div class="flex flex-wrap gap-4 text-sm">
            <span>Buffer: ${stats.usage_percent || 0}% (${stats.buffer_size_mb || 0}/${stats.max_size_mb || 0} MB)</span>
            <span>Total: ${stats.total_logs || 0} logs</span>
        `;

        if (Object.keys(levelDist).length > 0) {
          html += "<span>Levels: ";
          for (const [level, count] of Object.entries(levelDist)) {
            html += `${level}(${count}) `;
          }
          html += "</span>";
        }

        html += "</div>";
        statsDiv.innerHTML = html;
      }

      function updateLogCount(total) {
        document.getElementById("log-count").textContent = `${total} logs`;

        // Update pagination buttons
        document.getElementById("prev-page").disabled = currentLogPage === 0;
        document.getElementById("next-page").disabled =
          (currentLogPage + 1) * logsPerPage >= total;
      }

      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 = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

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

          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 = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

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

          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-50";
            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 onclick="downloadLogFile('${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 onclick="this.closest('.fixed').remove()"
                        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");
        }
      }

      async function downloadLogFile(filename) {
        try {
          const headers = {};
          const token = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

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

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

          const blob = await response.blob();
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = filename;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);

          // Close the modal if it exists
          const modal = document.querySelector(".fixed.inset-0");
          if (modal) modal.remove();

          showSuccessMessage(`Downloaded: ${filename}`);
        } catch (error) {
          console.error("Error downloading log file:", error);
          showErrorMessage(error.message || "Failed to download log file");
        }
      }

      function previousLogPage() {
        if (currentLogPage > 0) {
          currentLogPage--;
          refreshLogs();
        }
      }

      function nextLogPage() {
        currentLogPage++;
        refreshLogs();
      }

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

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

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

        // Load logs when logs tab is clicked
        const logsTab = document.getElementById("tab-logs");
        if (logsTab) {
          logsTab.addEventListener("click", () => {
            setTimeout(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");

          // 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) {
              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");
                document.getElementById("import-submit-btn").disabled = false;
              }
            } else {
              showImportError(result.message || "Import failed");
              document.getElementById("import-submit-btn").disabled = false;
            }
          } catch (error) {
            document.getElementById("import-loading").classList.add("hidden");
            showImportError(`Network error: ${error.message}`);
            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";

          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">
                  <h3 class="text-sm font-medium text-${textColor}-800 dark:text-${textColor}-200">
                    ${isPartialSuccess ? "Import Partially Completed" : "Import Completed Successfully"}
                  </h3>
                  <div class="mt-2 text-sm text-${textColor}-700 dark:text-${textColor}-300">
                    <p><strong>${result.created_count}</strong> tools imported successfully</p>
                    ${result.failed_count > 0 ? `<p><strong>${result.failed_count}</strong> tools failed to import</p>` : ""}
                    ${
                      result.errors && result.errors.length > 0
                        ? `
                      <details class="mt-2">
                        <summary class="cursor-pointer">View errors</summary>
                        <ul class="mt-1 list-disc list-inside text-xs">
                          ${result.errors
                            .slice(0, 5)
                            .map(
                              (error) =>
                                `<li>${error.name || "Tool"}: ${error.error?.message || "Unknown error"}</li>`,
                            )
                            .join("")}
                          ${result.errors.length > 5 ? `<li>... and ${result.errors.length - 5} more errors</li>` : ""}
                        </ul>
                      </details>
                    `
                        : ""
                    }
                    <p class="mt-2 text-xs">Page will refresh automatically...</p>
                  </div>
                </div>
              </div>
            </div>
          `;
          statusDiv.classList.remove("hidden");
        }

        // Show import error message
        function showImportError(message) {
          const statusDiv = document.getElementById("import-status");
          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">
                  <h3 class="text-sm font-medium text-red-800 dark:text-red-200">
                    Import Error
                  </h3>
                  <div class="mt-2 text-sm text-red-700 dark:text-red-300">
                    <p>${escapeHtml(message)}</p>
                  </div>
                </div>
              </div>
            </div>
          `;
          statusDiv.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");
          status.innerHTML = `<div class="text-${type === "error" ? "red" : "green"}-600">${escapeHtml(message)}</div>`;
          status.classList.remove("hidden");
        };

        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-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) {
              showDropdownStatus(
                "success",
                `✅ Successfully imported ${result.imported} tools`,
              );
              resetDropdownImport();
              setTimeout(() => {
                window.location.reload();
              }, 2000);
            } else {
              showDropdownStatus(
                "error",
                `❌ Import failed: ${result.detail || "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-50"
    >
      <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
              onclick="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
                        onclick="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
                    onchange="toggleImportMethod(this.value)"
                    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"
                    onchange="toggleImportMethod(this.value)"
                    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"
                        onchange="handleFileSelect(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 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"
                  onclick="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"
                    onclick="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"
                onclick="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"
                onclick="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-50 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="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-50 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"
          onclick="closeCreateTeamModal()"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="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
                onclick="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="#unified-teams-list"
              hx-swap="afterbegin"
            >
              <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 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">
                    Maximum 100 characters
                  </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 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"
                    max="1000"
                    value="50"
                    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">
                    Optional, defaults to 50
                  </p>
                </div>
              </div>

              <div class="mt-6 flex justify-end space-x-3">
                <button
                  type="button"
                  onclick="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-50 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"
          onclick="document.getElementById('team-edit-modal').classList.add('hidden')"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="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="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-50 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"
          onclick="document.getElementById('team-join-requests-modal').classList.add('hidden')"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="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
              onclick="document.getElementById('team-join-requests-modal').classList.add('hidden')"
              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>

    <!-- User Invitation Modal -->
    <div id="invite-user-modal" class="fixed inset-0 z-50 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"
          onclick="closeInviteUserModal()"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="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" onsubmit="submitUserInvitation(event)">
              <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"
                  onchange="toggleEmailInput(this.value)"
                >
                  <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"
                  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"
                  onclick="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-50 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"
          onclick="closeRoleAssignmentModal()"
        ></div>
        <span
          class="hidden sm:inline-block sm:align-middle sm:h-screen"
          aria-hidden="true"
          >&#8203;</span
        >
        <div
          class="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"
              onsubmit="submitRoleAssignment(event)"
            >
              <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"
                  onclick="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>

    <script>
      // 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
      let currentTeamFilter = 'all';
      let currentSearchFilter = '';

      function filterTeams(searchTerm) {
        currentSearchFilter = searchTerm.toLowerCase();
        applyTeamFilters();
      }

      function filterByRelationship(relationship) {
        currentTeamFilter = relationship;

        // Update active filter button
        document.querySelectorAll('.filter-btn').forEach(btn => {
          btn.classList.remove('active', 'bg-indigo-600', 'text-white');
          btn.classList.add('bg-white', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
        });

        const activeBtn = document.querySelector(`[data-filter="${relationship}"]`);
        if (activeBtn) {
          activeBtn.classList.add('active', 'bg-indigo-600', 'text-white');
          activeBtn.classList.remove('bg-white', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
        }

        applyTeamFilters();
      }

      function applyTeamFilters() {
        const teamCards = document.querySelectorAll('.team-card');

        teamCards.forEach(card => {
          const teamName = card.querySelector('.team-name')?.textContent.toLowerCase() || '';
          const teamDescription = card.querySelector('.team-description')?.textContent.toLowerCase() || '';
          const relationshipBadge = card.querySelector('.relationship-badge')?.textContent.toLowerCase() || '';

          // Check search filter
          const matchesSearch = currentSearchFilter === '' ||
                              teamName.includes(currentSearchFilter) ||
                              teamDescription.includes(currentSearchFilter);

          // Check relationship filter
          let matchesRelationship = true;
          if (currentTeamFilter === 'owner') {
            matchesRelationship = relationshipBadge.includes('owner');
          } else if (currentTeamFilter === 'member') {
            matchesRelationship = relationshipBadge.includes('member') && !relationshipBadge.includes('owner');
          } else if (currentTeamFilter === 'public') {
            matchesRelationship = relationshipBadge.includes('join');
          }
          // 'all' filter shows everything

          if (matchesSearch && matchesRelationship) {
            card.style.display = 'block';
          } else {
            card.style.display = 'none';
          }
        });
      }

      // 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'
          });
        }
      }

      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: '#unified-teams-list',
            swap: 'innerHTML'
          }).then(() => {
            initializeTeamManagement(); // Refresh the full list
          });
        }
      }

      function editTeamSafe(button) {
        const teamId = button.getAttribute('data-team-id');
        // 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');
        // Load team members management modal
        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 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: '#unified-teams-list',
            swap: 'innerHTML'
          }).then(() => {
            initializeTeamManagement(); // Refresh the full list
          });
        }
      }

      function cancelJoinRequest(teamId, requestId) {
        if (confirm('Cancel your join request?')) {
          htmx.ajax('DELETE', window.ROOT_PATH + '/admin/teams/' + teamId + '/join-request/' + requestId, {
            target: '#unified-teams-list',
            swap: 'innerHTML'
          }).then(() => {
            initializeTeamManagement(); // Refresh the full list
          });
        }
      }

      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 unified teams list
        htmx.ajax('GET', window.ROOT_PATH + '/admin/teams?unified=true', {
          target: '#unified-teams-list',
          swap: 'innerHTML'
        });
      }

      // Set up event listener for teams tab
      document.addEventListener('DOMContentLoaded', function() {
        const teamsTab = document.getElementById('tab-teams');
        if (teamsTab) {
          teamsTab.addEventListener('click', function() {
            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();
        }
      });

      // Select All / Clear All handlers for create server form
      document.addEventListener('DOMContentLoaded', function() {
        // Resources Select All / Clear All for create form
        const selectAllResourcesBtn = document.getElementById('selectAllResourcesBtn');
        const clearAllResourcesBtn = document.getElementById('clearAllResourcesBtn');
        if (selectAllResourcesBtn && clearAllResourcesBtn) {
          selectAllResourcesBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#associatedResources input[type="checkbox"][name="associatedResources"]');
            checkboxes.forEach(checkbox => checkbox.checked = true);
          });
          clearAllResourcesBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#associatedResources input[type="checkbox"][name="associatedResources"]');
            checkboxes.forEach(checkbox => checkbox.checked = false);
          });
        }

        // Prompts Select All / Clear All for create form
        const selectAllPromptsBtn = document.getElementById('selectAllPromptsBtn');
        const clearAllPromptsBtn = document.getElementById('clearAllPromptsBtn');
        if (selectAllPromptsBtn && clearAllPromptsBtn) {
          selectAllPromptsBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#associatedPrompts input[type="checkbox"][name="associatedPrompts"]');
            checkboxes.forEach(checkbox => checkbox.checked = true);
          });
          clearAllPromptsBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#associatedPrompts input[type="checkbox"][name="associatedPrompts"]');
            checkboxes.forEach(checkbox => checkbox.checked = false);
          });
        }

        // Select All / Clear All handlers for edit server form (should already exist but let's add them)
        const selectAllEditResourcesBtn = document.getElementById('selectAllEditResourcesBtn');
        const clearAllEditResourcesBtn = document.getElementById('clearAllEditResourcesBtn');
        if (selectAllEditResourcesBtn && clearAllEditResourcesBtn) {
          selectAllEditResourcesBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#edit-server-resources input[type="checkbox"][name="associatedResources"]');
            checkboxes.forEach(checkbox => checkbox.checked = true);
          });
          clearAllEditResourcesBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#edit-server-resources input[type="checkbox"][name="associatedResources"]');
            checkboxes.forEach(checkbox => checkbox.checked = false);
          });
        }

        const selectAllEditPromptsBtn = document.getElementById('selectAllEditPromptsBtn');
        const clearAllEditPromptsBtn = document.getElementById('clearAllEditPromptsBtn');
        if (selectAllEditPromptsBtn && clearAllEditPromptsBtn) {
          selectAllEditPromptsBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#edit-server-prompts input[type="checkbox"][name="associatedPrompts"]');
            checkboxes.forEach(checkbox => checkbox.checked = true);
          });
          clearAllEditPromptsBtn.addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('#edit-server-prompts input[type="checkbox"][name="associatedPrompts"]');
            checkboxes.forEach(checkbox => checkbox.checked = false);
          });
        }
      });

      // 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": "MCP-Gateway/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": "MCP Gateway"}
              },
              "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);
      }
    </script>
  </body>
</html>
