(function(){
  document.addEventListener('DOMContentLoaded', function(){
    const form = document.getElementById('loginForm');
    if (!form) return;
    // Helpers de cookies
    function setCookie(name, value, days){
      const d = new Date();
      d.setTime(d.getTime() + (days*24*60*60*1000));
      const expires = 'expires=' + d.toUTCString();
      const sameSite = 'SameSite=Lax';
      const secure = (location.protocol === 'https:') ? '; Secure' : '';
      document.cookie = name + '=' + encodeURIComponent(value) + '; ' + expires + '; path=/; ' + sameSite + secure;
    }
    function getCookie(name){
      const n = name + '=';
      const ca = document.cookie.split(';');
      for (let c of ca){
        while (c.charAt(0) === ' ') c = c.substring(1);
        if (c.indexOf(n) === 0) return decodeURIComponent(c.substring(n.length, c.length));
      }
      return '';
    }
    function deleteCookie(name){
      document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax';
    }

    // Prefill desde cookies
    const userInput = document.getElementById('usuario');
    const passInput = document.getElementById('clave');
    const rememberChk = document.getElementById('recordar');
    const savedUser = getCookie('remember_user');
    const savedPass = getCookie('remember_pass');
    if (savedUser) { userInput.value = savedUser; }
    if (savedPass) { passInput.value = savedPass; }
    if (rememberChk) { rememberChk.checked = !!(savedUser || savedPass); }

    form.addEventListener('submit', function(e){
      e.preventDefault();
      const usuario = document.getElementById('usuario').value.trim();
      const clave = document.getElementById('clave').value;
      const recordar = document.getElementById('recordar') ? document.getElementById('recordar').checked : false;
      const submitBtn = form.querySelector('button[type="submit"]');
      const original = submitBtn ? submitBtn.innerHTML : '';
      if (submitBtn){ submitBtn.disabled = true; submitBtn.innerHTML = 'Ingresando…'; }
      $.ajax({
        url: '/api/login',
        method: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({usuario, clave})
      }).done(function(resp){
        if (resp && resp.success) {
          // Guardar / limpiar cookies según "Recordar"
          if (recordar) {
            // 10 años
            setCookie('remember_user', usuario, 3650);
            setCookie('remember_pass', clave, 3650);
          } else {
            deleteCookie('remember_user');
            deleteCookie('remember_pass');
          }
          mostrarToast('Login correcto', { type: 'success', delay: 1500 });
          setTimeout(function(){ window.location.href = '/'; }, 300);
        } else {
          mostrarToast((resp && (resp.msg || resp.message)) ? (resp.msg || resp.message) : 'Error de login', { type: 'danger' });
        }
      }).fail(function(xhr){
        const msg = (xhr.responseJSON && (xhr.responseJSON.msg || xhr.responseJSON.message)) ? (xhr.responseJSON.msg || xhr.responseJSON.message) : 'Error de login';
        mostrarToast(msg, { type: 'danger' });
      }).always(function(){
        if (submitBtn){ submitBtn.disabled = false; submitBtn.innerHTML = original; }
      });
    });
  });
})();
