{% import '_macros.html' as ui %}
<div id="mapari-section">
  <style>
    /* Selectul de cod RAR e principalul vinovat de latimea tabelelor de mapari. Il limitam ca
       tabelul sa incapa in card fara scroll orizontal -> coloana Actiuni (kebab) ramane vizibila. */
    #mapari-section td select { width:100%; max-width:240px; min-width:150px; }
    /* In card per rand (sub 767px) selectul/inputurile umplu cardul. */
    @media (max-width:767px) {
      #mapari-section td select, #mapari-section td input[type=text] { max-width:none; min-width:0; }
    }
  </style>

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

  <!-- ============================================================ -->
  <!-- Sectiunea 1: De rezolvat (operatii needs_mapping)            -->
  <!-- ============================================================ -->
  <div class="card">
    <h2 style="font-size:15px; margin:0 0 8px;">De rezolvat</h2>

    {% if pending %}
    <div data-dt="10">
    <div class="dt-tools">
      <input type="search" data-dt-search class="dt-search"
             placeholder="Cauta operatie sau cod..." aria-label="Cauta in operatiile de rezolvat">
    </div>
    <div class="tablewrap tabel-card">
    <table>
      <thead><tr>
        <th>Operatie</th>
        <th>Sugestii</th>
        <th>Cod RAR</th>
        <th></th>
      </tr></thead>
      <tbody>
      {% for e in pending %}
      {% set top = e.suggestions[0] if e.suggestions else None %}
      {# L14-S6: pre-selectare din sugestie_principala (GOLD/SILVER/embedding) > fuzzy #}
      {% set preselect = e.sugestie_principala.cod_prestatie if e.sugestie_principala else (top.cod_prestatie if (top and top.score >= 60) else '') %}
        {# data-dt-row = haystack de cautare (randul contine un <select> cu tot nomenclatorul). #}
        <tr data-dt-row="{{ e.cod_op_service }} {{ e.denumire or '' }}
            {%- for s in e.suggestions[:3] %} {{ s.cod_prestatie }}{% endfor %}">
          <td data-eticheta="Operatie">
            <form id="map-rez-{{ loop.index }}" hx-post="/mapari" hx-target="#mapari-section" hx-swap="outerHTML">
              <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
              <input type="hidden" name="cod_op_service" value="{{ e.cod_op_service }}">
              {# L14-S6: denumire pt record_human_validation in GOLD partajat #}
              <input type="hidden" name="denumire" value="{{ e.denumire or '' }}">
            </form>
            <div><strong>{{ e.cod_op_service }}</strong>
              <span class="pill" title="submission-uri blocate">{{ e.blocked }} blocate</span></div>
            <div class="muted">{{ e.denumire or '(fara denumire)' }}</div>
          </td>
          <td class="muted" style="font-size:12px;" data-eticheta="Sugestii">
            {# 5.18 US-007: badge sursa pe sugestia sistemului — confirmat (GOLD) / similar
               (SILVER+embedding k-NN) / non-operatie (pre-filtru NUL). Suggestion-only. #}
            {% if e.sugestie_principala %}
              {% if e.sugestie_principala.sursa == 'gold_partajat' %}
                <span class="sugg-sursa sugg-sursa--confirmat" title="cod confirmat de un operator">confirmat</span>
              {% else %}
                <span class="sugg-sursa sugg-sursa--similar" title="operatie similara deja vazuta (k-NN/exact)">similar</span>
              {% endif %}
            {% elif e.surse_sugestie and e.surse_sugestie.nul %}
              <span class="sugg-sursa sugg-sursa--nul" title="pare non-operatie (ITP/plata/discount...)">non-operatie</span>
            {% endif %}
            {% if e.suggestions %}
              {% for s in e.suggestions[:3] %}
                <span class="sugg">{{ s.cod_prestatie }} ({{ s.score|round|int }}%)</span>{% if not loop.last %}, {% endif %}
              {% endfor %}
            {% elif not e.sugestie_principala and not (e.surse_sugestie and e.surse_sugestie.nul) %}—{% endif %}
          </td>
          <td data-eticheta="Cod RAR">
            <select name="cod_prestatie" form="map-rez-{{ loop.index }}" required
                    aria-label="Cod RAR pentru {{ e.cod_op_service }}">
              <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>
          </td>
          <td>
            <button type="submit" form="map-rez-{{ loop.index }}">Salveaza</button>
          </td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
    </div>
    <div class="dt-empty" data-dt-empty style="display:none;">Nicio operatie nu se potriveste cautarii.</div>
    <div class="dt-pager" data-dt-pager></div>
    </div>
    {% endif %}
  </div>

  <!-- ============================================================ -->
  <!-- Sectiunea 2: Mapari operatii salvate (operations_mapping)    -->
  <!-- ============================================================ -->
  <div class="card">
    <h2 style="font-size:15px; margin:0 0 12px;">Mapari operatii salvate</h2>

    {% if not saved_mappings %}
    <div class="empty">
      Nicio mapare salvata inca. Pe masura ce mapezi operatii, ele apar aici si le poti edita oricand.
    </div>
    {% else %}
    <div data-dt="10">
    <div class="dt-tools">
      <input type="search" data-dt-search class="dt-search"
             placeholder="Cauta operatie sau cod RAR..." aria-label="Cauta in maparile salvate">
    </div>
    <div class="tablewrap tabel-card">
    <table>
      <thead><tr>
        <th>Operatie</th>
        <th>Cod RAR</th>
        <th>Actiuni</th>
      </tr></thead>
      <tbody>
      {% for m in saved_mappings %}
        {# data-dt-row = haystack de cautare (randul contine un <select> cu tot nomenclatorul). #}
        <tr data-dt-row="{{ m.cod_op_service }} {{ m.cod_prestatie }} {{ m.nume_prestatie or '' }}">
          <td data-eticheta="Operatie">
            <form id="map-salv-{{ loop.index }}" hx-post="/mapari/salvate" hx-target="#mapari-section" hx-swap="outerHTML">
              <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
              <input type="hidden" name="cod_op_service" value="{{ m.cod_op_service }}">
            </form>
            <form id="map-del-{{ loop.index }}" hx-post="/mapari/salvate/sterge" hx-target="#mapari-section" hx-swap="outerHTML"
                  hx-confirm="Stergi maparea pentru {{ m.cod_op_service }}?">
              <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
              <input type="hidden" name="cod_op_service" value="{{ m.cod_op_service }}">
            </form>
            <div><strong>{{ m.cod_op_service }}</strong></div>
            <div class="muted map-acum" style="font-size:12px;">
              acum: {{ m.cod_prestatie }}{% if m.nume_prestatie %} — {{ m.nume_prestatie }}{% endif %}
            </div>
          </td>
          <td data-eticheta="Cod RAR">
            <select name="cod_prestatie" form="map-salv-{{ loop.index }}" required
                    aria-label="Cod RAR pentru {{ m.cod_op_service }}">
              {% for n in nomenclator %}
              <option value="{{ n.cod_prestatie }}" {% if n.cod_prestatie == m.cod_prestatie %}selected{% endif %}>
                {{ n.cod_prestatie }} — {{ n.nume_prestatie }}
              </option>
              {% endfor %}
            </select>
          </td>
          <td style="text-align:right; white-space:nowrap;" data-eticheta="Actiuni">
            {# Butoane act_btn (desktop: text; mobil: iconita 44px).
               data-dirty-form e citit de JS din base.html: la schimbarea select-ului din acelasi rand,
               JS adauga clasa "dirty" pe butonul de salvare (fundal --accent = modificari nesalvate). #}
            {{ ui.act_btn('Salveaza', 'save', 'save', 'type="submit" form="map-salv-' ~ loop.index ~ '" data-dirty-form="map-salv-' ~ loop.index ~ '"') }}
            {{ ui.act_btn('Sterge', 'trash', 'del', 'type="submit" form="map-del-' ~ loop.index ~ '"') }}
          </td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
    </div>
    <div class="dt-empty" data-dt-empty style="display:none;">Nicio mapare nu se potriveste cautarii.</div>
    <div class="dt-pager" data-dt-pager></div>
    </div>
    {% endif %}
  </div>

  <!-- ============================================================ -->
  <!-- Sectiunea 3: Reguli automate pe text (operation_text_rules)  -->
  <!-- ============================================================ -->
  <div class="card">
    <h2 style="font-size:15px; margin:0 0 8px;">Reguli automate (text)</h2>
    <p class="muted" style="margin:0 0 12px; font-size:13px; max-width:680px;">
      O regula leaga orice operatie al carei text <strong>contine</strong> (nu egal, ci substring)
      un cuvant de un cod RAR. Util pentru operatii fara cod intern: ex. orice operatie care
      <em>contine</em> „verificare" primeste codul ales. Match insensibil la majuscule/diacritice.
    </p>

    {% if not text_rules %}
    <div class="empty" style="margin-bottom:12px;">
      Inca nu ai reguli. Ex: operatia contine «verificare» &rarr; OE-2.
      Mapeaza automat operatii similare fara cod intern. Adauga prima regula mai jos.
    </div>
    {% endif %}

    <div class="tablewrap tabel-card">
    <table>
      <thead><tr>
        <th>Daca operatia contine</th>
        <th>Cod RAR</th>
        <th>Actiuni</th>
      </tr></thead>
      <tbody>
      {% for r in text_rules %}
        <tr>
          <td data-eticheta="Daca operatia contine">
            <form id="rt-del-{{ loop.index }}" hx-post="/mapari/reguli-text/sterge"
                  hx-target="#mapari-section" hx-swap="outerHTML"
                  hx-confirm="Stergi regula «{{ r.pattern }}»?">
              <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
              <input type="hidden" name="pattern" value="{{ r.pattern }}">
            </form>
            <div>contine <strong>«{{ r.pattern }}»</strong></div>
          </td>
          <td class="muted" style="font-size:12px;" data-eticheta="Cod RAR">
            {{ r.cod_prestatie }}
          </td>
          <td style="text-align:right; white-space:nowrap;">
            {{ ui.act_btn('Sterge', 'trash', 'del', 'type="submit" form="rt-del-' ~ loop.index ~ '"') }}
          </td>
        </tr>
      {% endfor %}
        {# Rand de adaugare (mereu prezent ca placeholder, inclusiv in empty state). #}
        <tr>
          <td data-eticheta="Daca operatia contine">
            <form id="rt-add" hx-post="/mapari/reguli-text" hx-target="#mapari-section" hx-swap="outerHTML">
              <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
              <input type="text" name="pattern" required
                     placeholder="ex. verificare"
                     aria-label="Text continut in operatie"
                     style="width:100%; max-width:240px;"
                     hx-post="/mapari/reguli-text/preview"
                     hx-trigger="keyup delay:400ms"
                     hx-target="#rt-preview"
                     hx-swap="innerHTML"
                     hx-include="#rt-add">
            </form>
          </td>
          <td data-eticheta="Cod RAR">
            <select name="cod_prestatie" form="rt-add" required aria-label="Cod RAR pentru regula text">
              <option value="">— alege cod RAR —</option>
              {% for n in nomenclator %}
              <option value="{{ n.cod_prestatie }}">{{ n.cod_prestatie }} — {{ n.nume_prestatie }}</option>
              {% endfor %}
            </select>
          </td>
          <td style="text-align:right; white-space:nowrap;">
            <button type="submit" form="rt-add">Adauga</button>
          </td>
        </tr>
        {# Preview pre-salvare: cate operatii nemapate potriveste pattern-ul. #}
        <tr>
          <td colspan="3" style="padding-top:0;">
            <div id="rt-preview" aria-live="polite"></div>
          </td>
        </tr>
      </tbody>
    </table>
    </div>
  </div>

  <!-- ============================================================ -->
  <!-- Sectiunea 4: Formate de coloane salvate (column_mappings)    -->
  <!-- ============================================================ -->
  <div class="card">
    <h2 style="font-size:15px; margin:0 0 12px;">Formate de coloane salvate</h2>

    {% if not column_formats %}
    <div class="empty">
      Niciun format de coloane salvat inca. La primul import, maparea coloanelor fisierului
      se retine aici si se reaplica automat la fisierele cu acelasi antet.
    </div>
    {% else %}
    <p class="muted" style="margin:0 0 12px; font-size:13px;">
      Antetele de fisier recunoscute. Un fisier cu alte coloane = format nou separat.
    </p>

    <div data-dt="10">
    <div class="dt-tools">
      <input type="search" data-dt-search class="dt-search"
             placeholder="Cauta coloana sau camp..." aria-label="Cauta in formatele de coloane">
    </div>
    <div class="tablewrap tabel-card">
    <table>
      <thead><tr>
        <th>Coloane</th>
        <th>Mapari (coloana &rarr; camp)</th>
        <th>Format data</th>
        <th></th>
      </tr></thead>
      <tbody>
      {% for f in column_formats %}
        <tr>
          <td style="white-space:nowrap;" data-eticheta="Coloane">
            <strong>{{ f.columns | length }} coloane</strong>
          </td>
          <td class="muted" style="font-size:12px; white-space:normal; max-width:340px;" data-eticheta="Mapari (coloana &rarr; camp)">
            {% for col, camp in f.mappings.items() %}
              <span class="sugg">{{ col }}</span> &rarr; {{ camp }}{% if not loop.last %}; {% endif %}
            {% endfor %}
          </td>
          <td data-eticheta="Format data">
            <form id="fmt-edit-{{ loop.index }}" hx-post="/formate-coloane/editeaza"
                  hx-target="#mapari-section" hx-swap="outerHTML"
                  style="display:flex; gap:6px; align-items:center;">
              <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
              <input type="hidden" name="format_id" value="{{ f.id }}">
              <input type="text" name="format_data" value="{{ f.format_data or '' }}"
                     placeholder="ex. DD.MM.YYYY" aria-label="Format data" style="max-width:130px;">
              <button type="submit">Salveaza data</button>
            </form>
          </td>
          <td>
            <form hx-post="/formate-coloane/sterge" hx-target="#mapari-section" hx-swap="outerHTML"
                  hx-confirm="Stergi acest format de coloane?">
              <input type="hidden" name="csrf_token" value="{{ csrf_token or '' }}">
              <input type="hidden" name="format_id" value="{{ f.id }}">
              {{ ui.act_btn('Sterge', 'trash', 'del', 'type="submit"') }}
            </form>
          </td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
    </div>
    <div class="dt-empty" data-dt-empty style="display:none;">Niciun format nu se potriveste cautarii.</div>
    <div class="dt-pager" data-dt-pager></div>
    </div>
    {% endif %}
  </div>

</div>
