window.jQuery(document).ready(() => {
  function changeLibraryPosition() {
    if (document.querySelector(".brandy-layout-library-wrapper")) {
      setTimeout(() => {
        if (document.querySelector(".brandy-layout-library-wrapper")) {
          observer.disconnect();
        }
      }, 1000);
      return;
    }

    const Modal = wp.components.Modal;

    const availableLayouts = {
      "brandy//archive-product": [
        {
          id: "brandy/archive-product-1",
          name: "Product list with no sidebar",
          image:
            brandyLayoutLibraryData.asset_url + "images/archive-product-1.png",
        },
        {
          id: "brandy/archive-product-2",
          name: "Product list with filter left sidebar",
          image:
            brandyLayoutLibraryData.asset_url + "images/archive-product-2.png",
        },
        {
          id: "brandy/archive-product-3",
          name: "Product list with filter right sidebar",
          image:
            brandyLayoutLibraryData.asset_url + "images/archive-product-3.png",
        },
        {
          id: "brandy/archive-product-4",
          name: "Product list with no sidebar (grid)",
          image:
            brandyLayoutLibraryData.asset_url + "images/archive-product-4.png",
          disabled: true,
        },
        {
          id: "brandy/archive-product-5",
          name: "Product list with filter left sidebar (grid)",
          image:
            brandyLayoutLibraryData.asset_url + "images/archive-product-5.png",
          disabled: true,
        },
        {
          id: "brandy/archive-product-6",
          name: "Product list with filter right sidebar (grid)",
          image:
            brandyLayoutLibraryData.asset_url + "images/archive-product-6.png",
          disabled: true,
        },
      ],
      "brandy//home": [
        {
          id: "brandy/blog-1",
          name: "Blog with right sidebar",
          image: brandyLayoutLibraryData.asset_url + "images/blog-1.png",
        },
        {
          id: "brandy/blog-2",
          name: "Blog with left sidebar",
          image: brandyLayoutLibraryData.asset_url + "images/blog-2.png",
        },
        {
          id: "brandy/blog-3",
          name: "Blog with no sidebar",
          image: brandyLayoutLibraryData.asset_url + "images/blog-3.png",
        },
        {
          id: "brandy/blog-4",
          name: "Blog with right sidebar (grid)",
          image: brandyLayoutLibraryData.asset_url + "images/blog-4.png",
        },
        {
          id: "brandy/blog-5",
          name: "Blog with left sidebar (grid)",
          image: brandyLayoutLibraryData.asset_url + "images/blog-5.png",
        },
        {
          id: "brandy/blog-6",
          name: "Blog with no sidebar (grid)",
          image: brandyLayoutLibraryData.asset_url + "images/blog-6.png",
        },
      ],
      "brandy//single-product": [
        {
          id: "brandy/single-product-1",
          name: "Single product with bottom thumbnail gallery",
          image:
            brandyLayoutLibraryData.asset_url + "images/single-product-1.png",
        },
        {
          id: "brandy/single-product-2",
          name: "Single product with left thumbnail gallery",
          image:
            brandyLayoutLibraryData.asset_url + "images/single-product-2.png",
        },
        {
          id: "brandy/single-product-3",
          name: "Single product with vertical gallery",
          image:
            brandyLayoutLibraryData.asset_url + "images/single-product-3.png",
        },
        {
          id: "brandy/single-product-4",
          name: "Single product with grid gallery",
          image:
            brandyLayoutLibraryData.asset_url + "images/single-product-4.png",
        },
      ],
      "brandy//about-us": [
        {
          id: "brandy/about-us-1",
          name: "About us 1",
          image: brandyLayoutLibraryData.asset_url + "images/archive-product-6.png",
        },
        {
          id: "brandy/about-us-2",
          name: "About us 2",
          image: brandyLayoutLibraryData.asset_url + "images/archive-product-6.png",
        }
      ],
    };

    // Create a React element for the App using wp.element
    const { createElement, createRoot, useState, useMemo } = wp.element;
    const { Button } = wp.components;
    const { dispatch, select, useSelect } = wp.data;
    const { __experimentalGetAllowedPatterns } = select("core/block-editor");

    const LayoutPicker = ({ closeDialog }) => {
      const [selectedLayout, setSelectedLayout] = useState("");
      const changeLayout = (layout) => {
        const allPatterns = __experimentalGetAllowedPatterns();
        const foundPattern = allPatterns.find(
          (pattern) => pattern.name === layout.id
        );
        if (!foundPattern) {
          return;
        }
        dispatch("core/block-editor").resetBlocks([]);
        setTimeout(() => {
          const insertionPoint =
            wp.data.select("core/block-editor").getBlockInsertionPoint()
              ?.rootClientId || "";
          dispatch("core/block-editor").insertBlocks(
            foundPattern.blocks,
            undefined,
            insertionPoint
          );
        }, 100);
        closeDialog();
      };

      const pageTemplateId = useSelect((select) =>
        select("core/edit-site")?.getEditedPostId()
      );

      const layouts = useMemo(() => {
        if ( !availableLayouts[pageTemplateId] ) {
          return [];
        }
        return availableLayouts[pageTemplateId];
      }, [pageTemplateId]);

      return createElement(
        "div",
        { className: "brandy-layout-library-picker" },
        createElement(
          "div",
          { className: "brandy-layout-library-picker-header" },
          createElement(
            "p",
            { className: "brandy-layout-library-picker-title" },
            "Select a layout"
          ),
          createElement(
            "div",
            { className: "brandy-layout-library-layout-list" },
            layouts.map((layout) =>
              createElement(LayoutItem, {
                layout,
                selectedLayout,
                setSelectedLayout,
              })
            )
          ),
          createElement(
            Button,
            {
              variant: "primary",
              onClick: () => changeLayout(selectedLayout),
              disabled: !selectedLayout,
            },
            "Change Layout"
          )
        )
      );
    };

    const LayoutItem = ({ layout, selectedLayout, setSelectedLayout }) => {
      return createElement(
        "div",
        {
          className: `brandy-layout-library-layout-item${
            selectedLayout.id === layout.id ? " selected" : ""
          }${layout.disabled ? " disabled" : ""}`,
          onClick: () => {
            if (layout.disabled) {
              return;
            }
            setSelectedLayout(layout);
          },
        },
        createElement("img", {
          src: layout.image,
          className: "brandy-layout-library-layout-item-image",
        }),
        createElement(
          "span",
          { className: "brandy-layout-library-layout-item-name" },
          layout.name + (layout.disabled ? " (Coming soon)" : "")
        )
      );
    };

    const App = () => {
      const pageTemplateId = useSelect((select) =>
        select("core/edit-site")?.getEditedPostId()
      );

      const [openDialog, setOpenDialog] = useState(false);

      const handleOpenDialog = () => {
        setOpenDialog(true);
      };

      const isProperPageTemplate = availableLayouts[pageTemplateId] ? true : false;

      return createElement(
        "div",
        { className: "brandy-layout-library-wrapper" },
        isProperPageTemplate &&
          createElement(
            "button",
            { className: "button", onClick: handleOpenDialog },
            "Brandy Layout Library"
          ),
        openDialog &&
          createElement(
            Modal,
            {
              title: "Brandy Layout Library",
              onRequestClose: () => {
                setOpenDialog(false);
              },
              open: openDialog,
              isFullScreen: true,
            },
            createElement(LayoutPicker, {
              closeDialog: () => {
                setOpenDialog(false);
              },
            })
          )
      );
    };

    const library = document.createElement("div");
    createRoot(library).render(createElement(App));

    setTimeout(() => {
      if (document.querySelector(".brandy-layout-library-wrapper")) {
        return;
      }
      document.querySelector(".editor-header__settings").prepend(library);
    }, 1);
  }

  const observer = new MutationObserver(function (mutations) {
    changeLibraryPosition();
  });

  if (!window.wp) {
    return;
  }

  const { registerPlugin } = window.wp.plugins ?? {};
  const { PluginSidebar } = window.wp.editSite ?? window.wp.editPost ?? {};

  if (PluginSidebar) {
    registerPlugin("brandy-layout-library", {
      render: function () {
        const interval = setInterval(() => {
          const targetElement = document.querySelector(
            ".editor-header__settings"
          );

          if (targetElement) {
            observer.observe(
              document.querySelector(".editor-header__settings"),
              {
                childList: true,
                subtree: true,
              }
            );

            changeLibraryPosition();
            clearInterval(interval);
          }
        }, 100);
      },
    });
  }
});
