import { useLocation, useOutlet } from "react-router";
import { useState } from "react";
import Header from "./components/Header";
import Footer from "./components/Footer";
import { AnimatePresence } from "motion/react";
import { motion } from "motion/react";
import { ToastProvider } from "./contexts/Toast";
import { useLoading } from "./hooks/useLoading";
import LoadingBar from "./components/LoadingBar";
import { LoadingProvider } from "./contexts/Loading";

const AnimatedOutlet = () => {
  const o = useOutlet();
  const [outlet] = useState(o);

  return <div>{outlet}</div>;
};

function LoadingBarWrapper() {
  const { isLoading } = useLoading();
  return isLoading ? <LoadingBar /> : null;
}

function App() {
  const location = useLocation();
  return (
    <LoadingProvider>
      <div className="flex flex-col min-h-screen">
        <Header />
        <LoadingBarWrapper />
        <main className="overflow-hidden flex flex-grow transition-color-mode md:p-10 2xl:px-70 bg-surface dark:bg-surface-dark">
          <ToastProvider>
            <AnimatePresence mode="popLayout">
              <motion.div
                className="w-full ovwerflow-hidden"
                key={location.pathname}
                initial={{ opacity: 0, x: 50 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 50 }}
              >
                <AnimatedOutlet />
              </motion.div>
            </AnimatePresence>
          </ToastProvider>
        </main>
        <Footer />
      </div>
    </LoadingProvider>
  );
}

export default App;
