{% if factura %}
  {% if factura_view and factura_view.is_structured %}
  <section class="invoice-workspace" id="factura_workspace" aria-labelledby="factura-workspace-title">
    <header class="invoice-workspace__header">
      <div>
        <p class="invoice-workspace__eyebrow">Soporte administrativo</p>
        <h2 id="factura-workspace-title">Consulta de factura</h2>
        <p>Revisa la información persistida de la factura, sus líneas y la referencia tarifaria SOAT.</p>
      </div>
      <div class="invoice-workspace__meta" aria-label="Resumen de factura">
        <span class="ui-pill">{{ factura_view.canonical_lines|length }} líneas canónicas</span>
        {% if factura_view.patient_name %}<span class="ui-pill">{{ factura_view.patient_name }}</span>{% endif %}
      </div>
    </header>

    <nav class="invoice-tabs" role="tablist" aria-label="Vistas de la factura">
      <button id="factura-tab-canonica" class="invoice-tabs__tab" type="button" role="tab"
        aria-selected="true" aria-controls="factura-panel-canonica" tabindex="0" data-factura-tab="canonica">
        Factura canónica
      </button>
      <button id="factura-tab-secciones" class="invoice-tabs__tab" type="button" role="tab"
        aria-selected="false" aria-controls="factura-panel-secciones" tabindex="-1" data-factura-tab="secciones">
        Clasificación por secciones
      </button>
      <button id="factura-tab-soat" class="invoice-tabs__tab" type="button" role="tab"
        aria-selected="false" aria-controls="factura-panel-soat" tabindex="-1" data-factura-tab="soat">
        Análisis SOAT
      </button>
    </nav>

    <section id="factura-panel-canonica" class="invoice-tab-panel" role="tabpanel"
      aria-labelledby="factura-tab-canonica" data-factura-panel="canonica" tabindex="0">
      <div class="invoice-identity-grid">
        {% for group in factura_view.identity_groups %}
        <article class="invoice-surface invoice-identity-card">
          <h3>{{ group.title }}</h3>
          <dl class="invoice-key-values">
            {% for field in group.fields %}
            <div><dt>{{ field.label }}</dt><dd>{% if field.value and field.is_date %}<time data-local-date datetime="{{ field.value }}">{{ field.value }}</time>{% else %}{{ field.value or 'No informado' }}{% endif %}</dd></div>
            {% endfor %}
          </dl>
        </article>
        {% endfor %}
      </div>

      <article class="invoice-surface invoice-section-card">
        <div class="invoice-section-card__header">
          <div><p class="invoice-section-card__kicker">Detalle económico</p><h3>Líneas canónicas</h3></div>
          <span class="invoice-count">{{ factura_view.canonical_lines|length }}</span>
        </div>
        {% if factura_view.canonical_lines %}
        <div class="ui-table-wrap ui-table-wrap--dense-wide invoice-table-wrap">
          <table class="ui-table">
            <caption class="ui-sr-only">Líneas canónicas de la factura</caption>
            <thead><tr><th>Fecha</th><th>Código factura</th><th>Referencia / CUPS</th><th>Descripción</th><th>Categoría</th><th>Cantidad</th><th>Valor unitario</th><th>Total</th></tr></thead>
            <tbody>
              {% for line in factura_view.canonical_lines %}
              <tr>
                <td>{% if line.fecha_servicio and line.fecha_servicio != '—' %}<time data-local-date datetime="{{ line.fecha_servicio }}">{{ line.fecha_servicio }}</time>{% else %}—{% endif %}</td>
                <td>{{ line.codigo_facturacion or '—' }}</td>
                <td>{{ line.codigo_referencia or '—' }}</td>
                <td class="ui-table-cell--wrap">{{ line.descripcion or '—' }}</td>
                <td>{{ line.categoria or '—' }}</td>
                <td>{{ line.cantidad or '—' }}</td>
                <td>{{ line.valor_unitario or '—' }}</td>
                <td>{{ line.total or '—' }}</td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
        {% else %}
        <p class="invoice-empty" role="status">No hay líneas canónicas persistidas.</p>
        {% endif %}
      </article>

      <div class="invoice-summary-grid">
        <article class="invoice-surface invoice-section-card">
          <div class="invoice-section-card__header"><div><p class="invoice-section-card__kicker">Cierre declarado</p><h3>Resumen financiero</h3></div></div>
          <dl class="invoice-financial-grid">
            {% for item in factura_view.financial %}<div><dt>{{ item.label }}</dt><dd>{{ item.value }}</dd></div>{% endfor %}
          </dl>
        </article>
        <article class="invoice-surface invoice-section-card">
          <div class="invoice-section-card__header"><div><p class="invoice-section-card__kicker">Trazabilidad</p><h3>Observaciones</h3></div></div>
          {% if factura_view.observations %}<ul class="invoice-observations">{% for observation in factura_view.observations %}<li>{{ observation }}</li>{% endfor %}</ul>
          {% else %}<p class="invoice-empty">Sin observaciones persistidas.</p>{% endif %}
        </article>
      </div>
    </section>

    <section id="factura-panel-secciones" class="invoice-tab-panel" role="tabpanel"
      aria-labelledby="factura-tab-secciones" data-factura-panel="secciones" tabindex="0" hidden>
      <div class="invoice-panel-intro"><p class="invoice-section-card__kicker">Clasificación documental</p><h3>Servicios y procedimientos</h3><p>Las líneas se conservan en la sección persistida de la factura para facilitar su revisión sin mezclar categorías.</p></div>
      <div class="invoice-service-sections">
        {% for section in factura_view.sections %}
        <article class="invoice-surface invoice-section-card" data-invoice-section="{{ section.key }}">
          <div class="invoice-section-card__header"><div><h3>{{ section.label }}</h3></div><span class="invoice-count">{{ section.count }}</span></div>
          {% if section.rows %}
          <div class="ui-table-wrap ui-table-wrap--dense-wide invoice-table-wrap">
            <table class="ui-table"><caption class="ui-sr-only">{{ section.label }}</caption><thead><tr>{% for column in section.columns %}<th>{{ column.label }}</th>{% endfor %}</tr></thead>
              <tbody>{% for row in section.rows %}<tr>{% for column in section.columns %}<td class="ui-table-cell--wrap">{{ row.get(column.key, '—') }}</td>{% endfor %}</tr>{% endfor %}</tbody>
            </table>
          </div>
          {% else %}<p class="invoice-empty" role="status">No hay registros en esta sección.</p>{% endif %}
        </article>
        {% endfor %}
      </div>
    </section>

    <section id="factura-panel-soat" class="invoice-tab-panel" role="tabpanel"
      aria-labelledby="factura-tab-soat" data-factura-panel="soat" tabindex="0" hidden>
      <div class="invoice-panel-intro"><p class="invoice-section-card__kicker">Referencia persistida</p><h3>Análisis SOAT</h3><p>Consulta la valuación guardada junto con sus reglas y evidencias. Esta vista no ejecuta nuevos cálculos.</p></div>
      {% if factura_view.soat.available %}
      <article class="invoice-surface invoice-section-card">
        <div class="invoice-section-card__header"><div><h3>Resumen tarifario SOAT</h3></div></div>
        <dl class="invoice-soat-summary">{% for item in factura_view.soat.summary %}<div><dt>{{ item.label }}</dt><dd>{{ item.value }}</dd></div>{% endfor %}</dl>
        {% if factura_view.soat.note %}<p class="invoice-note">{{ factura_view.soat.note }}</p>{% endif %}
      </article>
      {% if factura_view.soat.procedures %}
      <article class="invoice-surface invoice-section-card">
        <div class="invoice-section-card__header"><div><h3>Procedimientos valuados</h3></div><span class="invoice-count">{{ factura_view.soat.procedures|length }}</span></div>
        <div class="ui-table-wrap ui-table-wrap--dense-wide invoice-table-wrap">
          <table class="ui-table"><caption class="ui-sr-only">Procedimientos con análisis SOAT persistido</caption><thead><tr><th>Código facturado / CUPS</th><th>Código SOAT</th><th>Descripción</th><th>Grupo</th><th>Estado</th><th>Regla aplicada</th><th>Tarifa base</th><th>Valor liquidado</th><th>Línea canónica</th></tr></thead>
            <tbody>{% for procedure in factura_view.soat.procedures %}<tr data-soat-status="{{ procedure.estado_codigo }}"><td>{{ procedure.codigo_facturado_cups }}</td><td>{{ procedure.codigo_soat }}</td><td class="ui-table-cell--wrap">{{ procedure.descripcion }}</td><td>{{ procedure.grupo }}</td><td><span class="invoice-status invoice-status--{{ procedure.estado_codigo }}">{{ procedure.estado }}</span></td><td class="ui-table-cell--wrap">{{ procedure.regla }}</td><td>{{ procedure.valor_base }}</td><td>{{ procedure.valor_liquidado }}</td><td>{{ procedure.linea_canonica }}{% if procedure.linea_canonica_descripcion %}<small>{{ procedure.linea_canonica_descripcion }}</small>{% endif %}</td></tr>
            <tr class="invoice-details-row"><td colspan="9"><details class="invoice-details"><summary>Consultar evidencia, componentes, códigos asociados y cruce CUPS-SOAT</summary><div class="invoice-details__grid">
              <div><h4>Evidencia</h4>{% if procedure.evidencia %}<ul>{% for evidence in procedure.evidencia %}<li>{{ evidence }}</li>{% endfor %}</ul>{% else %}<p>Sin evidencia persistida.</p>{% endif %}</div>
              <div><h4>Componentes y códigos</h4>{% if procedure.componentes %}<div class="ui-table-wrap"><table class="ui-table"><thead><tr><th>Componente</th><th>Base</th><th>Liquidado</th><th>Código</th></tr></thead><tbody>{% for component in procedure.componentes %}<tr><td>{{ component.name }}</td><td>{{ component.base }}</td><td>{{ component.liquidated }}</td><td>{{ component.code }}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p>Sin componentes asociados.</p>{% endif %}</div>
              <div><h4>Cruce CUPS-SOAT</h4>{% if procedure.cruce %}<dl class="invoice-key-values">{% for detail in procedure.cruce %}<div><dt>{{ detail.label }}</dt><dd>{{ detail.value }}</dd></div>{% endfor %}</dl>{% else %}<p>Sin cruce CUPS-SOAT persistido.</p>{% endif %}</div>
            </div></details></td></tr>{% endfor %}</tbody>
          </table>
        </div>
      </article>
      {% else %}<p class="invoice-empty" role="status">No hay procedimientos con valuación SOAT persistida.</p>{% endif %}
      {% else %}<div class="invoice-empty-state" role="status"><h3>Sin evaluación SOAT persistida</h3><p>La factura no contiene un resumen tarifario SOAT guardado para consulta.</p></div>{% endif %}
    </section>
  </section>
  {% else %}
  <div class="card">
    <div class="section-header">💰 Información de Factura</div>
    <div class="epicrisis-panel epicrisis-panel--neutral">
      <div id="factura_content">{{ factura_view.legacy_html if factura_view and factura_view.legacy_html else factura.analisis_html|safe }}</div>
      <div class="epicrisis-panel epicrisis-panel--warning epicrisis-mt-lg">
        <p class="epicrisis-callout"><strong>Procesamiento Inteligente:</strong> Los procedimientos de factura se procesan automáticamente al generar la epicrisis.</p>
      </div>
    </div>
  </div>
  {% endif %}
{% else %}
<div class="epicrisis-empty-state" role="status">
  <p class="app-page__eyebrow">Soporte administrativo</p>
  <h2>Factura no disponible</h2>
  <p>No hay un análisis de factura asociado a este caso. La pestaña permanecerá disponible cuando se incorpore el documento.</p>
</div>
{% endif %}
