const INVITATION_KEY = 'alqove.pending-invitation';
export const INVITATION_PATH = '/invitations/accept';

/** Only the email landing page reads raw tokens. They never enter auth URLs. */
export function captureInvitation(): string | null {
  const params = new URLSearchParams(window.location.search);
  const token = params.get('token');
  // Scrub first, including on storage failure. Preserve Next's history state.
  window.history.replaceState(window.history.state, '', INVITATION_PATH);
  if (params.has('token')) {
    sessionStorage.removeItem(INVITATION_KEY);
    if (params.getAll('token').length === 1 && token) sessionStorage.setItem(INVITATION_KEY, token);
  }
  return pendingInvitationToken();
}

export function pendingInvitationToken(): string | null {
  try {
    return typeof window === 'undefined' ? null : sessionStorage.getItem(INVITATION_KEY);
  } catch {
    return null;
  }
}

export function clearInvitation(): void {
  sessionStorage.removeItem(INVITATION_KEY);
}

export function authDestination(): string {
  if (pendingInvitationToken()) return INVITATION_PATH;
  const next = typeof window === 'undefined' ? null : new URLSearchParams(window.location.search).get('next');
  return next === '/staff' || next === INVITATION_PATH ? next : '/';
}
