import React, { useEffect } from "react";
import MobileHeader from "./mobile-header";
import Sidebar, { SidebarProps } from "./sidebar";

export type PanelProps = SidebarProps & { children: JSX.Element };

function Panel({ children, ...sidebarProps }: PanelProps) {
  useEffect(() => {
    const node = document.querySelector(".mobile-menu");

    if (!node) return;

    const openMenu = () => {
      document.querySelector(".layout")?.classList.add("open-menu");
      history.pushState("menu", "");
    };

    const toggleMenu = () => {
      document.querySelector(".layout")?.classList.toggle("open-menu");
    };

    node.addEventListener("click", openMenu, false);
    addEventListener("popstate", toggleMenu);

    return () => {
      node.removeEventListener("click", openMenu);
      removeEventListener("popstate", toggleMenu);
    };
  }, []);

  return (
    <div className="layout">
      <MobileHeader />
      <div className="main-container">
        <Sidebar {...sidebarProps} />
        <div className="content pb-40 mr-40">{children}</div>
      </div>
    </div>
  );
}

export default Panel;
