"use client"

import type React from "react"

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

interface AuthContextType {
  isLoggedIn: boolean
  login: (username: string, password: string) => Promise<boolean>
  logout: () => void
}

const AuthContext = createContext<AuthContextType>({
  isLoggedIn: false,
  login: async () => false,
  logout: () => {},
})

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

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false)

  useEffect(() => {
    const token = localStorage.getItem("isLoggedIn")
    if (token === "true") {
      setIsLoggedIn(true)
    }
  }, [])

  const login = async (username: string, password: string) => {
    const adminUser = process.env.NEXT_PUBLIC_ADMIN_USER ?? "admin"
    const adminPass = process.env.NEXT_PUBLIC_ADMIN_PASSWORD ?? "admin"
    if (username === adminUser && password === adminPass) {
      localStorage.setItem("isLoggedIn", "true")
      setIsLoggedIn(true)
      return true
    }
    return false
  }

  const logout = () => {
    localStorage.removeItem("isLoggedIn")
    setIsLoggedIn(false)
  }

  return <AuthContext.Provider value={{ isLoggedIn, login, logout }}>{children}</AuthContext.Provider>
}
