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

var NET = {
  u: null,
};

function renderNetwork(el) {
  NET.u = getUser();
  var idinv = NET.u.idinv || NET.u.id_inver;

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

    '<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>' +

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

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

  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 = '';
    netLoadRoot(idinv);
  };

  netLoadRoot(idinv);
}

/* ── Carga raíz ─────────────────────────────────────────────── */
function netLoadRoot(idinv) {
  var listEl  = document.getElementById('netList');
  var statsEl = document.getElementById('netStats');
  listEl.innerHTML = '<div class="loading-overlay"><div class="spinner-lg"></div><span>Cargando red...</span></div>';
  statsEl.innerHTML = '';

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

    var calCount = 0;
    for (var i = 0; i < red.length; i++) {
      if (red[i].calificacion && 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">' + red.length + '</div>' +
          '<div class="stat-label">Directos</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 en red</div>' +
        '</div>' +
      '</div>';

    if (red.length === 0) {
      listEl.innerHTML = '<div class="empty-state"><div class="empty-icon">👥</div><h3>Sin distribuidores</h3><p>No hay nadie en tu red aún.</p></div>';
      return;
    }

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

/* ── Construye HTML de una lista de distribuidores ──────────── */
function netBuildList(items, depth) {
  var html = '';
  for (var i = 0; i < items.length; i++) {
    html += netDistCard(items[i], depth);
  }
  return html;
}

/* ── Tarjeta individual ──────────────────────────────────────── */
function netDistCard(d, depth) {
  var nombre = ((d.nombre || '') + ' ' + (d.appat || '') + ' ' + (d.apmat || '')).trim();
  var ini    = initials(d.nombre, d.appat);
  var pts    = parseFloat(d.puntos_mes) || 0;
  var estOk  = (parseInt(d.estatus) === 1);
  var indent = depth * 18;
  var hasKids = !!d.tiene_hijos;

  return (
    '<div class="net-node">' +
      '<div class="dist-card" style="' + (indent ? 'margin-left:' + indent + 'px;border-left:3px solid var(--teal);' : '') + '">' +
        '<div class="dist-avatar" style="' + (depth > 0 ? 'width:36px;height:36px;font-size:13px' : '') + '">' + 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 || '—') + ' · Nv ' + (d.nivel || '—') + ' ' + calBadge(pts) + '</div>' +
        '</div>' +
        '<div class="dist-pts">' + formatPts(pts) + '<small>pts</small></div>' +
        (hasKids
          ? '<button class="net-toggle" data-id="' + d.idinv + '" data-depth="' + (depth + 1) + '" ' +
              'title="Ver red de ' + escHtml(d.nombre) + '" ' +
              'style="background:none;border:none;cursor:pointer;font-size:18px;color:var(--navy);' +
                     'padding:4px 8px;border-radius:6px;transition:transform .2s;line-height:1">▶</button>'
          : '<span style="width:36px;display:inline-block"></span>') +
      '</div>' +
      (hasKids
        ? '<div class="net-children" id="nch-' + d.idinv + '" style="display:none;overflow:hidden"></div>'
        : '') +
    '</div>'
  );
}

/* ── Conecta los botones de expansión ─────────────────────────── */
function netWireToggles(container) {
  var btns = container.querySelectorAll('.net-toggle');
  for (var i = 0; i < btns.length; i++) {
    (function(btn) {
      btn.addEventListener('click', function(e) {
        e.stopPropagation();
        var id    = parseInt(btn.dataset.id);
        var depth = parseInt(btn.dataset.depth);
        var chEl  = document.getElementById('nch-' + id);
        if (!chEl) return;

        var isOpen = chEl.style.display !== 'none';

        if (isOpen) {
          /* — Colapsar — */
          chEl.style.display = 'none';
          btn.style.transform = '';
        } else {
          /* — Expandir — */
          if (chEl.dataset.loaded) {
            /* Ya cargado, solo mostrar */
            chEl.style.display = 'block';
            btn.style.transform = 'rotate(90deg)';
          } else {
            /* Primera vez: llamar API */
            btn.textContent = '⏳';
            btn.disabled = true;

            apiGet('/network/list?padre=' + id, function(data) {
              var red = data.red || [];
              if (red.length === 0) {
                chEl.innerHTML =
                  '<div style="margin-left:' + (depth * 18) + 'px;padding:8px 12px;' +
                       'color:var(--text-muted);font-size:13px">Sin distribuidores</div>';
              } else {
                chEl.innerHTML = netBuildList(red, depth);
                netWireToggles(chEl);
              }
              chEl.dataset.loaded = '1';
              chEl.style.display  = 'block';
              btn.textContent     = '▶';
              btn.style.transform = 'rotate(90deg)';
              btn.disabled        = false;
            }, function() {
              btn.textContent = '▶';
              btn.disabled    = false;
            });
          }
        }
      });
    })(btns[i]);
  }
}

/* ── Búsqueda ────────────────────────────────────────────────── */
function netSearch(query) {
  var listEl  = document.getElementById('netList');
  var statsEl = document.getElementById('netStats');
  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 encontró "' + escHtml(query) + '"</p></div>';
      return;
    }
    statsEl.innerHTML =
      '<div style="font-size:13px;color:var(--text-muted);padding:4px 0">🔍 ' + red.length + ' resultado(s) para "' + escHtml(query) + '"</div>';

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