import { createContext, useContext, useState, useEffect, ReactNode } from 'react'

interface AuthContextType {
    isLoggedIn: boolean
    token: string | null
    login: (token: string) => void
    logout: () => void
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export const AuthProvider = ({ children }: { children: ReactNode }) => {
    const [token, setToken] = useState<string | null>(null)

    useEffect(() => {
        const saved = localStorage.getItem('access_token')
        if (saved) setToken(saved)
    }, [])

    const login = (newToken: string) => {
        localStorage.setItem('access_token', newToken)
        setToken(newToken)
    }

    const logout = () => {
        localStorage.removeItem('access_token')
        setToken(null)
    }

    return (
        <AuthContext.Provider value={{ isLoggedIn: !!token, token, login, logout }}>
            {children}
        </AuthContext.Provider>
    )
}

export const useAuth = () => {
    const context = useContext(AuthContext)
    if (!context) throw new Error('useAuth must be used within AuthProvider')
    return context
}
