{% extends "base.html" %}
{% block title %}Fédération{% endblock %}

{% block content %}

<div class="flex items-center justify-between mb-6">
  <h1 class="text-xl font-bold text-gray-900">Fédération</h1>
  <div class="flex gap-2">
    <a href="{{ url_for('network.remote_instance_new') }}" class="btn-secondary btn-sm">+ Ajouter une instance</a>
    <form method="post" action="{{ url_for('network.network_sync_all') }}">
      <button type="submit" class="btn-primary btn-sm">Synchroniser tout</button>
    </form>
  </div>
</div>

{# ── Onglets ─────────────────────────────────────────────────────── #}
<div class="flex border-b border-gray-200 mb-6 gap-1">
  <button id="tab-btn-reseau" onclick="setTab('reseau')"
          class="tab-btn px-4 py-2 text-sm font-medium border-b-2 border-blue-600 text-blue-600 -mb-px">
    Vue réseau
  </button>
  <button id="tab-btn-instances" onclick="setTab('instances')"
          class="tab-btn px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700 -mb-px">
    Instances ({{ instances | length }})
  </button>
</div>

{# ══════════════════ PANNEAU : VUE RÉSEAU ══════════════════════════ #}
<div id="pane-reseau">

{% macro instance_section(inst_name, inst_url, jobs_data, inst_id=None, inst_status=None, last_seen=None) %}
<div class="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden mb-6">
  <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between gap-4">
    <div class="flex items-center gap-3 min-w-0">
      <h2 class="text-base font-semibold text-gray-800">{{ inst_name }}</h2>
      {% if inst_id %}
        {% set sc = {'online':'bg-green-100 text-green-700','error':'bg-red-100 text-red-700','offline':'bg-gray-100 text-gray-500'} %}
        <span class="text-xs px-2 py-0.5 rounded-full font-medium {{ sc.get(inst_status, 'bg-gray-100 text-gray-400') }}">
          {{ inst_status or 'unknown' }}
        </span>
        {% if last_seen %}
          <span class="text-xs text-gray-400 hidden sm:inline">sync {{ last_seen.strftime('%d/%m %H:%M') }}</span>
        {% endif %}
      {% else %}
        <span class="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full font-medium">local</span>
      {% endif %}
      {% if inst_url %}
        <span class="text-xs font-mono text-gray-400 truncate hidden md:inline">{{ inst_url }}</span>
      {% endif %}
    </div>
    {% if inst_id %}
    <div class="flex gap-2 shrink-0">
      <form method="post" action="{{ url_for('network.remote_instance_sync', inst_id=inst_id) }}">
        <button type="submit" class="btn-secondary btn-sm">Sync</button>
      </form>
      <a href="{{ url_for('network.remote_instance_edit', inst_id=inst_id) }}"
         class="btn-secondary btn-sm">Éditer</a>
    </div>
    {% endif %}
  </div>

  {% if not jobs_data %}
    <div class="px-6 py-8 text-center text-gray-400 text-sm">
      {% if inst_id %}
        Aucune donnée — cliquez sur "Sync" pour récupérer l'état de cette instance.
      {% else %}
        Aucun job configuré.
        <a href="{{ url_for('jobs.job_new') }}" class="text-blue-600 hover:underline ml-1">Créer un job →</a>
      {% endif %}
    </div>
  {% else %}
  <div class="overflow-x-auto">
    <table class="w-full text-sm">
      <thead>
        <tr class="text-xs text-gray-500 uppercase tracking-wide bg-gray-50">
          <th class="px-6 py-3 text-left font-medium">Job</th>
          <th class="px-6 py-3 text-left font-medium">Type</th>
          <th class="px-6 py-3 text-left font-medium">Dernière exéc.</th>
          <th class="px-6 py-3 text-left font-medium">Statut</th>
          <th class="px-6 py-3 text-left font-medium">Taille</th>
          <th class="px-6 py-3 text-right font-medium">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-100">
        {% for row in jobs_data %}
        <tr class="hover:bg-gray-50">
          <td class="px-6 py-3 font-medium text-gray-900">{{ row.name }}</td>
          <td class="px-6 py-3">
            <span class="bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded font-mono">{{ row.type }}</span>
          </td>
          <td class="px-6 py-3 text-xs text-gray-500">
            {% if row.last_run_at %}{{ row.last_run_at.strftime('%d/%m/%Y %H:%M') }}
            {% else %}<span class="text-gray-300">Jamais</span>{% endif %}
          </td>
          <td class="px-6 py-3">
            {% if row.last_status == 'success' %}
              <span class="bg-green-100 text-green-700 text-xs font-medium px-2 py-0.5 rounded-full">✓ succès</span>
            {% elif row.last_status == 'error' %}
              <span class="bg-red-100 text-red-700 text-xs font-medium px-2 py-0.5 rounded-full">✗ erreur</span>
            {% elif row.last_status == 'running' %}
              <span class="bg-blue-100 text-blue-700 text-xs font-medium px-2 py-0.5 rounded-full animate-pulse">⟳ en cours</span>
            {% else %}
              <span class="text-gray-300 text-xs">—</span>
            {% endif %}
          </td>
          <td class="px-6 py-3 text-xs text-gray-500">
            {% if row.last_size_human is defined %}{{ row.last_size_human }}
            {% elif row.size_human is defined %}{{ row.size_human }}
            {% else %}—{% endif %}
          </td>
          <td class="px-6 py-3 text-right">
            <div class="flex items-center justify-end gap-2">
              {% if inst_id and row.job_id %}
              <form method="post"
                    action="{{ url_for('network.remote_job_run', inst_id=inst_id, job_id=row.job_id) }}"
                    onsubmit="return confirm('Lancer « {{ row.name }} » sur {{ inst_name }} ?')">
                <button type="submit" class="btn-primary btn-sm">▶ Lancer</button>
              </form>
              {% elif not inst_id and row.job_id %}
              <form method="post"
                    action="{{ url_for('jobs.job_run_now', job_id=row.job_id) }}"
                    onsubmit="return confirm('Lancer « {{ row.name }} » maintenant ?')">
                <button type="submit" class="btn-primary btn-sm">▶ Lancer</button>
              </form>
              {% endif %}
              {% if inst_id and row.job_id %}
              <form method="post"
                    action="{{ url_for('network.archive_pull_latest', inst_id=inst_id, remote_job_id=row.job_id) }}"
                    onsubmit="return confirm('Rapatrier la dernière archive de « {{ row.name }} » depuis {{ inst_name }} ?')">
                <button type="submit" class="btn-ghost btn-sm">← Rapatrier</button>
              </form>
              {% endif %}
            </div>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% endif %}
</div>
{% endmacro %}

{{ instance_section(instance_name, instance_url, local_jobs_data) }}

{% if not instances %}
  <div class="bg-white rounded-xl border border-gray-200 px-6 py-10 text-center text-gray-400">
    <p>Aucune instance distante enregistrée.</p>
    <a href="{{ url_for('network.remote_instance_new') }}" class="mt-2 inline-block text-blue-600 hover:underline text-sm">
      Ajouter une instance →
    </a>
  </div>
{% else %}
  {% for inst in instances %}
    {{ instance_section(inst.name, inst.url_display, inst.remote_runs,
                        inst_id=inst.id, inst_status=inst.status, last_seen=inst.last_seen) }}
  {% endfor %}
{% endif %}

</div>{# /pane-reseau #}

{# ══════════════════ PANNEAU : INSTANCES ══════════════════════════ #}
<div id="pane-instances" class="hidden">

{% if not instances %}
  <div class="bg-white rounded-xl border border-gray-200 px-6 py-12 text-center text-gray-400">
    <p class="text-lg">Aucune instance distante configurée.</p>
    <p class="text-sm mt-2">Ajoutez une instance pour voir son état et déclencher des sauvegardes à distance.</p>
    <a href="{{ url_for('network.remote_instance_new') }}" class="mt-4 inline-block text-blue-600 hover:underline text-sm">
      Ajouter une première instance →
    </a>
  </div>
{% else %}
  <div class="space-y-4">
    {% for inst in instances %}
    {% set status_color = {
      'online':  'bg-green-100 text-green-700',
      'error':   'bg-red-100 text-red-700',
      'offline': 'bg-gray-100 text-gray-500',
    }.get(inst.status, 'bg-gray-100 text-gray-400') %}

    <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
      <div class="flex items-start justify-between gap-4">

        <div class="space-y-2 min-w-0 flex-1">
          <div class="flex items-center gap-2 flex-wrap">
            <span class="font-semibold text-gray-900">{{ inst.name }}</span>
            <span class="text-xs px-2 py-0.5 rounded-full font-medium {{ status_color }}">
              {{ inst.status or 'unknown' }}
            </span>
            {% if inst.last_seen %}
              <span class="text-xs text-gray-400">vu {{ inst.last_seen.strftime('%d/%m %H:%M') }}</span>
            {% endif %}
          </div>

          <p class="text-sm font-mono text-gray-500">{{ inst.url_display }}</p>

          {% if inst.remote_runs %}
          <div class="mt-3 border-t border-gray-100 pt-3">
            <p class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
              Jobs ({{ inst.remote_runs | length }})
            </p>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
              {% for rr in inst.remote_runs %}
              {% set run_color = {
                'success': 'text-green-600',
                'error':   'text-red-600',
                'running': 'text-blue-600',
              }.get(rr.last_status, 'text-gray-400') %}
              <div class="text-xs bg-gray-50 rounded-lg px-3 py-2 space-y-0.5">
                <p class="font-medium text-gray-800 truncate">{{ rr.job_name }}</p>
                <p class="text-gray-400">{{ rr.job_type }}</p>
                {% if rr.last_run_at %}
                  <p class="{{ run_color }} font-medium">
                    {{ rr.last_status }} — {{ rr.last_run_at.strftime('%d/%m %H:%M') }}
                  </p>
                {% else %}
                  <p class="text-gray-300">jamais exécuté</p>
                {% endif %}
                {% if rr.last_size_bytes %}
                  <p class="text-gray-400">{{ rr.last_size_human }}</p>
                {% endif %}
              </div>
              {% endfor %}
            </div>
          </div>
          {% endif %}
        </div>

        <div class="flex items-center gap-2 shrink-0 flex-wrap justify-end">
          <form method="post" action="{{ url_for('network.remote_instance_test', inst_id=inst.id) }}">
            <button type="submit" class="btn-secondary btn-sm">Tester</button>
          </form>
          <form method="post" action="{{ url_for('network.remote_instance_sync', inst_id=inst.id) }}">
            <button type="submit" class="btn-secondary btn-sm">Synchroniser</button>
          </form>
          <a href="{{ url_for('network.remote_instance_edit', inst_id=inst.id) }}"
             class="btn-secondary btn-sm">Éditer</a>
          <form method="post" action="{{ url_for('network.remote_instance_delete', inst_id=inst.id) }}"
                onsubmit="return confirm('Supprimer l\'instance « {{ inst.name }} » ?')">
            <button type="submit" class="btn-danger btn-icon-sm">✕</button>
          </form>
        </div>

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

</div>{# /pane-instances #}

<script>
function setTab(name) {
  ['reseau', 'instances'].forEach(function(t) {
    const pane = document.getElementById('pane-' + t);
    const btn  = document.getElementById('tab-btn-' + t);
    const active = t === name;
    pane.classList.toggle('hidden', !active);
    btn.classList.toggle('border-blue-600', active);
    btn.classList.toggle('text-blue-600', active);
    btn.classList.toggle('border-transparent', !active);
    btn.classList.toggle('text-gray-500', !active);
  });
  history.replaceState(null, '', location.pathname + '?tab=' + name);
}
// Restore tab from URL
const urlTab = new URLSearchParams(location.search).get('tab');
if (urlTab === 'instances') setTab('instances');
</script>
{% endblock %}
