/* ============================================================
   views/earnings.js — Ganancias
   ============================================================ */

function renderEarnings(el) {
  apiGet('/earnings/list', function(data) {
    var isVip    = parseInt(data.isVip)   || 0;
    var depo     = data.depo              || 'PENDIENTE';
    var pending  = parseFloat(data.pendiente) || 0;
    var historial= data.historial         || [];

    el.innerHTML =
      '<div class="page-header">' +
        '<div class="section-title" style="margin:0">Mis Ganancias</div>' +
      '</div>' +

      // KYC alert
      (!isVip
        ? '<div style="background:#fff8e6;border:1px solid #f5c842;border-radius:var(--radius);padding:14px 16px;margin-bottom:16px;display:flex;align-items:center;gap:12px">' +
            '<span style="font-size:22px">⚠️</span>' +
            '<div><strong style="color:#8a6d00">Verificación pendiente</strong><br><span style="font-size:13px;color:#a07d00">Completa tu KYC para habilitar el cobro de ganancias.</span></div>' +
            '<button class="btn btn-outline btn-sm" onclick="goTo(\'kyc\')" style="margin-left:auto">Verificar →</button>' +
          '</div>'
        : ''
      ) +
      (isVip === 2
        ? '<div style="background:#e8f4fd;border:1px solid #90caf9;border-radius:var(--radius);padding:14px 16px;margin-bottom:16px">' +
            '⏳ <strong>KYC en revisión.</strong> Tu documentación está siendo verificada.' +
          '</div>'
        : ''
      ) +

      // Pending earnings hero
      '<div style="background:linear-gradient(135deg,var(--navy) 0%,var(--teal-dark) 100%);border-radius:var(--radius-lg);padding:28px;color:var(--white);margin-bottom:20px;text-align:center">' +
        '<div style="font-size:13px;opacity:.85;margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px">Ganancias pendientes de cobro</div>' +
        '<div style="font-size:44px;font-weight:900;margin-bottom:8px">' + formatMXN(pending) + '</div>' +
        '<div style="font-size:13px;opacity:.8">Método de cobro: <strong>' + escHtml(depo) + '</strong></div>' +
        (isVip === 1 && pending > 0
          ? '<button class="btn" onclick="earningsChangeMethod()" style="margin-top:14px;background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.4)">✏️ Cambiar método</button>'
          : ''
        ) +
      '</div>' +

      // Historial
      '<div class="card">' +
        '<div class="card-header"><span class="card-title">Historial (últimos 6 meses)</span></div>' +
        (isVip !== 1
          ? '<div class="empty-state" style="padding:32px"><div class="empty-icon">🔒</div><h3>Requiere verificación</h3><p>Completa tu KYC para ver el historial de ganancias.</p></div>'
          : buildEarningsTable(historial)
        ) +
      '</div>';

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

function buildEarningsTable(rows) {
  if (!rows || rows.length === 0) {
    return '<div class="empty-state"><div class="empty-icon">💰</div><h3>Sin historial</h3><p>Aún no tienes ganancias registradas.</p></div>';
  }
  var html = '<div class="table-wrap"><table><thead><tr><th>Período</th><th>Real</th><th>A pagar</th><th>Estado</th></tr></thead><tbody>';
  for (var i = 0; i < rows.length; i++) {
    var r = rows[i];
    var status = parseInt(r.status);
    html += '<tr>' +
      '<td>' + formatDate(r.fechap) + '</td>' +
      '<td class="money">' + formatMXN(r._real) + '</td>' +
      '<td class="money green">' + formatMXN(r.apagar) + '</td>' +
      '<td>' + (status === 0
        ? '<span class="badge badge-warning">Pendiente</span>'
        : '<span class="badge badge-success">Pagado</span>') + '</td>' +
    '</tr>';
  }
  html += '</tbody></table></div>';
  return html;
}

function earningsChangeMethod() {
  showModal('Cambiar método de cobro',
    '<div class="form-group">' +
      '<label class="form-label">Método de cobro</label>' +
      '<select class="form-control" id="depoSelect">' +
        '<option value="DEPOSITO">Depósito bancario</option>' +
        '<option value="VOUCHER">Voucher</option>' +
      '</select>' +
    '</div>',
    '<button class="btn btn-outline" onclick="hideModal()">Cancelar</button>' +
    '<button class="btn btn-primary" onclick="saveDepoMethod()">Guardar</button>'
  );
}

function saveDepoMethod() {
  var val = document.getElementById('depoSelect').value;
  apiPost('/profile/update', { depo: val }, function() {
    hideModal();
    toast('Método de cobro actualizado.', 'success');
    goTo('earnings');
  });
}
