/* ============================================================
   views/dashboard.js
   ============================================================ */

function renderDashboard(el) {
  apiGet('/dashboard/summary', function(data) {
    var u = getUser();
    var nombre = ((u.nombre || '') + ' ' + (u.appat || '')).trim() || 'Distribuidor';
    var puntos  = parseFloat(data.puntos_mes)           || 0;
    var ganan   = parseFloat(data.ganancias_pendientes) || 0;
    var calMes  = parseInt(data.directos_calificados)   || 0;
    var redDir  = parseInt(data.directos_red)           || 0;
    var ultimas = data.ultimas_transacciones            || [];
    var isVip   = u.isVip;
    var vipBadge = isVip === true || isVip === 1
      ? '<span class="badge badge-success" style="margin-left:8px">✓ Verificado</span>'
      : (isVip === 2 ? '<span class="badge badge-warning" style="margin-left:8px">⏳ En revisión</span>'
                     : '<span class="badge badge-muted" style="margin-left:8px">Sin verificar</span>');

    // Calificación del mes
    var calColor = puntos >= 1500 ? 'success' : puntos >= 624 ? 'teal' : 'warning';
    var calTxt   = puntos >= 1500 ? '⭐ Calificación Completa: recibe de todos los niveles según el plan de compensación'
                 : puntos >= 624  ? '✓ Calificación Parcial: recibe 10% de tu primer nivel'
                 : '⚠️ Sin calificar este mes';

    // Contenedor del ticker (se rellena cuando llegan los avisos)
    var tickerHtml = '<div id="dashTicker" style="display:none;align-items:center;gap:10px;background:var(--navy);border-radius:var(--radius);padding:10px 14px;margin-bottom:14px;cursor:pointer;overflow:hidden" onclick="dashTickerClick()">' +
      '<span style="font-size:15px;flex-shrink:0">📢</span>' +
      '<div style="flex:1;overflow:hidden;white-space:nowrap;position:relative">' +
        '<span id="dashTickerText" style="display:inline-block;color:#fff;font-size:13px;font-weight:500"></span>' +
      '</div>' +
      '<span style="color:rgba(255,255,255,.6);font-size:11px;flex-shrink:0">Ver ›</span>' +
    '</div>';

    el.innerHTML =
      tickerHtml +
      // Header
      '<div style="background:var(--navy);border-radius:var(--radius-lg);padding:24px;color:var(--white);margin-bottom:20px">' +
        '<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">' +
          '<div>' +
            '<div style="font-size:13px;opacity:.8;margin-bottom:4px">Bienvenido de vuelta</div>' +
            '<div style="font-size:22px;font-weight:800">' + escHtml(nombre) + vipBadge + '</div>' +
            '<div style="font-size:13px;opacity:.8;margin-top:4px">Ref: ' + escHtml(u.referencia || '—') + ' · ' + escHtml(u.centros_idcd ? 'CD ' + u.centros_idcd : '') + '</div>' +
          '</div>' +
          '<div style="text-align:right">' +
            '<div style="font-size:11px;opacity:.75;text-transform:uppercase;letter-spacing:.5px">Puntos del mes</div>' +
            '<div style="font-size:36px;font-weight:900;line-height:1.1">' + formatPts(puntos) + '</div>' +
            '<div style="font-size:11px;opacity:.8;margin-top:2px">' + calTxt + '</div>' +
          '</div>' +
        '</div>' +
        // Progress bar
        '<div style="margin-top:16px">' +
          '<div style="display:flex;justify-content:space-between;font-size:11px;opacity:.8;margin-bottom:6px">' +
            '<span>0</span><span>Parcial: 624</span><span>Completa: 1,500</span>' +
          '</div>' +
          '<div style="background:rgba(255,255,255,.2);border-radius:20px;height:8px;overflow:hidden">' +
            '<div style="background:var(--teal-light);height:100%;border-radius:20px;width:' + Math.min(100, puntos/15) + '%;transition:width .6s ease"></div>' +
          '</div>' +
        '</div>' +
      '</div>' +

      // Stats
      '<div class="stats-grid">' +
        statCard('💰', 'navy',    formatMXN(ganan), 'Ganancias pendientes') +
        statCard('👥', 'teal',    redDir,            'Directos en red') +
        statCard('✅', 'success', calMes,            'Directos calificados') +
        statCard('📊', 'warning', formatPts(puntos), 'Puntos del mes') +
      '</div>' +

      // Quick actions
      '<div class="card mb-20">' +
        '<div class="card-header"><span class="card-title">Acciones rápidas</span></div>' +
        '<div class="card-body" style="display:flex;flex-wrap:wrap;gap:10px">' +
          '<button class="btn btn-teal" onclick="goTo(\'newpurchase\')">🛒 Nueva Compra</button>' +
          '<button class="btn btn-primary" onclick="goTo(\'network\')">🌐 Ver Mi Red</button>' +
          '<button class="btn btn-outline" onclick="goTo(\'earnings\')">💰 Mis Ganancias</button>' +
          (isVip === 0 ? '<button class="btn btn-outline" onclick="goTo(\'kyc\')">🪪 Verificación</button>' : '') +
        '</div>' +
      '</div>' +

      // Recent transactions
      '<div class="card">' +
        '<div class="card-header">' +
          '<span class="card-title">Últimas Transacciones</span>' +
          '<button class="btn btn-ghost btn-sm" onclick="goTo(\'purchases\')">Ver todas →</button>' +
        '</div>' +
        renderTransTable(ultimas) +
      '</div>';

    // Cargar avisos DESPUÉS de que el DOM del dashboard ya existe
    apiGet('/avisos', function(avisos) {
      if (avisos && avisos.length) {
        dashRenderTicker(avisos);
      }
    }, function() { /* silencioso */ });

  }, function(err) {
    el.innerHTML = errorState('No se pudo cargar el dashboard', err);
  });
}

function statCard(icon, color, val, label) {
  return '<div class="stat-card">' +
    '<div class="stat-icon ' + color + '">' + icon + '</div>' +
    '<div class="stat-value">' + val + '</div>' +
    '<div class="stat-label">' + label + '</div>' +
  '</div>';
}

function renderTransTable(rows) {
  if (!rows || rows.length === 0) {
    return '<div class="empty-state"><div class="empty-icon">📋</div><h3>Sin transacciones recientes</h3></div>';
  }
  var html = '<div class="table-wrap"><table><thead><tr><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>' + formatDate(r.fechat) + '</td>' +
      '<td>' + tipoBadge(r.tipostr_idtipostr) + '</td>' +
      '<td class="money">' + formatMXN(r.total || r.cantidad) + '</td>' +
      '<td><strong>' + formatPts(r.puntos) + '</strong> pts</td>' +
    '</tr>';
  }
  html += '</tbody></table></div>';
  return html;
}

function errorState(title, detail) {
  return '<div class="empty-state"><div class="empty-icon">⚠️</div><h3>' + escHtml(title) + '</h3><p>' + escHtml(detail || '') + '</p></div>';
}

// ── Ticker de avisos ──────────────────────────────────────────────────────────
var _dashAvisos    = [];
var _dashTickerIdx = 0;
var _dashTickerAnim = null;

function dashRenderTicker(avisos) {
  _dashAvisos = avisos;
  _dashTickerIdx = 0;

  var wrap = document.getElementById('dashTicker');
  var txt  = document.getElementById('dashTickerText');
  if (!wrap || !txt) return;

  wrap.style.display = 'flex';
  dashTickerShow();
}

function dashTickerShow() {
  var txt = document.getElementById('dashTickerText');
  if (!txt || !_dashAvisos.length) return;

  var av = _dashAvisos[_dashTickerIdx];
  var fullText = '📢  ' + av.titulo + '   —   ' + av.mensaje;

  // Colocar el texto justo al borde derecho visible
  txt.style.transition = 'none';
  txt.style.transform  = 'translateX(0px)';
  txt.textContent = fullText;

  setTimeout(function() {
    var textW    = txt.scrollWidth;
    var speed    = 120; // px por segundo — más rápido y legible
    var duration = Math.max(4, textW / speed);

    txt.style.transition = 'transform ' + duration + 's linear';
    txt.style.transform  = 'translateX(-' + (textW + 20) + 'px)';

    if (_dashTickerAnim) clearTimeout(_dashTickerAnim);
    _dashTickerAnim = setTimeout(function() {
      _dashTickerIdx = (_dashTickerIdx + 1) % _dashAvisos.length;
      dashTickerShow();
    }, duration * 1000 + 500);
  }, 80);
}

function dashTickerClick() {
  if (!_dashAvisos.length) return;
  var av = _dashAvisos[_dashTickerIdx];

  // Modal con el aviso completo
  var existing = document.getElementById('dashAvisoModal');
  if (existing) existing.remove();

  var modal = document.createElement('div');
  modal.id = 'dashAvisoModal';
  modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px';
  modal.innerHTML =
    '<div style="background:#fff;border-radius:var(--radius-lg);max-width:480px;width:100%;box-shadow:var(--shadow-lg);overflow:hidden">' +
      '<div style="background:var(--navy);padding:16px 20px;display:flex;justify-content:space-between;align-items:center">' +
        '<div style="color:#fff;font-size:16px;font-weight:700">📢 ' + escHtml(av.titulo) + '</div>' +
        '<button onclick="document.getElementById(\'dashAvisoModal\').remove()" style="color:rgba(255,255,255,.7);font-size:22px;line-height:1;background:none;border:none;cursor:pointer">×</button>' +
      '</div>' +
      '<div style="padding:20px 24px">' +
        '<p style="font-size:14px;color:var(--text);line-height:1.7;white-space:pre-wrap">' + escHtml(av.mensaje) + '</p>' +
      '</div>' +
    '</div>';

  modal.addEventListener('click', function(e) {
    if (e.target === modal) modal.remove();
  });

  document.body.appendChild(modal);
}
