import React, { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion, useCycle } from "framer-motion";
import { Outlet } from "react-router-dom";
import Navbar from "./Components/Navbar";
import Sidebar from "./Components/Sidebar";
import Footer from "./Components/Footer";
const itemVariants = {
  closed: {
    opacity: 0,
  },
  open: { opacity: 1 },
};
const sideVariants = {
  closed: {
    transition: {
      staggerChildren: 0.2,
      staggerDirection: -1,
    },
  },
  open: {
    transition: {
      staggerChildren: 0.2,
      staggerDirection: 1,
    },
  },
};
const Root = () => {
  const [sideBarOpen, setSideBarOpen] = useCycle(false, true);
  const sideNav = useRef();
  useEffect(() => {
      function handleClickOutside(event) {
        if (sideNav.current && !sideNav.current.contains(event.target)) {
          setSideBarOpen(false);
        }
      }
      // Bind the event listener
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        // Unbind the event listener on clean up
        document.removeEventListener("mousedown", handleClickOutside);
      };
  }, [sideNav]);

  return (
    <div className="xl:max-w-6xl mx-auto">
      <Navbar sideBarOpen={sideBarOpen} openSideBar={setSideBarOpen} />
      <div className="flex">
        <AnimatePresence>
          {sideBarOpen && (
            <motion.aside
              className="fixed w-full sm:w-fit min-h-screen h-[100vh] overflow-y-auto z-40"
              ref={sideNav}
              initial={{ width: 0 }}
              animate={{
                width: 300,
              }}
              exit={{
                width: 0,
                transition: { delay: 0.7, duration: 0.3 },
              }}
            >
              <motion.div
                className="container"
                initial="closed"
                animate="open"
                exit="closed"
                variants={sideVariants}
              >
                <Sidebar onClose={() => setSideBarOpen(false)} />
              </motion.div>
            </motion.aside>
          )}
        </AnimatePresence>
        <div id="detail" className="py-3 mt-24 px-2 w-full">
          <Outlet />
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Root;
