{% if curation_schema_version %}
{% set review_statuses = ['pendiente_revision', 'pendiente_servicio_externo', 'conflicto'] %}
{% set discrepancy_statuses = ['realizado_no_facturado', 'facturado_sin_soporte_exacto'] %}
{% set diagnosticos_por_revisar = (diagnosticos_curados or []) | selectattr('status', 'in', review_statuses) | list %}
{% set procedimientos_por_revisar = (procedimientos_curados or []) | selectattr('status', 'in', review_statuses) | list %}
{% set decisiones_diagnostico = (diagnosticos_curados or []) | rejectattr('decisions', 'undefined') | selectattr('decisions') | list %}
{% set decisiones_procedimiento = (procedimientos_curados or []) | rejectattr('decisions', 'undefined') | selectattr('decisions') | list %}
{% set pending_total = diagnosticos_por_revisar|length + procedimientos_por_revisar|length %}
{% set evidence_total = namespace(value=0) %}
{% for item in diagnosticos_por_revisar + procedimientos_por_revisar %}
  {% set evidence_total.value = evidence_total.value + (item.evidence|length if item.evidence else 0) %}
{% endfor %}

{% macro readable(value) %}{{ (value or 'No informado')|replace('_', ' ')|capitalize }}{% endmacro %}

{% macro item_codes(item, kind) %}
  <div class="curation-item__codes">
    {% if kind == 'diagnostico' %}
    <span class="ui-pill code-chip code-chip--cie10">CIE-10 · {{ item.code or 'sin código' }}</span>
    {% else %}
    {% if item.codigo_cups %}<span class="ui-pill code-chip code-chip--cups">CUPS · {{ item.codigo_cups }}</span>{% endif %}
    {% if item.codigo_soat %}<span class="ui-pill code-chip code-chip--soat">SOAT · {{ item.codigo_soat }}</span>{% endif %}
    {% if item.codigo_facturacion %}<span class="ui-pill code-chip code-chip--billing">Factura · {{ item.codigo_facturacion }}</span>{% endif %}
    {% endif %}
  </div>
{% endmacro %}

{% macro evidence_list(item) %}
  {% if item.evidence %}
  <section class="audit-sheet__section audit-sheet__section--evidence" aria-labelledby="audit-evidence-{{ item.item_id }}">
    <h4 id="audit-evidence-{{ item.item_id }}">Evidencia documental <span>{{ item.evidence|length }}</span></h4>
    <ul class="audit-evidence-list">
      {% for evidence in item.evidence %}
      <li>
        <strong>{{ evidence.filename or 'Archivo sin nombre' }}</strong>
        <span class="audit-evidence-list__meta">{{ readable(evidence.document_type) }}{% if evidence.page %} · página {{ evidence.page }}{% endif %}{% if evidence.section %} · {{ evidence.section }}{% endif %}</span>
        {% if evidence.excerpt %}<details class="audit-evidence__excerpt"><summary>Ver extracto</summary><blockquote>{{ evidence.excerpt }}</blockquote></details>{% endif %}
      </li>
      {% endfor %}
    </ul>
  </section>
  {% endif %}
{% endmacro %}

{% macro review_template(item, kind, template_id) %}
<template id="{{ template_id }}">
  <div data-audit-sheet-content data-curation-item="{{ item.item_id }}"
    data-original-code="{{ item.code if kind == 'diagnostico' else item.codigo_cups }}"
    data-original-description="{{ item.description }}"
    data-requires-reason="{{ 'true' if item.reconciliation_status in discrepancy_statuses else 'false' }}">
    <div class="audit-sheet__summary">
      <span class="ui-pill curation-status">{{ readable(item.status) }}</span>
      <span class="audit-severity">Prioridad: {{ 'bloqueante' if item.status == 'conflicto' else 'alta' if item.reconciliation_status in discrepancy_statuses else 'media' if item.status == 'pendiente_servicio_externo' else 'normal' }}</span>
      {{ item_codes(item, kind) }}
    </div>
    <section class="audit-sheet__section audit-sheet__section--reason">
      <h4>Por qué requiere revisión</h4>
      <p>{{ item.reconciliation_reason or (item.warnings|first if item.warnings else 'La conciliación automática necesita una decisión humana antes de publicar este elemento.') }}</p>
      {% if item.warnings %}<div class="audit-warning-list" aria-label="Advertencias">{% for warning in item.warnings %}<span>{{ readable(warning) }}</span>{% endfor %}</div>{% endif %}
    </section>
    {% if kind == 'procedimiento' %}
    <section class="audit-sheet__section audit-sheet__section--states"><h4>Estados documentales</h4><div class="curation-state-grid" aria-label="Estados documentales">
      {% for state, label in [('documentado', 'Documentado'), ('realizado', 'Realizado'), ('facturado', 'Facturado')] %}
      <span class="{{ 'is-active' if state in item.states else '' }}">{{ 'Sí: ' if state in item.states else 'No: ' }}{{ label }}</span>
      {% endfor %}
    </div></section>
    {% endif %}
    {{ evidence_list(item) }}
    <button type="button" class="ui-button ui-button--secondary ui-button--small" data-audit-edit>Editar propuesta</button>
    <div class="audit-edit-form" data-audit-edit-form hidden>
      <label><span>Código corregido</span><input data-curation-code value="{{ item.code if kind == 'diagnostico' else item.codigo_cups }}"></label>
      <label><span>Descripción corregida</span><input data-curation-description value="{{ item.description }}"></label>
      {% if item.soat_candidates %}
      <label><span>Candidato SOAT 2026</span><select data-curation-soat-candidate><option value="">Selecciona un candidato</option>{% for candidate in item.soat_candidates %}<option value="{{ candidate.soat_code }}">{{ candidate.soat_code }} · grupo {{ candidate.surgical_group or 'sin grupo' }} · {{ candidate.description }}</option>{% endfor %}</select></label>
      {% endif %}
      {% if item.reconciliation_status in discrepancy_statuses %}
      <fieldset class="curation-reference"><legend>Referencia tarifaria SOAT por omisión facturada</legend>
        <label><input type="checkbox" data-curation-reference-toggle> Calcular referencia separada</label>
        <label><span>SOAT exacto</span><input data-curation-manual-soat inputmode="numeric" pattern="[0-9]{4,5}" placeholder="Ejemplo: 01101"></label>
        <label><span>Grupo oficial</span><input data-curation-manual-group inputmode="numeric" type="number" min="2" max="23" placeholder="2–13 o 20–23"></label>
        <div class="curation-reference__components" role="group" aria-label="Componentes omitidos">{% for component, label in [('cirujano', 'Cirujano'), ('anestesia', 'Anestesia'), ('ayudantia', 'Ayudantía'), ('sala', 'Sala'), ('materiales', 'Materiales')] %}<label><input type="checkbox" value="{{ component }}" data-curation-component> {{ label }}</label>{% endfor %}</div>
      </fieldset>
      {% endif %}
    </div>
    <label class="audit-reason"><span>Motivo <small data-audit-reason-hint>{{ '(obligatorio)' if item.reconciliation_status in discrepancy_statuses else '(opcional si apruebas sin cambios)' }}</small></span><textarea data-curation-reason rows="3"></textarea></label>
    <p class="audit-sheet__error" data-audit-item-error role="alert" hidden></p>
  </div>
</template>
{% endmacro %}

{% macro history_template(item, kind, template_id) %}
{% set decision = item.decisions|last %}
<template id="{{ template_id }}">
  <div data-audit-sheet-content data-audit-readonly>
    <div class="audit-sheet__summary"><span class="ui-pill curation-status curation-status--ready">Decisión registrada</span>{{ item_codes(item, kind) }}</div>
    <dl class="pdf-detail-list">
      <div><dt>Decisión</dt><dd>{{ readable(decision.decision) }}</dd></div>
      <div><dt>Actor</dt><dd>{{ decision.actor }}</dd></div>
      <div><dt>Fecha</dt><dd><time datetime="{{ decision.decided_at }}" data-audit-date>{{ decision.decided_at }}</time></dd></div>
      <div><dt>Motivo</dt><dd>{{ decision.reason or 'Sin motivo registrado' }}</dd></div>
      <div><dt>Valor original</dt><dd>{{ decision.original_code or 'Sin código' }} · {{ decision.original_description or 'Sin descripción' }}</dd></div>
      {% if decision.corrected_code or decision.corrected_description %}<div><dt>Valor corregido</dt><dd>{{ decision.corrected_code or decision.original_code }} · {{ decision.corrected_description or decision.original_description }}</dd></div>{% endif %}
    </dl>
    {{ evidence_list(item) }}
  </div>
</template>
{% endmacro %}

{% macro audit_row(item, kind, suffix) %}
{% set discrepancy = item.reconciliation_status in discrepancy_statuses %}
{% set risk = 1 if item.status == 'conflicto' else 2 if discrepancy else 3 if item.status == 'pendiente_servicio_externo' else 4 %}
{% set template_id = 'audit-review-' ~ kind ~ '-' ~ suffix %}
<article class="audit-row" data-audit-row data-audit-kind="{{ kind }}" data-audit-risk="{{ risk }}" data-status="{{ item.status }}">
  <div class="audit-row__type"><span>{{ 'Diagnóstico' if kind == 'diagnostico' else 'Procedimiento' }}</span>{{ item_codes(item, kind) }}</div>
  <div class="audit-row__content"><strong>{{ item.description }}</strong><p>{% set linked_conflict = namespace(message='') %}{% for conflict in conflictos_curacion or [] %}{% if item.item_id in conflict.item_ids and not linked_conflict.message %}{% set linked_conflict.message = conflict.message %}{% endif %}{% endfor %}{{ linked_conflict.message or item.reconciliation_reason or (item.warnings|first if item.warnings else 'Requiere validación humana de la propuesta automática.') }}</p></div>
  <div class="audit-row__meta"><span class="audit-severity">{{ 'Bloqueante' if risk == 1 else 'Discrepancia' if risk == 2 else 'Servicio externo' if risk == 3 else 'Revisión general' }}</span><span>{{ item.evidence|length if item.evidence else 0 }} evidencias</span></div>
  <button type="button" class="ui-button ui-button--secondary ui-button--small" data-audit-open="{{ template_id }}" data-audit-title="{{ item.description }}">Revisar</button>
</article>
{{ review_template(item, kind, template_id) }}
{% endmacro %}

<section class="audit-workspace" aria-labelledby="curation-ledger-title" data-curation-ledger data-curation-version="{{ curation_version }}">
  <header class="audit-workspace__header"><div><p class="pdf-workspace__eyebrow">Conciliación clínica trazable</p><h2 id="curation-ledger-title">Auditoría</h2><p>Revisa y resuelve únicamente los hallazgos que requieren intervención humana.</p></div><span class="ui-pill curation-status curation-status--{{ 'pending' if pending_total else 'ready' }}">{{ 'Revisión pendiente' if pending_total else 'Conciliación al día' }}</span></header>
  <dl class="audit-metrics" aria-label="Estado general de auditoría"><div><dt>Pendientes</dt><dd>{{ pending_total }}</dd></div><div><dt>Conflictos</dt><dd>{{ conflictos_curacion|length if conflictos_curacion else 0 }}</dd></div><div><dt>Evidencias</dt><dd>{{ evidence_total.value }}</dd></div></dl>
  {% if curation_generation_blocked %}<div class="ui-alert ui-alert--warning curation-alert" role="alert"><div class="ui-alert__title">Hay conflictos bloqueantes por resolver.</div><div class="ui-alert__body">{{ curation_blocking_reason or 'Existe un conflicto principal sin resolver.' }}</div></div>{% endif %}

  <div data-audit-tabs>
    <nav class="pdf-tabs audit-tabs" role="tablist" aria-label="Categorías de hallazgos">
      {% for key, label, count in [('todos', 'Por revisar', pending_total), ('diagnosticos', 'Diagnósticos', diagnosticos_por_revisar|length), ('procedimientos', 'Procedimientos', procedimientos_por_revisar|length)] %}<button id="audit-tab-{{ key }}" class="pdf-tabs__tab" type="button" role="tab" aria-selected="{{ 'true' if loop.first else 'false' }}" aria-controls="audit-panel-{{ key }}" tabindex="{{ '0' if loop.first else '-1' }}" data-audit-tab="{{ key }}"><span>{{ label }}</span><span class="pdf-tabs__count">{{ count }}</span></button>{% endfor %}
    </nav>
    {% for key in ['todos', 'diagnosticos', 'procedimientos'] %}
    <section id="audit-panel-{{ key }}" class="audit-panel" role="tabpanel" aria-labelledby="audit-tab-{{ key }}" data-audit-panel="{{ key }}" {{ 'hidden' if not loop.first else '' }}>
      <div class="audit-list" data-audit-list>
        {% if key in ['todos', 'diagnosticos'] %}{% for item in diagnosticos_por_revisar %}{{ audit_row(item, 'diagnostico', key ~ '-' ~ loop.index) }}{% endfor %}{% endif %}
        {% if key in ['todos', 'procedimientos'] %}{% for item in procedimientos_por_revisar %}{{ audit_row(item, 'procedimiento', key ~ '-' ~ loop.index) }}{% endfor %}{% endif %}
      </div>
      {% set category_count = pending_total if key == 'todos' else diagnosticos_por_revisar|length if key == 'diagnosticos' else procedimientos_por_revisar|length %}
      {% if not category_count %}<div class="audit-panel__empty" role="status"><strong>Sin hallazgos pendientes</strong><span>No hay elementos por revisar en esta categoría.</span></div>{% endif %}
    </section>
    {% endfor %}
  </div>

  {% set visible_ids = namespace(values=[]) %}{% for item in diagnosticos_por_revisar + procedimientos_por_revisar %}{% set visible_ids.values = visible_ids.values + [item.item_id] %}{% endfor %}
  {% set orphan_conflicts = namespace(values=[]) %}{% for conflict in conflictos_curacion or [] %}{% set match = namespace(found=false) %}{% for item_id in conflict.item_ids %}{% if item_id in visible_ids.values %}{% set match.found = true %}{% endif %}{% endfor %}{% if not match.found %}{% set orphan_conflicts.values = orphan_conflicts.values + [conflict] %}{% endif %}{% endfor %}
  {% if orphan_conflicts.values %}<div class="curation-conflicts ui-alert ui-alert--warning"><div class="ui-alert__title">Alertas sin hallazgo vinculado</div><ul class="ui-list">{% for conflict in orphan_conflicts.values %}<li>{{ conflict.message }}</li>{% endfor %}</ul></div>{% endif %}

  {% if decisiones_diagnostico or decisiones_procedimiento %}<details class="audit-history"><summary>Decisiones registradas <span>{{ decisiones_diagnostico|length + decisiones_procedimiento|length }}</span></summary><div class="audit-history__list">
    {% for item in decisiones_diagnostico %}{% set template_id = 'audit-history-d-' ~ loop.index %}<button type="button" data-audit-open="{{ template_id }}" data-audit-title="{{ item.description }}"><span>CIE-10 · {{ item.code or 'sin código' }}</span><strong>{{ item.description }}</strong><small>{{ readable((item.decisions|last).decision) }} · {{ (item.decisions|last).actor }}</small></button>{{ history_template(item, 'diagnostico', template_id) }}{% endfor %}
    {% for item in decisiones_procedimiento %}{% set template_id = 'audit-history-p-' ~ loop.index %}<button type="button" data-audit-open="{{ template_id }}" data-audit-title="{{ item.description }}"><span>CUPS · {{ item.codigo_cups or 'sin código' }}</span><strong>{{ item.description }}</strong><small>{{ readable((item.decisions|last).decision) }} · {{ (item.decisions|last).actor }}</small></button>{{ history_template(item, 'procedimiento', template_id) }}{% endfor %}
  </div></details>{% endif %}
  <details class="curation-catalogs"><summary>Catálogos utilizados</summary><ul class="ui-list">{% for catalog in catalogos_utilizados %}<li>{{ catalog.system|upper }} · {{ catalog.index_name }} · {{ catalog.fingerprint[:12] }}</li>{% endfor %}</ul></details>
  <p class="curation-feedback" data-curation-feedback role="status" aria-live="polite"></p>

  <dialog id="audit_review_sheet" class="pdf-sheet audit-sheet" aria-labelledby="audit-sheet-title"><form method="dialog" class="pdf-sheet__surface" data-audit-sheet-form><header><div><p class="pdf-workspace__eyebrow" data-audit-sheet-kicker>Revisión de hallazgo</p><h3 id="audit-sheet-title" data-audit-sheet-title>Detalle</h3></div><button class="pdf-sheet__close" value="cancel" aria-label="Cerrar revisión">×</button></header><div class="pdf-sheet__body" data-audit-sheet-body></div><footer class="pdf-sheet__actions" data-audit-sheet-actions><button type="button" class="ui-button ui-button--danger ui-button--small" data-curation-action="reject">Rechazar</button><button type="button" class="ui-button ui-button--small" data-curation-action="resolve">Resolver issue</button></footer></form></dialog>
</section>
{% else %}
<section class="audit-workspace epicrisis-empty-state" role="status"><p class="app-page__eyebrow">Conciliación clínica</p><h2>Auditoría aún sin datos de conciliación</h2><p>Este caso no tiene resultados de conciliación disponibles. Revisa los documentos asociados antes de tomar una decisión.</p></section>
{% endif %}
