{#
  _chips_prestatii.html — control unificat chips prestatii.

  UN singur container `.chips`: chips cod (legate de operatie sau libere), chips
  warning pentru operatii nemapate, chip `Nedeclarat` pentru itemi exclusi, si
  selectul unic `chips_pick` la final. Fara `.op-row`, fara butoane Adauga/+ —
  selectul adauga instant la `change` (POST /form-chips, chips_action=add).

  Diagrama starii per item (chips_state.items[i]):
    cod=""  & exclus=0  -> chip warning  (warn OP-X . fara cod), click = tinta
    cod=""  & exclus=1  -> chip Nedeclarat (line-through), x -> readuce warning
    cod!="" (op="" sau op!="") -> chip cod (eticheta COD, tooltip = operatia sursa
                                  sau "cod adaugat manual")

  Stare persistata intr-UN SINGUR hidden `chips_state` (JSON versionat)
  + hidden `chips_target_index` (tinta curenta; comutata CLIENT-SIDE la click pe
  un chip warning, fara round-trip — indexul pleaca la server abia la urmatorul
  add) + hidden `chips_submission_id` (ecouat ca sa "salveaza ca regula" ramana
  disponibil dupa re-randari via /form-chips).

  Context vars (toate cu defaults):
    prestatii_chips     — list of {cod_prestatie, cod_op_service, denumire, exclus}
    nomenclator_rar     — list of {cod_prestatie, nume_prestatie} pentru select
    has_r_odo           — True daca vreun chip e R-ODO/I-ODO (server-computed)
    chips_added_index   — index-ul chip-ului tocmai adaugat (emfaza chip-nou)
    chips_target_index  — index-ul operatiei tinta curente (sau none)
    chips_submission_id — id submission cand chips sunt in modalul de detaliu
                          (activeaza butonul "salveaza ca regula")
    form_chips_url      — URL pentru HTMX; default '/form-chips'
    chips_section_id    — ID div (default 'chips-section')
    csrf_token          — CSRF (trecut prin hx-include din form parinte)
#}
{% set _chips_url = form_chips_url or '/form-chips' %}
{% set _sec_id = chips_section_id or 'chips-section' %}
{% set _chips = prestatii_chips or [] %}
{% set _sub_id = chips_submission_id if (chips_submission_id is defined and chips_submission_id) else '' %}
{% set _target_idx = chips_target_index if (chips_target_index is defined and chips_target_index is not none) else none %}
{% set _target_op = (_chips[_target_idx].cod_op_service or '') if (_target_idx is not none and _target_idx < _chips | length) else '' %}

<div id="{{ _sec_id }}" class="chips-editor" data-has-r-odo="{{ 'true' if has_r_odo else 'false' }}"
     aria-live="polite" aria-label="Prestatii cod RAR">

  {# ===== Stare: UN SINGUR hidden JSON versionat + tinta + submission id ===== #}
  <input type="hidden" name="chips_state" value='{{ chips_state_json(_chips) }}'>
  <input type="hidden" name="chips_target_index" id="chips-target-index"
         value="{{ _target_idx if _target_idx is not none else '' }}">
  <input type="hidden" name="chips_submission_id" value="{{ _sub_id }}">

  <div class="camp-slim" style="margin-bottom:8px;">
    <label>Prestatii — cod RAR</label>

    <div class="chips" role="group" aria-label="Prestatii cod RAR">
      {% for chip in _chips %}
      {% set _idx = loop.index0 %}
      {% set _is_target = _target_idx is not none and _idx == _target_idx %}

      {% if chip.cod_op_service and not chip.cod_prestatie and not chip.exclus %}
      {# ===== Chip warning: operatie nemapata — click comuta tinta client-side ===== #}
      {% set _label = chip.cod_op_service %}
      {% set _label_scurt = (_label[:18] ~ '…') if _label | length > 18 else _label %}
      {% set _title = chip.cod_op_service ~ (' — ' ~ chip.denumire if chip.denumire and chip.denumire != chip.cod_op_service else '') %}
      <button type="button"
              class="chip chip-op-warn {% if _is_target %}is-target{% endif %}"
              data-chip-idx="{{ _idx }}"
              data-op-nume="{{ chip.cod_op_service }}"
              title="{{ _title }}"
              onclick="window.chipsSetTarget && window.chipsSetTarget(this, {{ _idx }})"
              aria-pressed="{{ 'true' if _is_target else 'false' }}"
              aria-label="Operatia {{ chip.cod_op_service }} nu are cod RAR{% if _is_target %} (tinta curenta){% endif %}">
        &#9888; {{ _label_scurt }} &middot; fara cod
      </button>

      {% elif chip.exclus %}
      {# ===== Chip Nedeclarat: vizibil (line-through), x readuce warning-ul ===== #}
      <span class="chip chip-nedeclarat"
            title="{{ chip.cod_op_service or 'Cod liber' }} — nu se declara la RAR"
            aria-label="{{ chip.cod_op_service or 'Operatia' }} nu se declara la RAR">
        Nedeclarat
        <button type="button" class="chip-del"
                hx-post="{{ _chips_url }}"
                hx-disabled-elt="this"
                hx-indicator="#{{ _sec_id }}"
                hx-include="closest form"
                hx-target="#{{ _sec_id }}"
                hx-swap="outerHTML"
                hx-vals='{"chips_action":"remove","chips_remove_index":{{ _idx }}}'
                aria-label="Anuleaza Nedeclarat pentru {{ chip.cod_op_service or 'cod liber' }} (readuce avertismentul)">
          &times;
        </button>
      </span>

      {% elif chip.cod_prestatie %}
      {# ===== Chip cod: legat de operatie sau liber ===== #}
      {% set _is_warn = chip.cod_prestatie in ('R-ODO', 'I-ODO') %}
      {% set _e_nou = (chips_added_index is defined) and chips_added_index is not none and _idx == chips_added_index %}
      {% set _tooltip = (chip.cod_op_service ~ (' — ' ~ chip.denumire if chip.denumire and chip.denumire != chip.cod_op_service else '')) if chip.cod_op_service else 'cod adaugat manual' %}
      <span class="chip {% if _is_warn %}chip-warn{% endif %} {% if _e_nou %}chip-nou{% endif %}"
            title="{{ _tooltip }}"
            aria-label="Prestatie {{ chip.cod_prestatie }}{% if chip.cod_op_service %} pentru {{ chip.cod_op_service }}{% endif %}">
        <span class="chip-cod-label">COD</span> {{ chip.cod_prestatie }}
        <button type="button" class="chip-del"
                hx-post="{{ _chips_url }}"
                hx-disabled-elt="this"
                hx-indicator="#{{ _sec_id }}"
                hx-include="closest form"
                hx-target="#{{ _sec_id }}"
                hx-swap="outerHTML"
                hx-vals='{"chips_action":"remove","chips_remove_index":{{ _idx }}}'
                aria-label="Sterge codul {{ chip.cod_prestatie }}{% if chip.cod_op_service %} pentru {{ chip.cod_op_service }}{% endif %}">
          &times;
        </button>
      </span>
      {# "salveaza ca regula op->cod" — apare doar cand submission_id e cunoscut
         (modalul de detaliu, nu la re-randarea stateless via /form-chips fara ecou). #}
      {% if _sub_id and chip.cod_op_service and chip.cod_prestatie %}
      <span id="save-rule-slot-{{ _idx }}" class="save-rule-slot">
        <button type="button"
                style="font-size:10px;color:var(--muted);background:none;border:none;cursor:pointer;text-decoration:underline;padding:0;margin-left:-2px;line-height:1;"
                hx-post="/trimitere/{{ _sub_id }}/salveaza-regula-chip"
                hx-disabled-elt="this"
                hx-indicator="#{{ _sec_id }}"
                hx-include="closest form"
                hx-target="#detaliu-modal-body"
                hx-swap="innerHTML"
                hx-vals='{"salveaza_op":{{ chip.cod_op_service | tojson }},"salveaza_cod":{{ chip.cod_prestatie | tojson }}}'
                aria-label="Salveaza regula {{ chip.cod_op_service }} -> {{ chip.cod_prestatie }}">
          salveaza ca regula
        </button>
      </span>
      {% endif %}
      {% endif %}
      {% endfor %}

      {# ===== Selectul unic: adauga instant la schimbare, placeholder numeste tinta ===== #}
      {% if nomenclator_rar %}
      <select name="chips_pick"
              id="chips-picker"
              class="chips-picker"
              hx-trigger="change"
              hx-post="{{ _chips_url }}"
              hx-target="#{{ _sec_id }}"
              hx-swap="outerHTML"
              hx-include="closest form"
              hx-disabled-elt="this"
              hx-indicator="#{{ _sec_id }}"
              hx-vals='{"chips_action":"add"}'
              aria-label="{% if _target_op %}Alege cod RAR pentru {{ _target_op }}{% else %}Adauga cod RAR{% endif %}">
        <option value="">{% if _target_op %}Cod pentru {{ _target_op }} — alege{% else %}— adauga cod RAR —{% endif %}</option>
        {% if _target_idx is not none %}
        {% set _sugestii = sugestii_tinta if (sugestii_tinta is defined and sugestii_tinta) else [] %}
        {% if _sugestii %}
        <optgroup label="Sugestii">
          {% for s in _sugestii %}
          <option value="{{ s.cod_prestatie }}">{{ s.cod_prestatie }} — {{ s.nume_prestatie }}</option>
          {% endfor %}
        </optgroup>
        {% endif %}
        <option value="{{ EXCLUDE_SENTINEL }}">Nu se declara la RAR (exclude operatia)</option>
        {% endif %}
        {% for n in (nomenclator_rar or []) %}
        <option value="{{ n.cod_prestatie }}">{{ n.cod_prestatie }} — {{ n.nume_prestatie }}</option>
        {% endfor %}
      </select>
      {% else %}
      {# T-D1/T-E5 (5.16): empty state cand nomenclatorul lipseste #}
      <div class="chips-nom-gol" style="font-size:11px;color:var(--warn);padding:4px 0;">
        Nomenclator indisponibil — adaugarea de coduri RAR nu e posibila.
      </div>
      {% endif %}
    </div>

    {# Rezultatul ultimei adaugari: refuz (rol=alert) sau confirmare.
       Clasa chips-extra-error pastrata pe eroare (selector stabil pentru teste/QA). #}
    {% if chips_error is defined and chips_error %}
    <div class="chips-extra-error" style="font-size:11px;color:var(--err);padding:2px 0;" role="alert">
      {{ chips_error }}
    </div>
    {% elif chips_ok is defined and chips_ok %}
    <div class="chips-adaugat-ok" style="font-size:11px;color:var(--ok);padding:2px 0;" role="status">
      {{ chips_ok }}
    </div>
    {% endif %}
  </div>
</div>

<script>
(function () {
  if (window.__chipsUnifiedBound) { return; }
  window.__chipsUnifiedBound = true;

  // Click pe chip warning -> comuta tinta CLIENT-SIDE (fara round-trip). Click
  // pe tinta activa = no-op (nu se poate "deselecta" tinta cat exista warnings).
  window.chipsSetTarget = function (btn, idx) {
    var hidden = document.getElementById('chips-target-index');
    if (!hidden) { return; }
    if (String(idx) === hidden.value) { return; }
    hidden.value = String(idx);
    document.querySelectorAll('.chip-op-warn.is-target').forEach(function (el) {
      el.classList.remove('is-target');
      el.setAttribute('aria-pressed', 'false');
    });
    btn.classList.add('is-target');
    btn.setAttribute('aria-pressed', 'true');
    var picker = document.getElementById('chips-picker');
    if (picker && picker.options.length) {
      picker.options[0].textContent = 'Cod pentru ' + (btn.dataset.opNume || '') + ' — alege';
    }
  };

  // Focus restaurat pe select dupa fiecare swap outerHTML al sectiunii.
  document.body.addEventListener('htmx:afterSettle', function (evt) {
    var t = evt.target;
    if (t && t.classList && t.classList.contains('chips-editor')) {
      var el = document.getElementById('chips-picker');
      if (el) { el.focus(); }
    }
  });
})();
</script>
