<!-- htmlhint doctype-first:false -->
<table id="gateways-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-center text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Actions</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">S. No.</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Gateway ID</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Name</th>
      <th class="px-6 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-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Tags</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Status</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Last Seen</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Owner</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Team</th>
      <th class="px-6 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider">Visibility</th>
    </tr>
  </thead>
  <tbody id="gateways-table-body" class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700">
    {% for gateway in data %}
      {% set gateway_label = gateway.name or gateway.id %}
      {% set can_modify = is_admin or gateway.ownerEmail == current_user_email or (gateway.visibility == 'team' and gateway.teamId and user_team_roles.get(gateway.teamId|string) == 'owner') %}
      {% set can_authorize = can_modify or gateway.visibility == 'public' or (gateway.visibility == 'team' and gateway.teamId and gateway.teamId|string in user_team_roles) %}
      <tr id="gateway-row-{{ gateway.id }}" data-enabled="{{ gateway.enabled|lower }}" data-owner-email="{{ gateway.ownerEmail }}" data-team-id="{{ gateway.teamId or '' }}" data-visibility="{{ gateway.visibility }}">
        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
          <div class="relative"
               x-data="Admin.overflowMenu('gateways-table-wrapper')"
               @click.away="menuOpen = false"
               @keydown.escape="menuOpen = false; $refs.trigger.focus()">
            <!-- Three-dot trigger -->
            <button
              type="button"
              x-ref="trigger"
              @click="menuOpen ? (menuOpen = false) : openMenu()"
              class="p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-gray-200 dark:hover:bg-gray-700 transition-colors"
              :aria-expanded="menuOpen"
              aria-haspopup="menu"
              aria-label="Actions"
              x-tooltip="'Actions'"
            >
              <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                <path d="M6 10a2 2 0 11-4 0 2 2 0 014 0zm6 0a2 2 0 11-4 0 2 2 0 014 0zm6 0a2 2 0 11-4 0 2 2 0 014 0z"/>
              </svg>
            </button>

            <!-- Dropdown menu (fixed-positioned to escape overflow/scroll containers) -->
            <div
              x-ref="menu"
              x-cloak
              x-show="menuOpen"
              x-transition:enter="transition ease-out duration-100"
              x-transition:enter-start="opacity-0 scale-95"
              x-transition:enter-end="opacity-100 scale-100"
              x-transition:leave="transition ease-in duration-75"
              x-transition:leave-start="opacity-100 scale-100"
              x-transition:leave-end="opacity-0 scale-95"
              class="fixed w-44 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-50 py-1"
              :style="`top: ${menuTop}px; left: ${menuLeft}px; display: ${menuOpen ? 'block' : 'none'}`"
              role="menu"
              aria-orientation="vertical"
              @keydown.arrow-down.prevent="navigate(1)"
              @keydown.arrow-up.prevent="navigate(-1)"
            >
              <!-- Test -->
              <button
                type="button"
                role="menuitem"
                tabindex="0"
                @click="menuOpen = false; Admin.testGateway({{ gateway.url|tojson_attr }})"
                class="w-full flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
              >Test</button>

              {% if gateway.authType == 'oauth' and can_authorize %}
              <!-- OAuth Authorize -->
              <a
                href="{{ root_path }}/oauth/authorize/{{ gateway.id }}"
                @click="menuOpen = false"
                role="menuitem"
                tabindex="0"
                class="flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
              >🔐 Authorize</a>
              {% endif %}

              {% if can_modify %}
              <!-- Fetch / Refresh Tools (all auth types) -->
              <button
                type="button"
                role="menuitem"
                tabindex="0"
                id="refresh-tools-{{ gateway.id }}"
                @click="menuOpen = false; Admin.refreshGatewayTools({{ gateway.id|tojson_attr }}, {{ gateway.name|tojson_attr }}, $event.currentTarget)"
                class="w-full flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                x-tooltip="'{% if gateway.toolCount == 0 %}First-time fetch from MCP server{% else %}Re-fetch latest tools from MCP server{% endif %}'"
              >{% if gateway.toolCount == 0 %}Fetch Tools{% else %}Refresh Tools{% endif %}</button>
              {% endif %}

              <hr class="border-gray-200 dark:border-gray-600 my-1">

              <!-- View -->
              <button
                type="button"
                role="menuitem"
                tabindex="0"
                @click="menuOpen = false; Admin.viewGateway({{ gateway.id|tojson_attr }})"
                class="w-full flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
              >View</button>

              {% if can_modify %}
              <!-- Edit -->
              <button
                type="button"
                role="menuitem"
                tabindex="0"
                @click="menuOpen = false; Admin.editGateway({{ gateway.id|tojson_attr }})"
                class="w-full flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
              >Edit</button>

              <hr class="border-gray-200 dark:border-gray-600 my-1">

              <!-- Activate / Deactivate -->
              <form method="POST" action="{{ root_path }}/admin/gateways/{{ gateway.id }}/state" class="contents" @submit="menuOpen = false" data-action-submit="handleToggleSubmit" data-arg0="gateways">
                <input type="hidden" name="activate" value="{{ 'false' if gateway.enabled else 'true' }}" />
                <button
                  type="submit"
                  role="menuitem"
                  tabindex="0"
                  class="w-full flex items-center px-4 py-2 text-sm {% if gateway.enabled %}text-yellow-600 dark:text-yellow-400{% else %}text-green-600 dark:text-green-400{% endif %} hover:bg-gray-100 dark:hover:bg-gray-700"
                >{% if gateway.enabled %}Deactivate{% else %}Activate{% endif %}</button>
              </form>

              <!-- Delete -->
              <form method="POST" action="{{ root_path }}/admin/gateways/{{ gateway.id }}/delete" class="contents" @submit="menuOpen = false" data-action-submit="handleDeleteSubmit" data-arg0="gateway" data-arg1="{{ gateway_label|tojson_attr }}" data-arg2="gateways">
                <button
                  type="submit"
                  role="menuitem"
                  tabindex="0"
                  class="w-full flex items-center px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700"
                >Delete</button>
              </form>
              {% endif %}
            </div>
          </div>
        </td>
        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">{{ (pagination.page - 1) * pagination.per_page + 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">{{ gateway.id }}</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-normal break-words text-sm text-gray-500 dark:text-gray-300 w-24 max-w-xs">{{ gateway.url }}</td>
        <td class="px-6 py-4 whitespace-nowrap">
          {% if gateway.tags %}
            {% for tag in gateway.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" data-tag="{% if tag is mapping %}{{ tag.id }}{% else %}{{ tag }}{% endif %}">
              {% if tag is mapping %}{{ tag.id }}{% else %}{{ tag }}{% endif %}
            </span>
            {% endfor %}
          {% else %}
            <span class="text-gray-500 dark:text-gray-300 text-xs">None</span>
          {% endif %}
        </td>
        <td class="px-6 py-4 whitespace-nowrap text-sm">
          {% if gateway.enabled %}
          <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Active</span>
          {% else %}
          <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Inactive</span>
          {% endif %}
        </td>
        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
          {% if gateway.lastSeen %}{{ gateway.lastSeen[:19] if gateway.lastSeen is string else gateway.lastSeen.strftime('%Y-%m-%d %H:%M:%S') }}{% else %}Never{% endif %}
        </td>
        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
          {% if gateway.ownerEmail %}{{ gateway.ownerEmail }}{% else %}<span class="text-gray-400">N/A</span>{% endif %}
        </td>
        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
          {% if gateway.team %}{{ gateway.team }}{% else %}<span class="text-gray-400 dark:text-gray-600 text-xs">None</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-gray-100 text-gray-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>
      </tr>
    {% endfor %}
  </tbody>
</table>

<!-- Out-of-band swap for pagination controls -->
<div id="gateways-pagination-controls" hx-swap-oob="true">
  {% set base_url = root_path + '/admin/gateways/partial' %}
  {% set hx_target = '#gateways-table' %}
  {% set hx_swap = 'outerHTML' %}
  {% set hx_indicator = '#gateways-loading' %}
  {% set table_name = 'gateways' %}
  {% set query_params = query_params if query_params is defined else {'include_inactive': include_inactive} %}
  {% include 'pagination_controls.html' %}
</div>
