/* eslint-disable @typescript-eslint/no-explicit-any */

import styles from "./dash.module.scss";
import Sidebar from "@/components/dashboard/sidebar";
import Navbar from "@/components/dashboard/navbar";
import Flash from "@/components/shared/Flash";
import { Head, usePage, router } from "@inertiajs/react";
import { useEffect } from "react";

interface FlashProps {
  success?: string | null;
  error?: string | null;
  warning?: string | null;
  info?: string | null;
}

const DashboardLayout = ({ children, title }: any) => {
  const { props } = usePage<{ flash?: FlashProps }>();

  useEffect(() => {
    const handleNavigation = () => {
      // disable inertia restoring scroll
      window.history.scrollRestoration = "manual";

      // wait for render
      requestAnimationFrame(() => {
        const layout = document.querySelector(
          `.${styles.layout}`
        ) as HTMLElement;

        if (layout) {
          layout.scrollTo({
            top: 0,
            behavior: "smooth", // 🔥 smooth animation
          });
        }

        // fallback
        window.scrollTo({
          top: 0,
          behavior: "smooth",
        });
      });
    };

    const removeListener = router.on("navigate", handleNavigation);

    return () => removeListener();
  }, []);

  return (
    <>
      <Head title={title} />

      <Flash
        success={props.flash?.success}
        error={props.flash?.error}
        warning={props.flash?.warning}
        info={props.flash?.info}
      />

      <div className={styles.layout}>
        {/* SIDEBAR */}
        <div className={styles.layout__sidebar}>
          <Sidebar />
        </div>

        {/* CONTENT */}
        <div className={styles.layout__content}>
          {/* NAVBAR */}
          <div className={styles.layout__content__navbar}>
            <Navbar />
          </div>

          {/* CHILDREN */}
          <div className={styles["layout__content--children"]}>
            {children}
          </div>
        </div>
      </div>
    </>
  );
};

export default DashboardLayout;