import { createContext, useContext, useState, useEffect } from 'react'
import { getMe } from '../api'

const UserContext = createContext(null)

export function UserProvider({ children, token, onLogout }) {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!token) {
      setUser(null)
      setLoading(false)
      return
    }

    getMe(token)
      .then(data => {
        setUser(data)
        setLoading(false)
      })
      .catch(() => {
        onLogout()
        setLoading(false)
      })
  }, [token])

  const value = {
    user,
    token,
    loading,
    role: user?.role || 'user',
    isGuest: user?.isGuest || user?.role === 'guest',
    isModerator: ['moderator', 'superadmin'].includes(user?.role),
    isSuperadmin: user?.role === 'superadmin'
  }

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

export function useUser() {
  const context = useContext(UserContext)
  if (!context) {
    throw new Error('useUser must be used within UserProvider')
  }
  return context
}
