import { useEffect, useRef, useState } from "react";
import dynamic from 'next/dynamic';
import allNavData from "../../../data/navData.json";
import ScrollTop from "../ScrollTop";
import { Toaster } from "react-hot-toast";
import Preloader from "@/components/preloader/Preloader";
import CommonAnimation from "../CommonAnimation";
import ScrollSmootherComponents from "../ScrollSmootherComponents";

// Dynamic imports for headers and footers
const Header1 = dynamic(() => import("@/components/header/Header1"));
const Header2 = dynamic(() => import("@/components/header/Header2"));
const Header3 = dynamic(() => import("@/components/header/Header3"));
const Header4 = dynamic(() => import("@/components/header/Header4"));
const Header5 = dynamic(() => import("@/components/header/Header5"));
const Footer1 = dynamic(() => import("@/components/footer/Footer1"));
const Footer2 = dynamic(() => import("@/components/footer/Footer2"));
const Footer3 = dynamic(() => import("@/components/footer/Footer3"));
const Footer4 = dynamic(() => import("@/components/footer/Footer4"));
const Footer5 = dynamic(() => import("@/components/footer/Footer5"));

// Header component map for better performance
const headerComponents = {
  header1: Header1,
  header2: Header2,
  header3: Header3,
  header4: Header4,
  header5: Header5
};

// Footer component map for better performance
const footerComponents = {
  footer1: Footer1,
  footer2: Footer2,
  footer3: Footer3,
  footer4: Footer4,
  footer5: Footer5
};

const HeaderContent = ({ header, navData }) => {
  const HeaderComponent = headerComponents[header] || Header3;
  return header === "none" ? null : <HeaderComponent navData={navData} />;
};

const FooterContent = ({ footer }) => {
  const FooterComponent = footerComponents[footer] || Footer3;
  return footer === "none" ? null : <FooterComponent />;
};

export default function RootLayout({
  children,
  header = "",
  footer = "",
  defaultMode = "",
}) {
  const [mode, setMode] = useState(defaultMode);
  const [navData, setNavData] = useState({});

  useEffect(() => {
    setNavData(allNavData);
    if (mode === "dark") {
      document.body.classList.add("dark");
    } else {
      document.body.classList.remove("dark");
    }
  }, [mode]);

  return (
    <CommonAnimation>
      <div className="has-smooth" id="has_smooth">
        <ScrollSmootherComponents />
        <ScrollTop />
        <Toaster position="bottom-center" />
        <Preloader />
        <HeaderContent header={header} navData={navData} />
        <div id="smooth-wrapper">
          <div id="smooth-content">
            {children}
            <FooterContent footer={footer} />
          </div>
        </div>
      </div>
    </CommonAnimation>
  );
}