/* ============================================================
   views/catalog.js — Catálogo de productos
   ============================================================ */

function renderCatalog(el) {
  apiGet('/catalog/productos', function(data) {
    var linea       = data.linea       || [];
    var insc        = data.inscripciones || [];
    var promos      = data.promociones || [];

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

      '<div class="tabs">' +
        '<div class="tab-btn active" data-tab="linea">Línea (' + linea.length + ')</div>' +
        '<div class="tab-btn" data-tab="insc">Inscripciones (' + insc.length + ')</div>' +
        (promos.length ? '<div class="tab-btn" data-tab="promos">Promociones (' + promos.length + ')</div>' : '') +
      '</div>' +

      '<div id="catContent"></div>';

    // Tab switching
    var tabs = el.querySelectorAll('.tab-btn');
    for (var i = 0; i < tabs.length; i++) {
      (function(tab) {
        tab.addEventListener('click', function() {
          for (var j = 0; j < tabs.length; j++) tabs[j].classList.remove('active');
          tab.classList.add('active');
          var which = tab.dataset.tab;
          var items = which === 'linea' ? linea : which === 'insc' ? insc : promos;
          document.getElementById('catContent').innerHTML = renderProductGrid(items, which === 'promos');
        });
      })(tabs[i]);
    }

    // Render initial tab
    document.getElementById('catContent').innerHTML = renderProductGrid(linea, false);

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

function renderProductGrid(items, isPromo) {
  if (!items || items.length === 0) {
    return '<div class="empty-state"><div class="empty-icon">🛍️</div><h3>Sin productos</h3></div>';
  }
  var html = '<div class="products-grid">';
  for (var i = 0; i < items.length; i++) {
    var p = items[i];
    var idKey = isPromo ? p.idpromod : p.id_prod;
    html += '<div class="product-card">' +
      '<div class="product-img-placeholder"><span>' + (isPromo ? '🎁' : '📦') + '</span></div>' +
      '<div class="product-info">' +
        '<div class="product-name">' + escHtml(p.nombre || p.nombreProd) + '</div>' +
        (p.presentacion ? '<div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">' + escHtml(p.presentacion) + '</div>' : '') +
        '<div class="product-price">' + formatMXN(p.precio) + '</div>' +
        '<div class="product-pts">🏆 ' + formatPts(p.puntos) + ' pts</div>' +
      '</div>' +
    '</div>';
  }
  html += '</div>';
  return html;
}
