/* ============================================================
   views/profile.js — Mi Perfil
   ============================================================ */

function renderProfile(el) {
  var u = getUser();

  var nombre  = ((u.nombre || '') + ' ' + (u.appat || '') + ' ' + (u.apmat || '')).trim();
  var ini     = initials(u.nombre, u.appat);
  var isVip   = u.isVip;
  var vipLbl  = isVip === 1 || isVip === true
    ? '<span class="badge badge-success">✓ Verificado</span>'
    : isVip === 2
    ? '<span class="badge badge-warning">⏳ En revisión</span>'
    : '<span class="badge badge-muted">Sin verificar</span>';

  el.innerHTML =
    // Header card
    '<div class="profile-header">' +
      '<div class="profile-avatar">' + escHtml(ini) + '</div>' +
      '<div>' +
        '<div class="profile-name">' + escHtml(nombre) + '</div>' +
        '<div class="profile-ref">Ref: ' + escHtml(u.referencia || '—') + ' · Usuario: ' + escHtml(u.nombre_usuario || '') + '</div>' +
        '<div style="margin-top:8px;display:flex;gap:8px;flex-wrap:wrap">' +
          vipLbl +
          (u.isVip !== 1 ? '<button class="btn btn-sm" onclick="goTo(\'kyc\')" style="background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.4);font-size:11px">Verificar cuenta →</button>' : '') +
        '</div>' +
      '</div>' +
    '</div>' +

    '<div style="display:flex;flex-wrap:wrap;gap:16px">' +

      // Contact info
      '<div class="card" style="flex:1 1 300px">' +
        '<div class="card-header"><span class="card-title">📞 Contacto</span></div>' +
        '<div class="card-body">' +
          '<form id="profileContactForm">' +
            formField('tel1',   'Teléfono',          u.tel1,  'tel') +
            formField('tel2',   'Celular',            u.tel2,  'tel') +
            formField('wa',     'WhatsApp',           u.wa,    'tel') +
            formField('email',  'Correo electrónico', u.email, 'email') +
            '<button type="submit" class="btn btn-primary btn-full mt-12">Guardar contacto</button>' +
          '</form>' +
        '</div>' +
      '</div>' +

      // Address info
      '<div class="card" style="flex:1 1 300px">' +
        '<div class="card-header"><span class="card-title">🏠 Dirección</span></div>' +
        '<div class="card-body">' +
          '<form id="profileAddressForm">' +
            formField('domicilio', 'Calle y número',  u.domicilio) +
            formField('colonia',   'Colonia',          u.colonia) +
            formField('cp',        'Código postal',    u.cp,       'number') +
            formField('ciudad',    'Ciudad',           u.ciudad) +
            '<div class="form-group">' +
              '<label class="form-label">Estado</label>' +
              '<input type="text" class="form-control" value="' + escHtml(u.nombre_estado || '') + '" readonly style="background:var(--bg)">' +
            '</div>' +
            '<button type="submit" class="btn btn-primary btn-full mt-12">Guardar dirección</button>' +
          '</form>' +
        '</div>' +
      '</div>' +

      // Bank info
      '<div class="card" style="flex:1 1 300px">' +
        '<div class="card-header"><span class="card-title">🏦 Banco</span></div>' +
        '<div class="card-body">' +
          '<div class="form-group"><label class="form-label">Banco</label>' +
            '<input class="form-control" value="' + escHtml(u.nombre_banco || '—') + '" readonly style="background:var(--bg)"></div>' +
          '<div class="form-group"><label class="form-label">No. de cuenta / CLABE</label>' +
            '<input class="form-control" id="noCuenta" value="' + escHtml(u.nocuenta || '') + '" placeholder="Número de cuenta"></div>' +
          '<button class="btn btn-primary btn-full" onclick="saveNoCuenta()">Guardar cuenta</button>' +
          '<p class="text-muted text-sm mt-8">Para cambiar tu banco, contacta a soporte.</p>' +
        '</div>' +
      '</div>' +

      // Change password
      '<div class="card" style="flex:1 1 300px">' +
        '<div class="card-header"><span class="card-title">🔒 Contraseña</span></div>' +
        '<div class="card-body">' +
          '<form id="pwdForm">' +
            '<div class="form-group"><label class="form-label">Contraseña actual</label><input type="password" class="form-control" id="pwdOld" required></div>' +
            '<div class="form-group"><label class="form-label">Nueva contraseña</label><input type="password" class="form-control" id="pwdNew" required></div>' +
            '<div class="form-group"><label class="form-label">Confirmar nueva</label><input type="password" class="form-control" id="pwdConf" required></div>' +
            '<button type="submit" class="btn btn-primary btn-full">Cambiar contraseña</button>' +
          '</form>' +
        '</div>' +
      '</div>' +

    '</div>'; // end flex row

  // Wire contact form
  document.getElementById('profileContactForm').onsubmit = function(e) {
    e.preventDefault();
    var payload = {
      tel1:  document.querySelector('[name="tel1"]').value,
      tel2:  document.querySelector('[name="tel2"]').value,
      wa:    document.querySelector('[name="wa"]').value,
      email: document.querySelector('[name="email"]').value,
    };
    profileSave(payload, 'Contacto actualizado correctamente.');
  };

  // Wire address form
  document.getElementById('profileAddressForm').onsubmit = function(e) {
    e.preventDefault();
    var payload = {
      domicilio: document.querySelector('[name="domicilio"]').value,
      colonia:   document.querySelector('[name="colonia"]').value,
      cp:        document.querySelector('[name="cp"]').value,
      ciudad:    document.querySelector('[name="ciudad"]').value,
    };
    profileSave(payload, 'Dirección actualizada correctamente.');
  };

  // Wire password form
  document.getElementById('pwdForm').onsubmit = function(e) {
    e.preventDefault();
    var oldP = document.getElementById('pwdOld').value;
    var newP = document.getElementById('pwdNew').value;
    var conf = document.getElementById('pwdConf').value;
    if (!oldP || !newP) { toast('Completa todos los campos.', 'warning'); return; }
    if (newP !== conf)   { toast('Las contraseñas nuevas no coinciden.', 'warning'); return; }
    if (newP.length < 6) { toast('La contraseña debe tener al menos 6 caracteres.', 'warning'); return; }
    apiPost('/profile/change-password', { password_actual: oldP, password_nueva: newP }, function() {
      toast('Contraseña cambiada correctamente.', 'success');
      document.getElementById('pwdForm').reset();
    }, function(err) { toast(err, 'error'); });
  };
}

function formField(name, label, val, type) {
  type = type || 'text';
  return '<div class="form-group">' +
    '<label class="form-label">' + escHtml(label) + '</label>' +
    '<input type="' + type + '" class="form-control" name="' + name + '" value="' + escHtml(val || '') + '">' +
  '</div>';
}

function profileSave(payload, successMsg) {
  apiPost('/profile/update', payload, function() {
    // Update local user
    var u = getUser();
    for (var k in payload) { if (Object.prototype.hasOwnProperty.call(payload, k)) u[k] = payload[k]; }
    saveUser(u);
    toast(successMsg, 'success');
  }, function(err) { toast(err, 'error'); });
}

function saveNoCuenta() {
  var val = document.getElementById('noCuenta').value.trim();
  if (!val) { toast('Ingresa el número de cuenta.', 'warning'); return; }
  profileSave({ nocuenta: val }, 'Número de cuenta actualizado.');
}
