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

{% block topbar_actions %}
<a href="{{ url_for('transacciones.nueva') }}?tipo=ingreso" class="btn btn-success btn-sm">
  <i class="bi bi-plus-lg"></i> Ingreso
</a>
<a href="{{ url_for('transacciones.nueva') }}?tipo=gasto" class="btn btn-danger btn-sm">
  <i class="bi bi-plus-lg"></i> Gasto
</a>
<a href="{{ url_for('facturas.nueva_emitida') }}" class="btn btn-primary btn-sm">
  <i class="bi bi-file-earmark-plus"></i> Nueva factura
</a>
{% endblock %}

{% block content %}

{% if mostrar_onboarding %}
<div class="mb-4" style="background:linear-gradient(135deg,#0f2744,#1a3a6e);border-radius:16px;padding:1.75rem;color:#fff">
  <div class="d-flex align-items-center gap-2 mb-3">
    <i class="bi bi-rocket-takeoff" style="font-size:1.3rem;color:#60a5fa"></i>
    <span class="fw-bold" style="font-size:1rem">Primeros pasos — empieza aquí</span>
    <span class="badge ms-auto" style="background:rgba(255,255,255,.15);color:#fff;font-size:.72rem">{{ [1 if true else 0, 1 if n_clientes > 0 else 0, 1 if n_facturas > 0 else 0] | sum }}/3 completados</span>
  </div>
  <div class="row g-2">

    <div class="col-md-4">
      <div style="background:rgba(34,197,94,.15);border:1px solid rgba(34,197,94,.3);border-radius:10px;padding:1rem;height:100%">
        <div class="d-flex align-items-center gap-2 mb-1">
          <span style="width:22px;height:22px;background:#22c55e;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <i class="bi bi-check" style="font-size:.8rem;color:#fff"></i>
          </span>
          <span class="fw-semibold" style="font-size:.88rem">Empresa configurada</span>
        </div>
        <div style="font-size:.78rem;opacity:.75;padding-left:30px">Tu nombre y NIF están listos.</div>
      </div>
    </div>

    <div class="col-md-4">
      <a href="{{ url_for('clientes.nuevo') }}" style="text-decoration:none">
        <div style="background:rgba(255,255,255,{{ '.12' if n_clientes > 0 else '.06' }});border:1px solid rgba(255,255,255,{{ '.25' if n_clientes > 0 else '.1' }});border-radius:10px;padding:1rem;height:100%;transition:.15s" onmouseover="this.style.background='rgba(255,255,255,.15)'" onmouseout="this.style.background='rgba(255,255,255,{{ '.12' if n_clientes > 0 else '.06' }})'">
          <div class="d-flex align-items-center gap-2 mb-1">
            {% if n_clientes > 0 %}
            <span style="width:22px;height:22px;background:#22c55e;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0">
              <i class="bi bi-check" style="font-size:.8rem;color:#fff"></i>
            </span>
            {% else %}
            <span style="width:22px;height:22px;background:rgba(255,255,255,.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:700;flex-shrink:0;color:#fff">2</span>
            {% endif %}
            <span class="fw-semibold" style="font-size:.88rem;color:#fff">Añade un cliente</span>
            <i class="bi bi-arrow-right ms-auto" style="font-size:.8rem;opacity:.6;color:#fff"></i>
          </div>
          <div style="font-size:.78rem;opacity:.7;padding-left:30px;color:#fff">Necesario para crear facturas.</div>
        </div>
      </a>
    </div>

    <div class="col-md-4">
      <a href="{{ url_for('facturas.nueva_emitida') }}" style="text-decoration:none">
        <div style="background:rgba(255,255,255,{{ '.12' if n_facturas > 0 else '.06' }});border:1px solid rgba(255,255,255,{{ '.25' if n_facturas > 0 else '.1' }});border-radius:10px;padding:1rem;height:100%;transition:.15s" onmouseover="this.style.background='rgba(255,255,255,.15)'" onmouseout="this.style.background='rgba(255,255,255,{{ '.12' if n_facturas > 0 else '.06' }})'">
          <div class="d-flex align-items-center gap-2 mb-1">
            {% if n_facturas > 0 %}
            <span style="width:22px;height:22px;background:#22c55e;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0">
              <i class="bi bi-check" style="font-size:.8rem;color:#fff"></i>
            </span>
            {% else %}
            <span style="width:22px;height:22px;background:rgba(255,255,255,.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:700;flex-shrink:0;color:#fff">3</span>
            {% endif %}
            <span class="fw-semibold" style="font-size:.88rem;color:#fff">Crea tu primera factura</span>
            <i class="bi bi-arrow-right ms-auto" style="font-size:.8rem;opacity:.6;color:#fff"></i>
          </div>
          <div style="font-size:.78rem;opacity:.7;padding-left:30px;color:#fff">Empieza a facturar ahora.</div>
        </div>
      </a>
    </div>

  </div>
</div>
{% endif %}

{% if facturas_vencidas %}
<div class="alert alert-danger d-flex align-items-start gap-3 mb-4" role="alert">
  <i class="bi bi-exclamation-triangle-fill fs-4 flex-shrink-0 mt-1"></i>
  <div class="flex-grow-1">
    <div class="fw-bold mb-1">
      {{ facturas_vencidas|length }} factura(s) vencida(s) sin cobrar —
      Total: {{ "%.2f"|format(facturas_vencidas | sum(attribute='total')) }} €
    </div>
    <div class="d-flex flex-wrap gap-2">
      {% for f in facturas_vencidas[:5] %}
      <a href="{{ url_for('facturas.detalle_emitida', id=f.id) }}"
         class="btn btn-sm btn-outline-danger">
        {{ f.numero }} · {{ f.cliente_nombre or 'Sin cliente' }} · {{ "%.2f"|format(f.total) }} € · vencida {{ f.fecha_vencimiento }}
      </a>
      {% endfor %}
      {% if facturas_vencidas|length > 5 %}
      <a href="{{ url_for('facturas.emitidas') }}?estado=pendiente" class="btn btn-sm btn-danger">
        +{{ facturas_vencidas|length - 5 }} más →
      </a>
      {% endif %}
    </div>
  </div>
</div>
{% endif %}

<!-- KPI Cards -->
<div class="row row-cols-2 row-cols-xl-5 g-3 mb-4">
  <div class="col">
    <div class="stat-card h-100" style="background:linear-gradient(135deg,{% if margen_mes >= 0 %}#059669,#047857{% else %}#dc2626,#b91c1c{% endif %})">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold" style="opacity:.85">Margen este mes</div>
          <div class="fw-bold fs-4">{{ "%.2f"|format(margen_mes) }} €</div>
          <div class="small" style="opacity:.75">Ingresos − Gastos</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:44px;height:44px;flex-shrink:0">
          <i class="bi bi-arrow-left-right fs-5 text-white"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col">
    <div class="stat-card h-100" style="background:linear-gradient(135deg,{% if balance >= 0 %}#7c3aed,#6d28d9{% else %}#dc2626,#b91c1c{% endif %})">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold" style="opacity:.85">Balance total</div>
          <div class="fw-bold fs-4">{{ "%.2f"|format(balance) }} €</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:44px;height:44px;flex-shrink:0">
          <i class="bi bi-wallet2 fs-5 text-white"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col">
    <div class="stat-card h-100" style="background:linear-gradient(135deg,#10b981,#059669)">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold" style="opacity:.85">Ingresos este mes</div>
          <div class="fw-bold fs-4">{{ "%.2f"|format(ingresos_mes) }} €</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:44px;height:44px;flex-shrink:0">
          <i class="bi bi-graph-up-arrow fs-5 text-white"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col">
    <div class="stat-card h-100" style="background:linear-gradient(135deg,#ef4444,#dc2626)">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold" style="opacity:.85">Gastos este mes</div>
          <div class="fw-bold fs-4">{{ "%.2f"|format(gastos_mes) }} €</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:44px;height:44px;flex-shrink:0">
          <i class="bi bi-graph-down-arrow fs-5 text-white"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col">
    <div class="stat-card h-100" style="background:linear-gradient(135deg,#f59e0b,#d97706)">
      <div class="d-flex align-items-start justify-content-between">
        <div>
          <div class="small mb-1 fw-semibold" style="opacity:.85">Pendientes de cobro</div>
          <div class="fw-bold fs-4">{{ "%.2f"|format(fp_emitidas[1]) }} €</div>
          <div class="small" style="opacity:.75">{{ fp_emitidas[0] }} factura(s)</div>
        </div>
        <div class="rounded-circle d-flex align-items-center justify-content-center bg-white bg-opacity-25" style="width:44px;height:44px;flex-shrink:0">
          <i class="bi bi-hourglass-split fs-5 text-white"></i>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row g-3 mb-4">
  <!-- Gráfica ingresos vs gastos -->
  <div class="col-lg-8">
    <div class="card h-100">
      <div class="card-header d-flex align-items-center justify-content-between py-3">
        <span><i class="bi bi-bar-chart me-2"></i>Ingresos vs Gastos — últimos 6 meses</span>
      </div>
      <div class="card-body">
        <canvas id="chartMensual" height="110"></canvas>
      </div>
    </div>
  </div>

  <!-- Gastos por categoría -->
  <div class="col-lg-4">
    <div class="card h-100">
      <div class="card-header py-3">
        <span><i class="bi bi-pie-chart me-2"></i>Gastos por categoría</span>
      </div>
      <div class="card-body">
        {% if gastos_categoria %}
        <canvas id="chartCategoria" height="160"></canvas>
        {% else %}
        <div class="text-center text-muted py-4">Sin datos aún</div>
        {% endif %}
      </div>
    </div>
  </div>
</div>

<div class="row g-3">
  <!-- Últimas transacciones -->
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header d-flex align-items-center justify-content-between py-3">
        <span><i class="bi bi-clock-history me-2"></i>Últimas transacciones</span>
        <a href="{{ url_for('transacciones.lista') }}" class="btn btn-sm btn-outline-secondary">Ver todas</a>
      </div>
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead>
            <tr>
              <th>Fecha</th>
              <th>Descripción</th>
              <th>Categoría</th>
              <th class="text-end">Importe</th>
            </tr>
          </thead>
          <tbody>
            {% for t in ultimas %}
            <tr>
              <td class="text-muted small">{{ t.fecha }}</td>
              <td class="small">{{ t.descripcion }}</td>
              <td>
                {% if t.categoria_nombre %}
                <span class="badge rounded-pill" style="background:{{ t.categoria_color }}20;color:{{ t.categoria_color }};font-size:.72rem">
                  {{ t.categoria_nombre }}
                </span>
                {% endif %}
              </td>
              <td class="text-end fw-semibold {% if t.tipo == 'ingreso' %}text-success{% else %}text-danger{% endif %}">
                {% if t.tipo == 'ingreso' %}+{% else %}-{% endif %}{{ "%.2f"|format(t.importe) }} €
              </td>
            </tr>
            {% else %}
            <tr><td colspan="4" class="text-center text-muted py-3">Sin transacciones registradas</td></tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Próximas a vencer -->
  <div class="col-lg-5">
    <div class="card">
      <div class="card-header d-flex align-items-center justify-content-between py-3">
        <span><i class="bi bi-calendar-exclamation me-2"></i>Próximas a vencer</span>
        <a href="{{ url_for('facturas.emitidas') }}?estado=pendiente" class="btn btn-sm btn-outline-secondary">Ver todas</a>
      </div>
      <div class="list-group list-group-flush">
        {% for f in proximas_vencer %}
        <a href="{{ url_for('facturas.detalle_emitida', id=f.id) }}" class="list-group-item list-group-item-action py-3">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="fw-semibold small">{{ f.numero }}</div>
              <div class="text-muted" style="font-size:.78rem">{{ f.cliente_nombre or 'Sin cliente' }}</div>
            </div>
            <div class="text-end">
              <div class="fw-bold text-danger small">{{ "%.2f"|format(f.total) }} €</div>
              <div class="text-muted" style="font-size:.72rem">vence {{ f.fecha_vencimiento }}</div>
            </div>
          </div>
        </a>
        {% else %}
        <div class="text-center text-muted py-4 small">Sin facturas pendientes</div>
        {% endfor %}
      </div>
    </div>

    <!-- Facturas a pagar -->
    <div class="card mt-3">
      <div class="card-body py-3">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <div class="text-muted small">Facturas a pagar (proveedores)</div>
            <div class="fw-bold text-danger">{{ "%.2f"|format(fp_recibidas[1]) }} €</div>
          </div>
          <a href="{{ url_for('facturas.recibidas') }}?estado=pendiente" class="btn btn-sm btn-outline-danger">
            {{ fp_recibidas[0] }} factura(s)
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

{% if top_productos %}
<div class="row g-3 mt-1">
  <div class="col-12">
    <div class="card">
      <div class="card-header d-flex align-items-center justify-content-between py-3">
        <span><i class="bi bi-trophy me-2"></i>Top productos facturados este mes</span>
        <a href="{{ url_for('inventario.index') }}" class="btn btn-sm btn-outline-secondary">Ver inventario</a>
      </div>
      <div class="table-responsive">
        <table class="table table-hover mb-0" style="font-size:.875rem">
          <thead>
            <tr>
              <th style="width:50%">Producto</th>
              <th class="text-center">Unidades</th>
              <th class="text-end">Importe facturado</th>
            </tr>
          </thead>
          <tbody>
            {% for p in top_productos %}
            <tr>
              <td class="fw-semibold">{{ p.nombre }}</td>
              <td class="text-center text-muted">{{ "%.0f"|format(p.total_uds) }}</td>
              <td class="text-end fw-semibold text-success">{{ "%.2f"|format(p.total_importe) }} €</td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
{% endif %}

{% endblock %}

{% block extra_scripts %}
<script>
const meses = {{ meses | tojson }};
const ingresos = {{ datos_ingresos | tojson }};
const gastos = {{ datos_gastos | tojson }};

new Chart(document.getElementById('chartMensual'), {
  type: 'bar',
  data: {
    labels: meses,
    datasets: [
      { label: 'Ingresos', data: ingresos, backgroundColor: 'rgba(40,167,69,.75)', borderRadius: 6 },
      { label: 'Gastos',   data: gastos,   backgroundColor: 'rgba(220,53,69,.75)', borderRadius: 6 },
    ]
  },
  options: {
    plugins: { legend: { position: 'top' } },
    scales: { y: { beginAtZero: true, ticks: { callback: v => v + ' €' } } },
    responsive: true,
  }
});

{% if gastos_categoria %}
const catLabels = {{ gastos_categoria | map(attribute='nombre') | list | tojson }};
const catData   = {{ gastos_categoria | map(attribute='total') | list | tojson }};
const catColors = {{ gastos_categoria | map(attribute='color') | list | tojson }};
new Chart(document.getElementById('chartCategoria'), {
  type: 'doughnut',
  data: { labels: catLabels, datasets: [{ data: catData, backgroundColor: catColors, borderWidth: 2 }] },
  options: {
    plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } },
    cutout: '65%',
  }
});
{% endif %}
</script>
{% endblock %}
