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

const UserContext = createContext(null)

export function UserProvider({ children, token }) {
  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(() => {
        // Token invalid, clear it
        localStorage.removeItem('gsm_token')
        setUser(null)
        setLoading(false)
      })
  }, [token])

  // Get Discord avatar URL
  const getAvatarUrl = () => {
    if (!user?.discordId || !user?.avatar) {
      return null
    }
    return `https://cdn.discordapp.com/avatars/${user.discordId}/${user.avatar}.png?size=64`
  }

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

  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
}
