export function isTokenExpired(token: string): boolean {
  try {
    const payload = JSON.parse(atob(token.split('.')[1])) as { exp?: number }
    if (!payload || !payload.exp) {
      console.log('Token has no expiration data')
      return true
    }

    const currentTime = Math.floor(Date.now() / 1000)
    const isExpired = payload.exp < currentTime
    console.log(`Token expiration check: exp=${payload.exp}, now=${currentTime}, expired=${isExpired}`)
    return isExpired
  } catch (error) {
    console.log('Token validation error:', error)
    return true
  }
}

export function clearExpiredToken(): void {
  const token = localStorage.getItem('authToken')
  if (token && isTokenExpired(token)) {
    console.log('Clearing expired token from localStorage')
    localStorage.removeItem('authToken')
  } else if (token) {
    console.log('Token exists and is valid')
  } else {
    console.log('No token in localStorage')
  }
}