// AuthContext.tsx
"use client"
import { createContext, useContext, useEffect, useState } from "react"

type AuthContextType = {
  loggedIn: boolean                
  setLoggedIn: (value: boolean) => void
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

// -------------------------------------------------------------- داخل لایو اصلی رندر می شود
export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [loggedIn, setLoggedIn] = useState<boolean>(false)

  useEffect(() => {
    const token = localStorage.getItem("loginToken"); 
    setLoggedIn(Boolean(token));
  }, []);
  
  return (
    <AuthContext.Provider value={{ loggedIn, setLoggedIn }}>
      {children}
    </AuthContext.Provider>
  )
}

// -------------------------------------------------------------- جایی که پیام نمایش داده می شود استفاده می شود
// هوک سفارشی برای استفاده راحت‌تر از کانتکست احراز هویت
export function useAuth() {
  const context = useContext(AuthContext)
  if (!context) throw new Error("useAuth must be used within AuthProvider")
  return context
}
