/* ══════════════════════════════════════════════════════════════════════════
   MyKollectOr® — js/auth.js   v1.3
   Login, register, logout, ensureAuth — utilise MKO_API
   ══════════════════════════════════════════════════════════════════════════ */
(function (global) {
  'use strict';

  if (!global.MKO_API) { console.error('[MKO_AUTH] api.js manquant'); return; }
  var API = global.MKO_API;

  function decodeJwt(token) {
    try {
      var parts = token.split('.');
      if (parts.length !== 3) return null;
      var payload = parts[1].replace(/-/g,'+').replace(/_/g,'/');
      return JSON.parse(decodeURIComponent(atob(payload).split('').map(function(c){
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      }).join('')));
    } catch(e) { return null; }
  }

  function isExpired(token) {
    var p = decodeJwt(token);
    if (!p || !p.exp) return true;
    return (Date.now() / 1000) >= (p.exp - 60); /* marge 60s */
  }

  function isAuthenticated() {
    var t = API.getToken();
    return !!(t && !isExpired(t));
  }

  /* ensureAuth : vérifie ou rafraîchit sans jamais rediriger.
     Boot dashboard : afficher login pendant le refresh si nécessaire. */
  function ensureAuth() {
    var t = API.getToken();
    if (t && !isExpired(t)) return Promise.resolve();
    if (!API.getRefreshToken()) return Promise.reject(new Error('no_session'));
    return API.refresh();
  }

  /* requireAuth : pour les pages hors dashboard qui redirigent */
  function requireAuth() {
    return ensureAuth().catch(function() {
      API.clearTokens();
      window.location.href = 'dashboard.html';
      throw new Error('auth_failed');
    });
  }

  /* Login — data retourné : { token, refresh_token, user } */
  function login(email, password) {
    return API.post('/api/auth/login', { email: email, password: password }, { noAuth: true })
      .then(function(data) {
        if (!data || !data.token) throw new Error('login_invalid_response');
        API.setTokens(data.token, data.refresh_token || '');
        return data;
      });
  }

  /* Register — crée compte MKO + PS simultanément */
  function register(prenom, nom, email, password) {
    return API.post('/api/auth/register', { prenom:prenom, nom:nom, email:email, password:password }, { noAuth:true })
      .then(function(data) {
        if (!data || !data.token) throw new Error('register_invalid_response');
        API.setTokens(data.token, data.refresh_token || '');
        return data;
      });
  }

  function logout(opts) {
    opts = opts || {};
    var finish = function() { API.clearTokens(); clearMeCache(); };
    var rt = API.getRefreshToken();
    API.post('/api/auth/logout', rt ? { refresh_token:rt } : {}).then(finish, finish);
  }

  function forgotPassword(email) {
    return API.post('/api/auth/forgot-password', { email:email }, { noAuth:true });
  }

  function resetPassword(token, password) {
    return API.post('/api/auth/reset-password', { token:token, password:password }, { noAuth:true });
  }

  var ME_KEY = 'mko_me_cache';
  function getMe(opts) {
    opts = opts || {};
    if (!opts.fresh) {
      try {
        var c = JSON.parse(localStorage.getItem(ME_KEY)||'null');
        if (c && c.t && (Date.now()-c.t)<60000) return Promise.resolve(c.data);
      } catch(e) {}
    }
    return API.get('/api/auth/me').then(function(data) {
      try { localStorage.setItem(ME_KEY, JSON.stringify({t:Date.now(), data:data})); } catch(e){}
      return data;
    });
  }

  function clearMeCache() { try { localStorage.removeItem(ME_KEY); } catch(e){} }

  global.MKO_AUTH = {
    isAuthenticated: isAuthenticated, ensureAuth: ensureAuth, requireAuth: requireAuth,
    login: login, register: register, logout: logout,
    forgotPassword: forgotPassword, resetPassword: resetPassword,
    getMe: getMe, clearMeCache: clearMeCache,
    decodeJwt: decodeJwt, isExpired: isExpired
  };
})(window);
