{% extends "base.html" %}
{% block title %}{{ 'Éditer' if job else 'Nouveau job' }}{% endblock %}

{% block content %}
<div class="max-w-2xl">
  <h1 class="text-xl font-bold text-gray-900 mb-6">
    {{ 'Éditer « ' + job.name + ' »' if job else 'Nouveau job de sauvegarde' }}
  </h1>

  <form method="post"
        action="{{ url_for('jobs.job_edit', job_id=job.id) if job else url_for('jobs.job_new') }}"
        class="space-y-6">

    {# ── Infos générales ── #}
    <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-4">
      <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Général</h2>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Nom du job</label>
        <input type="text" name="name" required
               value="{{ job.name if job else '' }}"
               placeholder="ex: Nextcloud quotidien"
               class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Type</label>
        <select name="type" id="job-type"
                class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
          {% for val, label in [('ynh_app','Application YunoHost'), ('ynh_system','Système YunoHost'),
                                ('mysql','MySQL'), ('postgresql','PostgreSQL'),
                                ('custom_dir','Répertoire custom')] %}
            <option value="{{ val }}"
              {% if job and job.type == val %}selected{% endif %}
              >
              {{ label }}
            </option>
          {% endfor %}
        </select>
      </div>

      {# Type-specific config : ynh_app #}
      <div id="cfg-ynh_app" class="type-cfg space-y-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Application YunoHost</label>
          <select name="app_id" id="app_id"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            {% set current_app_id = (job.config_json | fromjson).get('app_id', '') if job and job.config_json else '' %}
            {% for ynh_app in ynh_apps %}
              <option value="{{ ynh_app.id }}"
                      {% if ynh_app.id == current_app_id %}selected{% endif %}>
                {% set _display = ynh_app.label or ynh_app.name %}
                {{ ynh_app.id }}{% if _display %} — {{ _display }}{% endif %}
              </option>
            {% endfor %}
            {% if not ynh_apps %}
              <option value="">Aucune application trouvée</option>
            {% endif %}
          </select>
        </div>
        <div class="flex items-center gap-2">
          {% set core_only = (job.config_json | fromjson).get('core_only', False) if job and job.config_json else False %}
          <input type="checkbox" name="core_only" value="1" id="core_only"
                 {% if core_only %}checked{% endif %}
                 class="rounded border-gray-300 text-blue-600">
          <label for="core_only" class="text-sm text-gray-700">
            Core only (BACKUP_CORE_ONLY=1) — exclut les données utilisateur
          </label>
        </div>
      </div>

      {# Type-specific config : ynh_system — sélection des hooks #}
      {% set _sys_hooks = [
        ('conf_ynh_settings', 'Paramètres YunoHost', false),
        ('conf_ynh_firewall',  'Firewall',            false),
        ('conf_ssowat',        'Portail SSO',         false),
        ('conf_nginx',         'Nginx',               false),
        ('conf_ynh_certs',     'Certificats SSL',     false),
        ('conf_ynh_domain',    'Domaines',            false),
        ('conf_ynh_user',      'Utilisateurs LDAP',   false),
        ('data_home',          'Répertoires home /home/*', true),
        ('data_mail',          'Courriers Dovecot',   true),
      ] %}
      {% set _saved_hooks = (job.config_json | fromjson).get('hooks', []) if job and job.config_json and job.type == 'ynh_system' else [] %}
      <div id="cfg-ynh_system" class="type-cfg hidden space-y-2">
        <p class="text-xs text-gray-500 mb-2">
          Tous cochés = sauvegarde complète. Décochez les hooks volumineux pour alléger l'archive.
        </p>
        {% for hook_id, hook_label, heavy in _sys_hooks %}
          <div class="flex items-center gap-2">
            <input type="checkbox" name="system_hooks" value="{{ hook_id }}" id="hook_{{ hook_id }}"
                   {% if not _saved_hooks or hook_id in _saved_hooks %}checked{% endif %}
                   class="rounded border-gray-300 text-blue-600">
            <label for="hook_{{ hook_id }}" class="text-sm text-gray-700">
              {{ hook_label }}{% if heavy %} <span class="text-xs text-amber-600 font-medium">(volumineux)</span>{% endif %}
            </label>
          </div>
        {% endfor %}
      </div>

      {# Type-specific config : mysql #}
      {% set db_cfg = (job.config_json | fromjson) if job and job.config_json else {} %}
      <div id="cfg-mysql" class="type-cfg hidden space-y-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Base de données</label>
          <select id="db-select-mysql" name="db_database"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
            {% set cur_db = db_cfg.get('database', '') if job and job.type == 'mysql' else '' %}
            {% if cur_db %}
              <option value="{{ cur_db }}" selected>{{ cur_db }}</option>
            {% else %}
              <option value="">Chargement…</option>
            {% endif %}
          </select>
          <p class="text-xs text-gray-400 mt-1">
            Dump via <code class="bg-gray-100 px-1 rounded">sudo mysqldump</code> — aucun mot de passe requis.
          </p>
        </div>
      </div>

      {# Type-specific config : postgresql #}
      <div id="cfg-postgresql" class="type-cfg hidden space-y-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Base de données</label>
          <select id="db-select-postgresql" name="db_database"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
            {% set cur_db = db_cfg.get('database', '') if job and job.type == 'postgresql' else '' %}
            {% if cur_db %}
              <option value="{{ cur_db }}" selected>{{ cur_db }}</option>
            {% else %}
              <option value="">Chargement…</option>
            {% endif %}
          </select>
          <p class="text-xs text-gray-400 mt-1">
            Dump via <code class="bg-gray-100 px-1 rounded">sudo -u postgres pg_dump</code> — aucun mot de passe requis.
          </p>
        </div>
      </div>

      {# Type-specific config : custom_dir #}
      {% set cd_cfg = (job.config_json | fromjson) if job and job.config_json and job.type == 'custom_dir' else {} %}
      {% set cd_restore = cd_cfg.get('restore', {}) %}
      <div id="cfg-custom_dir" class="type-cfg hidden space-y-4">

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Chemin à sauvegarder</label>
          <input type="text" name="source_path"
                 value="{{ cd_cfg.get('source_path', '') }}"
                 placeholder="/opt/monapp"
                 class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Exclusions <span class="font-normal text-gray-400">(une par ligne)</span></label>
          <textarea name="excludes" rows="3" placeholder="cache/&#10;logs/&#10;*.tmp"
                    class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">{{ cd_cfg.get('excludes', []) | join('\n') }}</textarea>
        </div>

        {# Section restauration (optionnel, collapsible) #}
        <details {% if cd_restore %}open{% endif %} class="border border-gray-200 rounded-lg">
          <summary class="px-4 py-3 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 select-none">
            Configuration de restauration <span class="text-gray-400 font-normal">(optionnel)</span>
          </summary>
          <div class="px-4 pb-4 pt-2 space-y-4 border-t border-gray-100">

            <div>
              <p class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Utilisateur système</p>
              <div class="grid grid-cols-3 gap-3">
                <div>
                  <label class="block text-xs text-gray-600 mb-1">Nom</label>
                  <input type="text" name="restore_user_name"
                         value="{{ cd_restore.get('system_user', {}).get('name', '') }}"
                         placeholder="monapp" class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
                <div>
                  <label class="block text-xs text-gray-600 mb-1">Home</label>
                  <input type="text" name="restore_user_home"
                         value="{{ cd_restore.get('system_user', {}).get('home', '') }}"
                         placeholder="/opt/monapp" class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
                <div>
                  <label class="block text-xs text-gray-600 mb-1">Shell</label>
                  <input type="text" name="restore_user_shell"
                         value="{{ cd_restore.get('system_user', {}).get('shell', '/bin/false') }}"
                         placeholder="/bin/false" class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
              </div>
            </div>

            <div>
              <p class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Service systemd</p>
              <div class="grid grid-cols-2 gap-3">
                <div>
                  <label class="block text-xs text-gray-600 mb-1">Nom du service</label>
                  <input type="text" name="restore_service_name"
                         value="{{ cd_restore.get('systemd_service', {}).get('name', '') }}"
                         placeholder="monapp" class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
                <div>
                  <label class="block text-xs text-gray-600 mb-1">Fichier .service</label>
                  <input type="text" name="restore_service_file"
                         value="{{ cd_restore.get('systemd_service', {}).get('service_file', '') }}"
                         placeholder="/opt/monapp/monapp.service" class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
              </div>
            </div>

            <div>
              <p class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Permissions</p>
              <div class="grid grid-cols-2 gap-3">
                <div>
                  <label class="block text-xs text-gray-600 mb-1">Propriétaire (user:group)</label>
                  <input type="text" name="restore_perm_owner"
                         value="{{ cd_restore.get('permissions', {}).get('owner', '') }}"
                         placeholder="monapp:monapp" class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
                <div>
                  <label class="block text-xs text-gray-600 mb-1">Mode (chmod)</label>
                  <input type="text" name="restore_perm_mode"
                         value="{{ cd_restore.get('permissions', {}).get('mode', '') }}"
                         placeholder="750" class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
              </div>
            </div>

            <div>
              <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                Commandes post-restauration <span class="font-normal text-gray-400">(une par ligne)</span>
              </label>
              <textarea name="restore_post_cmds" rows="3"
                        placeholder="systemctl restart monapp"
                        class="w-full border border-gray-300 rounded px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-blue-500">{{ cd_restore.get('post_restore_commands', []) | join('\n') }}</textarea>
            </div>

          </div>
        </details>
      </div>
    </div>

    {# ── Planification ── #}
    {% set has_cron = job and job.cron_expr %}
    <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-4">
      <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Planification</h2>
      <div class="flex items-center gap-3">
        <input type="checkbox" id="scheduled" name="scheduled" value="1"
               {% if not job or has_cron %}checked{% endif %}
               class="rounded border-gray-300 text-blue-600">
        <label for="scheduled" class="text-sm font-medium text-gray-700">Planification automatique</label>
      </div>
      <div id="cron-field" {% if job and not has_cron %}class="hidden"{% endif %}>
        <label class="block text-sm font-medium text-gray-700 mb-1">Expression cron</label>
        <input type="text" name="cron_expr" id="cron_expr"
               value="{{ job.cron_expr if has_cron else '0 3 * * *' }}"
               placeholder="0 3 * * *"
               class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
        <p class="text-xs text-gray-400 mt-1">
          Format : minute heure jour mois jour_semaine
          — ex: <code class="bg-gray-100 px-1 rounded">0 3 * * *</code> = tous les jours à 3h
          · <code class="bg-gray-100 px-1 rounded">0 3 * * 1</code> = chaque lundi à 3h
        </p>
      </div>
    </div>

    {# ── Rétention ── #}
    {% set gfs_cfg = (job.retention_gfs_config | fromjson) if job and job.retention_gfs_config else {} %}
    <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-4">
      <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Rétention</h2>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Mode</label>
        <select name="retention_mode" id="retention_mode"
                class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
          {% for val, label in [('count','Garder les N dernières archives'),
                                ('daily','1 archive par jour sur N jours glissants'),
                                ('gfs','Grand-Père-Père-Fils (GFS)')] %}
            <option value="{{ val }}"
              {% if job and job.retention_mode == val %}selected{% endif %}>
              {{ label }}
            </option>
          {% endfor %}
        </select>
      </div>

      {# Mode count / daily : un seul champ N #}
      <div id="retention-simple">
        <label class="block text-sm font-medium text-gray-700 mb-1">Valeur (N)</label>
        <input type="number" name="retention_value" id="retention_value" min="1" max="365"
               value="{{ job.retention_value if job and job.retention_mode != 'gfs' else 7 }}"
               class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      </div>

      {# Mode GFS : trois champs Fils / Père / Grand-Père #}
      <div id="retention-gfs" class="hidden space-y-3">
        <div class="grid grid-cols-3 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Fils (journaliers)</label>
            <input type="number" name="gfs_daily" min="1" max="31"
                   value="{{ gfs_cfg.get('daily', 7) }}"
                   class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            <p class="text-xs text-gray-400 mt-1">dernières archives</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Père (hebdos)</label>
            <input type="number" name="gfs_weekly" min="1" max="52"
                   value="{{ gfs_cfg.get('weekly', 4) }}"
                   class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            <p class="text-xs text-gray-400 mt-1">semaines glissantes</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Grand-Père (mensuels)</label>
            <input type="number" name="gfs_monthly" min="1" max="60"
                   value="{{ gfs_cfg.get('monthly', 12) }}"
                   class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            <p class="text-xs text-gray-400 mt-1">mois glissants</p>
          </div>
        </div>
      </div>

      <p id="retention-help" class="text-xs text-gray-400"></p>
    </div>

    {# ── Destination ── #}
    <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-3">
      <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Transfert après sauvegarde</h2>
      {% if destinations or remote_instances %}
        {% set sel_dest_ids = job.job_destinations | selectattr('dest_type','eq','ssh') | map(attribute='dest_id') | list if job else [] %}
        {% set sel_inst_ids = job.job_destinations | selectattr('dest_type','eq','instance') | map(attribute='dest_id') | list if job else [] %}
        {% if destinations %}
          <p class="text-xs font-semibold text-gray-500 uppercase tracking-wide">SSH / rsync</p>
          {% for d in destinations %}
            <div class="flex items-center gap-2">
              <input type="checkbox" name="transfer_targets" value="dest:{{ d.id }}"
                     id="tr_dest_{{ d.id }}"
                     {% if d.id in sel_dest_ids %}checked{% endif %}
                     class="rounded border-gray-300 text-blue-600">
              <label for="tr_dest_{{ d.id }}" class="text-sm text-gray-700">
                {{ d.name }} <span class="font-mono text-xs text-gray-400">— {{ d.remote_str }}</span>
              </label>
            </div>
          {% endfor %}
        {% endif %}
        {% if remote_instances %}
          <p class="text-xs font-semibold text-gray-500 uppercase tracking-wide {% if destinations %}mt-2{% endif %}">Instances fédérées</p>
          {% for inst in remote_instances %}
            <div class="flex items-center gap-2">
              <input type="checkbox" name="transfer_targets" value="inst:{{ inst.id }}"
                     id="tr_inst_{{ inst.id }}"
                     {% if inst.id in sel_inst_ids %}checked{% endif %}
                     class="rounded border-gray-300 text-blue-600">
              <label for="tr_inst_{{ inst.id }}" class="text-sm text-gray-700">
                {{ inst.name }} <span class="font-mono text-xs text-gray-400">— {{ inst.url }}</span>
              </label>
            </div>
          {% endfor %}
        {% endif %}
      {% else %}
        <p class="text-xs text-gray-400">
          Aucune destination configurée.
          <a href="{{ url_for('dest.destination_new') }}" class="text-blue-600 hover:underline">Créer une destination SSH →</a>
          &nbsp;|&nbsp;
          <a href="{{ url_for('cfg.settings') }}?tab=instances" class="text-blue-600 hover:underline">Ajouter une instance fédérée →</a>
        </p>
      {% endif %}
    </div>

    {# ── Options ── #}
    <div class="bg-white rounded-xl border border-gray-200 p-6">
      <div class="flex items-center gap-3">
        <input type="checkbox" name="enabled" value="1" id="enabled"
               {% if not job or job.enabled %}checked{% endif %}
               class="rounded border-gray-300 text-blue-600">
        <label for="enabled" class="text-sm font-medium text-gray-700">Job activé</label>
      </div>
    </div>

    {# ── Actions ── #}
    <div class="flex gap-3">
      <button type="submit" class="btn-primary btn-md">
        {{ 'Enregistrer' if job else 'Créer le job' }}
      </button>
      <a href="{{ url_for('jobs.index') }}" class="btn-secondary btn-md">Annuler</a>
    </div>
  </form>
</div>

<script>
  const retentionHelp = {
    count: "Ex : N=7 → conserve les 7 dernières archives, supprime les plus anciennes.",
    daily: "Ex : N=30 → conserve 1 archive par jour sur les 30 derniers jours. Les doublons du même jour sont supprimés.",
    gfs:   "Ex : Fils=7, Père=4, GP=12 → 7 archives récentes + 1 par semaine sur 4 semaines + 1 par mois sur 12 mois. Une archive peut couvrir plusieurs niveaux."
  };

  const dbCache = {};

  function loadDatabases(dbType) {
    const sel = document.getElementById('db-select-' + dbType);
    if (!sel) return;
    if (dbCache[dbType]) {
      populateSelect(sel, dbCache[dbType]);
      return;
    }
    fetch("{{ url_for('cfg.internal_databases', db_type='__TYPE__') }}".replace('__TYPE__', dbType))
      .then(r => r.json())
      .then(dbs => {
        dbCache[dbType] = dbs;
        populateSelect(sel, dbs);
      })
      .catch(() => {
        sel.innerHTML = '<option value="">Impossible de charger les bases</option>';
      });
  }

  function populateSelect(sel, dbs) {
    const current = sel.querySelector('option[selected]')?.value || '';
    sel.innerHTML = '';
    if (!dbs.length) {
      sel.innerHTML = '<option value="">Aucune base trouvée</option>';
      return;
    }
    dbs.forEach(db => {
      const opt = document.createElement('option');
      opt.value = db;
      opt.textContent = db;
      if (db === current) opt.selected = true;
      sel.appendChild(opt);
    });
  }

  function showTypeConfig() {
    document.querySelectorAll('.type-cfg').forEach(el => {
      el.classList.add('hidden');
      el.querySelectorAll('input, select, textarea').forEach(f => f.disabled = true);
    });
    const type = document.getElementById('job-type').value;
    const el = document.getElementById('cfg-' + type);
    if (el) {
      el.classList.remove('hidden');
      el.querySelectorAll('input, select, textarea').forEach(f => f.disabled = false);
    }
    if (type === 'mysql' || type === 'postgresql') loadDatabases(type);
  }

  function updateRetentionMode() {
    const mode = document.getElementById('retention_mode').value;
    const simple = document.getElementById('retention-simple');
    const gfsBlock = document.getElementById('retention-gfs');
    const simpleInput = document.getElementById('retention_value');
    const gfsInputs = gfsBlock.querySelectorAll('input');

    if (mode === 'gfs') {
      simple.classList.add('hidden');
      simpleInput.disabled = true;
      simpleInput.required = false;
      gfsBlock.classList.remove('hidden');
      gfsInputs.forEach(i => { i.disabled = false; i.required = true; });
    } else {
      simple.classList.remove('hidden');
      simpleInput.disabled = false;
      simpleInput.required = true;
      gfsBlock.classList.add('hidden');
      gfsInputs.forEach(i => { i.disabled = true; i.required = false; });
    }

    document.getElementById('retention-help').textContent = retentionHelp[mode] || '';
  }

  // Auto-remplissage du nom si le champ est vide
  const nameInput = document.querySelector('[name=name]');
  function suggestName() {
    if (nameInput.value.trim()) return; // ne pas écraser si déjà renseigné
    const type = document.getElementById('job-type').value;
    let suggestion = '';
    if (type === 'ynh_app') {
      const sel = document.getElementById('app_id');
      suggestion = sel ? sel.value : '';
    } else if (type === 'ynh_system') {
      suggestion = 'Système YunoHost';
    } else if (type === 'mysql') {
      const sel = document.getElementById('db-select-mysql');
      suggestion = sel ? sel.value : '';
    } else if (type === 'postgresql') {
      const sel = document.getElementById('db-select-postgresql');
      suggestion = sel ? sel.value : '';
    } else if (type === 'custom_dir') {
      const src = document.querySelector('[name=source_path]');
      if (src && src.value.trim()) {
        const parts = src.value.trim().replace(/\/+$/, '').split('/');
        suggestion = parts[parts.length - 1] || '';
      }
    }
    if (suggestion) nameInput.value = suggestion;
  }

  document.getElementById('job-type').addEventListener('change', function() { showTypeConfig(); suggestName(); });
  const appSel = document.getElementById('app_id');
  if (appSel) appSel.addEventListener('change', function() {
    {% if not job %}
    const opt = appSel.options[appSel.selectedIndex];
    if (opt) {
      const sep = opt.text.indexOf(' — ');
      nameInput.value = sep !== -1 ? opt.text.slice(sep + 3) : opt.text;
    }
    {% else %}
    suggestName();
    {% endif %}
  });
  ['db-select-mysql', 'db-select-postgresql'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('change', suggestName);
  });
  const srcPath = document.querySelector('[name=source_path]');
  if (srcPath) srcPath.addEventListener('input', suggestName);

  document.getElementById('retention_mode').addEventListener('change', updateRetentionMode);
  showTypeConfig();
  suggestName(); // pré-remplit le nom si champ vide à l'ouverture du formulaire
  updateRetentionMode();

  // Toggle planification cron
  const scheduledChk = document.getElementById('scheduled');
  const cronField = document.getElementById('cron-field');
  const cronInput = document.getElementById('cron_expr');
  function toggleCron() {
    if (scheduledChk.checked) {
      cronField.classList.remove('hidden');
      cronInput.disabled = false;
      cronInput.required = true;
    } else {
      cronField.classList.add('hidden');
      cronInput.disabled = true;
      cronInput.required = false;
    }
  }
  scheduledChk.addEventListener('change', toggleCron);
  toggleCron();
</script>
{% endblock %}
