<!DOCTYPE html>
<html lang="{{ get_lang(request)[:2] }}" data-bs-theme="light">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}MoE Admin{% endblock %}</title>
  <link rel="stylesheet" href="/static/css/bootstrap.min.css">
  <link rel="stylesheet" href="/static/css/bootstrap-icons.min.css">
  {% block head_extra %}{% endblock %}
  <script>
    /* Apply saved theme before first paint to avoid flash */
    (function(){
      const t = localStorage.getItem('moe-theme') || 'light';
      document.documentElement.setAttribute('data-bs-theme', t);
    })();
  </script>
  <style>
    body { background-color: var(--bs-body-bg); }
    .navbar-brand span { color: #6ea8fe; font-weight: 700; }
    .card { border: none; box-shadow: 0 1px 4px rgba(0,0,0,.08); border-radius: 10px; }
    .card-header { border-radius: 10px 10px 0 0 !important; font-weight: 600; font-size: .9rem; letter-spacing: .03em; }
    .section-icon { font-size: 1.1rem; margin-right: 6px; }
    .status-badge { font-size: .78rem; padding: .35em .7em; }
    .expert-table td { vertical-align: middle; padding: .3rem .5rem; }
    .expert-table th { font-size: .82rem; color: #6c757d; font-weight: 600; padding: .4rem .5rem; }
    .btn-add-model { font-size: .82rem; }
    .form-label { font-size: .88rem; font-weight: 500; color: #495057; }
    .form-control, .form-select { font-size: .9rem; }
    .flash-bar { border-radius: 0; position: sticky; top: 56px; z-index: 999; }
    footer { font-size: .78rem; color: #adb5bd; }
    /* Collapse chevron rotation */
    [data-bs-toggle="collapse"] .bi-chevron-down { transition: transform .2s ease; }
    [data-bs-toggle="collapse"][aria-expanded="true"] .bi-chevron-down { transform: rotate(-180deg); }
    /* Sortable table headers */
    th.sortable { cursor: pointer; user-select: none; white-space: nowrap; }
    th.sortable:hover { background: rgba(0,0,0,.05); }
    [data-bs-theme="dark"] th.sortable:hover { background: rgba(255,255,255,.07); }
    th.sortable .sort-ind { font-size: .65em; opacity: .3; margin-left: .3em; vertical-align: middle; }
    th.sortable.sort-asc .sort-ind, th.sortable.sort-desc .sort-ind { opacity: 1; }
  </style>
</head>
<body>

<nav class="navbar navbar-dark bg-dark sticky-top">
  <div class="container-fluid px-3">

    {# ── Brand ── #}
    <a class="navbar-brand d-flex align-items-center gap-2 me-3" href="/">
      <i class="bi bi-diagram-3-fill" style="color:#6ea8fe;font-size:1.3rem"></i>
      <span>MoE</span><span class="text-white fw-normal ms-1">Admin</span>
    </a>

    {% if request.session.get("authenticated") %}

    {# ── Desktop Nav: visible ≥992px — grouped dropdowns ── #}
    {# Active-state helpers for dropdown highlight #}
    {% set _p = request.url.path %}
    {% set _monitoring_active   = _p in ['/monitoring', '/live-monitoring', '/statistics', '/benchmarks', '/starfleet', '/pipeline-log'] %}
    {% set _infra_active        = _p in ['/servers', '/knowledge', '/federation', '/quarantine', '/maintenance'] %}
    {% set _tools_active        = _p in ['/profiles', '/skills', '/mcp-tools', '/tool-eval'] or _p.startswith('/templates') %}
    {% set _users_active        = _p.startswith('/users') or _p.startswith('/teams') or _p.startswith('/user-content') %}
    {% set _codex_active   = _p in ['/codex', '/catalog', '/approval', '/explorer', '/notebook', '/link-analysis', '/timeline', '/kestra', '/forms', '/search', '/charts', '/superset', '/compliance', '/workshop', '/timeseries', '/notes', '/geo', '/dossier'] %}

    <div class="d-none d-lg-flex align-items-center gap-1 flex-grow-1">
      {# Config – direct link #}
      <a href="/" class="btn btn-sm btn-outline-light {% if _p == '/' %}active{% endif %}">
        <i class="bi bi-sliders me-1"></i>{{ t(request, 'nav.config') }}
      </a>

      {# Monitoring dropdown #}
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-light dropdown-toggle {% if _monitoring_active %}active{% endif %}"
                data-bs-toggle="dropdown" aria-expanded="false">
          <i class="bi bi-graph-up me-1"></i>{{ t(request, 'nav.monitoring') }}
        </button>
        <ul class="dropdown-menu dropdown-menu-dark">
          <li><a class="dropdown-item {% if _p == '/monitoring' %}active{% endif %}" href="/monitoring">
            <i class="bi bi-graph-up me-2 text-info"></i>{{ t(request, 'nav.monitoring') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/live-monitoring' %}active{% endif %}" href="/live-monitoring">
            <i class="bi bi-activity me-2 text-info"></i>{{ t(request, 'nav.live') }}
          </a></li>
          <li><hr class="dropdown-divider border-secondary"></li>
          <li><a class="dropdown-item {% if _p.startswith('/statistics') %}active{% endif %}" href="/statistics">
            <i class="bi bi-bar-chart-line me-2 text-secondary"></i>{{ t(request, 'nav.statistics') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/token-timeline' %}active{% endif %}" href="/token-timeline">
            <i class="bi bi-diagram-2 me-2 text-info"></i>{{ t(request, 'nav.token_timeline') }}
          </a></li>
          <li><a class="dropdown-item {% if _p.startswith('/benchmarks') %}active{% endif %}" href="/benchmarks">
            <i class="bi bi-speedometer2 me-2 text-secondary"></i>{{ t(request, 'nav.benchmarks') }}
          </a></li>
          <li><hr class="dropdown-divider border-secondary"></li>
          <li><a class="dropdown-item {% if _p == '/starfleet' %}active{% endif %}" href="/starfleet">
            <i class="bi bi-broadcast me-2" style="color:#f5a623;"></i>{{ t(request, 'nav.starfleet') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/pipeline-log' %}active{% endif %}" href="/pipeline-log">
            <i class="bi bi-journal-text me-2 text-success"></i>{{ t(request, 'nav.pipeline_log') }}
          </a></li>
        </ul>
      </div>

      {# Infrastruktur dropdown #}
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-light dropdown-toggle {% if _infra_active %}active{% endif %}"
                data-bs-toggle="dropdown" aria-expanded="false">
          <i class="bi bi-hdd-stack me-1"></i>Infra
        </button>
        <ul class="dropdown-menu dropdown-menu-dark">
          <li><a class="dropdown-item {% if _p == '/servers' %}active{% endif %}" href="/servers">
            <i class="bi bi-hdd-stack me-2 text-info"></i>{{ t(request, 'nav.server') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/knowledge' %}active{% endif %}" href="/knowledge">
            <i class="bi bi-database-gear me-2 text-success"></i>Knowledge
          </a></li>
          <li><a class="dropdown-item {% if _p == '/federation' %}active{% endif %}" href="/federation">
            <i class="bi bi-globe2 me-2 text-success"></i>Federation
          </a></li>
          <li><hr class="dropdown-divider border-secondary"></li>
          <li><a class="dropdown-item {% if _p == '/quarantine' %}active{% endif %}" href="/quarantine">
            <i class="bi bi-shield-exclamation me-2 text-danger"></i>{{ t(request, 'nav.quarantine') }}
          </a></li>
          <li><a class="dropdown-item {% if _p.startswith('/maintenance') %}active{% endif %}" href="/maintenance">
            <i class="bi bi-wrench me-2 text-secondary"></i>{{ t(request, 'nav.maintenance') }}
          </a></li>
        </ul>
      </div>

      {# Tools dropdown #}
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-light dropdown-toggle {% if _tools_active %}active{% endif %}"
                data-bs-toggle="dropdown" aria-expanded="false">
          <i class="bi bi-tools me-1"></i>Tools
        </button>
        <ul class="dropdown-menu dropdown-menu-dark">
          <li><a class="dropdown-item {% if _p == '/profiles' %}active{% endif %}" href="/profiles">
            <i class="bi bi-person-badge me-2 text-warning"></i>{{ t(request, 'nav.cc_profiles') }}{% if enabled_profiles_count is defined and enabled_profiles_count %}<span class="badge bg-success ms-2" style="font-size:.6rem">{{ enabled_profiles_count }}</span>{% endif %}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/skills' %}active{% endif %}" href="/skills">
            <i class="bi bi-terminal me-2 text-warning"></i>{{ t(request, 'nav.skills') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/mcp-tools' %}active{% endif %}" href="/mcp-tools">
            <i class="bi bi-puzzle me-2 text-warning"></i>{{ t(request, 'nav.mcp_tools') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/tool-eval' %}active{% endif %}" href="/tool-eval">
            <i class="bi bi-clipboard-data me-2 text-warning"></i>{{ t(request, 'nav.tool_eval') }}
          </a></li>
          <li><hr class="dropdown-divider border-secondary"></li>
          <li><a class="dropdown-item {% if _p.startswith('/templates') %}active{% endif %}" href="/templates">
            <i class="bi bi-collection me-2 text-warning"></i>{{ t(request, 'nav.templates') }}
          </a></li>
        </ul>
      </div>

      {# Codex dropdown — only when moe-codex is deployed #}
      {% if codex_url %}
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-light dropdown-toggle {% if _codex_active %}active{% endif %}"
                data-bs-toggle="dropdown" aria-expanded="false">
          <i class="bi bi-layers me-1"></i>Codex
        </button>
        <ul class="dropdown-menu dropdown-menu-dark" style="min-width:220px">

          {# ── Platform ───────────────────────────────────────────────── #}
          <li><h6 class="dropdown-header text-uppercase" style="font-size:.68rem;letter-spacing:.07em;color:#888">
            {{ t(request, 'nav.codex_platform') }}
          </h6></li>
          <li><a class="dropdown-item {% if _p == '/codex' %}active{% endif %}" href="/codex">
            <i class="bi bi-layers me-2" style="color:#b09bff"></i>{{ t(request, 'page.enterprise') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/catalog' %}active{% endif %}" href="/catalog">
            <i class="bi bi-card-list me-2" style="color:#b09bff"></i>{{ t(request, 'page.catalog') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/approval' %}active{% endif %}" href="/approval">
            <i class="bi bi-check2-circle me-2" style="color:#b09bff"></i>{{ t(request, 'page.approval') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/notebook' %}active{% endif %}" href="/notebook">
            <i class="bi bi-journal-code me-2" style="color:#b09bff"></i>{{ t(request, 'page.notebook') }}
          </a></li>

          {# ── BI & Analytics ─────────────────────────────────────────── #}
          <li><hr class="dropdown-divider border-secondary my-1"></li>
          <li><h6 class="dropdown-header text-uppercase" style="font-size:.68rem;letter-spacing:.07em;color:#888">
            {{ t(request, 'nav.codex_bi') }}
          </h6></li>
          <li><a class="dropdown-item {% if _p == '/superset' %}active{% endif %}" href="/superset">
            <i class="bi bi-bar-chart-steps me-2 text-warning"></i>{{ t(request, 'page.superset') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/charts' %}active{% endif %}" href="/charts">
            <i class="bi bi-bar-chart-line me-2" style="color:#b09bff"></i>{{ t(request, 'page.charts') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/timeseries' %}active{% endif %}" href="/timeseries">
            <i class="bi bi-activity me-2 text-primary"></i>{{ t(request, 'page.timeseries') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/search' %}active{% endif %}" href="/search">
            <i class="bi bi-search me-2" style="color:#b09bff"></i>{{ t(request, 'page.search') }}
          </a></li>

          {# ── Investigation ──────────────────────────────────────────── #}
          <li><hr class="dropdown-divider border-secondary my-1"></li>
          <li><h6 class="dropdown-header text-uppercase" style="font-size:.68rem;letter-spacing:.07em;color:#888">
            {{ t(request, 'nav.codex_investigation') }}
          </h6></li>
          <li><a class="dropdown-item {% if _p == '/dossier' %}active{% endif %}" href="/dossier">
            <i class="bi bi-folder2-open me-2 text-warning"></i>{{ t(request, 'page.dossier') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/explorer' %}active{% endif %}" href="/explorer">
            <i class="bi bi-diagram-3-fill me-2" style="color:#b09bff"></i>{{ t(request, 'page.explorer') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/link-analysis' %}active{% endif %}" href="/link-analysis">
            <i class="bi bi-diagram-3 me-2" style="color:#b09bff"></i>{{ t(request, 'page.link_analysis') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/timeline' %}active{% endif %}" href="/timeline">
            <i class="bi bi-clock-history me-2" style="color:#b09bff"></i>{{ t(request, 'page.timeline') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/geo' %}active{% endif %}" href="/geo">
            <i class="bi bi-map me-2 text-success"></i>{{ t(request, 'page.geo') }}
          </a></li>

          {# ── Pipelines & Content ─────────────────────────────────────── #}
          <li><hr class="dropdown-divider border-secondary my-1"></li>
          <li><h6 class="dropdown-header text-uppercase" style="font-size:.68rem;letter-spacing:.07em;color:#888">
            {{ t(request, 'nav.codex_pipelines') }}
          </h6></li>
          <li><a class="dropdown-item {% if _p == '/kestra' %}active{% endif %}" href="/kestra">
            <i class="bi bi-diagram-2 me-2" style="color:#b09bff"></i>{{ t(request, 'page.kestra') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/forms' %}active{% endif %}" href="/forms">
            <i class="bi bi-ui-checks me-2" style="color:#b09bff"></i>{{ t(request, 'page.forms') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/workshop' %}active{% endif %}" href="/workshop">
            <i class="bi bi-grid-1x2 me-2 text-info"></i>{{ t(request, 'page.workshop') }}
          </a></li>
          <li><a class="dropdown-item {% if _p == '/notes' %}active{% endif %}" href="/notes">
            <i class="bi bi-journal-richtext me-2 text-warning"></i>{{ t(request, 'page.notes') }}
          </a></li>

          {# ── Security & Compliance ──────────────────────────────────── #}
          <li><hr class="dropdown-divider border-secondary my-1"></li>
          <li><h6 class="dropdown-header text-uppercase" style="font-size:.68rem;letter-spacing:.07em;color:#888">
            {{ t(request, 'nav.codex_security') }}
          </h6></li>
          <li><a class="dropdown-item {% if _p == '/compliance' %}active{% endif %}" href="/compliance">
            <i class="bi bi-shield-check me-2 text-success"></i>{{ t(request, 'page.compliance') }}
          </a></li>
        </ul>
      </div>
      {% endif %}

      {# Verwaltung dropdown #}
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-light dropdown-toggle {% if _users_active %}active{% endif %}"
                data-bs-toggle="dropdown" aria-expanded="false">
          <i class="bi bi-people me-1"></i>{{ t(request, 'nav.users') }}
        </button>
        <ul class="dropdown-menu dropdown-menu-dark">
          <li><a class="dropdown-item {% if _p.startswith('/users') %}active{% endif %}" href="/users">
            <i class="bi bi-people me-2 text-secondary"></i>{{ t(request, 'nav.users') }}
          </a></li>
          <li><a class="dropdown-item {% if _p.startswith('/teams') %}active{% endif %}" href="/teams">
            <i class="bi bi-diagram-3 me-2 text-secondary"></i>{{ t(request, 'nav.teams') }}
          </a></li>
          <li><a class="dropdown-item {% if _p.startswith('/user-content') %}active{% endif %}" href="/user-content">
            <i class="bi bi-person-lines-fill me-2 text-secondary"></i>{{ t(request, 'nav.user_content') }}
          </a></li>
        </ul>
      </div>
    </div>

    {# ── Right utilities: always visible ── #}
    <div class="d-flex align-items-center gap-2 ms-auto">
      <span class="text-secondary small d-none d-md-inline">
        <i class="bi bi-person-circle me-1"></i>{{ request.session.get("user","admin") }}
      </span>
      {# Language Switcher #}
      {% set cur_lang = get_lang(request) %}
      <form method="POST" action="/set-language" id="admin-lang-form" class="d-flex align-items-center">
        <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
        <select name="lang" class="form-select form-select-sm text-white bg-dark border-secondary"
                style="width:auto;font-size:.8rem"
                onchange="document.getElementById('admin-lang-form').submit()">
          <option value="de_DE" {% if cur_lang == 'de_DE' %}selected{% endif %}>🇩🇪</option>
          <option value="en_EN" {% if cur_lang == 'en_EN' %}selected{% endif %}>🇬🇧</option>
          <option value="fr_FR" {% if cur_lang == 'fr_FR' %}selected{% endif %}>🇫🇷</option>
          <option value="zh_CN" {% if cur_lang == 'zh_CN' %}selected{% endif %}>🇨🇳</option>
        </select>
      </form>
      {# Theme Toggle #}
      <button type="button" id="themeToggleBtn" class="btn btn-sm btn-outline-light"
              onclick="toggleTheme()" title="{{ t(request, 'btn.toggle_theme') }}">
        <i class="bi bi-moon-stars-fill" id="themeIcon"></i>
      </button>
      {# Logout #}
      <a href="/logout" class="btn btn-sm btn-outline-secondary" title="{{ t(request, 'nav.logout') }}">
        <i class="bi bi-box-arrow-right"></i><span class="d-none d-lg-inline ms-1">{{ t(request, 'nav.logout') }}</span>
      </a>
      {# Hamburger: visible <1400px #}
      <button class="navbar-toggler d-lg-none border-0 ps-1" type="button"
              data-bs-toggle="offcanvas" data-bs-target="#moeNavOffcanvas"
              aria-controls="moeNavOffcanvas" aria-label="Navigation öffnen">
        <span class="navbar-toggler-icon"></span>
      </button>
    </div>

    {# ── Offcanvas: Mobile / Tablet Navigation ── #}
    <div class="offcanvas offcanvas-end text-bg-dark" tabindex="-1" id="moeNavOffcanvas"
         aria-labelledby="moeNavOffcanvasLabel" style="width:280px">
      <div class="offcanvas-header border-bottom border-secondary pb-2">
        <span class="offcanvas-title fw-bold" id="moeNavOffcanvasLabel">
          <i class="bi bi-diagram-3-fill me-2" style="color:#6ea8fe"></i>MoE Admin
        </span>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Schließen"></button>
      </div>
      <div class="offcanvas-body px-2 py-3">
        <ul class="nav flex-column gap-1">
          <li class="nav-item">
            <a href="/" class="nav-link text-white {% if request.url.path == '/' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-sliders me-2 text-info"></i>{{ t(request, 'nav.config') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/monitoring" class="nav-link text-white {% if request.url.path == '/monitoring' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-graph-up me-2 text-info"></i>{{ t(request, 'nav.monitoring') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/live-monitoring" class="nav-link text-white {% if request.url.path == '/live-monitoring' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-activity me-2 text-info"></i>{{ t(request, 'nav.live') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/servers" class="nav-link text-white {% if request.url.path == '/servers' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-hdd-stack me-2 text-info"></i>{{ t(request, 'nav.server') }}
            </a>
          </li>
          <li><hr class="border-secondary my-1"></li>
          <li class="nav-item">
            <a href="/profiles" class="nav-link text-white {% if request.url.path == '/profiles' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-person-badge me-2 text-warning"></i>{{ t(request, 'nav.cc_profiles') }}{% if enabled_profiles_count is defined and enabled_profiles_count %} <span class="badge bg-success ms-1">{{ enabled_profiles_count }}</span>{% endif %}
            </a>
          </li>
          <li class="nav-item">
            <a href="/skills" class="nav-link text-white {% if request.url.path == '/skills' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-terminal me-2 text-warning"></i>{{ t(request, 'nav.skills') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/mcp-tools" class="nav-link text-white {% if request.url.path == '/mcp-tools' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-tools me-2 text-warning"></i>{{ t(request, 'nav.mcp_tools') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/tool-eval" class="nav-link text-white {% if request.url.path == '/tool-eval' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-clipboard-data me-2 text-warning"></i>{{ t(request, 'nav.tool_eval') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/templates" class="nav-link text-white {% if request.url.path.startswith('/templates') %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-collection me-2 text-warning"></i>{{ t(request, 'nav.templates') }}
            </a>
          </li>
          <li><hr class="border-secondary my-1"></li>
          <li class="nav-item">
            <a href="/knowledge" class="nav-link text-white {% if request.url.path == '/knowledge' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-database-gear me-2 text-success"></i>Knowledge
            </a>
          </li>
          <li class="nav-item">
            <a href="/federation" class="nav-link text-white {% if request.url.path == '/federation' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-globe2 me-2 text-success"></i>Federation
            </a>
          </li>
          <li class="nav-item">
            <a href="/quarantine" class="nav-link text-white {% if request.url.path == '/quarantine' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-shield-exclamation me-2 text-danger"></i>{{ t(request, 'nav.quarantine') }}
            </a>
          </li>
          <li><hr class="border-secondary my-1"></li>
          <li class="nav-item">
            <a href="/users" class="nav-link text-white {% if request.url.path.startswith('/users') %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-people me-2 text-secondary"></i>{{ t(request, 'nav.users') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/user-content" class="nav-link text-white {% if request.url.path.startswith('/user-content') %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-person-lines-fill me-2 text-secondary"></i>{{ t(request, 'nav.user_content') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/maintenance" class="nav-link text-white {% if request.url.path.startswith('/maintenance') %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-wrench me-2 text-secondary"></i>{{ t(request, 'nav.maintenance') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/statistics" class="nav-link text-white {% if request.url.path.startswith('/statistics') %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-bar-chart-line me-2 text-secondary"></i>{{ t(request, 'nav.statistics') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/benchmarks" class="nav-link text-white {% if request.url.path.startswith('/benchmarks') %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-speedometer2 me-2 text-secondary"></i>{{ t(request, 'nav.benchmarks') }}
            </a>
          </li>
          {% if codex_url %}
          <li><hr class="border-secondary my-1"></li>
          <li class="nav-item">
            <span class="nav-link text-secondary px-2 py-1 small fw-semibold">
              <i class="bi bi-building me-1"></i>{{ t(request, 'nav.enterprise') }}
            </span>
          </li>
          <li class="nav-item">
            <a href="/codex" class="nav-link text-white {% if _p == '/codex' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-layers me-2" style="color:#b09bff"></i>{{ t(request, 'page.enterprise') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/catalog" class="nav-link text-white {% if _p == '/catalog' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-card-list me-2" style="color:#b09bff"></i>{{ t(request, 'page.catalog') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/approval" class="nav-link text-white {% if _p == '/approval' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-check2-circle me-2" style="color:#b09bff"></i>{{ t(request, 'page.approval') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/explorer" class="nav-link text-white {% if _p == '/explorer' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-search me-2" style="color:#b09bff"></i>{{ t(request, 'page.explorer') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/notebook" class="nav-link text-white {% if _p == '/notebook' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-journal-code me-2" style="color:#b09bff"></i>{{ t(request, 'page.notebook') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/link-analysis" class="nav-link text-white {% if _p == '/link-analysis' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-diagram-3 me-2" style="color:#b09bff"></i>{{ t(request, 'page.link_analysis') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/timeline" class="nav-link text-white {% if _p == '/timeline' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-clock-history me-2" style="color:#b09bff"></i>{{ t(request, 'page.timeline') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/kestra" class="nav-link text-white {% if _p == '/kestra' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-diagram-2 me-2" style="color:#b09bff"></i>{{ t(request, 'page.kestra') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/forms" class="nav-link text-white {% if _p == '/forms' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-ui-checks me-2" style="color:#b09bff"></i>{{ t(request, 'page.forms') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/search" class="nav-link text-white {% if _p == '/search' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-search me-2" style="color:#b09bff"></i>{{ t(request, 'page.search') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/charts" class="nav-link text-white {% if _p == '/charts' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-bar-chart-line me-2" style="color:#b09bff"></i>{{ t(request, 'page.charts') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/superset" class="nav-link text-white {% if _p == '/superset' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-bar-chart-steps me-2 text-warning"></i>{{ t(request, 'page.superset') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/compliance" class="nav-link text-white {% if _p == '/compliance' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-shield-check me-2 text-success"></i>{{ t(request, 'page.compliance') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/geo" class="nav-link text-white {% if _p == '/geo' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-map me-2 text-success"></i>{{ t(request, 'page.geo') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/timeseries" class="nav-link text-white {% if _p == '/timeseries' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-activity me-2 text-primary"></i>{{ t(request, 'page.timeseries') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/notes" class="nav-link text-white {% if _p == '/notes' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-journal-richtext me-2 text-warning"></i>{{ t(request, 'page.notes') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/workshop" class="nav-link text-white {% if _p == '/workshop' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-grid-1x2 me-2 text-info"></i>{{ t(request, 'page.workshop') }}
            </a>
          </li>
          <li class="nav-item">
            <a href="/dossier" class="nav-link text-white {% if _p == '/dossier' %}fw-bold{% endif %} rounded px-2 py-2">
              <i class="bi bi-folder2-open me-2 text-warning"></i>{{ t(request, 'page.dossier') }}
            </a>
          </li>
          {% endif %}
          <li><hr class="border-secondary my-1"></li>
          <li class="nav-item">
            <span class="nav-link text-secondary px-2 py-1 small">
              <i class="bi bi-person-circle me-1"></i>{{ request.session.get("user","admin") }}
            </span>
          </li>
          <li class="nav-item">
            <a href="/logout" class="nav-link text-danger px-2 py-2 rounded">
              <i class="bi bi-box-arrow-right me-2"></i>{{ t(request, 'nav.logout') }}
            </a>
          </li>
        </ul>
      </div>
    </div>

    {% endif %}
  </div>
</nav>

{% block flash %}{% endblock %}

<main class="container py-4">
  {% block content %}{% endblock %}
</main>

<footer class="text-center py-3 mt-2">
  {{ t(request, 'footer.text') }}
</footer>

<script src="/static/js/bootstrap.bundle.min.js"></script>
<script>
/* ─── moeSort: generic sortable table utility ─────────────────────────────── */
(function () {
  function cellVal(td) {
    return ((td && (td.dataset.sort ?? td.textContent)) || '').trim();
  }
  function initSortable(tbl) {
    if (!tbl || tbl._moeSortInit) return;
    tbl._moeSortInit = true;
    tbl.querySelectorAll('thead th').forEach((th, colIdx) => {
      if (th.dataset.nosort !== undefined || !th.textContent.trim()) return;
      th.classList.add('sortable');
      const ind = document.createElement('span');
      ind.className = 'sort-ind';
      ind.textContent = '⇕';
      th.appendChild(ind);
      th._dir = 0;
      th.addEventListener('click', () => {
        const tbody = tbl.tBodies[0];
        if (!tbody) return;
        tbl.querySelectorAll('thead th.sortable').forEach(o => {
          if (o !== th) { o.classList.remove('sort-asc', 'sort-desc'); o._dir = 0; o.querySelector('.sort-ind').textContent = '⇕'; }
        });
        th._dir = th._dir === 1 ? -1 : 1;
        th.classList.toggle('sort-asc', th._dir === 1);
        th.classList.toggle('sort-desc', th._dir === -1);
        ind.textContent = th._dir === 1 ? '▲' : '▼';
        const rows = [...tbody.rows];
        const isNum = rows.every(r => {
          const v = cellVal(r.cells[colIdx]);
          return v === '' || v === '–' || !isNaN(parseFloat(v.replace(/[^\d.,-]/g, '').replace(',', '.')));
        });
        rows.sort((a, b) => {
          const va = cellVal(a.cells[colIdx]), vb = cellVal(b.cells[colIdx]);
          if (isNum) {
            return th._dir * ((parseFloat(va.replace(/[^\d.,-]/g, '').replace(',', '.')) || 0) -
                              (parseFloat(vb.replace(/[^\d.,-]/g, '').replace(',', '.')) || 0));
          }
          return th._dir * va.localeCompare(vb, undefined, { numeric: true, sensitivity: 'base' });
        });
        rows.forEach(r => tbody.appendChild(r));
      });
    });
  }
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('table[data-sortable]').forEach(initSortable);
  });
  window.moeSort = { init: initSortable };
})();
</script>
<script>
const CSRF_TOKEN = "{{ csrf_token }}";
/* ─── CSRF: inject X-CSRF-Token into all mutating fetch() calls ─────────── */
(function(){
  const _origFetch = window.fetch;
  const MUTATING = new Set(['POST','PUT','DELETE','PATCH']);
  window.fetch = function(url, opts) {
    opts = opts || {};
    const method = (opts.method || 'GET').toUpperCase();
    if (MUTATING.has(method)) {
      opts.headers = Object.assign({'X-CSRF-Token': CSRF_TOKEN}, opts.headers || {});
    }
    return _origFetch.call(this, url, opts);
  };
})();
</script>
<script>
/* ─── i18n strings for JS ───────────────────────────────────────────────── */
window.MoeI18n = {
  select_placeholder: "{{ t(request, 'js.select_placeholder') }}",
  search_placeholder: "{{ t(request, 'js.search_placeholder') }}",
  no_options:         "{{ t(request, 'js.no_options') }}"
};

/* ─── Shared Single-Select Dropdown Utility ─────────────────────────────── */
function escHtml(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}

/**
 * Builds a checkbox-style single-select dropdown inside the element with wrapperId.
 * Stores the selected value in a hidden input #wrapperId_val.
 * items: [{value, label}] or [string]
 */
function buildSingleDropdown(wrapperId, items, currentVal, onChange) {
  const wrap = document.getElementById(wrapperId);
  if (!wrap) return;
  const norm  = items.map(o => typeof o === 'string' ? {value:o,label:o} : o);
  const cur   = norm.find(o => o.value === currentVal);
  const valId = wrapperId + '_val', lblId = wrapperId + '_lbl';
  const filtId = wrapperId + '_filter';
  const opts  = norm.map(o => {
    const on = o.value === currentVal;
    return `<li class="dd-opt-li"><a class="dropdown-item d-flex align-items-center gap-2 py-1 small${on?' active':''}" href="#"
      data-val="${escHtml(o.value)}" data-lbl="${escHtml(o.label)}">
      <i class="bi bi-check2 flex-shrink-0${on?'':' invisible'}"></i><span>${escHtml(o.label)}</span>
    </a></li>`;
  }).join('');
  wrap.innerHTML = `
    <input type="hidden" id="${valId}" value="${escHtml(currentVal||'')}">
    <div class="dropdown">
      <button class="btn btn-sm btn-outline-secondary dropdown-toggle w-100 text-start" type="button"
              data-bs-toggle="dropdown" data-bs-auto-close="outside">
        <span id="${lblId}">${escHtml(cur ? cur.label : (currentVal||window.MoeI18n.select_placeholder))}</span>
      </button>
      <ul class="dropdown-menu p-1" style="max-height:320px;overflow-y:auto;min-width:100%">
        <li class="px-2 pt-1 pb-1 sticky-top bg-white">
          <input id="${filtId}" type="text" class="form-control form-control-sm" placeholder="${window.MoeI18n.search_placeholder}"
                 autocomplete="off" oninput="_ddFilter(this,'${wrapperId}')">
        </li>
        <li><hr class="dropdown-divider mt-0 mb-1"></li>
        ${opts||`<li><span class="dropdown-item text-muted small">${window.MoeI18n.no_options}</span></li>`}
      </ul>
    </div>`;
  // Prevent dropdown close when clicking inside (filter input or items)
  wrap.querySelector('.dropdown-menu')?.addEventListener('click', e => e.stopPropagation());
  wrap.querySelector(`#${filtId}`)?.addEventListener('keydown', e => e.stopPropagation());
  wrap.querySelectorAll('[data-val]').forEach(a => a.addEventListener('click', e => {
    e.preventDefault();
    const val=a.dataset.val, lbl=a.dataset.lbl;
    document.getElementById(valId).value = val;
    document.getElementById(lblId).textContent = lbl;
    wrap.querySelectorAll('[data-val]').forEach(x => {
      const t = x.dataset.val === val;
      x.classList.toggle('active', t);
      x.querySelector('.bi-check2')?.classList.toggle('invisible', !t);
    });
    // Close dropdown after selection
    const btn = wrap.querySelector('[data-bs-toggle="dropdown"]');
    bootstrap.Dropdown.getInstance(btn)?.hide();
    if (onChange) onChange(val);
  }));
}
function _ddFilter(input, wrapperId) {
  const term = input.value.toLowerCase();
  document.getElementById(wrapperId)?.querySelectorAll('.dd-opt-li').forEach(li => {
    const a = li.querySelector('[data-val]');
    if (!a) return;
    const match = a.dataset.val.toLowerCase().includes(term) || a.dataset.lbl.toLowerCase().includes(term);
    li.style.display = match ? '' : 'none';
  });
}

/** Read current value from a dropdown built with buildSingleDropdown */
function getDdValue(wrapperId) {
  return document.getElementById(wrapperId+'_val')?.value ?? '';
}

/**
 * Wraps a native <select id="selectId"> with a custom dropdown.
 * The native select is hidden but stays in the DOM for form submission.
 * Call syncDropdown(selectId) if you programmatically change select.value externally.
 */
function convertSelectToDropdown(selectId) {
  const sel = document.getElementById(selectId);
  if (!sel || sel._ddConverted) return;
  sel._ddConverted = true;
  const wrapperId = selectId + '_dd';
  sel._ddWrapperId = wrapperId;
  sel.style.cssText = 'position:absolute;width:1px;height:1px;opacity:0;pointer-events:none';
  const wrap = document.createElement('div');
  wrap.id = wrapperId;
  sel.parentNode.insertBefore(wrap, sel.nextSibling);
  const items = [...sel.options].map(o => ({value:o.value, label:o.text.trim()}));
  buildSingleDropdown(wrapperId, items, sel.value, val => {
    sel.value = val;
    sel.dispatchEvent(new Event('change', {bubbles:true}));
  });
}

/** Re-sync a converted dropdown's UI when native select.value was changed externally */
function syncDropdown(selectId) {
  const sel = document.getElementById(selectId);
  if (!sel || !sel._ddWrapperId) return;
  const w=sel._ddWrapperId, val=sel.value;
  const valEl=document.getElementById(w+'_val'), lblEl=document.getElementById(w+'_lbl');
  if (valEl) valEl.value = val;
  if (lblEl) { const o=[...sel.options].find(o=>o.value===val); if(o) lblEl.textContent=o.text.trim(); }
  const wrap=document.getElementById(w);
  if (wrap) wrap.querySelectorAll('[data-val]').forEach(a => {
    const t=a.dataset.val===val;
    a.classList.toggle('active',t);
    a.querySelector('.bi-check2')?.classList.toggle('invisible',!t);
  });
}
</script>
<script>
/* ─── Dark / Light theme toggle ─────────────────────────────────────────── */
function _applyTheme(theme) {
  document.documentElement.setAttribute('data-bs-theme', theme);
  localStorage.setItem('moe-theme', theme);
  const icon = document.getElementById('themeIcon');
  if (icon) icon.className = theme === 'dark' ? 'bi bi-sun-fill' : 'bi bi-moon-stars-fill';
}
function toggleTheme() {
  const cur = document.documentElement.getAttribute('data-bs-theme') || 'light';
  _applyTheme(cur === 'dark' ? 'light' : 'dark');
}
/* Sync icon after page load */
document.addEventListener('DOMContentLoaded', function() {
  const cur = localStorage.getItem('moe-theme') || 'light';
  _applyTheme(cur);
});
</script>
{% block scripts %}{% endblock %}
</body>
</html>
