import { createContext, useContext, useState, useEffect } from 'react'
import { useAuth } from './AuthContext'

const ProfileContext = createContext(null)

export function ProfileProvider({ children }) {
  const { session } = useAuth()
  const [profiles,      setProfiles]      = useState([])
  const [activeProfile, setActiveProfileState] = useState(null)
  const [loading,       setLoading]       = useState(true)

  const loadProfiles = async () => {
    try {
      const token = localStorage.getItem('bodytrack_token') || ''
      const res = await fetch('/api/profiles', {
        headers: { 'X-Auth-Token': token }
      })
      if (!res.ok) return []
      return await res.json()
    } catch(e) { return [] }
  }

  // Re-load whenever session changes (login/logout/switch)
  useEffect(() => {
    if (!session) {
      setActiveProfileState(null)
      setProfiles([])
      setLoading(false)
      return
    }
    setLoading(true)
    loadProfiles().then(data => {
      setProfiles(data)
      // Always use the profile_id from the session token – not localStorage
      const match = data.find(p => p.id === session.profile_id)
      setActiveProfileState(match || data[0] || null)
      setLoading(false)
    })
  }, [session?.profile_id])  // re-runs when profile changes

  const setActiveProfile = (profile) => {
    setActiveProfileState(profile)
    localStorage.setItem('bodytrack_active_profile', profile.id)
  }

  const refreshProfiles = () => loadProfiles().then(data => {
    setProfiles(data)
    if (activeProfile) {
      const updated = data.find(p => p.id === activeProfile.id)
      if (updated) setActiveProfileState(updated)
    }
  })

  return (
    <ProfileContext.Provider value={{ profiles, activeProfile, setActiveProfile, refreshProfiles, loading }}>
      {children}
    </ProfileContext.Provider>
  )
}

export function useProfile() {
  return useContext(ProfileContext)
}
