"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Open_Sans, Oswald } from "next/font/google";
// import "./globals.css";
import HeaderAfter from "@/components/header-after";
import FooterAfter from "@/components/footer-after";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../../styles/dark-style.css';
import '../../styles/admin-style.css';
import '../../styles/general-style.css';
import '../../styles/dropdown-fixes.css';
import { isValidJWTStructure, isTokenExpired } from '@/lib/jwtUtils';
import { validateTokenWithServer } from '@/lib/authUtils';
import { logger } from '@/lib/logger';




const openSans = Open_Sans({
  subsets: ["latin"],
  variable: "--font-open-sans",
});

const oswald = Oswald({
  subsets: ["latin"],
  variable: "--font-oswald",
});

// export const metadata: Metadata = {
//   title: "Global Influencer Marketing Agency & Platform | TheAgency",
//   description: "We are global Influencer marketing experts offering cutting-edge digital, TikTok, Instagram & YouTube influencer marketing campaigns, content creation, performance tracking and more.",
// };

export default function AuthenticatedLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const [authenticated, setAuthenticated] = useState(false);
  const [checked, setChecked] = useState(false);
  const router = useRouter();

  // Check authentication with server-side validation
  useEffect(() => {
    const checkAuthentication = async () => {
      if (typeof window === "undefined") {
        setChecked(true);
        return;
      }

      const token = localStorage.getItem("access_token");
      
      if (!token) {
        setAuthenticated(false);
        setChecked(true);
        return;
      }

      // Quick client-side validation first
      if (!isValidJWTStructure(token) || isTokenExpired(token)) {
        localStorage.removeItem("access_token");
        setAuthenticated(false);
        setChecked(true);
        return;
      }

      // Server-side validation (async)
      try {
        const isValid = await validateTokenWithServer(token);
        setAuthenticated(isValid);
        
        if (!isValid) {
          localStorage.removeItem("access_token");
        }
      } catch (error) {
        logger.error("Token validation error:", error);
        // On error, fall back to client-side check
        setAuthenticated(!isTokenExpired(token));
      } finally {
        setChecked(true);
      }
    };

    checkAuthentication();
  }, []);

  // Redirect to login if not authenticated
  useEffect(() => {
    if (checked && !authenticated) {
      router.replace("/login");
      // window.location.href = "/login";
    }
  }, [checked, authenticated, router]);

  // While checking auth or if unauthenticated, render nothing
  if (!checked || !authenticated) {
    return null;
  }
  return (
    <div className={`${openSans.variable} ${oswald.variable} antialiased`}>
      {/* <ReactQueryProvider> */}
      <HeaderAfter />
      {children}
      <FooterAfter />
      {/* <FooterBefore /> */}
      {/* </ReactQueryProvider> */}
    </div>
  );
}
