import {
  createContext,
  useState,
  useEffect
} from "react"

export const AuthContext = createContext()

export function AuthProvider({ children }) {

  // 🔥 AMBIL USER DARI LOCAL STORAGE
  const [user, setUser] = useState(() => {

    const savedUser = localStorage.getItem("user")

    return savedUser
      ? JSON.parse(savedUser)
      : null
  })

  // 🔥 SIMPAN USER KE LOCAL STORAGE
  useEffect(() => {

    if (user) {

      localStorage.setItem(
        "user",
        JSON.stringify(user)
      )

    } else {

      localStorage.removeItem("user")

    }

  }, [user])

  // 🔥 LOGIN
  const login = (data) => {
    setUser(data)
  }

  // 🔥 LOGOUT
  const logout = () => {
    setUser(null)
  }

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