/**
 * Sessão do colaborador: validação de token, logout e credenciais lembradas no login.
 */
(function (global) {
  'use strict';

  var LS_TOKEN = 'auth_token';
  var LS_TENANT = 'tenant_slug';
  var LS_EMPLOYEE = 'employee_id';
  var LS_ROLE = 'role';
  var LS_REMEMBER = 'registropro_remember_credentials';
  var LS_SAVED_LOGIN = 'registropro_saved_login';
  var LS_SAVED_PASSWORD = 'registropro_saved_password';
  var LS_LAST_USER = 'registropro_last_login_user';

  var PUBLIC_PAGES = {
    'login.html': true,
    'splash.html': true,
    'index.html': true,
    'reset_passowrd.html': true,
    'reset_passowrd_selfie.html': true,
    'senha_alterada_sucesso.html': true
  };

  var sessionCheckPromise = null;
  var redirecting = false;
  var SESSION_VALID_CACHE_KEY = 'registropro_session_valid_at';
  var SESSION_CACHE_MS = 10 * 60 * 1000;
  var sessionGuardDebounceTimer = null;

  function safeGet(key) {
    try {
      return global.localStorage ? global.localStorage.getItem(key) : null;
    } catch (e) {
      return null;
    }
  }

  function safeSet(key, value) {
    try {
      if (global.localStorage) global.localStorage.setItem(key, value);
    } catch (e) {}
  }

  function safeRemove(key) {
    try {
      if (global.localStorage) global.localStorage.removeItem(key);
    } catch (e) {}
  }

  function currentPageName() {
    try {
      var path = (global.location && global.location.pathname) || '';
      var parts = path.split('/');
      return (parts[parts.length - 1] || '').toLowerCase();
    } catch (e) {
      return '';
    }
  }

  function isPublicPage(page) {
    page = page || currentPageName();
    return !!PUBLIC_PAGES[page];
  }

  function encodeSecret(value) {
    try {
      return global.btoa(unescape(encodeURIComponent(String(value || ''))));
    } catch (e) {
      return String(value || '');
    }
  }

  function decodeSecret(value) {
    if (!value) return '';
    try {
      return decodeURIComponent(escape(global.atob(String(value))));
    } catch (e) {
      return String(value);
    }
  }

  function registroProGetAuthToken() {
    var t = safeGet(LS_TOKEN);
    return t && String(t).trim() ? String(t).trim() : '';
  }

  function registroProIsRememberCredentialsEnabled() {
    return safeGet(LS_REMEMBER) === '1';
  }

  function registroProLoadRememberedCredentials() {
    if (!registroProIsRememberCredentialsEnabled()) {
      return { login: '', password: '' };
    }
    return {
      login: decodeSecret(safeGet(LS_SAVED_LOGIN) || ''),
      password: decodeSecret(safeGet(LS_SAVED_PASSWORD) || '')
    };
  }

  function registroProSaveRememberedCredentials(login, password, enabled) {
    if (enabled) {
      safeSet(LS_REMEMBER, '1');
      safeSet(LS_SAVED_LOGIN, encodeSecret(login));
      safeSet(LS_SAVED_PASSWORD, encodeSecret(password));
      if (login) safeSet(LS_LAST_USER, String(login).trim());
      return;
    }
    safeRemove(LS_REMEMBER);
    safeRemove(LS_SAVED_LOGIN);
    safeRemove(LS_SAVED_PASSWORD);
  }

  function registroProApplyRememberedCredentialsToForm(userInput, passwordInput, rememberCheckbox) {
    if (!userInput && !passwordInput) return;
    var creds = registroProLoadRememberedCredentials();
    if (creds.login && userInput) userInput.value = creds.login;
    if (creds.password && passwordInput) passwordInput.value = creds.password;
    if (!creds.login && userInput) {
      var lastUser = safeGet(LS_LAST_USER);
      if (lastUser) userInput.value = lastUser;
    }
    if (rememberCheckbox) rememberCheckbox.checked = registroProIsRememberCredentialsEnabled();
  }

  function registroProClearAuthSession(options) {
    options = options || {};
    clearSessionCache();
    var keepRemember = options.keepRememberCredentials !== false;
    var preserveKeys = ['registropro_timeline_events', 'API_BASE_URL', 'ponto_bio_registered'];
    if (keepRemember && registroProIsRememberCredentialsEnabled()) {
      preserveKeys.push(LS_REMEMBER, LS_SAVED_LOGIN, LS_SAVED_PASSWORD, LS_LAST_USER);
    }
    var preserved = {};
    preserveKeys.forEach(function (k) {
      var v = safeGet(k);
      if (v !== null) preserved[k] = v;
    });
    try {
      if (global.localStorage) global.localStorage.clear();
    } catch (e) {}
    Object.keys(preserved).forEach(function (k) {
      safeSet(k, preserved[k]);
    });
    try {
      if (global.sessionStorage) global.sessionStorage.clear();
    } catch (e2) {}
  }

  function registroProRedirectToLogin(reason) {
    if (redirecting) return;
    redirecting = true;
    var page = currentPageName();
    if (page === 'login.html') {
      redirecting = false;
      return;
    }
    var url = 'login.html';
    if (reason) {
      url += '?reason=' + encodeURIComponent(String(reason));
    }
    try {
      global.location.replace(url);
    } catch (e) {
      global.location.href = url;
    }
  }

  function markSessionCacheValid() {
    try {
      if (global.sessionStorage) {
        global.sessionStorage.setItem(SESSION_VALID_CACHE_KEY, String(Date.now()));
      }
    } catch (e) {}
  }

  function isSessionCacheFresh() {
    try {
      if (!global.sessionStorage) return false;
      var raw = global.sessionStorage.getItem(SESSION_VALID_CACHE_KEY);
      var t = parseInt(raw || '0', 10);
      if (!t) return false;
      return Date.now() - t < SESSION_CACHE_MS;
    } catch (e2) {
      return false;
    }
  }

  function clearSessionCache() {
    try {
      if (global.sessionStorage) global.sessionStorage.removeItem(SESSION_VALID_CACHE_KEY);
    } catch (e) {}
  }

  function registroProValidateAuthToken() {
    var token = registroProGetAuthToken();
    if (!token) {
      return Promise.resolve({ valid: false, reason: 'no_token' });
    }
    if (typeof registroProGetProfileApiUrl !== 'function') {
      return Promise.resolve({ valid: true, reason: 'no_api', data: null });
    }
    var url = registroProGetProfileApiUrl();
    var tenantSlug = safeGet(LS_TENANT);
    var employeeId = safeGet(LS_EMPLOYEE);
    if (tenantSlug && employeeId && url.indexOf('tenant_slug=') === -1) {
      url += (url.indexOf('?') >= 0 ? '&' : '?') +
        'tenant_slug=' + encodeURIComponent(tenantSlug) +
        '&employee_id=' + encodeURIComponent(employeeId);
    }
    return fetch(url, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        Authorization: 'Bearer ' + token
      },
      cache: 'no-store'
    })
      .then(function (res) {
        return res
          .json()
          .catch(function () {
            return null;
          })
          .then(function (json) {
            if (res.ok && json && json.ok === true && json.data) {
              return { valid: true, data: json.data };
            }
            if (res.status === 401 || res.status === 403) {
              return { valid: false, reason: 'invalid_token', status: res.status };
            }
            if (token) {
              return { valid: true, reason: 'soft_fail', status: res.status, data: null };
            }
            return { valid: false, reason: 'invalid_token', status: res.status };
          });
      })
      .catch(function () {
        if (token) {
          return { valid: true, reason: 'network', data: null };
        }
        return { valid: false, reason: 'network' };
      });
  }

  function registroProEnsureValidSession(options) {
    options = options || {};
    if (isPublicPage()) {
      return Promise.resolve(true);
    }
    var token = registroProGetAuthToken();
    if (!token) {
      registroProClearAuthSession({ keepRememberCredentials: true });
      registroProRedirectToLogin('no_session');
      return Promise.resolve(false);
    }
    if (!options.force && isSessionCacheFresh()) {
      return Promise.resolve(true);
    }
    if (sessionCheckPromise && !options.force) {
      return sessionCheckPromise;
    }
    sessionCheckPromise = registroProValidateAuthToken().then(function (result) {
      sessionCheckPromise = null;
      if (result.valid) {
        markSessionCacheValid();
        if (result.data && result.data.employee_id != null) {
          safeSet(LS_EMPLOYEE, String(result.data.employee_id));
        }
        return true;
      }
      if (result.reason === 'invalid_token') {
        registroProClearAuthSession({ keepRememberCredentials: true });
        registroProRedirectToLogin('session_expired');
        return false;
      }
      if (registroProGetAuthToken()) {
        markSessionCacheValid();
        return true;
      }
      registroProClearAuthSession({ keepRememberCredentials: true });
      registroProRedirectToLogin('session_expired');
      return false;
    });
    return sessionCheckPromise;
  }

  function registroProInstallSessionGuard() {
    if (isPublicPage()) return;

    function runCheck(force) {
      registroProEnsureValidSession({ force: !!force });
    }

    function scheduleCheck(force) {
      if (sessionGuardDebounceTimer) {
        clearTimeout(sessionGuardDebounceTimer);
        sessionGuardDebounceTimer = null;
      }
      sessionGuardDebounceTimer = setTimeout(function () {
        sessionGuardDebounceTimer = null;
        runCheck(force);
      }, force ? 0 : 400);
    }

    runCheck(true);

    global.document.addEventListener('resume', function () {
      scheduleCheck(true);
    }, false);
  }

  function registroProBootstrapLoginPage() {
    var params = {};
    try {
      var q = (global.location.search || '').replace(/^\?/, '');
      if (q) {
        q.split('&').forEach(function (pair) {
          var kv = pair.split('=');
          params[decodeURIComponent(kv[0] || '')] = decodeURIComponent(kv[1] || '');
        });
      }
    } catch (e) {}

    var userInput = global.document.getElementById('loginUser');
    var passwordInput = global.document.getElementById('loginPassword');
    var rememberCheckbox = global.document.getElementById('rememberCredentials');

    registroProApplyRememberedCredentialsToForm(userInput, passwordInput, rememberCheckbox);

    var existingToken = registroProGetAuthToken();
    if (!existingToken) {
      if (params.reason === 'session_expired' && global.window && typeof global.window.pushMsg === 'function') {
        global.window.pushMsg('Sua sessão expirou. Entre novamente com CPF ou e-mail e senha.', 'Sessão expirada');
      }
      return;
    }

    registroProValidateAuthToken().then(function (result) {
      if (result.valid) {
        markSessionCacheValid();
        global.location.replace('New_palnel.html');
        return;
      }
      if (result.reason !== 'invalid_token' && existingToken) {
        markSessionCacheValid();
        global.location.replace('New_palnel.html');
        return;
      }
      var hadExpiredToken = !!existingToken;
      registroProClearAuthSession({ keepRememberCredentials: true });
      registroProApplyRememberedCredentialsToForm(userInput, passwordInput, rememberCheckbox);
      if (
        (hadExpiredToken || params.reason === 'session_expired') &&
        global.window &&
        typeof global.window.pushMsg === 'function'
      ) {
        global.window.pushMsg('Sua sessão expirou. Entre novamente com CPF ou e-mail e senha.', 'Sessão expirada');
      }
    });
  }

  function registroProOnLoginSuccess(login, password, rememberEnabled) {
    registroProSaveRememberedCredentials(login, password, !!rememberEnabled);
    if (login) safeSet(LS_LAST_USER, String(login).trim());
    if (typeof global.registroProSyncProfileForScreenCapture === 'function') {
      global.registroProSyncProfileForScreenCapture();
    } else if (typeof global.registroProApplyScreenCapturePolicy === 'function') {
      global.registroProApplyScreenCapturePolicy();
    }
  }

  global.registroProGetAuthToken = registroProGetAuthToken;
  global.registroProIsRememberCredentialsEnabled = registroProIsRememberCredentialsEnabled;
  global.registroProLoadRememberedCredentials = registroProLoadRememberedCredentials;
  global.registroProSaveRememberedCredentials = registroProSaveRememberedCredentials;
  global.registroProApplyRememberedCredentialsToForm = registroProApplyRememberedCredentialsToForm;
  global.registroProClearAuthSession = registroProClearAuthSession;
  global.registroProRedirectToLogin = registroProRedirectToLogin;
  global.registroProValidateAuthToken = registroProValidateAuthToken;
  global.registroProEnsureValidSession = registroProEnsureValidSession;
  global.registroProInstallSessionGuard = registroProInstallSessionGuard;
  global.registroProBootstrapLoginPage = registroProBootstrapLoginPage;
  global.registroProOnLoginSuccess = registroProOnLoginSuccess;

  function boot() {
    var page = currentPageName();
    if (page === 'login.html') {
      registroProBootstrapLoginPage();
      return;
    }
    if (!isPublicPage(page)) {
      registroProInstallSessionGuard();
    }
  }

  if (global.document.readyState === 'loading') {
    global.document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})(typeof window !== 'undefined' ? window : this);
