"use client"
import { useEffect, useState } from "react";
import { jwtDecode } from 'jwt-decode';  // Corrected import
import LoginPage from "@/app/login/page";
import DashboardPage from "@/app/dashboard/page";

export default function Home() {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);

  useEffect(() => {
    const token = localStorage.getItem("token");

    // If token exists and is not expired, set authentication to true
    if (token && !isTokenExpired(token)) {
      setIsAuthenticated(true);
    } else {
      localStorage.removeItem("token"); // Remove token if it's expired or invalid
      setIsAuthenticated(false); // Ensure authentication state is false
    }
  }, []);

  const isTokenExpired = (token: string): boolean => {
    try {
      const decoded: { exp?: number } = jwtDecode(token); // Decode the token
      const currentTime = Date.now() / 1000; // Get the current time in seconds
      // Check if the token has expired
      return decoded.exp ? decoded.exp < currentTime : true;
    } catch (e) {
      // If decoding fails, consider the token as invalid or expired
      console.error("Invalid token", e);
      return true;
    }
  };

  return isAuthenticated ? <DashboardPage /> : <LoginPage />;
}
