"use client"

import { createContext, useContext, useState, ReactNode } from "react"
import { currentUser } from "@/data/users"
import type { User } from "@/types"

interface UserContextValue {
  user: User
  updateAvatar: (url: string) => void
}

const UserContext = createContext<UserContextValue | null>(null)

export function UserProvider({ children }: { children: ReactNode }) {
  const [avatar, setAvatar] = useState(currentUser.avatar)

  const user: User = { ...currentUser, avatar }

  return (
    <UserContext.Provider value={{ user, updateAvatar: setAvatar }}>
      {children}
    </UserContext.Provider>
  )
}

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