type SessionExpiredListener = () => void;

export const SESSION_EXPIRED_EVENT = 'ehandyhire:session-expired';
export const SESSION_REVOKED_KEY = 'ehandyhire:session-revoked';

export function isPortalPath(pathname: string) {
  return pathname.startsWith('/worker') || pathname.startsWith('/customer');
}

export function onSessionExpired(listener: SessionExpiredListener): () => void {
  if (typeof window === 'undefined') return () => {};

  const handler = () => listener();
  window.addEventListener(SESSION_EXPIRED_EVENT, handler);
  return () => window.removeEventListener(SESSION_EXPIRED_EVENT, handler);
}

export function emitSessionExpired() {
  if (typeof window === 'undefined') return;
  window.dispatchEvent(new CustomEvent(SESSION_EXPIRED_EVENT));
}

/** Notify other browser tabs that this session was ended (logout or invalidation). */
export function broadcastSessionRevoked() {
  if (typeof window === 'undefined') return;
  localStorage.setItem(SESSION_REVOKED_KEY, String(Date.now()));
}

export function hasStoredAccessToken() {
  if (typeof window === 'undefined') return false;
  return Boolean(localStorage.getItem('accessToken'));
}

export function shouldNotifySessionExpired(endpoint: string, status: number, hadAuth: boolean) {
  if (status !== 401 || !hadAuth) return false;
  if (typeof window === 'undefined') return false;

  const publicAuthEndpoints = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/logout'];
  return !publicAuthEndpoints.some((path) => endpoint.startsWith(path));
}

export function shouldShowSessionExpiredModal() {
  if (typeof window === 'undefined') return false;
  return isPortalPath(window.location.pathname);
}
