"use client"

import { createContext, useContext, useState, useCallback, ReactNode } from "react"

type ViewAsRole = "player" | "tournament_admin" | "club_admin" | null

interface RoleSwitcherContextType {
  viewAsRole: ViewAsRole
  setViewAsRole: (role: ViewAsRole) => void
  effectiveRole: string | null
}

const RoleSwitcherContext = createContext<RoleSwitcherContextType | undefined>(undefined)

export function RoleSwitcherProvider({ children }: { children: ReactNode }) {
  const [viewAsRole, setViewAsRole] = useState<ViewAsRole>(null)

  const value = {
    viewAsRole,
    setViewAsRole: useCallback((role: ViewAsRole) => setViewAsRole(role), []),
    effectiveRole: viewAsRole,
  }

  return (
    <RoleSwitcherContext.Provider value={value}>
      {children}
    </RoleSwitcherContext.Provider>
  )
}

export function useRoleSwitcher() {
  const context = useContext(RoleSwitcherContext)
  if (!context) {
    throw new Error("useRoleSwitcher must be used within RoleSwitcherProvider")
  }
  return context
}
