// ══════════════════════════════════════════════
// RRB Admin — Module: distribuidores
// ══════════════════════════════════════════════

function distInit() {
  document.getElementById('dist-estado').textContent = '';
  document.getElementById('dist-tabla').style.display = 'none';
  document.getElementById('dist-empty').style.display = 'none';
  document.getElementById('dist-tbody').innerHTML = '';
}

async function distBuscar() {
  const q = (document.getElementById('dist-input').value || '').trim();
  if (!q) {
    document.getElementById('dist-estado').textContent = 'Escribe al menos un carácter para buscar.';
    return;
  }
  document.getElementById('dist-estado').textContent = '⏳ Buscando...';
  document.getElementById('dist-tabla').style.display = 'none';
  document.getElementById('dist-empty').style.display = 'none';
  try {
    const res = await fetch(`api/distribuidores-buscar.php?q=${encodeURIComponent(q)}`, { headers: { Authorization: 'Bearer ' + token() } });
    const data = await res.json();
    if (!data.ok) throw new Error(data.error || 'Error desconocido');
    const rows = data.distribuidores || [];
    document.getElementById('dist-estado').textContent =
      rows.length > 0 ? `${rows.length} resultado(s) encontrado(s)` : '';
    if (rows.length === 0) {
      document.getElementById('dist-empty').style.display = 'block';
      return;
    }
    const tbody = document.getElementById('dist-tbody');
    tbody.innerHTML = rows.map(d => `
      <tr style="border-bottom:1px solid var(--border);cursor:pointer" onclick="distVerDetalle(${d.id_inv})">
        <td style="padding:10px 12px;font-weight:600;color:var(--primary)">${d.referencia || '-'}</td>
        <td style="padding:10px 12px">${d.nombre || ''} ${d.appat || ''} ${d.apmat || ''}</td>
        <td style="padding:10px 12px;font-family:monospace">${d.rfc || '-'}</td>
        <td style="padding:10px 12px">${d.email || '-'}</td>
        <td style="padding:10px 12px;text-align:center">
          <button onclick="event.stopPropagation();distVerDetalle(${d.id_inv})"
            style="padding:5px 14px;background:var(--primary);color:#fff;border:none;border-radius:6px;font-size:12px;cursor:pointer">
            Ver detalle
          </button>
        </td>
      </tr>
    `).join('');
    document.getElementById('dist-tabla').style.display = 'table';
  } catch(e) {
    document.getElementById('dist-estado').textContent = `❌ Error: ${e.message}`;
  }
}

let _distCurrentId = null;

function distCerrarDetalle() {
  document.getElementById('dist-detalle-panel').style.display = 'none';
  document.getElementById('dist-tabla').style.display = 'table';
  document.getElementById('dist-estado').style.display = '';
  const empty = document.getElementById('dist-empty');
  if (empty && empty.style.display !== 'none') empty.style.display = 'none';
  _distCurrentId = null;
}

function distEditarDatosInline() {
  if (_distCurrentId) distEditarDatos(_distCurrentId);
}

async function distVerDetalle(idInv) {
  _distCurrentId = idInv;
  // Ocultar tabla de resultados y mostrar panel inline
  document.getElementById('dist-tabla').style.display = 'none';
  document.getElementById('dist-empty').style.display = 'none';
  document.getElementById('dist-estado').style.display = 'none';
  const panel = document.getElementById('dist-detalle-panel');
  panel.style.display = 'block';
  // Scroll al panel
  panel.scrollIntoView({ behavior: 'smooth', block: 'start' });
  document.getElementById('dist-det-body').innerHTML =
    '<div style="text-align:center;padding:40px;color:#aaa">⏳ Cargando...</div>';
  document.getElementById('dist-det-tx-body').innerHTML = '';
  document.getElementById('dist-det-tx-wrap').style.display = 'none';
  try {
    const [resD, resTx, resG, resV] = await Promise.all([
      fetch(`api/distribuidores-detalle.php?id=${idInv}`, { headers: { Authorization: 'Bearer ' + token() } }),
      fetch(`api/distribuidores-transacciones.php?id=${idInv}`, { headers: { Authorization: 'Bearer ' + token() } }),
      fetch(`api/distribuidores-ganancias.php?id=${idInv}`, { headers: { Authorization: 'Bearer ' + token() } }),
      fetch(`api/distribuidores-vouchers.php?id=${idInv}`, { headers: { Authorization: 'Bearer ' + token() } })
    ]);
    const dataD  = await resD.json();
    const dataTx = await resTx.json();
    const dataG  = await resG.json();
    const dataV  = await resV.json();
    if (!dataD.ok) throw new Error(dataD.error || 'Error al cargar detalle');
    const d = dataD.distribuidor;
    _distEditData = d; // guardar para el formulario de edición
    document.getElementById('dist-det-titulo').textContent =
      `${d.nombre || ''} ${d.appat || ''} ${d.apmat || ''}`.trim() || 'Distribuidor';
    const fechasEl = document.getElementById('dist-det-fechas');
    if (fechasEl) {
      const partes = [];
      if (d.fecha_nac) partes.push('Nac: ' + d.fecha_nac);
      if (d.fecha_registro || d.fecharegistro) partes.push('Ingreso: ' + (d.fecha_registro || d.fecharegistro));
      fechasEl.textContent = partes.join('  |  ');
    }
    const pats = dataD.patrocinadores || [];
    const patsHtml = pats.length > 0
      ? pats.map(p => `
          <div style="display:grid;grid-template-columns:30px 1fr 1fr 2fr;gap:8px;align-items:center;padding:8px 0;border-bottom:1px solid var(--border)">
            <div style="font-size:11px;color:var(--muted);font-weight:700;text-align:center">${p.nivel}</div>
            <div style="font-weight:700;color:var(--primary);font-size:13px">${p.referencia || '-'}</div>
            <div style="font-family:monospace;font-size:12px;color:#555">${p.rfc || '-'}</div>
            <div style="font-size:13px">${p.nombre_completo || '-'}</div>
          </div>`).join('')
      : '<div style="color:var(--muted);font-size:13px;padding:8px 0">Sin patrocinadores registrados</div>';
    document.getElementById('dist-det-body').innerHTML = `
      <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;margin-bottom:16px">
        <div style="background:#f5f8fc;border-radius:8px;padding:12px">
          <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">Referencia</div>
          <div style="font-weight:700;color:var(--primary)">${d.referencia || '-'}</div>
        </div>
        <div style="background:#f5f8fc;border-radius:8px;padding:12px">
          <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">RFC</div>
          <div style="font-weight:600;font-family:monospace">${d.rfc || '-'}</div>
        </div>
        <div style="background:#f5f8fc;border-radius:8px;padding:12px">
          <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">Correo</div>
          <div>${d.email || '-'}</div>
        </div>
        <div style="background:#f5f8fc;border-radius:8px;padding:12px">
          <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">Teléfonos</div>
          ${d.telefono ? '<div style="font-size:13px">📞 Tel1: ' + d.telefono + '</div>' : ''}
          ${d.celular   ? '<div style="font-size:13px">📱 Tel2: ' + d.celular   + '</div>' : ''}
          ${d.whatsapp  ? '<div style="font-size:13px">💬 WA: '   + d.whatsapp  + '</div>' : ''}
          ${!d.telefono && !d.celular && !d.whatsapp ? '<div>-</div>' : ''}
        </div>
        <div style="background:#f5f8fc;border-radius:8px;padding:12px;grid-column:span 2">
          <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">Domicilio</div>
          <div style="font-size:13px;line-height:1.6">
            ${d.domicilio ? '<div>' + d.domicilio + '</div>' : ''}
            ${d.colonia   ? '<div>' + d.colonia   + '</div>' : ''}
            <div>${[d.ciudad, d.estado].filter(Boolean).join(', ')}${d.cp ? ' C.P. ' + d.cp : ''}</div>
          </div>

        </div>
      </div>

      <!-- Reporte de Red -->
      <div style="margin-bottom:16px;border:1px solid var(--border);border-radius:8px;overflow:hidden">
        <div style="padding:10px 14px;background:#f5f8fc;display:flex;align-items:center;gap:10px;flex-wrap:wrap">
          <span style="font-size:16px">🌐</span>
          <span style="font-weight:600;font-size:13px;flex:1">Reporte de Red</span>
          <select id="dist-red-mes" style="padding:5px 8px;border:1px solid var(--border);border-radius:6px;font-size:13px;background:#fff">
          </select>
          <button onclick="distGenerarReporte(this)" style="padding:6px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;font-size:13px;font-weight:600;cursor:pointer">📊 Generar Ganancias</button>
        </div>
      </div>

      <details style="margin-bottom:16px;border:1px solid var(--border);border-radius:8px;overflow:hidden">
        <summary style="padding:10px 14px;cursor:pointer;font-weight:600;font-size:13px;background:#f5f8fc;user-select:none;list-style:none;display:flex;align-items:center;gap:8px">
          <span style="font-size:16px">🔑</span> Datos de Acceso a Oficina Virtual
          <span style="margin-left:auto;font-size:11px;color:var(--muted)">▼ ver</span>
        </summary>
        <div style="padding:12px 14px">
          <pre id="dist-acceso-txt" style="font-family:inherit;font-size:14px;line-height:1.8;margin:0 0 10px;white-space:pre-wrap">Datos de Acceso a Oficina Virtual
Referencia: ${d.referencia || '-'}
Usuario: ${d.usuario || '-'}
Contraseña: ${d.contrasena || '-'}
www.sistemarrb.com</pre>
          <button onclick="(() => { const txt = document.getElementById('dist-acceso-txt').innerText; navigator.clipboard.writeText(txt).then(() => { this.textContent = '✅ Copiado'; setTimeout(() => this.textContent = '📋 Copiar', 2000); }); })()" style="padding:6px 16px;border:1px solid var(--primary);border-radius:6px;background:#fff;color:var(--primary);font-size:13px;font-weight:600;cursor:pointer">📋 Copiar</button>
        </div>
      </details>
      <details style="margin-bottom:16px;border:1px solid var(--border);border-radius:8px;overflow:hidden">
        <summary style="padding:10px 14px;cursor:pointer;font-weight:600;font-size:13px;background:#f5f8fc;user-select:none;list-style:none;display:flex;align-items:center;gap:8px">
          <span style="font-size:16px">👥</span> Cadena de patrocinadores (${pats.length} nivel${pats.length !== 1 ? 'es' : ''})
          <span style="margin-left:auto;font-size:11px;color:var(--muted)">▼ ver</span>
        </summary>
        <div style="padding:4px 14px 12px">
          <div style="display:grid;grid-template-columns:30px 1fr 1fr 2fr;gap:8px;padding:6px 0;border-bottom:2px solid var(--border)">
            <div style="font-size:10px;color:var(--muted);font-weight:700">#</div>
            <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase">Referencia</div>
            <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase">RFC</div>
            <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase">Nombre</div>
          </div>
          ${patsHtml}
        </div>
      </details>
      ${(() => {
        const gs = (dataG && dataG.ok) ? (dataG.ganancias || []) : [];
        const statusColor = { 'Por Pagar': '#fff3cd', 'Depósito': '#d4edda', 'Voucher': '#cce5ff', 'Retenida': '#f8d7da' };
        const statusText  = { 'Por Pagar': '#856404', 'Depósito': '#155724', 'Voucher': '#004085', 'Retenida': '#721c24' };
        const gRows = gs.length > 0 ? gs.map(g => `
          <div style="border-bottom:1px solid var(--border);padding:8px 0">
            <div style="display:grid;grid-template-columns:110px 80px 80px 80px 80px 90px;gap:6px;align-items:center;font-size:13px">
              <div style="font-weight:600">${g.mes_nombre} ${g.anio_corresponde}</div>
              <div style="text-align:right">${fmtMxn(g.total || 0)}</div>
              <div style="text-align:right;font-weight:700;color:var(--primary)">${fmtMxn(g._real || 0)}</div>
              <div style="text-align:right">${fmtMxn(g.apagar || 0)}</div>
              <div style="text-align:right;color:#888;font-size:12px">${fmtMxn(g.impuestos || 0)}</div>
              <div style="text-align:center">
                <span style="padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;background:${statusColor[g.status_label]||'#eee'};color:${statusText[g.status_label]||'#333'}">${g.status_label}</span>
              </div>
            </div>
            <div style="display:flex;flex-wrap:wrap;gap:16px;margin-top:5px;font-size:12px;color:#666">
              <span><span style="color:var(--muted);font-size:11px">Fecha pago:</span> ${g.fechaf || '-'}</span>
              <span><span style="color:var(--muted);font-size:11px">No. cuenta:</span> ${g.nocuenta || '-'}</span>
              <span><span style="color:var(--muted);font-size:11px">Folio:</span> ${g.folio || '-'}</span>
              ${g.observaciones ? '<span><span style="color:var(--muted);font-size:11px">Obs:</span> ' + g.observaciones + '</span>' : ''}
            </div>
          </div>`).join('') : '<div style="color:var(--muted);font-size:13px;padding:8px 0">Sin ganancias en los últimos 6 meses</div>';
        return `
        <details style="margin-bottom:16px;border:1px solid var(--border);border-radius:8px;overflow:hidden">
          <summary style="padding:10px 14px;cursor:pointer;font-weight:600;font-size:13px;background:#f5f8fc;user-select:none;list-style:none;display:flex;align-items:center;gap:8px">
            <span style="font-size:16px">💰</span> Ganancias últimos 6 meses (${gs.length} registro${gs.length !== 1 ? 's' : ''})
            <span style="margin-left:auto;font-size:11px;color:var(--muted)">▼ ver</span>
          </summary>
          <div style="padding:4px 14px 12px">
            <div style="display:grid;grid-template-columns:110px 80px 80px 80px 80px 90px;gap:6px;padding:6px 0;border-bottom:2px solid var(--border)">
              <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase">Mes</div>
              <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;text-align:right">Total</div>
              <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;text-align:right">Real</div>
              <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;text-align:right">A Pagar</div>
              <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;text-align:right">Impuesto</div>
              <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;text-align:center">Status</div>
            </div>
            ${gRows}
          </div>
        </details>`;
      })()} 
      ${(() => {
        const vs = (dataV && dataV.ok) ? (dataV.vouchers || []) : [];
        const vRows = vs.length > 0 ? vs.map(v => `
          <div style="border-bottom:1px solid var(--border);padding:8px 0;cursor:pointer" onclick="vpVerDetalle(${v.idv})" onmouseover="this.style.background='#f0f4f8'" onmouseout="this.style.background=''">
            <div style="display:grid;grid-template-columns:80px 90px 90px 70px 1fr;gap:8px;align-items:center;font-size:13px">
              <div style="font-family:monospace;font-weight:700;color:var(--primary)">#${v.idv}</div>
              <div style="text-align:right"><span style="font-size:11px;color:var(--muted)">Total</span><br>${fmtMxn(v.total || 0)}</div>
              <div style="text-align:right"><span style="font-size:11px;color:var(--muted)">Restante</span><br><strong>${fmtMxn(v.restante || 0)}</strong></div>
              <div style="text-align:center">
                <span style="padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;background:${v.status_label==='Activo'?'#d4edda':'#e2e3e5'};color:${v.status_label==='Activo'?'#155724':'#383d41'}">${v.status_label}</span>
              </div>
              <div style="font-size:12px;color:#666">${v.fecha_cre || '-'}</div>
            </div>
            ${v.observaciones ? '<div style="font-size:12px;color:#666;margin-top:4px"><span style="color:var(--muted);font-size:11px">Obs:</span> ' + v.observaciones + '</div>' : ''}
          </div>`).join('') : '<div style="color:var(--muted);font-size:13px;padding:8px 0">Sin vouchers en los últimos 6 meses</div>';
        return `
        <details style="margin-bottom:16px;border:1px solid var(--border);border-radius:8px;overflow:hidden">
          <summary style="padding:10px 14px;cursor:pointer;font-weight:600;font-size:13px;background:#f5f8fc;user-select:none;list-style:none;display:flex;align-items:center;gap:8px">
            <span style="font-size:16px">🎫</span> Vouchers últimos 6 meses (${vs.length} voucher${vs.length !== 1 ? 's' : ''})
            <span style="margin-left:auto;font-size:11px;color:var(--muted)">▼ ver</span>
          </summary>
          <div style="padding:4px 14px 12px">
            ${vRows}
          </div>
        </details>`;
      })()} 
    `;
    const txs = dataTx.transacciones || [];
    const DIST_TX_TIPO = {
      6:  { label: 'Especial',      bg: '#fff3cd', color: '#856404' },
      10: { label: 'Venta',         bg: '#d4edda', color: '#155724' },
      11: { label: 'Por Asignar',   bg: '#cce5ff', color: '#004085' },
      12: { label: 'Asignación',    bg: '#d4edda', color: '#155724' },
    };
    const rows = txs.length > 0 ? txs.map(t => {
      const tipo = DIST_TX_TIPO[t.tipotransaccion] || { label: t.tipotransaccion || '-', bg: '#f0f0f0', color: '#333' };
      return `
      <tr style="border-bottom:1px solid var(--border);cursor:pointer" onclick="distVerTx(${t.idtransacciones})" title="Ver detalle" onmouseover="this.style.background='#f0f4fb'" onmouseout="this.style.background=''">
        <td style="padding:8px 12px;font-family:monospace;font-size:12px;color:var(--primary);font-weight:700">${t.idtransacciones || '-'}</td>
        <td style="padding:8px 12px">${t.fechat || '-'}</td>
        <td style="padding:8px 12px"><span style="padding:3px 9px;border-radius:12px;font-size:11px;font-weight:700;background:${tipo.bg};color:${tipo.color}">${tipo.label}</span></td>
        <td style="padding:8px 12px;text-align:right;font-weight:600">${fmtNum(t.unidades || 0)}</td>
        <td style="padding:8px 12px;text-align:right">${fmtMxn(t.monto_mxn || 0)}</td>
      </tr>`;
    }).join('') : '<tr><td colspan="5" style="text-align:center;padding:20px;color:#aaa">Sin transacciones en los últimos 6 meses</td></tr>';
    document.getElementById('dist-det-tx-body').innerHTML = rows;
    document.getElementById('dist-det-tx-wrap').style.display = 'block';
    // Inicializar selector de mes AHORA que el DOM ya tiene el elemento
    (function() {
      const sel = document.getElementById('dist-red-mes');
      if (!sel) return;
      sel.innerHTML = '';
      const now = new Date();
      const meses = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
      for (let i = 0; i <= 6; i++) {
        const dt = new Date(now.getFullYear(), now.getMonth() - i, 1);
        const val = dt.getFullYear() + '-' + String(dt.getMonth()+1).padStart(2,'0');
        const opt = document.createElement('option');
        opt.value = val;
        opt.textContent = meses[dt.getMonth()] + ' ' + dt.getFullYear();
        if (i === 0) opt.selected = true;
        sel.appendChild(opt);
      }
    })();
  } catch(e) {
    document.getElementById('dist-det-body').innerHTML =
      `<div style="color:#dc3545;padding:20px">❌ Error: ${e.message}</div>`;
  }
}

function distCerrarModal() {
  distCerrarDetalle();
}

function distVerTx(idTx) {
  // Reutilizar exactamente el mismo modal y lógica que txVerDetalle
  txVerDetalle(idTx);
}

// ── Editar datos del distribuidor ────────────────────────────────────────────
let _distEditData = null; // guarda los datos actuales para pre-llenar el form

async function distEditarDatos(idInv) {
  // Cargar lista de estados para el select
  let estados = [];
  try {
    const idPais = (_distEditData && _distEditData.id_pais) ? _distEditData.id_pais : 0;
    const r = await fetch('api/estados-lista.php' + (idPais ? '?pais=' + idPais : ''), { headers: { Authorization: 'Bearer ' + token() } });
    const j = await r.json();
    if (j.ok) estados = j.estados;
  } catch(e) {}

  const d = _distEditData;
  if (!d) return;

  const optsEstados = estados.map(e =>
    `<option value="${e.idestado}" ${e.idestado == d.id_estado ? 'selected' : ''}>${e.nombre}</option>`
  ).join('');

  document.getElementById('modal-dist-edit-body').innerHTML = `
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">RFC</label>
        <input id="de-rfc" value="${d.rfc||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">Correo</label>
        <input id="de-email" type="email" value="${d.email||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">Tel 1</label>
        <input id="de-tel1" value="${d.telefono||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">Tel 2</label>
        <input id="de-tel2" value="${d.celular||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">WhatsApp</label>
        <input id="de-wa" value="${d.whatsapp||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">C.P.</label>
        <input id="de-cp" value="${d.cp||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div style="grid-column:span 2">
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">Domicilio</label>
        <input id="de-domicilio" value="${d.domicilio||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">Colonia</label>
        <input id="de-colonia" value="${d.colonia||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">Ciudad</label>
        <input id="de-ciudad" value="${d.ciudad||''}" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px" />
      </div>
      <div style="grid-column:span 2">
        <label style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase">Estado</label>
        <select id="de-estado" style="width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:6px;font-size:13px;box-sizing:border-box;margin-top:4px">
          <option value="0">-- Seleccionar estado --</option>
          ${optsEstados}
        </select>
      </div>
    </div>
    <div id="de-msg" style="margin-top:12px;font-size:13px"></div>
  `;
  document.getElementById('modal-dist-edit').style.display = 'flex';
}

async function distGuardarEdicion() {
  const d = _distEditData;
  if (!d) return;
  const btn = document.getElementById('de-btn-guardar');
  btn.disabled = true;
  btn.textContent = 'Guardando...';
  const body = {
    id:                d.id_inv,
    rfc:               document.getElementById('de-rfc').value.trim(),
    email:             document.getElementById('de-email').value.trim(),
    tel1:              document.getElementById('de-tel1').value.trim(),
    tel2:              document.getElementById('de-tel2').value.trim(),
    wa:                document.getElementById('de-wa').value.trim(),
    domicilio:         document.getElementById('de-domicilio').value.trim(),
    colonia:           document.getElementById('de-colonia').value.trim(),
    ciudad:            document.getElementById('de-ciudad').value.trim(),
    cp:                document.getElementById('de-cp').value.trim(),
    estados_idestado:  document.getElementById('de-estado').value,
  };
  try {
    const r = await fetch('api/distribuidores-actualizar.php', {
      method: 'PUT',
      headers: { 'Authorization': 'Bearer ' + token(), 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    });
    const j = await r.json();
    const msg = document.getElementById('de-msg');
    if (j.ok) {
      msg.innerHTML = '<span style="color:#155724;background:#d4edda;padding:6px 12px;border-radius:6px">✅ Datos actualizados correctamente</span>';
      setTimeout(() => {
        document.getElementById('modal-dist-edit').style.display = 'none';
        distVerDetalle(d.id_inv); // recargar el detalle
      }, 1200);
    } else {
      msg.innerHTML = '<span style="color:#721c24;background:#f8d7da;padding:6px 12px;border-radius:6px">❌ ' + (j.error || 'Error al guardar') + '</span>';
      btn.disabled = false;
      btn.textContent = 'Guardar cambios';
    }
  } catch(e) {
    document.getElementById('de-msg').innerHTML = '<span style="color:#721c24">❌ Error de conexión</span>';
    btn.disabled = false;
    btn.textContent = 'Guardar cambios';
  }
}

// ── Reporte de Red ───────────────────────────────────────────────────────────
async function distGenerarReporte(btn) {
  if (!_distCurrentId) return;
  const sel = document.getElementById('dist-red-mes');
  const [anio, mes] = (sel ? sel.value : '').split('-');
  if (!anio || !mes) return;

  const origText = btn ? btn.textContent : '';
  if (btn) { btn.disabled = true; btn.textContent = '⏳ Generando...'; }

  try {
    const r = await fetch(`api/distribuidor-reporte-red.php?id=${_distCurrentId}&anio=${anio}&mes=${mes}`, {
      headers: { Authorization: 'Bearer ' + token() }
    });
    const data = await r.json();
    if (!data.ok) throw new Error(data.error || 'Error al generar reporte');

    const meses = ['','Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
    const mesNombre = meses[parseInt(mes)] + ' ' + anio;

    const calLabel = {
      'no_calificado': '<span style="background:#f8d7da;color:#721c24;padding:3px 10px;border-radius:12px;font-size:12px;font-weight:700">No calificado</span>',
      'parcial':       '<span style="background:#fff3cd;color:#856404;padding:3px 10px;border-radius:12px;font-size:12px;font-weight:700">Calificación parcial</span>',
      'calificado':    '<span style="background:#d4edda;color:#155724;padding:3px 10px;border-radius:12px;font-size:12px;font-weight:700">Calificado</span>',
    }[data.calificacion] || data.calificacion;

    // Construir HTML del reporte
    let html = `
      <style>
        .rr-table { width:100%; border-collapse:collapse; font-size:13px; }
        .rr-table th { background:#1a3a6b; color:#fff; padding:8px 10px; text-align:left; font-size:11px; font-weight:700; text-transform:uppercase; }
        .rr-table th.r { text-align:right; }
        .rr-table td { padding:7px 10px; border-bottom:1px solid #e5e9f2; }
        .rr-table td.r { text-align:right; }
        .rr-table tr:hover td { background:#f5f8fc; }
        .rr-nivel-hdr { background:#1a3a6b; color:#fff; padding:8px 14px; font-weight:700; font-size:13px; margin-top:16px; border-radius:6px 6px 0 0; display:flex; justify-content:space-between; align-items:center; }
        .rr-nivel-hdr .badge { background:rgba(255,255,255,.2); padding:2px 10px; border-radius:10px; font-size:12px; }
        .rr-nivel-wrap { border:1px solid #d0d8e8; border-top:none; border-radius:0 0 6px 6px; overflow:hidden; margin-bottom:4px; }
        .rr-open { background:#d4edda; color:#155724; }
        .rr-closed { background:#f8d7da; color:#721c24; }
      </style>
      <div style="font-family:system-ui,sans-serif;max-width:900px;margin:0 auto;padding:16px">
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;flex-wrap:wrap">
          <div style="flex:1">
            <h2 style="margin:0;font-size:18px;color:#1a3a6b">🌐 Reporte de Red &mdash; ${mesNombre}</h2>
            <div style="font-size:13px;color:#666;margin-top:4px">Distribuidor ID: ${_distCurrentId}</div>
          </div>
          <div style="text-align:right">
            <div style="font-size:13px;margin-bottom:4px">Puntos propios: <strong>${fmtNum(data.puntos_propios)}</strong></div>
            <div>${calLabel}</div>
          </div>
        </div>

        <!-- Resumen de calificación -->
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin-bottom:16px">
          <div style="background:#f5f8fc;border:1px solid #d0d8e8;border-radius:8px;padding:12px;text-align:center">
            <div style="font-size:22px;font-weight:700;color:#1a3a6b">${data.directos_624}</div>
            <div style="font-size:11px;color:#666;margin-top:2px">Directos calificados (624+)</div>
          </div>
          <div style="background:#f5f8fc;border:1px solid #d0d8e8;border-radius:8px;padding:12px;text-align:center">
            <div style="font-size:22px;font-weight:700;color:#1a3a6b">${data.directos_1500}</div>
            <div style="font-size:11px;color:#666;margin-top:2px">Directos plenos (1500+)</div>
          </div>
          <div style="background:#f5f8fc;border:1px solid #d0d8e8;border-radius:8px;padding:12px;text-align:center">
            <div style="font-size:22px;font-weight:700;color:#1a3a6b">${data.niveles_abiertos}</div>
            <div style="font-size:11px;color:#666;margin-top:2px">Niveles abiertos</div>
          </div>
          <div style="background:#f5f8fc;border:1px solid #d0d8e8;border-radius:8px;padding:12px;text-align:center">
            <div style="font-size:22px;font-weight:700;color:#1a3a6b">${data.total_personas}</div>
            <div style="font-size:11px;color:#666;margin-top:2px">Personas con compras</div>
          </div>
        </div>

        <!-- Tabla de ganancias por nivel -->
        <h3 style="font-size:14px;color:#1a3a6b;margin:0 0 8px">Tabla de Ganancias por Nivel</h3>
        <div style="overflow-x:auto;margin-bottom:20px">
          <table class="rr-table">
            <thead>
              <tr>
                <th>Nivel</th>
                <th>%</th>
                <th class="r">Puntos en red</th>
                <th class="r">Generado</th>
                <th class="r">A recibir</th>
                <th>Estado</th>
              </tr>
            </thead>
            <tbody>
              ${data.tabla_ganancias.filter(g => g.puntos > 0 || g.nivel <= data.niveles_abiertos).map(g => `
                <tr>
                  <td><strong>Nivel ${g.nivel}</strong></td>
                  <td>${g.porcentaje}%</td>
                  <td class="r">${fmtNum(g.puntos)}</td>
                  <td class="r">${fmtMxn(g.generado)}</td>
                  <td class="r" style="font-weight:700;color:${g.abierto && g.recibir > 0 ? '#155724' : '#999'}">${g.abierto ? fmtMxn(g.recibir) : '-'}</td>
                  <td><span class="${g.abierto ? 'rr-open' : 'rr-closed'}" style="padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700">${g.abierto ? '✅ Abierto' : '🔒 Cerrado'}</span></td>
                </tr>`).join('')}
              <tr style="background:#f5f8fc;font-weight:700">
                <td colspan="3">TOTAL</td>
                <td class="r">${fmtMxn(data.total_generado)}</td>
                <td class="r" style="color:#155724;font-size:15px">${fmtMxn(data.total_recibir)}</td>
                <td></td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Detalle por nivel -->
        <h3 style="font-size:14px;color:#1a3a6b;margin:0 0 8px">Detalle de la Red por Nivel</h3>
        ${data.niveles.length === 0 ? '<p style="color:#aaa;text-align:center;padding:20px">Sin personas con compras en la red este período</p>' : ''}
        ${data.niveles.map(niv => `
          <div class="rr-nivel-hdr">
            <span>Nivel ${niv.nivel}</span>
            <div style="display:flex;gap:8px;align-items:center">
              <span class="badge">${niv.total_personas} persona${niv.total_personas !== 1 ? 's' : ''}</span>
              <span class="badge">${fmtNum(niv.total_puntos)} pts</span>
            </div>
          </div>
          <div class="rr-nivel-wrap">
            <table class="rr-table">
              <thead><tr><th>Referencia</th><th>Nombre</th><th class="r">Puntos</th></tr></thead>
              <tbody>
                ${niv.personas.map(p => `<tr><td style="font-family:monospace;color:#1a3a6b">${p.referencia}</td><td>${p.nombre_completo}</td><td class="r">${fmtNum(p.puntos)}</td></tr>`).join('')}
                <tr style="background:#f5f8fc;font-weight:700"><td colspan="2">Total nivel ${niv.nivel}</td><td class="r">${fmtNum(niv.total_puntos)}</td></tr>
              </tbody>
            </table>
          </div>`).join('')}
      </div>`;

    // Abrir ventana popup con el reporte
    const w = window.open('', '_blank', 'width=960,height=700,scrollbars=yes,resizable=yes');
    w.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Reporte de Red — ${mesNombre}</title></head><body style="margin:0;background:#fff">${html}</body></html>`);
    w.document.close();

  } catch(e) {
    alert('❌ Error al generar reporte: ' + e.message);
  } finally {
    if (btn) { btn.disabled = false; btn.textContent = origText; }
  }
}

