// ── Provider: User Context ──
// Fetches the current authenticated user on mount via /api/auth/me,
// provides logout (POSTs to /api/auth/logout and redirects to /login),
// and an updateAvatar helper to optimistically update the user object.

"use client"

import { createContext, useContext, useState, useEffect, ReactNode, useCallback } from "react"
import { useRouter } from "next/navigation"
import type { User } from "@/types"

interface UserContextValue {
  user: User | null
  loading: boolean
  error: string | null
  logout: () => Promise<void>
  updateAvatar: (url: string) => void
}

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

/**
 * UserProvider — fetches the authenticated user session on mount.
 * Provides user data, loading/error states, logout, and avatar update helpers.
 */
export function UserProvider({ children }: { children: ReactNode }) {
  const router = useRouter()
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchUser = useCallback(async () => {
    try {
      const res = await fetch("/api/auth/me")
      if (res.ok) {
        const data = await res.json()
        const u = data.user
        setUser({
          id: u.id,
          name: `${u.firstName} ${u.lastName}`,
          email: u.email,
          role: u.role,
          active: true,
          avatar: u.avatar,
          createdAt: new Date().toISOString(),
        })
      } else {
        setUser(null)
      }
    } catch {
      console.warn("Failed to fetch user in user provider")
      setUser(null)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchUser()
  }, [fetchUser])

  const logout = useCallback(async () => {
    try {
      await fetch("/api/auth/logout", { method: "POST" })
    } catch {
      console.warn("Failed to logout in user provider")
    }
    setUser(null)
    router.push("/login")
  }, [router])

  const updateAvatar = useCallback((url: string) => {
    setUser((prev) => (prev ? { ...prev, avatar: url } : prev))
  }, [])

  return (
    <UserContext.Provider value={{ user, loading, error, logout, updateAvatar }}>
      {children}
    </UserContext.Provider>
  )
}

/**
 * useUser — hook to access the user context.
 * Must be called within a UserProvider tree.
 */
export function useUser() {
  const ctx = useContext(UserContext)
  if (!ctx) throw new Error("useUser must be used within UserProvider")
  return ctx
}
