<!DOCTYPE html>
<html lang="fr" class="bg-gray-50">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{% block title %}Backup Manager{% endblock %} — {{ instance_name }}</title>
  <link rel="icon" type="image/png" href="{{ url_for('static', filename='icon.png') }}">
  <link rel="apple-touch-icon" href="{{ url_for('static', filename='icon.png') }}">
  <script src="https://cdn.tailwindcss.com"></script>
  <style type="text/tailwindcss">
    @layer components {
      /* Bouton principal (créer, lancer, enregistrer) — bleu */
      .btn-primary   { @apply inline-flex items-center gap-1.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-full shadow-sm transition; }
      /* Bouton secondaire (tester, éditer, sync, historique) — gris ardoise */
      .btn-secondary { @apply inline-flex items-center gap-1.5 bg-slate-100 hover:bg-slate-200 text-slate-700 font-medium rounded-full transition; }
      /* Bouton action légère (rapatrier, toggle, télécharger) — gris neutre */
      .btn-ghost     { @apply inline-flex items-center gap-1 bg-gray-100 hover:bg-gray-200 text-gray-600 font-medium rounded-full transition; }
      /* Bouton destructeur — rouge */
      .btn-danger    { @apply inline-flex items-center gap-1 bg-red-100 hover:bg-red-200 text-red-600 font-medium rounded-full transition; }
      /* Tailles */
      .btn-sm      { @apply text-xs px-3 py-1.5; }
      .btn-md      { @apply text-sm px-5 py-2; }
      .btn-icon-sm { @apply text-xs px-2 py-1; }
    }
  </style>
</head>
<body class="min-h-screen bg-gray-50">

  <div class="fixed top-0 left-0 right-0 z-50" id="site-header">
  <nav class="bg-gray-900 text-white shadow-lg">
    <div class="max-w-7xl mx-auto px-6 py-3 flex items-center justify-between">
      <div class="flex items-center gap-3">
        <img src="{{ url_for('static', filename='icon.png') }}" alt="logo" class="w-7 h-7 rounded">
        <a href="{{ url_for('jobs.index') }}" class="text-lg font-bold tracking-tight">Backup Manager</a>
        <span class="bg-blue-600 text-xs font-medium px-2 py-0.5 rounded">{{ instance_name }}</span>
      </div>
      <div class="flex items-center gap-4 text-sm">
        <a href="{{ url_for('jobs.index') }}"
           class="text-gray-300 hover:text-white transition {% if request.endpoint and request.endpoint.startswith('jobs.') and request.endpoint != 'jobs.job_new' %}text-white font-semibold{% endif %}">
          Dashboard
        </a>
        <a href="{{ url_for('jobs.archives') }}"
           class="text-gray-300 hover:text-white transition {% if request.endpoint == 'jobs.archives' %}text-white font-semibold{% endif %}">
          Archives
        </a>
        <a href="{{ url_for('overview.overview') }}"
           class="text-gray-300 hover:text-white transition {% if request.endpoint and request.endpoint.startswith('overview.') %}text-white font-semibold{% endif %}">
          Vue globale
        </a>
        <a href="{{ url_for('cfg.settings') }}"
           class="text-gray-300 hover:text-white transition {% if request.endpoint and request.endpoint.startswith('cfg.') %}text-white font-semibold{% endif %}">
          Paramètres
        </a>
        <a href="{{ url_for('jobs.job_new') }}"
           class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1.5 rounded font-medium transition">
          + Nouveau job
        </a>
      </div>
    </div>
  </nav>

  <!-- Barre d'activité (dans le bloc sticky avec la navbar) -->
  <div id="activity-bar"
       class="hidden bg-gray-900 border-b border-blue-700 text-white text-xs px-6 py-2 flex items-center justify-center gap-3 shadow">
    <span class="inline-block w-2 h-2 rounded-full bg-blue-400 animate-pulse shrink-0"></span>
    <span class="text-blue-300 font-medium shrink-0">En cours</span>
    <div id="activity-list" class="flex gap-4 flex-wrap text-gray-200"></div>
  </div><!-- fin #activity-bar -->
  </div><!-- fin #site-header -->

  <!-- Spacer : hauteur calculée dynamiquement par JS pour compenser le header fixed -->
  <div id="header-spacer"></div>

  <main class="max-w-7xl mx-auto w-full px-6 py-8">
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        <div class="mb-6 space-y-2">
          {% for category, message in messages %}
            <div class="px-4 py-3 rounded-lg text-sm font-medium
              {% if category == 'error' %}bg-red-50 text-red-800 border border-red-200
              {% elif category == 'info' %}bg-blue-50 text-blue-800 border border-blue-200
              {% else %}bg-green-50 text-green-800 border border-green-200{% endif %}">
              {{ message }}
            </div>
          {% endfor %}
        </div>
      {% endif %}
    {% endwith %}

    {% block content %}{% endblock %}
  </main>

  <footer class="text-center text-xs text-gray-400 py-4">
    Backup Manager — instance <strong>{{ instance_name }}</strong>
  </footer>

  {% block scripts %}{% endblock %}
  <script>
  // Spacer pour compenser le header fixed — recalculé au load et sur resize
  function syncHeaderSpacer() {
    const h = document.getElementById('site-header');
    const s = document.getElementById('header-spacer');
    if (h && s) s.style.height = h.offsetHeight + 'px';
  }
  window.addEventListener('load', syncHeaderSpacer);
  window.addEventListener('resize', syncHeaderSpacer);
  (function() {
    const bar = document.getElementById('activity-bar');
    const list = document.getElementById('activity-list');
    const LABELS = { backup: 'Sauvegarde', restore: 'Restauration', push: 'Push', pull: 'Pull' };

    function elapsed(isoStr) {
      const sec = Math.round((Date.now() - new Date(isoStr).getTime()) / 1000);
      if (sec < 60) return sec + 's';
      return Math.floor(sec / 60) + 'min' + (sec % 60 ? (sec % 60) + 's' : '');
    }

    let prevCount = 0;

    function render(items) {
      const count = items ? items.length : 0;

      // Un job vient de se terminer → recharger la page pour mettre à jour les statuts
      if (prevCount > 0 && count < prevCount) {
        setTimeout(() => location.reload(), 800);
      }
      prevCount = count;

      if (count === 0) {
        bar.classList.add('hidden');
        syncHeaderSpacer();
        return;
      }
      bar.classList.remove('hidden');
      syncHeaderSpacer();
      list.innerHTML = items.map(it => {
        const label = LABELS[it.kind] || it.kind;
        const since = it.started_at ? ' · ' + elapsed(it.started_at) : '';
        const size = it.size_human ? ' · ' + it.size_human : '';
        return `<span class="bg-gray-800 rounded px-2 py-0.5">${label} <strong>${it.name}</strong>${since}${size}</span>`;
      }).join('');
    }

    function poll() {
      fetch('{{ url_for("api.api_running") }}', {
        headers: { 'X-BackupManager-Key': '{{ api_token }}' }
      })
        .then(r => r.ok ? r.json() : null)
        .then(data => render(data && data.running ? data.running : []))
        .catch(() => {});
    }

    poll();
    setInterval(poll, 5000);
  })();
  </script>
</body>
</html>
