import { createContext, type ReactNode, useContext } from 'react';
import type { Profile } from '@/types/types';
import { useClerkAuthImplementation, useGuestAuthImplementation } from '@/hooks/useAuth';
import { useClerkAvailability } from '@/contexts/ClerkAvailabilityContext';

interface AuthContextType {
  user: any; // Using any for compatibility with existing Supabase User type if needed, but primarily using profile
  profile: Profile | null;
  loading: boolean;
  signOut: () => Promise<void>;
  refreshProfile: () => Promise<void>;
  mockLogin?: (id: string) => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

function ClerkAuthProvider({ children }: { children: ReactNode }) {
  const auth = useClerkAuthImplementation();
  const { user: profile, clerkUser, isLoading, signOut, refreshProfile } = auth;

  if (profile && typeof window !== 'undefined') {
    (window as any).__CURRENT_PROFILE_ID = profile.id;
  } else if (!isLoading && typeof window !== 'undefined') {
    (window as any).__CURRENT_PROFILE_ID = null;
  }

  return (
    <AuthContext.Provider value={{ 
      user: clerkUser, 
      profile, 
      loading: isLoading, 
      signOut, 
      refreshProfile 
    }}>
      {children}
    </AuthContext.Provider>
  );
}

function GuestAuthProvider({ children }: { children: ReactNode }) {
  const auth = useGuestAuthImplementation();
  const { user: profile, isLoading, signOut, refreshProfile, mockLogin } = auth;

  if (profile && typeof window !== 'undefined') {
    (window as any).__CURRENT_PROFILE_ID = profile.id;
  } else if (!isLoading && typeof window !== 'undefined') {
    (window as any).__CURRENT_PROFILE_ID = null;
  }

  return (
    <AuthContext.Provider value={{ 
      user: profile, 
      profile, 
      loading: isLoading, 
      signOut, 
      refreshProfile,
      mockLogin
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export function AuthProvider({ children }: { children: ReactNode }) {
  const { isClerkAvailable, loading: availabilityLoading } = useClerkAvailability();

  if (availabilityLoading) {
    return null; // Or a loader
  }

  if (isClerkAvailable) {
    return <ClerkAuthProvider>{children}</ClerkAuthProvider>;
  }

  return <GuestAuthProvider>{children}</GuestAuthProvider>;
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}
