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

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>' +

      purchaseSummary(txs) +

      '<div class="card">' +
        '<div class="card-header">' +
          '<span class="card-title">Historial</span>' +
          '<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 id="purchasesTable">' +
          buildPurchasesTable(txs) +
        '</div>' +
      '</div>';

    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);
      wireTableClicks();
    };

    wireTableClicks();

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

function wireTableClicks() {
  var rows = document.querySelectorAll('tr[data-txid]');
  for (var i = 0; i < rows.length; i++) {
    (function(row) {
      row.style.cursor = 'pointer';
      row.addEventListener('click', function() {
        showPurchaseDetail(parseInt(row.dataset.txid));
      });
    })(rows[i]);
  }
}

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 = '<div class="table-wrap"><table><thead><tr>' +
    '<th>ID</th><th>Fecha</th><th>Tipo</th><th>Importe</th><th>Puntos</th><th></th>' +
    '</tr></thead><tbody>';
  for (var i = 0; i < rows.length; i++) {
    var r = rows[i];
    html += '<tr data-txid="' + r.idtransacciones + '" title="Ver detalle">' +
      '<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>' +
      '<td style="color:var(--text-muted);font-size:18px">›</td>' +
    '</tr>';
  }
  html += '</tbody></table></div>';
  return html;
}

/* ── Modal de detalle ──────────────────────────────────────── */
function showPurchaseDetail(idTx) {
  showModal('Detalle de compra',
    '<div class="loading-overlay" style="padding:32px"><div class="spinner-lg"></div></div>',
    ''
  );

  apiGet('/purchases/detail?id=' + idTx, function(data) {
    var tx   = data.transaccion  || {};
    var pago = data.pago         || null;
    var prod = data.pedido.length ? data.pedido : data.productos;
    var envio= data.envio        || null;
    var asig = data.asignaciones || [];
    var nsal = data.nsalida      || [];

    // ── Encabezado ───────────────────────────────────────────
    var body =
      '<div style="background:var(--navy);' +
           'border-radius:var(--radius);padding:18px 20px;color:#fff;margin-bottom:20px">' +
        '<div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:8px">' +
          '<div>' +
            '<div style="font-size:12px;opacity:.8">Nota #' + tx.idtransacciones + ' · ' + formatDate(tx.fechat) + '</div>' +
            '<div style="font-size:18px;font-weight:800;margin-top:2px">' + escHtml(tx.nombre_completo) + '</div>' +
            '<div style="font-size:12px;opacity:.8;margin-top:2px">Ref: ' + escHtml(tx.referencia || '—') + '</div>' +
          '</div>' +
          '<div style="text-align:right">' +
            tipoBadge(tx.tipostr_idtipostr) +
            '<div style="font-size:22px;font-weight:900;margin-top:6px">' + formatMXN(tx.monto) + '</div>' +
            '<div style="font-size:12px;opacity:.85">🏆 ' + formatPts(tx.puntos) + ' pts</div>' +
          '</div>' +
        '</div>' +
      '</div>';

    // ── Productos ─────────────────────────────────────────────
    if (prod && prod.length > 0) {
      body += sectionTitle('🛍️ Productos');
      body += '<div class="table-wrap" style="margin-bottom:16px"><table>' +
        '<thead><tr><th>Producto</th><th style="text-align:center">Cant.</th><th>Precio</th><th>Puntos</th></tr></thead><tbody>';
      var totalProd = 0;
      for (var i = 0; i < prod.length; i++) {
        var p = prod[i];
        var cant = parseInt(p.cant) || 1;
        totalProd += (parseFloat(p.precio) || 0) * cant;
        body += '<tr>' +
          '<td>' +
            (p.es_promo ? '<span class="badge badge-navy" style="margin-right:4px">Promo</span>' : '') +
            escHtml(p.nombre) +
          '</td>' +
          '<td style="text-align:center;font-weight:700">' + cant + '</td>' +
          '<td>' + formatMXN(p.precio) + '</td>' +
          '<td style="color:var(--teal-dark)">' + formatPts(p.puntos) + ' pts</td>' +
        '</tr>';
      }
      body += '</tbody></table></div>';
    }

    // ── Forma de pago ─────────────────────────────────────────
    if (pago) {
      body += sectionTitle('💳 Forma de pago');
      body += '<div style="background:var(--bg);border-radius:var(--radius-sm);padding:14px 16px;margin-bottom:16px">';
      var pagoItems = [
        { lbl: 'Efectivo',   val: pago.efectivo,  icon: '💵' },
        { lbl: 'Depósito',   val: pago.deposito,  icon: '🏦' },
        { lbl: 'Tarjeta',    val: pago.tarjeta,   icon: '💳' },
        { lbl: 'Regalías',   val: pago.regalias,  icon: '🏆' },
        { lbl: 'Voucher',    val: pago.voucher,   icon: '🎫' },
        { lbl: 'Abono',      val: pago.abono,     icon: '📩' },
        { lbl: 'Por pagar',  val: pago.porpagar,  icon: '⏳' },
      ];
      for (var pi = 0; pi < pagoItems.length; pi++) {
        var item = pagoItems[pi];
        if (parseFloat(item.val) > 0) {
          body += '<div style="display:flex;justify-content:space-between;padding:5px 0;' +
            (item.lbl === 'Por pagar' ? 'color:var(--danger);font-weight:700' : '') + '">' +
            '<span>' + item.icon + ' ' + item.lbl + '</span>' +
            '<span>' + formatMXN(item.val) + '</span>' +
          '</div>';
        }
      }
      if (tx.costoEnvio > 0) {
        body += '<div style="display:flex;justify-content:space-between;padding:5px 0">' +
          '<span>🚚 Envío</span><span>' + formatMXN(tx.costoEnvio) + '</span></div>';
      }
      body += '<div style="border-top:1px solid var(--border);margin-top:8px;padding-top:8px;' +
        'display:flex;justify-content:space-between;font-weight:800;color:var(--navy)">' +
        '<span>Total</span><span>' + formatMXN(tx.monto) + '</span></div>';
      body += '</div>';
    }

    // ── Envío a domicilio ─────────────────────────────────────
    if (envio) {
      body += sectionTitle('🚚 Envío a domicilio');
      var dir = [envio.calle, envio.noExt, envio.noInt, envio.entre1 ? 'entre ' + envio.entre1 : '',
                 envio.entre2, envio.colonia, envio.ciudad, envio.estado, envio.cp]
                .filter(Boolean).join(', ');
      body += '<div style="background:var(--bg);border-radius:var(--radius-sm);padding:12px 16px;' +
        'font-size:13px;margin-bottom:16px">' + escHtml(dir) + '</div>';
    }

    // ── Productos por asignar ─────────────────────────────────
    if (nsal && nsal.length > 0) {
      body += sectionTitle('📦 Productos por asignar');
      body += '<div class="table-wrap" style="margin-bottom:16px"><table>' +
        '<thead><tr><th>Producto</th><th style="text-align:center">Cantidad</th><th style="text-align:center">Asignados</th><th>Estado</th></tr></thead><tbody>';
      for (var ni = 0; ni < nsal.length; ni++) {
        var ns     = nsal[ni];
        var cant   = parseInt(ns.cant)    || 0;
        var asig2  = parseInt(ns.asignar) || 0;
        var completo = asig2 >= cant;
        var falta    = cant - asig2;
        body += '<tr>' +
          '<td>' + escHtml(ns.nombre) + '</td>' +
          '<td style="text-align:center;font-weight:700">' + cant + '</td>' +
          '<td style="text-align:center">' + asig2 + '</td>' +
          '<td>' + (completo
            ? '<span class="badge badge-success">✓ Completo</span>'
            : '<span class="badge badge-warning">' + falta + ' pendiente' + (falta !== 1 ? 's' : '') + '</span>') + '</td>' +
        '</tr>';
      }
      body += '</tbody></table></div>';
    }

    // ── Asignaciones realizadas ───────────────────────────────
    if (asig && asig.length > 0) {
      body += sectionTitle('✅ Asignaciones realizadas');
      body += '<div class="table-wrap" style="margin-bottom:16px"><table>' +
        '<thead><tr><th>Transacción</th><th>Distribuidor</th><th>Fecha</th><th>Puntos</th></tr></thead><tbody>';
      for (var ai = 0; ai < asig.length; ai++) {
        var a = asig[ai];
        body += '<tr>' +
          '<td style="font-size:12px;color:var(--text-muted)">#' + a.idtransacciones + '</td>' +
          '<td style="font-size:13px">' + escHtml(a.nombre) +
            (a.referencia ? ' <span style="color:var(--text-muted);font-size:11px">(' + escHtml(a.referencia) + ')</span>' : '') +
          '</td>' +
          '<td>' + formatDate(a.fechat) + '</td>' +
          '<td style="color:var(--teal-dark);font-weight:700">' + formatPts(a.puntos) + ' pts</td>' +
        '</tr>';
      }
      body += '</tbody></table></div>';
    }

    document.getElementById('modalTitle').textContent = 'Nota #' + tx.idtransacciones;
    document.getElementById('modalBody').innerHTML = body;
    document.getElementById('modalFooter').innerHTML =
      '<button class="btn btn-outline" onclick="hideModal()">Cerrar</button>';

  }, function(err) {
    document.getElementById('modalBody').innerHTML =
      '<div class="empty-state"><div class="empty-icon">⚠️</div><h3>Error</h3><p>' + escHtml(err) + '</p></div>';
    document.getElementById('modalFooter').innerHTML =
      '<button class="btn btn-outline" onclick="hideModal()">Cerrar</button>';
  });
}

function sectionTitle(txt) {
  return '<div style="font-size:13px;font-weight:700;color:var(--navy);' +
    'margin-bottom:8px;display:flex;align-items:center;gap:6px">' + txt + '</div>';
}
