// ERP entry — public site at erp.* ; landing is / ; login and setup linked from there

(function () {

  'use strict';



  function origin() {

    return window.location.origin;

  }



  const HOME = origin() + '/';

  const LOGIN = origin() + '/static/login.html';

  const SETUP = origin() + '/setup';

  const DASHBOARD = origin() + '/static/index.html';

  const TOKEN_KEY = 'token';

  const EXP_KEY = 'token_exp';

  const LOGIN_INTENT_KEY = 'cnp_erp_login_intent';



  function nowSec() {

    return Math.floor(Date.now() / 1000);

  }



  function isAuthenticated() {

    const t = localStorage.getItem(TOKEN_KEY);

    if (!t) return false;

    const exp = parseInt(localStorage.getItem(EXP_KEY) || '0', 10);

    if (exp && nowSec() > exp) return false;

    return true;

  }



  function isOnline() {

    return typeof navigator === 'undefined' || navigator.onLine !== false;

  }



  function pathIncludes(fragment) {

    return (window.location.pathname || '').includes(fragment);

  }



  function isPublicEntryPath() {

    const p = window.location.pathname || '/';

    if (p === '/' || p === '/home') return true;

    if (pathIncludes('cnp-solutions.html')) return true;

    if (pathIncludes('login.html')) return true;

    if (p === '/setup' || p.startsWith('/setup')) return true;

    if (pathIncludes('company-setup.html')) return true;

    return false;

  }



  function markLoginIntent() {

    try {

      sessionStorage.setItem(LOGIN_INTENT_KEY, '1');

    } catch (_) { /* ignore */ }

  }



  function clearLoginIntent() {

    try {

      sessionStorage.removeItem(LOGIN_INTENT_KEY);

    } catch (_) { /* ignore */ }

  }



  function redirectLogin() {
    markLoginIntent();
    window.location.replace(LOGIN + '?from=home');
  }



  function redirectHome() {

    window.location.replace(HOME);

  }



  /** Unauthenticated deep links to ERP app pages → login. */

  function gateToHomeIfNeeded() {

    if (!isOnline() || isAuthenticated()) return false;

    if (isPublicEntryPath()) return false;

    redirectLogin();

    return true;

  }



  function gateDashboardEntry() {

    if (!pathIncludes('index.html')) return false;

    if (!isOnline() || isAuthenticated()) return false;

    redirectLogin();

    return true;

  }



  /** Block bookmarked login URLs unless user came from the public site (or setup). */
  function gateLoginEntry() {
    if (!isOnline() || isAuthenticated()) return false;
    try {
      const params = new URLSearchParams(window.location.search);
      if (params.get('from') === 'home') {
        markLoginIntent();
        return false;
      }
      const p = window.location.pathname || '';
      if (p === '/setup' || p.startsWith('/setup/') || pathIncludes('company-setup.html')) {
        return false;
      }
      try {
        if (sessionStorage.getItem(LOGIN_INTENT_KEY) === '1') {
          return false;
        }
      } catch (_) { /* ignore */ }
      const ref = document.referrer || '';
      if (ref) {
        try {
          const refUrl = new URL(ref);
          if (refUrl.origin === window.location.origin) {
            const rp = refUrl.pathname || '/';
            if (
              rp === '/' || rp === '/home' || pathIncludes('cnp-solutions.html') ||
              rp.startsWith('/static/') || rp === '/setup' || rp.startsWith('/setup/')
            ) {
              markLoginIntent();
              return false;
            }
          }
        } catch (_) { /* ignore bad referrer */ }
      }
    } catch (_) { /* ignore */ }
    redirectHome();
    return true;
  }



  window.CNP_ERP = {

    homeUrl: HOME,

    loginUrl: LOGIN,

    setupUrl: SETUP,

    dashboardUrl: DASHBOARD,

    isOnline,

    isAuthenticated,

    markLoginIntent,

    clearLoginIntent,

    gateToHomeIfNeeded,

    gateDashboardEntry,

    gateLoginEntry,

    loginUrlWithIntent: function () {
      return LOGIN + '?from=home';
    },

    redirectToLogin: function () {
      markLoginIntent();
      window.location.href = LOGIN + '?from=home';
    },

    redirectAfterLogout: function () {

      clearLoginIntent();

      window.location.replace(HOME);

    },

    redirectWhenUnauthenticated: function () {

      markLoginIntent();

      window.location.replace(LOGIN);

    }

  };

})();


