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

const AuthContext = createContext(null)

export function AuthProvider({ children }) {
  const [user,    setUser]    = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.get('/api/auth/me')
      .then(d => setUser(d.user))
      .catch(() => setUser(null))
      .finally(() => setLoading(false))
  }, [])

  async function login(identity, password) {
    const d = await api.post('/api/auth/login', { email: identity, username: identity, password })
    setUser(d.user)
    return d.user
  }

  async function signup(username, email, password) {
    const d = await api.post('/api/auth/signup', { username, email, password })
    setUser(d.user)
    return d.user
  }

  async function logout() {
    await api.post('/api/auth/logout', {}).catch(() => {})
    setUser(null)
  }

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

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