/* ============================================================
   views/newpurchase.js — Nueva Compra
   ============================================================ */

var NP = {
  cart: [],       // [{prod, qty, precio, puntos, nombre}]
  pagos: [],      // [{banco_idbanco, referencia, monto}]
  productos: [],
  inscripciones: [],
  promociones: [],
  bancos: [],
  tab: 'linea',
};

function renderNewPurchase(el) {
  NP.cart  = [];
  NP.pagos = [];

  apiGet('/catalog/productos', function(data) {
    NP.productos     = data.linea        || [];
    NP.inscripciones = data.inscripciones || [];
    NP.promociones   = data.promociones  || [];
    NP.bancos        = data.bancos        || [];
    buildNewPurchaseUI(el);
  }, function(err) {
    el.innerHTML = errorState('No se pudo cargar el catálogo', err);
  });
}

function buildNewPurchaseUI(el) {
  el.innerHTML =
    '<div class="page-header">' +
      '<div class="section-title" style="margin:0">Nueva Compra</div>' +
    '</div>' +

    // Step 1 - Products
    '<div class="card mb-16">' +
      '<div class="card-header"><span class="card-title">1. Selecciona productos</span></div>' +
      '<div class="card-body" style="padding-bottom:8px">' +
        '<div class="tabs" style="margin-bottom:12px">' +
          '<div class="tab-btn active" data-nptab="linea">Línea</div>' +
          '<div class="tab-btn" data-nptab="insc">Inscripciones</div>' +
          (NP.promociones.length ? '<div class="tab-btn" data-nptab="promos">Promos</div>' : '') +
        '</div>' +
        '<div id="npProdGrid"></div>' +
      '</div>' +
    '</div>' +

    // Step 2 - Cart
    '<div class="card mb-16">' +
      '<div class="card-header"><span class="card-title">2. Carrito</span></div>' +
      '<div class="card-body" id="npCart"><div class="text-muted text-center" style="padding:20px">Selecciona productos para agregarlos al carrito.</div></div>' +
      '<div class="card-footer" id="npCartFooter" style="display:none">' +
        '<div style="display:flex;justify-content:space-between;align-items:center">' +
          '<div>' +
            '<div style="font-size:13px;color:var(--text-muted)">Total</div>' +
            '<div style="font-size:22px;font-weight:800;color:var(--navy)" id="npTotal">$0.00</div>' +
            '<div style="font-size:12px;color:var(--teal-dark)" id="npPuntos">0 puntos</div>' +
          '</div>' +
        '</div>' +
      '</div>' +
    '</div>' +

    // Step 3 - Payments
    '<div class="card mb-16">' +
      '<div class="card-header"><span class="card-title">3. Pagos</span>' +
        '<button class="btn btn-outline btn-sm" id="npAddPago">+ Agregar pago</button>' +
      '</div>' +
      '<div class="card-body">' +
        '<div id="npPagos"><div class="text-muted text-sm">Sin pagos registrados.</div></div>' +
        '<div style="margin-top:12px">' +
          '<div style="font-size:13px;color:var(--text-muted)">Tipo de orden:</div>' +
          '<div style="display:flex;gap:10px;margin-top:6px">' +
            '<label style="display:flex;align-items:center;gap:6px;font-size:14px;cursor:pointer">' +
              '<input type="radio" name="npTipo" value="10" checked> Venta directa' +
            '</label>' +
            '<label style="display:flex;align-items:center;gap:6px;font-size:14px;cursor:pointer">' +
              '<input type="radio" name="npTipo" value="11"> Por asignar' +
            '</label>' +
          '</div>' +
        '</div>' +
      '</div>' +
    '</div>' +

    // Step 4 - Submit
    '<div class="card">' +
      '<div class="card-body" style="display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap">' +
        '<button class="btn btn-outline" onclick="goTo(\'catalog\')">Cancelar</button>' +
        '<button class="btn btn-teal btn-lg" id="npSubmitBtn">Registrar Compra 🛒</button>' +
      '</div>' +
    '</div>';

  // Wire product tabs
  var npTabs = el.querySelectorAll('[data-nptab]');
  for (var i = 0; i < npTabs.length; i++) {
    (function(tab) {
      tab.addEventListener('click', function() {
        for (var j = 0; j < npTabs.length; j++) npTabs[j].classList.remove('active');
        tab.classList.add('active');
        NP.tab = tab.dataset.nptab;
        renderNpGrid();
      });
    })(npTabs[i]);
  }

  document.getElementById('npAddPago').onclick = npAddPago;
  document.getElementById('npSubmitBtn').onclick = npSubmit;

  renderNpGrid();
}

function npProducts() {
  return NP.tab === 'linea' ? NP.productos
       : NP.tab === 'insc'  ? NP.inscripciones
                            : NP.promociones;
}

function renderNpGrid() {
  var gridEl = document.getElementById('npProdGrid');
  if (!gridEl) return;
  var prods = npProducts();
  if (!prods.length) { gridEl.innerHTML = '<p class="text-muted">Sin productos disponibles.</p>'; return; }
  var html = '<div class="products-grid">';
  for (var i = 0; i < prods.length; i++) {
    var p = prods[i];
    var isPromo = NP.tab === 'promos';
    var id = isPromo ? ('promo_' + p.idpromod) : ('prod_' + p.id_prod);
    html += '<div class="product-card" data-npid="' + id + '">' +
      '<div class="product-img-placeholder"><span>' + (isPromo ? '🎁' : (NP.tab === 'insc' ? '🎟️' : '📦')) + '</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>';
  gridEl.innerHTML = html;

  // Wire product clicks
  var cards = gridEl.querySelectorAll('.product-card');
  for (var k = 0; k < cards.length; k++) {
    (function(card) {
      card.addEventListener('click', function() {
        var npid   = card.dataset.npid;
        var isPromo = npid.indexOf('promo_') === 0;
        var rawId  = parseInt(npid.replace('prod_','').replace('promo_',''));
        var source = isPromo ? NP.promociones : (NP.tab === 'insc' ? NP.inscripciones : NP.productos);
        var prod   = null;
        for (var m = 0; m < source.length; m++) {
          var cmp = isPromo ? source[m].idpromod : source[m].id_prod;
          if (cmp === rawId) { prod = source[m]; break; }
        }
        if (!prod) return;
        npAddToCart(prod, isPromo);
      });
    })(cards[k]);
  }
}

function npAddToCart(prod, isPromo) {
  var id  = isPromo ? ('promo_' + prod.idpromod) : ('prod_' + prod.id_prod);
  var existing = null;
  for (var i = 0; i < NP.cart.length; i++) {
    if (NP.cart[i].id === id) { existing = NP.cart[i]; break; }
  }
  if (existing) {
    existing.qty++;
  } else {
    NP.cart.push({
      id:      id,
      rawId:   isPromo ? prod.idpromod : prod.id_prod,
      isPromo: isPromo,
      nombre:  prod.nombre || prod.nombreProd,
      precio:  parseFloat(prod.precio),
      puntos:  parseFloat(prod.puntos),
      qty:     1,
    });
  }
  renderNpCart();
  toast(escHtml(prod.nombre || prod.nombreProd) + ' agregado al carrito', 'success', 'Producto agregado');
}

function renderNpCart() {
  var cartEl   = document.getElementById('npCart');
  var footerEl = document.getElementById('npCartFooter');
  var totalEl  = document.getElementById('npTotal');
  var ptsEl    = document.getElementById('npPuntos');
  if (!cartEl) return;

  if (NP.cart.length === 0) {
    cartEl.innerHTML = '<div class="text-muted text-center" style="padding:20px">Carrito vacío.</div>';
    if (footerEl) footerEl.style.display = 'none';
    return;
  }

  var total = 0, totalPts = 0;
  var html = '';
  for (var i = 0; i < NP.cart.length; i++) {
    var item = NP.cart[i];
    total    += item.precio * item.qty;
    totalPts += item.puntos * item.qty;
    html += '<div class="cart-item">' +
      '<div class="cart-item-name">' + escHtml(item.nombre) + '</div>' +
      '<div class="cart-qty">' +
        '<button class="qty-btn" data-dec="' + i + '">−</button>' +
        '<span class="qty-val">' + item.qty + '</span>' +
        '<button class="qty-btn" data-inc="' + i + '">+</button>' +
      '</div>' +
      '<div class="cart-total">' + formatMXN(item.precio * item.qty) + '</div>' +
      '<button class="btn btn-ghost btn-sm" data-rm="' + i + '" style="color:var(--danger)">✕</button>' +
    '</div>';
  }
  cartEl.innerHTML = html;
  if (footerEl) { footerEl.style.display = 'block'; }
  if (totalEl) totalEl.textContent = formatMXN(total);
  if (ptsEl)   ptsEl.textContent   = formatPts(totalPts) + ' puntos';

  // Wire qty buttons
  cartEl.querySelectorAll('[data-dec]').forEach(function(btn) {
    btn.onclick = function() {
      var idx = parseInt(btn.dataset.dec);
      NP.cart[idx].qty--;
      if (NP.cart[idx].qty <= 0) NP.cart.splice(idx, 1);
      renderNpCart();
    };
  });
  cartEl.querySelectorAll('[data-inc]').forEach(function(btn) {
    btn.onclick = function() { NP.cart[parseInt(btn.dataset.inc)].qty++; renderNpCart(); };
  });
  cartEl.querySelectorAll('[data-rm]').forEach(function(btn) {
    btn.onclick = function() { NP.cart.splice(parseInt(btn.dataset.rm), 1); renderNpCart(); };
  });
}

function npAddPago() {
  var bancoOpts = '<option value="">— Selecciona banco —</option>';
  for (var i = 0; i < NP.bancos.length; i++) {
    bancoOpts += '<option value="' + NP.bancos[i].idbanco + '">' + escHtml(NP.bancos[i].nombre) + '</option>';
  }
  var idx = NP.pagos.length;
  NP.pagos.push({ banco_idbanco: null, referencia: '', monto: '' });

  var pagosEl = document.getElementById('npPagos');
  var div = document.createElement('div');
  div.className = 'payment-row';
  div.dataset.pi = idx;
  div.innerHTML =
    '<select class="form-control" data-field="banco" style="max-width:160px">' + bancoOpts + '</select>' +
    '<input type="text" class="form-control" placeholder="Referencia / No. depósito" data-field="ref">' +
    '<input type="number" class="form-control" placeholder="Monto $" min="0" step="0.01" data-field="monto" style="max-width:110px">' +
    '<button class="btn btn-outline btn-sm" data-rmpi="' + idx + '">✕</button>';
  pagosEl.appendChild(div);

  div.querySelector('[data-field="banco"]').onchange  = function() { NP.pagos[idx].banco_idbanco = parseInt(this.value) || null; };
  div.querySelector('[data-field="ref"]').oninput     = function() { NP.pagos[idx].referencia = this.value; };
  div.querySelector('[data-field="monto"]').oninput   = function() { NP.pagos[idx].monto = parseFloat(this.value) || 0; };
  div.querySelector('[data-rmpi]').onclick = function() {
    NP.pagos.splice(idx, 1);
    div.parentNode.removeChild(div);
  };
}

function npSubmit() {
  if (NP.cart.length === 0) { toast('Agrega al menos un producto al carrito.', 'warning'); return; }

  var tipo = document.querySelector('input[name="npTipo"]:checked');
  var tipoVal = tipo ? parseInt(tipo.value) : 10;

  var items = NP.cart.map(function(c) {
    return {
      id_prod:  c.isPromo ? null : c.rawId,
      idpromod: c.isPromo ? c.rawId : null,
      cantidad: c.qty,
      precio:   c.precio,
      puntos:   c.puntos,
    };
  });

  var payload = {
    tipo_nota: tipoVal,
    items:     items,
    pagos:     NP.pagos,
  };

  var btn = document.getElementById('npSubmitBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Registrando...';

  apiPost('/purchases/new', payload, function(data) {
    btn.disabled = false;
    btn.textContent = 'Registrar Compra 🛒';
    toast('Compra registrada correctamente. ID: ' + (data.idtransacciones || '—'), 'success', '¡Compra exitosa!');
    NP.cart  = [];
    NP.pagos = [];
    setTimeout(function() { goTo('purchases'); }, 1800);
  }, function(err) {
    btn.disabled = false;
    btn.textContent = 'Registrar Compra 🛒';
    toast(err, 'error', 'Error al registrar');
  });
}
