declare global {
  interface Window {
    Clerk?: {
      session?: {
        getToken: (options?: Record<string, unknown>) => Promise<string>;
      };
    };
  }
}

/**
 * Get a Clerk session JWT without React hooks (works from non-React modules).
 * Returns null if Clerk isn't initialized or user isn't signed in.
 * Retries up to 5 times with 500ms delay to handle Clerk handshake redirect.
 */
export async function getClerkSessionToken(): Promise<string | null> {
  const maxRetries = 5;
  const retryDelay = 500; // ms

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const clerk = typeof window === "undefined" ? undefined : window.Clerk;
      if (clerk?.session?.getToken) {
        const token = await clerk.session.getToken();
        if (token) return token;
      }
    } catch {
      // ignore and retry
    }

    // Only wait if we haven't exhausted retries
    if (attempt < maxRetries - 1) {
      await new Promise((resolve) => setTimeout(resolve, retryDelay));
    }
  }

  return null;
}


