import { useEffect, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { setCredentials, clearCredentials } from '../store/slices/authSlice'

export const useAuthState = () => {
  const [isInitialized, setIsInitialized] = useState(false)
  const isAuthenticated = useSelector(state => state.auth.isAuthenticated)
  const dispatch = useDispatch()

  useEffect(() => {
    const initializeAuth = () => {
      const token = localStorage.getItem('accessToken')
      
      if (token) {
        // Immediately set authentication state to prevent redirect
        dispatch(setCredentials({
          user: { email: 'Loading...' },
          token
        }))
      }
      
      setIsInitialized(true)
    }

    initializeAuth()
  }, [dispatch])

  return {
    isAuthenticated,
    isInitialized
  }
}
