/* ============================================================
   views/vouchers.js — Vouchers
   ============================================================ */

function renderVouchers(el) {
  apiGet('/voucher/list', function(data) {
    var vouchers = data.vouchers || data || [];

    el.innerHTML =
      '<div class="page-header">' +
        '<div class="section-title" style="margin:0">Mis Vouchers</div>' +
        '<button class="btn btn-teal" onclick="applyVoucherModal()">+ Aplicar Voucher</button>' +
      '</div>' +

      // Apply voucher quick bar
      '<div class="card mb-16">' +
        '<div class="card-header"><span class="card-title">Verificar Voucher</span></div>' +
        '<div class="card-body">' +
          '<div style="display:flex;gap:8px;flex-wrap:wrap">' +
            '<input type="text" id="voucherInput" class="form-control" placeholder="Código de voucher..." style="flex:1;min-width:180px" autocapitalize="characters">' +
            '<button class="btn btn-primary" onclick="verifyVoucher()">Verificar</button>' +
          '</div>' +
          '<div id="voucherResult" style="margin-top:12px"></div>' +
        '</div>' +
      '</div>' +

      // List
      '<div class="section-title">Mis Vouchers</div>' +
      (vouchers.length === 0
        ? '<div class="empty-state" style="background:var(--white);border-radius:var(--radius);border:1px solid var(--border);padding:40px"><div class="empty-icon">🎫</div><h3>Sin vouchers</h3><p>No tienes vouchers registrados.</p></div>'
        : vouchersList(vouchers)
      );

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

function vouchersList(vouchers) {
  var html = '';
  for (var i = 0; i < vouchers.length; i++) {
    var v = vouchers[i];
    var usado = parseInt(v.status) === 1;
    html += '<div class="voucher-card" style="' + (usado ? 'opacity:.65' : '') + '">' +
      '<div class="voucher-status">' + (usado ? 'Usado' : 'Disponible') + '</div>' +
      '<div class="voucher-code">' + escHtml(v.codigo || v.token || '—') + '</div>' +
      '<div class="voucher-amount">' + formatMXN(v.monto || v.valor || 0) + '</div>' +
      '<div class="voucher-info">' +
        (v.fecha ? 'Emitido: ' + formatDate(v.fecha) : '') +
        (v.descripcion ? ' · ' + escHtml(v.descripcion) : '') +
      '</div>' +
    '</div>';
  }
  return html;
}

function verifyVoucher() {
  var code = document.getElementById('voucherInput').value.trim().toUpperCase();
  var resEl = document.getElementById('voucherResult');
  if (!code) { toast('Ingresa un código de voucher.', 'warning'); return; }
  resEl.innerHTML = '<span class="text-muted text-sm">Verificando...</span>';

  apiGet('/voucher/verify?codigo=' + encodeURIComponent(code), function(data) {
    resEl.innerHTML =
      '<div style="background:#f0faf5;border:1px solid #a8ddc0;border-radius:var(--radius-sm);padding:12px 16px">' +
        '<div style="font-weight:700;color:var(--success)">✓ Voucher válido</div>' +
        '<div style="font-size:13px;margin-top:4px">' +
          'Monto: <strong>' + formatMXN(data.monto || data.valor || 0) + '</strong>' +
          (data.descripcion ? ' · ' + escHtml(data.descripcion) : '') +
        '</div>' +
      '</div>';
  }, function(err) {
    resEl.innerHTML =
      '<div style="background:#fdf0ef;border:1px solid #f5c6c3;border-radius:var(--radius-sm);padding:12px 16px;color:var(--danger)">' +
        '✗ ' + escHtml(err) +
      '</div>';
  });
}

function applyVoucherModal() {
  showModal('Aplicar Voucher',
    '<div class="form-group">' +
      '<label class="form-label">Código de voucher</label>' +
      '<input type="text" id="applyVoucherCode" class="form-control" placeholder="RRB-XXXX-XXXX" autocapitalize="characters">' +
    '</div>' +
    '<div class="form-group">' +
      '<label class="form-label">Monto a aplicar ($)</label>' +
      '<input type="number" id="applyVoucherMonto" class="form-control" placeholder="0.00" min="0" step="0.01">' +
    '</div>',
    '<button class="btn btn-outline" onclick="hideModal()">Cancelar</button>' +
    '<button class="btn btn-teal" onclick="doApplyVoucher()">Aplicar</button>'
  );
}

function doApplyVoucher() {
  var code  = (document.getElementById('applyVoucherCode').value || '').trim().toUpperCase();
  var monto = parseFloat(document.getElementById('applyVoucherMonto').value) || 0;
  if (!code) { toast('Ingresa el código.', 'warning'); return; }

  apiPost('/voucher/apply', { codigo: code, monto: monto }, function() {
    hideModal();
    toast('Voucher aplicado correctamente.', 'success');
    goTo('vouchers');
  }, function(err) {
    toast(err, 'error');
  });
}
