import { Clerk } from '@clerk/clerk-js';

const clerkPublishableKey = (import.meta as any).env?.VITE_CLERK_PUBLISHABLE_KEY || '';
const clerkSignInUrl = (import.meta as any).env?.VITE_CLERK_SIGN_IN_URL || '/sign-in';
const clerkSignUpUrl = (import.meta as any).env?.VITE_CLERK_SIGN_UP_URL || '/sign-up';

let clerk: Clerk | null = null;

export function getClerk(): Clerk | null {
  if (clerk) return clerk;

  if (!clerkPublishableKey) {
    console.warn('Clerk publishable key not configured');
    return null;
  }

  clerk = new Clerk(clerkPublishableKey);
  return clerk;
}

export function getClerkUrls() {
  return {
    signInUrl: clerkSignInUrl,
    signUpUrl: clerkSignUpUrl,
  };
}

export async function loadClerk(): Promise<Clerk | null> {
  const instance = getClerk();
  if (!instance) return null;

  try {
    await instance.load();
    return instance;
  } catch (err) {
    console.error('Failed to load Clerk:', err);
    return null;
  }
}
