/* ============================================================
   views/network.js — Mi Red (árbol MLM)
   ============================================================ */

var NET = {
  breadcrumb: [],   // [{id, nombre}]
  u: null,
};

function renderNetwork(el) {
  NET.u = getUser();
  var idinv = NET.u.idinv || NET.u.id_inver;
  NET.breadcrumb = [{ id: idinv, nombre: 'Mi Red' }];

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

    // Search bar
    '<div class="network-search mb-16">' +
      '<input type="text" id="netSearch" class="form-control" placeholder="Buscar por nombre o referencia..." autocomplete="off">' +
      '<button class="btn btn-teal" id="netSearchBtn">Buscar</button>' +
      '<button class="btn btn-outline" id="netClearBtn">Limpiar</button>' +
    '</div>' +

    // Breadcrumb
    '<div class="network-breadcrumb" id="netBreadcrumb"></div>' +

    // Stats bar
    '<div id="netStats" style="margin-bottom:16px"></div>' +

    // List
    '<div class="card"><div id="netList"></div></div>';

  // Wire search
  document.getElementById('netSearchBtn').onclick = function() {
    var q = document.getElementById('netSearch').value.trim();
    if (q) netSearch(q);
  };
  document.getElementById('netSearch').addEventListener('keydown', function(e) {
    if (e.key === 'Enter') document.getElementById('netSearchBtn').click();
  });
  document.getElementById('netClearBtn').onclick = function() {
    document.getElementById('netSearch').value = '';
    NET.breadcrumb = [{ id: idinv, nombre: 'Mi Red' }];
    netLoad(idinv);
  };

  netLoad(idinv);
}

function netLoad(padre) {
  var listEl  = document.getElementById('netList');
  var statsEl = document.getElementById('netStats');
  if (!listEl) return;
  listEl.innerHTML = '<div class="loading-overlay"><div class="spinner-lg"></div><span>Cargando red...</span></div>';
  netUpdateBreadcrumb();

  apiGet('/network/list?padre=' + padre, function(data) {
    var red   = data.red   || [];
    var total = data.total_red || 0;

    // Stats
    var calCount = 0;
    for (var i = 0; i < red.length; i++) {
      if (red[i].calificacion !== 'ninguna') calCount++;
    }
    statsEl.innerHTML =
      '<div style="display:flex;gap:12px;flex-wrap:wrap">' +
        '<div class="stat-card" style="flex:1 1 120px;padding:14px">' +
          '<div class="stat-value" style="font-size:22px">' + (data.modo === 'arbol' ? red.length : red.length) + '</div>' +
          '<div class="stat-label">' + (padre === (NET.u.idinv || NET.u.id_inver) ? 'Directos en red' : 'Hijos de este nodo') + '</div>' +
        '</div>' +
        '<div class="stat-card" style="flex:1 1 120px;padding:14px">' +
          '<div class="stat-value" style="font-size:22px">' + calCount + '</div>' +
          '<div class="stat-label">Calificados</div>' +
        '</div>' +
        '<div class="stat-card" style="flex:1 1 120px;padding:14px">' +
          '<div class="stat-value" style="font-size:22px">' + total + '</div>' +
          '<div class="stat-label">Total directos propios</div>' +
        '</div>' +
      '</div>';

    if (red.length === 0) {
      listEl.innerHTML = '<div class="empty-state"><div class="empty-icon">👥</div><h3>Sin distribuidores</h3><p>Este nodo no tiene distribuidores en su red.</p></div>';
      return;
    }

    var html = '';
    for (var j = 0; j < red.length; j++) {
      html += netDistCard(red[j]);
    }
    listEl.innerHTML = html;

    // Wire expand buttons
    var expandBtns = listEl.querySelectorAll('[data-expand]');
    for (var k = 0; k < expandBtns.length; k++) {
      (function(btn) {
        btn.addEventListener('click', function() {
          var id    = parseInt(btn.dataset.expand);
          var name  = btn.dataset.name;
          NET.breadcrumb.push({ id: id, nombre: name });
          netLoad(id);
        });
      })(expandBtns[k]);
    }

  }, function(err) {
    listEl.innerHTML = '<div class="empty-state"><div class="empty-icon">⚠️</div><h3>Error al cargar</h3><p>' + escHtml(err) + '</p></div>';
  });
}

function netSearch(query) {
  var listEl  = document.getElementById('netList');
  var statsEl = document.getElementById('netStats');
  if (!listEl) return;
  listEl.innerHTML = '<div class="loading-overlay"><div class="spinner-lg"></div><span>Buscando...</span></div>';
  statsEl.innerHTML = '';

  apiGet('/network/list?buscar=' + encodeURIComponent(query), function(data) {
    var red = data.red || [];
    if (red.length === 0) {
      listEl.innerHTML = '<div class="empty-state"><div class="empty-icon">🔍</div><h3>Sin resultados</h3><p>No se encontraron distribuidores con "' + escHtml(query) + '"</p></div>';
      return;
    }
    document.getElementById('netBreadcrumb').innerHTML = '<span class="breadcrumb-item">🔍 Resultados: ' + red.length + ' encontrados</span>';
    var html = '';
    for (var i = 0; i < red.length; i++) html += netDistCard(red[i]);
    listEl.innerHTML = html;

    // Wire expand buttons
    var expandBtns = listEl.querySelectorAll('[data-expand]');
    for (var k = 0; k < expandBtns.length; k++) {
      (function(btn) {
        btn.addEventListener('click', function() {
          var id   = parseInt(btn.dataset.expand);
          var name = btn.dataset.name;
          document.getElementById('netSearch').value = '';
          NET.breadcrumb = [{ id: NET.u.idinv || NET.u.id_inver, nombre: 'Mi Red' }, { id: id, nombre: name }];
          netLoad(id);
        });
      })(expandBtns[k]);
    }

  }, function(err) {
    listEl.innerHTML = '<div class="empty-state"><div class="empty-icon">⚠️</div><h3>Error</h3><p>' + escHtml(err) + '</p></div>';
  });
}

function netDistCard(d) {
  var nombre = ((d.nombre || '') + ' ' + (d.appat || '') + ' ' + (d.apmat || '')).trim();
  var ini    = initials(d.nombre, d.appat);
  var pts    = parseFloat(d.puntos_mes) || 0;
  var cal    = d.calificacion || 'ninguna';
  var estOk  = (parseInt(d.estatus) === 1);

  return '<div class="dist-card">' +
    '<div class="dist-avatar">' + escHtml(ini) + '</div>' +
    '<div class="dist-info">' +
      '<div class="dist-name">' + escHtml(nombre) + (estOk ? '' : ' <span class="badge badge-danger" style="font-size:10px">Inactivo</span>') + '</div>' +
      '<div class="dist-ref">Ref: ' + escHtml(d.referencia || '—') + ' · Nivel ' + (d.nivel || '—') + ' ' + calBadge(pts) + '</div>' +
    '</div>' +
    '<div class="dist-pts">' +
      formatPts(pts) +
      '<small>puntos</small>' +
    '</div>' +
    (d.tiene_hijos
      ? '<span class="dist-expand" data-expand="' + d.idinv + '" data-name="' + escHtml(nombre) + '" title="Ver red de ' + escHtml(d.nombre) + '">▶</span>'
      : '<span style="width:28px"></span>') +
  '</div>';
}

function netUpdateBreadcrumb() {
  var el = document.getElementById('netBreadcrumb');
  if (!el) return;
  var html = '';
  for (var i = 0; i < NET.breadcrumb.length; i++) {
    if (i > 0) html += '<span class="breadcrumb-sep">›</span>';
    if (i < NET.breadcrumb.length - 1) {
      var item = NET.breadcrumb[i];
      html += '<span class="breadcrumb-item" data-bc="' + i + '">' + escHtml(item.nombre) + '</span>';
    } else {
      html += '<span style="font-size:13px;font-weight:700;color:var(--navy)">' + escHtml(NET.breadcrumb[i].nombre) + '</span>';
    }
  }
  el.innerHTML = html;

  // Wire breadcrumb clicks
  var items = el.querySelectorAll('[data-bc]');
  for (var j = 0; j < items.length; j++) {
    (function(item) {
      item.addEventListener('click', function() {
        var idx = parseInt(item.dataset.bc);
        NET.breadcrumb = NET.breadcrumb.slice(0, idx + 1);
        netLoad(NET.breadcrumb[idx].id);
      });
    })(items[j]);
  }
}
