{% extends "base.html" %}
{% block title %}Clientes{% endblock %}
{% block page_title %}Clientes{% endblock %}

{% block topbar_actions %}
<a href="{{ url_for('clientes.nuevo') }}" class="btn btn-primary btn-sm">
  <i class="bi bi-plus-lg"></i> Nuevo cliente
</a>
{% endblock %}

{% block content %}
<div class="card">
  <div class="card-header py-3 d-flex align-items-center justify-content-between">
    <span><i class="bi bi-people me-2"></i>Listado de clientes</span>
    <form class="d-flex gap-2" method="get">
      <input type="search" name="q" value="{{ buscar }}" class="form-control form-control-sm" placeholder="Buscar...">
      <button class="btn btn-sm btn-outline-secondary">Buscar</button>
      {% if buscar %}<a href="{{ url_for('clientes.lista') }}" class="btn btn-sm btn-outline-secondary">✕</a>{% endif %}
    </form>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr>
          <th>Nombre</th><th>NIF/CIF</th><th>Email</th><th>Teléfono</th>
          <th class="text-end">Total facturado</th><th class="text-end">Pendiente cobro</th><th></th>
        </tr>
      </thead>
      <tbody>
        {% for c in clientes %}
        <tr>
          <td>
            <a href="{{ url_for('clientes.detalle', id=c.id) }}" class="fw-semibold text-decoration-none text-dark">{{ c.nombre }}</a>
            {% if c.ciudad %}<div class="text-muted" style="font-size:.78rem">{{ c.ciudad }}</div>{% endif %}
          </td>
          <td class="text-muted small">{{ c.nif or '—' }}</td>
          <td class="small">{{ c.email or '—' }}</td>
          <td class="small">{{ c.telefono or '—' }}</td>
          <td class="text-end fw-semibold small">{{ "%.2f"|format(stats[c.id].total) }} €</td>
          <td class="text-end small {% if stats[c.id].pendiente > 0 %}text-warning fw-semibold{% else %}text-muted{% endif %}">
            {{ "%.2f"|format(stats[c.id].pendiente) }} €
          </td>
          <td class="text-end">
            <a href="{{ url_for('clientes.editar', id=c.id) }}" class="btn btn-outline-secondary btn-action"><i class="bi bi-pencil"></i></a>
            <form method="post" action="{{ url_for('clientes.eliminar', id=c.id) }}" class="d-inline"
                  onsubmit="return confirm('¿Eliminar cliente?')">
              <button class="btn btn-outline-danger btn-action"><i class="bi bi-trash"></i></button>
            </form>
          </td>
        </tr>
        {% else %}
        <tr><td colspan="7" class="text-center text-muted py-4">
          {% if buscar %}Sin resultados para "{{ buscar }}"{% else %}No hay clientes registrados{% endif %}
        </td></tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</div>
{% endblock %}
