{% from "_eroare.html" import card_erori %}
{% import '_macros.html' as ui %}
{# Detaliu editabil in-place. Fragmentul se swap-uieste in corpul modalului global
   (#detaliu-modal-body). Heading-ul poarta id-ul folosit de aria-labelledby al dialogului.
   Operatie + cod RAR rezolvat apar IMPREUNA, read-only, folosind `prez.cod_rar`
   (fallback „nemapat"), fara eticheta separata „Cod RAR". #}
{% set cod_afis = prez.cod_rar if (prez.cod_rar and prez.cod_rar != '—') else 'nemapat' %}
<div class="card" id="detaliu-card-{{ id }}" style="border:none; padding:0; margin:0;">

  {# === Header — #id + pill stare + badge mediu RAR (US-010 PRD 5.20) + motiv === #}
  <div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin:0 0 8px;">
    <h2 id="detaliu-modal-titlu" style="font-size:15px; margin:0;">Detaliu trimitere #{{ id }}</h2>
    <span class="pill {{ stare_css }}">{{ stare_text }}</span>
    {% if rar_env %}
    {% set _eb = eticheta_env(rar_env) %}
    <span class="{{ _eb[1] }}" title="Mediu RAR: {{ _eb[0] }}">{{ _eb[0] }}</span>
    {% endif %}
  </div>
  {% if motiv %}
  <p class="muted" style="margin:0 0 12px; font-size:13px;">{{ motiv }}</p>
  {% elif stare_subtext %}
  <p class="muted" style="margin:0 0 12px; font-size:13px;">{{ stare_subtext }}</p>
  {% endif %}

  {# === Bloc eroare blocanta — DOAR in read-only.
       In editare, cardul 3-niveluri e inlocuit cu: erori per-camp in macro `camp`
       (text simplu .s-error) + rezumat top-of-form pentru erori fara camp (mai jos). === #}
  {% if not editabil and erori_3n %}
  <div style="margin:0 0 14px;">
    {{ card_erori(erori_3n) }}
  </div>
  {% endif %}

  {# === Mapare inline — alege cod RAR pentru operatiile nemapate.
       Cand nemapate_inline, linia „Operatie: X · nemapat" apare in formularul de mai jos
       (cod_afis = nemapat), iar aici e picker-ul; dupa mapare, re-render arata codul rezolvat. === #}
  {% if nemapate_inline %}
  <div style="margin:0 0 14px; padding-bottom:12px; border-bottom:1px solid var(--line);">
    <h3 style="font-size:14px; margin:0 0 4px;">Mapeaza codul operatiei</h3>
    <p class="muted" style="margin:0 0 10px; font-size:13px;">
      Alege codul RAR pentru fiecare operatie. La salvare, randul se re-rezolva pe loc
      (si celelalte randuri cu aceeasi operatie).
    </p>
    {% for op in nemapate_inline %}
    {% set top = op.suggestions[0] if op.suggestions else None %}
    {% set preselect = top.cod_prestatie if (top and top.score >= 60) else '' %}
    <form hx-post="/trimitere/{{ id }}/mapeaza" hx-target="#detaliu-modal-body" hx-swap="innerHTML"
          hx-disabled-elt="find button"
          style="margin:0 0 12px; padding:10px; border:1px solid var(--line); border-radius:8px;">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <input type="hidden" name="cod_op_service" value="{{ op.cod_op_service }}">
      <div style="margin-bottom:6px;">
        <strong>{{ op.cod_op_service }}</strong>
        {% if op.denumire and op.denumire != op.cod_op_service %}
        <span class="muted">— {{ op.denumire }}</span>
        {% endif %}
      </div>
      {% if op.suggestions %}
      <div class="muted" style="font-size:12px; margin-bottom:6px;">
        Sugestii:
        {% for s in op.suggestions[:3] %}
          <span class="sugg">{{ s.cod_prestatie }} ({{ s.score|round|int }}%)</span>{% if not loop.last %}, {% endif %}
        {% endfor %}
      </div>
      {% endif %}
      <div style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
        <select name="cod_prestatie" required aria-label="Cod RAR pentru {{ op.cod_op_service }}"
                style="flex:1; min-width:220px; max-width:380px;">
          <option value="">— alege cod RAR —</option>
          {% for n in nomenclator %}
          <option value="{{ n.cod_prestatie }}" {% if n.cod_prestatie == preselect %}selected{% endif %}>
            {{ n.cod_prestatie }} — {{ n.nume_prestatie }}
          </option>
          {% endfor %}
        </select>
        <button type="submit">Salveaza maparea</button>
      </div>
    </form>
    {% endfor %}
  </div>
  {% endif %}

  {# === Formular editabil (needs_data/needs_mapping) SAU context read-only.
       Zero dublare: campurile vehiculului apar O SINGURA DATA — editabile cand randul e
       corectabil, altfel read-only. Operatie + cod RAR read-only deasupra campurilor. === #}
  {% if editabil %}
  {% set err_map = {} %}
  {% for e in corectie_errors %}{% if e.field %}{% set _ = err_map.update({e.field: e.message}) %}{% endif %}{% endfor %}
  {# fix_map gol pentru Trimiteri (fix-hints vin din preview, nu din corectii de trimitere). #}
  {% set fix_map = {} %}
  {# vin_context pentru aria-label cu context VIN (D#6). #}
  {%- set vin_context = form_vin -%}
  {# btn_label pentru butonul primar al partial-ului. #}
  {%- set btn_label = 'Salveaza si retrimite' -%}

  {% if corectie_msg %}
  <div class="flash" style="{% if corectie_error %}border-color:var(--err); background:color-mix(in srgb, var(--err) 12%, var(--card));{% endif %} margin:0 0 12px;"
       {% if corectie_error %}role="alert"{% endif %}>{{ corectie_msg }}</div>
  {% endif %}

  {# Erori fara camp (field None) nu dispar silentios in editare —
     cardul 3n e ascuns, deci adaugam un rezumat simplu top-of-form.
     Erori cu camp raman afisate per-camp de macro-ul `camp` din _form_editare.html. #}
  {% for e in erori_3n if not e.field %}
  <div class="s-error" style="font-size:13px; margin:0 0 10px;" role="alert">{{ e.problema }}</div>
  {% endfor %}

  <form hx-post="/trimitere/{{ id }}/corecteaza"
        hx-target="#detaliu-modal-body" hx-swap="innerHTML"
        hx-disabled-elt="find button">
    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">

    {# Cleanup B (US-009 PRD 5.15): vechiul <select name="cod_prestatie"> eliminat.
       Chips din _form_editare.html (via _chips_prestatii.html) il inlocuiesc complet:
       emit hidden inputs name="cod_prestatie" + picker per-operatie (E4, US-007).
       post_corectie_trimitere foloseste form.getlist("cod_prestatie") → compatibil. #}

    {# Operatie service (cod intern + denumire venita prin API/import), distinct de
       operatia RAR mapata. op_service_cod="" cand lipseste → randul absent.
       RAMANE in _trimitere_detaliu.html (D#5). #}
    {% if prez.op_service_cod %}
    <div style="margin:0 0 12px;">
      <div class="muted" style="font-size:12px;">Operatie service</div>
      <div>{{ prez.op_service_cod }}{% if prez.op_service_denumire %} — {{ prez.op_service_denumire }}{% endif %}</div>
    </div>
    {% endif %}

    {# === Campurile vehicul/data/odo + erori/fix + buton — partial DRY (US-005). === #}
    {% include "_form_editare.html" %}
  </form>
  {% else %}
  {# Context read-only pentru randuri ne-editabile (sent/sending/queued/error). #}
  <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:12px 24px;">
    <div style="grid-column:1 / -1;">
      <div class="muted" style="font-size:12px;">Numar inmatriculare</div><div>{{ prez.vehicul_nr }}</div>
    </div>
    <div style="grid-column:1 / -1;">
      <div class="muted" style="font-size:12px;">VIN (serie sasiu)</div>
      <div style="word-break:break-all;">{{ prez.vin }}</div>
    </div>
    <div><div class="muted" style="font-size:12px;">Operatie</div><div>{{ prez.operatie }} &middot; {{ cod_afis }}</div></div>
    {# Operatie service (cod intern + denumire), distinct de operatia RAR.
       op_service_cod="" cand lipseste → randul absent (fara "—"). #}
    {% if prez.op_service_cod %}
    <div><div class="muted" style="font-size:12px;">Operatie service</div>
    <div>{{ prez.op_service_cod }}{% if prez.op_service_denumire %} — {{ prez.op_service_denumire }}{% endif %}</div></div>
    {% endif %}
    <div><div class="muted" style="font-size:12px;">Data prestatie</div><div>{{ prez.data_prestatie }}</div></div>
    <div><div class="muted" style="font-size:12px;">Odometru final</div><div>{{ prez.odometru }}</div></div>
  </div>
  {% endif %}

  {# === Rand tinut manual (queued AND held=1) — afordanta de eliberare (US-005/US-010, 5.19).
       Buton dedicat „Trimite acum": elibereaza randul (held 1->0); worker-ul il preia la
       urmatorul poll. Reincarca lista + inchide modalul. Confirmare 1-linie (ireversibil). === #}
  {% if tinut %}
  <div class="detaliu-actiuni-jos" style="margin-top:14px; padding-top:12px; border-top:1px solid var(--line);">
    <p class="muted" style="margin:0 0 8px; font-size:12.5px;">
      Prezentare tinuta manual — nu a plecat la RAR. Elibereaz-o pentru trimitere.
    </p>
    <form hx-post="/trimitere/{{ id }}/trimite-acum"
          hx-target="#submissions-wrap" hx-swap="innerHTML"
          hx-confirm="Trimit aceasta prezentare la RAR? Declararea este ireversibila (FINALIZATA)."
          hx-on::after-request="document.getElementById('modal-detaliu').hidden=true"
          hx-disabled-elt="find button" style="margin:0;">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <button type="submit"
              style="border:1px solid var(--accent); background:var(--accent); color:#fff;
                     font-weight:600; padding:6px 16px; border-radius:6px; cursor:pointer;">
        Trimite acum la RAR
      </button>
    </form>
  </div>
  {% endif %}

  {# === Actiuni de jos — primar Re-pune (doar error) + Sterge pe RAND SEPARAT === #}
  {% if status == 'error' or gestionabil %}
  <div class="detaliu-actiuni-jos" style="margin-top:14px; padding-top:12px; border-top:1px solid var(--line);">
    {# Error -> buton primar „Re-pune in coada" pe /repune (error nu e editabil pentru #}
    {# campuri vehicul, dar se poate schimba cod_prestatie prin acelasi formular). #}
    {% if status == 'error' %}
    <form hx-post="/trimitere/{{ id }}/repune"
          hx-target="#detaliu-modal-body" hx-swap="innerHTML"
          hx-disabled-elt="find button" style="margin:0 0 10px;">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      {# Select cod_prestatie optional in formularul /repune (doar pentru error). #}
      {% if nomenclator_rar %}
      <label for="cod-rar-error-{{ id }}" style="display:block; font-size:12px; color:var(--muted); margin-bottom:4px;">
        Operatie RAR (optional — schimba codul si re-pune)
      </label>
      <select id="cod-rar-error-{{ id }}" name="cod_prestatie"
              aria-label="Alege operatia RAR din nomenclator"
              style="width:100%; margin-bottom:8px; font-size:13px;">
        <option value="">— pastrat ({{ cod_prestatie_curent }}) —</option>
        {% for item in nomenclator_rar %}
        <option value="{{ item.cod_prestatie }}"
                {% if item.cod_prestatie == cod_prestatie_curent %}selected{% endif %}>
          {{ item.cod_prestatie }} — {{ item.nume_prestatie }}
        </option>
        {% endfor %}
      </select>
      {% endif %}
      <button type="submit">Re-pune in coada</button>
    </form>
    {% endif %}

    {# UN SINGUR Sterge, outline distructiv (var(--err)), pe rand separat, full-width pe mobil. #}
    {% if gestionabil %}
    <form hx-post="/trimitere/{{ id }}/sterge"
          hx-target="#detaliu-modal-body" hx-swap="innerHTML"
          hx-disabled-elt="find button"
          hx-confirm="Stergi definitiv trimiterea #{{ id }}? Nu se poate anula." style="margin:0;">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <button type="submit" class="btn-sterge"
              style="background:var(--card); color:var(--err); border-color:var(--err);">
        Sterge
      </button>
    </form>
    {% endif %}
  </div>
  {% endif %}

  {# === Detalii tehnice — colapsat implicit === #}
  <details style="margin-top:14px;">
    <summary class="muted" style="font-size:12px; cursor:pointer;">Detalii tehnice</summary>
    <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:10px 24px; margin-top:10px;">
      <div><div class="muted" style="font-size:12px;">Nr. prezentare RAR</div><div>{{ id_prezentare or '—' }}</div></div>
      <div><div class="muted" style="font-size:12px;">Cod HTTP RAR</div><div>{{ rar_status_code or '—' }}</div></div>
      <div><div class="muted" style="font-size:12px;">Reincercari</div><div>{{ retry_count }}</div></div>
      <div><div class="muted" style="font-size:12px;">Creat</div><div>{{ created_at }}</div></div>
      <div><div class="muted" style="font-size:12px;">Actualizat</div><div>{{ updated_at }}</div></div>
      <div><div class="muted" style="font-size:12px;">Urmatoarea incercare</div><div>{{ next_attempt_at }}</div></div>
      {% if erori_3n and erori_3n[0].cod %}
      <div><div class="muted" style="font-size:12px;">Cod eroare (brut)</div><div>{{ erori_3n[0].cod }}</div></div>
      {% endif %}
    </div>
    {% if rar_error %}
    <div style="margin-top:10px;">
      <div class="muted" style="font-size:12px;">Mesaj RAR (integral)</div>
      <pre style="white-space:pre-wrap; word-break:break-all; font-size:12px; margin:4px 0 0; color:var(--muted);">{{ rar_error }}</pre>
    </div>
    {% endif %}
  </details>
</div>
{# Focus-ul post-swap (incl. re-render corectie/mapare) e gestionat de htmx:afterSettle pe
   #detaliu-modal-body din base.html. Inchiderea modalului pe succes (queued/sterge) vine
   din HX-Trigger `inchideModal` emis de rute. #}
