{# Jinja macros for reusable table patterns. #}

{% macro results_summary(start_index, end_index, total) -%}
  {% if total and total > 0 %}
    Showing {{ start_index }}–{{ end_index }} of {{ total }}
  {% else %}
    No results
  {% endif %}
{%- endmacro %}

{% macro answer_table(headers, form_action=None, select_name='selected_ids', enable_bulk=False) -%}
  <form method="post" action="{{ form_action or '' }}" class="js-answer-table">
    <table class="table table-hover align-middle">
      <thead class="table-light">
        <tr>
          {% if enable_bulk %}
          <th style="width: 40px;"><input class="form-check-input js-select-all" type="checkbox"></th>
          {% endif %}
          {% for h in headers %}
            <th{% if h.width %} style="width: {{ h.width }};"{% endif %}{% if h.align == 'end' %} class="text-end"{% endif %}>{{ h.title }}</th>
          {% endfor %}
        </tr>
      </thead>
      <tbody>
        {{ caller() }}
      </tbody>
    </table>
  </form>
{%- endmacro %}

{% macro bulk_actions_bar() -%}
  <div class="d-flex gap-2 mb-2">
    {{ caller() }}
  </div>
{%- endmacro %}

{% macro pagination(base_url, page, total_pages, page_size, params=None) -%}
  {% if total_pages and total_pages > 1 %}
  <nav aria-label="Pagination">
    <ul class="pagination mb-0">
      <li class="page-item {% if page <= 1 %}disabled{% endif %}">
        <a class="page-link" href="{{ base_url }}?page={{ 1 if page <= 1 else page - 1 }}&page_size={{ page_size }}{% if params %}{% for k, v in params.items() %}{% if v %}&{{ k }}={{ v | urlencode }}{% endif %}{% endfor %}{% endif %}" aria-label="Previous">
          <span aria-hidden="true">&laquo;</span>
        </a>
      </li>

      {% set start_page = 1 if page - 2 < 1 else page - 2 %}
      {% set end_page = total_pages if page + 2 > total_pages else page + 2 %}
      {% for p in range(start_page, end_page + 1) %}
        <li class="page-item {% if p == page %}active{% endif %}">
          <a class="page-link" href="{{ base_url }}?page={{ p }}&page_size={{ page_size }}{% if params %}{% for k, v in params.items() %}{% if v %}&{{ k }}={{ v | urlencode }}{% endif %}{% endfor %}{% endif %}">{{ p }}</a>
        </li>
      {% endfor %}

      <li class="page-item {% if page >= total_pages %}disabled{% endif %}">
        <a class="page-link" href="{{ base_url }}?page={{ total_pages if page >= total_pages else page + 1 }}&page_size={{ page_size }}{% if params %}{% for k, v in params.items() %}{% if v %}&{{ k }}={{ v | urlencode }}{% endif %}{% endfor %}{% endif %}" aria-label="Next">
          <span aria-hidden="true">&raquo;</span>
        </a>
      </li>
    </ul>
  </nav>
  {% endif %}
{%- endmacro %}


