import { createContext, useContext, useState, useEffect } from 'react'
import { isAuthenticated as checkAuth, clearLoggedIn } from '@/utils/auth'

const AuthContext = createContext()

export function AuthProvider({ children }) {
  const [authenticated, setAuthenticated] = useState(() => {
    return checkAuth()
  })

  useEffect(() => {
    const handleStorageChange = () => {
      setAuthenticated(checkAuth())
    }
    
    window.addEventListener('storage', handleStorageChange)
    return () => window.removeEventListener('storage', handleStorageChange)
  }, [])

  const login = () => {
    setAuthenticated(true)
  }

  const logout = () => {
    clearLoggedIn()
    setAuthenticated(false)
  }

  return (
    <AuthContext.Provider value={{ authenticated, login, logout }}>
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  return useContext(AuthContext)
}