'use client';

import { useMe } from '@/lib/hooks/use-players';
import type { Player } from '@/lib/players';
import { createContext, useContext, type ReactNode } from 'react';

export const UserContext = createContext<{
  data: Player | null | undefined;
  isLoading: boolean;
  error: Error | null;
}>({
  data: null,
  isLoading: true,
  error: null
});

/**
 * Custom hook to get the user data from the context.
 *
 * @returns {Player | null | undefined} The user data.
 */
export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
};

export const UserProvider = ({ token, children }: { token: string; children: ReactNode }) => {
  const { data, isLoading, error } = useMe({ token });
  return <UserContext.Provider value={{ data, isLoading, error }}>{children}</UserContext.Provider>;
};
