/* ============================================================
   views/purchases.js — Historial de compras
   ============================================================ */

function renderPurchases(el) {
  apiGet('/purchases/list', function(data) {
    var txs = data.transacciones || data || [];

    el.innerHTML =
      '<div class="page-header">' +
        '<div class="section-title" style="margin:0">Mis Compras</div>' +
        '<button class="btn btn-teal" onclick="goTo(\'newpurchase\')">+ Nueva Compra</button>' +
      '</div>' +

      // Summary cards
      purchaseSummary(txs) +

      // Filter
      '<div class="card">' +
        '<div class="card-header">' +
          '<span class="card-title">Historial</span>' +
          '<div style="display:flex;gap:8px">' +
            '<select id="pFilter" class="form-control" style="width:auto;font-size:13px">' +
              '<option value="">Todos los tipos</option>' +
              '<option value="10">Ventas</option>' +
              '<option value="12">Asignaciones</option>' +
              '<option value="7,8">Pendientes</option>' +
            '</select>' +
          '</div>' +
        '</div>' +
        '<div class="table-wrap" id="purchasesTable">' +
          buildPurchasesTable(txs) +
        '</div>' +
      '</div>';

    // Filter
    document.getElementById('pFilter').onchange = function() {
      var val = this.value;
      var filtered = !val ? txs : txs.filter(function(r) {
        return val.split(',').indexOf(String(r.tipostr_idtipostr)) !== -1;
      });
      document.getElementById('purchasesTable').innerHTML = buildPurchasesTable(filtered);
    };

  }, function(err) {
    el.innerHTML = errorState('Error al cargar compras', err);
  });
}

function purchaseSummary(txs) {
  if (!txs || txs.length === 0) return '';
  var totalVentas = 0, totalPuntos = 0, pendientes = 0;
  for (var i = 0; i < txs.length; i++) {
    var t = txs[i];
    if (t.tipostr_idtipostr === 10 || t.tipostr_idtipostr === 12) {
      totalVentas += parseFloat(t.cantidad) || 0;
      totalPuntos += parseFloat(t.puntos)   || 0;
    }
    if (t.tipostr_idtipostr === 7 || t.tipostr_idtipostr === 8) pendientes++;
  }
  return '<div class="stats-grid mb-16">' +
    statCard('📋', 'navy',    txs.length,           'Total transacciones') +
    statCard('💵', 'success', formatMXN(totalVentas),'Monto total') +
    statCard('🏆', 'teal',    formatPts(totalPuntos),'Puntos acumulados') +
    statCard('⏳', 'warning', pendientes,             'Pendientes') +
  '</div>';
}

function buildPurchasesTable(rows) {
  if (!rows || rows.length === 0) {
    return '<div class="empty-state"><div class="empty-icon">📋</div><h3>Sin compras</h3><p>No hay transacciones en el período seleccionado.</p></div>';
  }
  var html = '<table><thead><tr><th>ID</th><th>Fecha</th><th>Tipo</th><th>Importe</th><th>Puntos</th></tr></thead><tbody>';
  for (var i = 0; i < rows.length; i++) {
    var r = rows[i];
    html += '<tr>' +
      '<td style="font-size:12px;color:var(--text-muted)">#' + r.idtransacciones + '</td>' +
      '<td>' + formatDate(r.fechat) + '</td>' +
      '<td>' + tipoBadge(r.tipostr_idtipostr) + '</td>' +
      '<td class="money">' + formatMXN(r.cantidad) + '</td>' +
      '<td><strong>' + formatPts(r.puntos) + '</strong> <span style="font-size:11px;color:var(--text-muted)">pts</span></td>' +
    '</tr>';
  }
  html += '</tbody></table>';
  return html;
}
