import { Navigate } from 'react-router-dom';
import {jwtDecode} from 'jwt-decode';

const getCookie = (name) => {
    const cookies = document.cookie.split(';');
    console.log(cookies);
    for (let cookie of cookies) {
      const [key, value] = cookie.trim().split('=');
      if (key === name) {
        return value;
      }
    }
    return null;
  };

  const isTokenValid = (token) => {
    try {
      const decodedToken = jwtDecode(token);
      const currentTime = Date.now() / 1000;
      if (decodedToken.exp < currentTime) {
        return false;
      }
      return true;
    } catch (error) {
      return false;
    }
  };
function ProtectedRoute({ children }) {
// const token = getCookie('access-token');
const token = localStorage.getItem('token');

  if (!token || !isTokenValid(token)) {
    return <Navigate to="/login" />;
  }

  return children;
}

export default ProtectedRoute;
