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

const AuthContext = createContext(null)

export function AuthProvider({ children }) {
  const [token, setToken] = useState(() => localStorage.getItem('hejyou_token'))
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!token) { setLoading(false); return }
    getMe(token)
      .then(setUser)
      .catch(() => { localStorage.removeItem('hejyou_token'); setToken(null) })
      .finally(() => setLoading(false))
  }, [token])

  const saveToken = (t) => { localStorage.setItem('hejyou_token', t); setToken(t) }
  const logout = () => { localStorage.removeItem('hejyou_token'); setToken(null); setUser(null) }

  return (
    <AuthContext.Provider value={{ token, user, setUser, saveToken, logout, loading }}>
      {children}
    </AuthContext.Provider>
  )
}

export const useAuth = () => useContext(AuthContext)
