{% extends "ui/templates/base/layout.html" %}
{% import "ui/templates/components/macros.html" as ui %}
{% block content %}
<div class="space-y-6">
  {% set perms = current_user_permissions or [] %}
  {% set roles = current_user_roles or [] %}
  {% set add_branch_cta = '<a href="/system-settings/branches/new" class="rounded-xl bg-slate-900 px-4 py-2 text-sm text-white">Add Branch</a>' if can_manage_branches(current_user, perms, roles) else '' %}

  {{ ui.page_shell('Branches', 'Branch directory with search, paging, and quick navigation to branch settings.', add_branch_cta) }}

  <div class="overflow-hidden rounded-3xl bg-white shadow-soft">
    {{ ui.search_bar('/system-settings/branches', filters.q, filters.per_page) }}

    {% if branches %}
    <table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-600">
        <tr>
          <th class="p-3 text-left">Branch</th>
          <th class="p-3 text-left">Audit Firm</th>
          <th class="p-3 text-left">Timezone</th>
          <th class="p-3 text-left">Flags</th>
          <th class="p-3 text-left">Actions</th>
        </tr>
      </thead>
      <tbody>
        {% for b in branches %}
        <tr class="border-t align-top">
          <td class="p-3">
            <div class="font-medium text-slate-900">{{ b.name }}</div>
            <div class="text-xs text-slate-500">{{ b.code }}</div>
          </td>
          <td class="p-3">
            {{ tenants[b.tenant_id].name if b.tenant_id in tenants else '-' }}
          </td>
          <td class="p-3">{{ b.timezone }}</td>
          <td class="p-3">
            <div class="flex flex-wrap gap-2">
              {{ ui.badge('Active','emerald') if b.is_active else ui.badge('Inactive','rose') }}
              {{ ui.badge('Login enabled','sky') if b.allow_login else ui.badge('Login disabled','amber') }}
              {% if b.is_head_office %}{{ ui.badge('Head Office','brand') }}{% endif %}
            </div>
          </td>
          <td class="p-3">
            {% if can_manage_branches(current_user, perms, roles) %}
              <a class="text-slate-900 underline" href="/system-settings/branches/{{ b.id }}/edit">Edit</a>
            {% else %}
              <span class="text-slate-400">View only</span>
            {% endif %}
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>

    {{ ui.pagination(branches_page, '/system-settings/branches', request.url.query) }}
    {% else %}
      <div class="p-6">
        {{ ui.empty_state('No branches found for the current scope.') }}
      </div>
    {% endif %}
  </div>
</div>
{% endblock %}