"use client"

import { useEffect, useState } from "react"
import { useSession } from "@/lib/auth-client"
import type { Profile } from "@/types"

interface UserState {
  user: { id: string; email: string; name?: string | null } | null
  profile: Profile | null
  loading: boolean
}

export function useUser(): UserState {
  const { data: session, isPending } = useSession()
  const [profile, setProfile] = useState<Profile | null>(null)
  const [profileLoading, setProfileLoading] = useState(true)

  const userId = session?.user?.id

  useEffect(() => {
    let active = true
    if (!userId) {
      setProfile(null)
      setProfileLoading(false)
      return
    }
    setProfileLoading(true)
    fetch("/api/profile")
      .then((r) => (r.ok ? r.json() : { profile: null }))
      .then((data) => {
        if (active) {
          setProfile(data.profile ?? null)
          setProfileLoading(false)
        }
      })
      .catch(() => {
        if (active) {
          setProfile(null)
          setProfileLoading(false)
        }
      })
    return () => {
      active = false
    }
  }, [userId])

  return {
    user: session?.user
      ? { id: session.user.id, email: session.user.email, name: session.user.name }
      : null,
    profile,
    loading: isPending || profileLoading,
  }
}
