<div id="import-section">
  {% set pas = 1 %}{% include '_stepper.html' %}
  {# Bara de upload accentuata (border de accent) ca sa ramana punctul
     de intrare evident chiar cu tabelul Trimiteri lung dedesubt. #}
  {% from '_eroare.html' import card_erori %}
  <div class="card" style="border-color:var(--accent);">

    {% if message %}
    <div class="flash" style="margin-bottom:12px;">{{ message }}</div>
    {% endif %}

    {% if eroare_upload %}
    <div style="margin-bottom:12px;">
      {{ card_erori([eroare_upload]) }}
    </div>
    {% elif error %}
    <div class="flash" style="border-color:var(--err); background:color-mix(in srgb, var(--err) 12%, var(--card)); margin-bottom:12px;"
         role="alert">{{ error }}</div>
    {% endif %}

    {% if sheets %}
    <div class="flash" style="border-color:var(--warn); background:color-mix(in srgb, var(--warn) 12%, var(--card)); margin-bottom:12px;">
      Fisierul are mai multe foi de lucru. Alege foaia de mai jos si incarca din nou.
    </div>
    {% endif %}

    <form id="upload-form"
          hx-post="/_import/upload"
          hx-target="#import-section"
          hx-swap="outerHTML"
          hx-encoding="multipart/form-data"
          hx-indicator="#upload-spinner">
      <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">

      {# Indicator mediu RAR (US-009, PRD 5.20): vizibil inainte de drop-zone #}
      {% set medii_rar = medii | default([]) %}
      {% if medii_rar | length == 0 %}
      {# Banner avertisment — non-blocant (upload continua; commit foloseste ancora globala) #}
      <div style="margin-bottom:10px; padding:8px 14px; border-radius:6px;
                  background:color-mix(in srgb, var(--warn, #e6b34a) 12%, var(--card));
                  border:1px solid var(--warn, #e6b34a); font-size:13px;" role="note">
        <strong>Niciun mediu RAR activ.</strong>
        Activeaza mediul de Productie sau Testare in
        <a href="?tab=cont" style="color:var(--accent);">Meniu cont &rsaquo; Cont</a>.
      </div>
      {% elif medii_rar | length == 1 %}
      {# Eticheta statica (un singur mediu disponibil) #}
      <input type="hidden" name="rar_env" value="{{ medii_rar[0] }}">
      <div style="margin-bottom:10px; font-size:var(--fs-sm); color:var(--muted);">
        Mediu RAR:
        <strong>{{ "Testare" if medii_rar[0] == "test" else "Productie" }}</strong>
      </div>
      {% else %}
      {# Selector (doua medii disponibile) #}
      <div style="margin-bottom:10px; display:flex; align-items:center; gap:10px;">
        <label for="rar-env-select"
               style="font-size:var(--fs-sm); color:var(--muted); white-space:nowrap;">
          Mediu RAR:
        </label>
        <select id="rar-env-select" name="rar_env">
          <option value="test" {% if env_default == "test" %}selected{% endif %}>Testare</option>
          <option value="prod" {% if env_default == "prod" %}selected{% endif %}>Productie</option>
        </select>
      </div>
      {% endif %}

      {% if sheets %}
      <div style="margin-bottom:12px;">
        <label for="sheet-select"
               style="display:block; margin-bottom:4px; font-size:13px; color:var(--muted);">
          Foaie de lucru
        </label>
        <select id="sheet-select" name="sheet_name" style="min-width:200px;">
          {% for s in sheets %}
          <option value="{{ s }}">{{ s }}</option>
          {% endfor %}
        </select>
      </div>
      {% endif %}

      {% if are_trimiteri and not sheets %}
      {# === Bara slim (returning user): eticheta + buton + zona de trage, pe un rand === #}
      <div class="drop-zone" id="drop-zone"
           role="region" aria-label="Zona de incarcare fisier"
           style="display:flex; align-items:center; gap:14px; flex-wrap:wrap;
                  padding:12px 16px; text-align:left;">
        <strong style="font-size:var(--fs-md);">Importa:</strong>
        <input id="file-input" type="file" name="file" accept=".xlsx,.xls,.csv"
               style="display:none;" aria-label="Selecteaza fisier xlsx sau csv">
        <button type="button" id="upload-btn"
                style="min-height:44px; padding:10px 20px; font-size:var(--fs-md);">
          Alege fisier (xlsx/csv)
        </button>
        <span class="muted" style="font-size:var(--fs-sm);">sau trage aici</span>
        <span class="muted" style="font-size:var(--fs-xs); margin-left:auto;">
          NU se trimite nimic la RAR pana confirmi.
        </span>
      </div>
      {% else %}
      {# === Hero first-run (sau re-upload multi-foaie): pastreaza copy-ul de bun venit === #}
      <div class="drop-zone" id="drop-zone"
           role="region" aria-label="Zona de incarcare fisier">
        {% if not sheets %}
        <p style="font-size:var(--fs-lg); margin:0 0 4px; font-weight:600;">Primul fisier? Trage-l aici.</p>
        <p class="muted" style="margin:0 0 16px; font-size:var(--fs-sm);">xlsx sau csv, max 5000 randuri</p>
        {% else %}
        <p class="muted" style="margin:0 0 16px; font-size:var(--fs-md);">
          Incarca fisierul din nou dupa ce ai ales foaia.
        </p>
        {% endif %}

        <input id="file-input" type="file" name="file" accept=".xlsx,.xls,.csv"
               style="display:none;" aria-label="Selecteaza fisier xlsx sau csv">
        <button type="button" id="upload-btn"
                style="min-height:44px; padding:10px 24px; font-size:var(--fs-md);">
          Alege fisier (xlsx/csv)
        </button>
      </div>

      <p class="muted" style="margin:8px 0 0; font-size:var(--fs-xs);">
        NU se trimite nimic la RAR pana confirmi explicit.
      </p>
      {% endif %}

      <span id="upload-spinner" class="htmx-indicator muted"
            style="font-size:var(--fs-sm); margin-top:6px; display:inline;">
        se parseaza fisierul...
      </span>
    </form>
  </div>
</div>

<script>
(function() {
  var btn = document.getElementById('upload-btn');
  var fi  = document.getElementById('file-input');
  var dz  = document.getElementById('drop-zone');
  var frm = document.getElementById('upload-form');

  /* Un singur sticky bar pe ecran — cand re-apare zona de upload
     (reset sau dupa commit), sectiunea Trimiteri redevine vizibila. */
  var trim = document.getElementById('trimiteri-section');
  if (trim) trim.style.display = '';

  /* Dupa un commit reusit (mesaj de succes), du utilizatorul la Trimiteri. */
  {% if message and not error %}
  if (trim) trim.scrollIntoView({behavior: 'smooth', block: 'start'});
  {% endif %}

  if (!btn || !fi || !frm) return;

  btn.addEventListener('click', function() { fi.click(); });

  fi.addEventListener('change', function() {
    if (fi.files.length > 0) frm.requestSubmit();
  });

  dz.addEventListener('dragover', function(e) {
    e.preventDefault();
    dz.classList.add('drag-over');
  });
  dz.addEventListener('dragleave', function(e) {
    if (!dz.contains(e.relatedTarget)) dz.classList.remove('drag-over');
  });
  dz.addEventListener('drop', function(e) {
    e.preventDefault();
    dz.classList.remove('drag-over');
    var f = (e.dataTransfer.files || [])[0];
    if (!f) return;
    try {
      var dt = new DataTransfer();
      dt.items.add(f);
      fi.files = dt.files;
    } catch (_) {}
    frm.requestSubmit();
  });
})();
</script>
