import React, { useEffect } from "react";
import "../styles/remixicon.css";
import "react-tabs/style/react-tabs.css";
import "swiper/css";
import "swiper/css/bundle";
// Chat Styles
import "../styles/chat.css";
// Globals Styles
import "../styles/globals.css";
// Rtl Styles
import "../styles/rtl.css";
// Dark Mode Styles
import "../styles/dark.css";
// Theme Styles
import theme from "../styles/theme";
import { SnackbarProvider } from "notistack";
import { ThemeProvider, CssBaseline } from "@mui/material";
import Layout from "@/components/_App/Layout";
import { UserProfileProvider } from "contexts/userProfileContext";
import { useRouter } from "next/router";
import { hasCookie } from "cookies-next";

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  const handlePopState = () => {
    // Check if the user is logged in or if you need to redirect them after logout
    if (!hasCookie("cmc-token")) {
      router.push("/auth/login");
    }
  };

  // Attach the event handler when the component mounts
  useEffect(() => {
    window.onpopstate = handlePopState;

    // Clean up the event handler when the component unmounts
    return () => {
      window.onpopstate = null;
    };
  }, []);

  return (
    <>
      <Head>
        <title>{!hasCookie("cmc-token") && "CMC - auth"}</title>
      </Head>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <UserProfileProvider>
          <SnackbarProvider
            maxSnack={3}
            autoHideDuration={2000}
            preventDuplicate
          >
            <Layout>
              <Component {...pageProps} />
            </Layout>
          </SnackbarProvider>
        </UserProfileProvider>
      </ThemeProvider>
    </>
  );
}

export default MyApp;
