// Auth Bootstrap - Synchronous auth state restoration
// This script MUST load first to prevent race conditions with navbar/API calls
(function () {
  'use strict';

  const TOKEN_KEY = 'token';
  const USER_KEY = 'user';
  const EXP_KEY = 'token_exp';

  function nowSec() { return Math.floor(Date.now() / 1000); }

  function getStoredToken() { return localStorage.getItem(TOKEN_KEY); }
  function getStoredUser() {
    try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); }
    catch { return null; }
  }
  function isTokenValid() {
    const t = getStoredToken();
    if (!t) return false;
    const exp = parseInt(localStorage.getItem(EXP_KEY) || '0', 10);
    if (exp && nowSec() > exp) {
      // Token expired - clean up
      localStorage.removeItem(TOKEN_KEY);
      localStorage.removeItem(USER_KEY);
      localStorage.removeItem(EXP_KEY);
      return false;
    }
    return true;
  }

  // NOTE: Removed aggressive early auth check that was causing premature redirects
  // Let individual pages handle auth requirements via auth.requireAuth() after DOM loads
  // This prevents race conditions where token hasn't loaded yet

  // Create minimal auth object immediately for other scripts
  window.authBootstrap = {
    isAuthenticated: () => isTokenValid(),
    getToken: getStoredToken,
    getUser: getStoredUser,
    authHeader: () => {
      const t = getStoredToken();
      return t ? { 'Authorization': 'Bearer ' + t } : {};
    }
  };

  // Install global fetch wrapper immediately to ensure auth headers
  if (!window.__authFetchBootstrapped) {
    window.__authFetchBootstrapped = true;
    const origFetch = window.fetch.bind(window);
    window.fetch = async function (input, init) {
      let headersObj = {};
      const url = typeof input === 'string' ? input : (input && input.url ? input.url : String(input));
      const optionalEndpoints = [
        '/api/v1/settings',
        '/api/v1/notifications',
        '/api/v1/roles/permissions',
        '/api/v1/admin/users',
        '/api/v1/branches'
      ];
      const isOptionalEndpoint = optionalEndpoints.some(ep => url.includes(ep));
      const isLoginPage = window.location.pathname.includes('login.html');

      try {
        init = init || {};
        init.headers = init.headers || {};

        if (init.headers instanceof Headers) {
          init.headers.forEach((v, k) => { headersObj[k] = v; });
        } else if (Array.isArray(init.headers)) {
          init.headers.forEach(([k, v]) => { headersObj[k] = v; });
        } else {
          headersObj = { ...init.headers };
        }

        const hasAuth = Object.keys(headersObj).some(k => k.toLowerCase() === 'authorization');
        if (!hasAuth && window.authBootstrap && window.authBootstrap.getToken()) {
          headersObj = { ...headersObj, ...window.authBootstrap.authHeader() };
        }

        init.headers = headersObj;
      } catch (e) {
        console.warn('[auth-bootstrap] Error in fetch wrapper:', e);
      }

      let resp = await origFetch(input, init);
      const token = window.authBootstrap && window.authBootstrap.getToken();

      if (resp.ok && token && window.auth && typeof window.auth.recordActivity === 'function') {
        try { window.auth.recordActivity(); } catch (_) { /* ignore */ }
      }

      if (resp.status === 401 && token && !isLoginPage && !isOptionalEndpoint
          && url.includes('/api/v1/') && !url.includes('/api/v1/auth/refresh')
          && window.auth && typeof window.auth.authHeader === 'function') {
        try {
          const refreshResp = await origFetch('/api/v1/auth/refresh', {
            method: 'POST',
            headers: window.auth.authHeader(),
          });
          if (refreshResp.ok) {
            const data = await refreshResp.json();
            if (data.access_token) {
              const base64 = data.access_token.split('.')[1];
              const json = atob(base64.replace(/-/g, '+').replace(/_/g, '/'));
              const payload = JSON.parse(json);
              localStorage.setItem(TOKEN_KEY, data.access_token);
              if (payload.exp) localStorage.setItem(EXP_KEY, payload.exp);
              console.log('[auth-bootstrap] Token refreshed after 401 — retrying request');
              const retryHeaders = { ...headersObj, Authorization: 'Bearer ' + data.access_token };
              resp = await origFetch(input, { ...init, headers: retryHeaders });
              if (resp.ok && window.auth && typeof window.auth.recordActivity === 'function') {
                try { window.auth.recordActivity(); } catch (_) { /* ignore */ }
              }
            }
          }
        } catch (e) {
          console.warn('[auth-bootstrap] Refresh-on-401 failed:', e);
        }
      }

      if (resp.status === 401 && !isOptionalEndpoint && !isLoginPage) {
        console.log('[auth-bootstrap] 401 on protected API — redirecting to login');
        console.log('[auth-bootstrap] URL:', url);
        localStorage.removeItem(TOKEN_KEY);
        localStorage.removeItem(USER_KEY);
        localStorage.removeItem(EXP_KEY);
        const returnTo = encodeURIComponent(window.location.pathname + window.location.search);
        window.location.replace('/static/login.html?return=' + returnTo);
      }

      return resp;
    };
  }

  console.log('[auth-bootstrap] Auth state initialized, token valid:', isTokenValid());
})();
