/**
 * Brandy Layout Library
 *
 * Registers a PluginSidebar that pins an icon to the editor's top-right
 * toolbar. Click the icon → sidebar opens with a launcher → click "Open
 * Layout Library" → fullscreen modal opens with the LayoutPicker.
 *
 * Stable, official path — no MutationObserver, no DOM injection, no race
 * conditions, no dual-React risk (everything renders through wp.element's
 * React end-to-end).
 */
(function () {
  if (!window.wp || !window.wp.plugins || !window.wp.element) {
    return;
  }

  var el = wp.element.createElement;
  var useState = wp.element.useState;
  var useMemo = wp.element.useMemo;
  var __ = wp.i18n.__;
  var registerPlugin = wp.plugins.registerPlugin;
  var Modal = wp.components.Modal;
  var Button = wp.components.Button;
  var dispatch = wp.data.dispatch;
  var select = wp.data.select;
  var useSelect = wp.data.useSelect;

  var SIDEBAR_KEY = "brandy-layout-library/brandy-layout-library";

  function closeOurSidebar() {
    // Dispatch on both editors — only the active one's call has effect, the
    // other is a no-op. Belt-and-braces against editor-context detection.
    ["core/edit-post", "core/edit-site"].forEach(function (ns) {
      var d = dispatch(ns);
      if (d && d.closeGeneralSidebar) {
        d.closeGeneralSidebar();
      }
    });
  }

  // Use the site editor's PluginSidebar if available, otherwise post editor.
  var PluginSidebar =
    (wp.editSite && wp.editSite.PluginSidebar) ||
    (wp.editPost && wp.editPost.PluginSidebar) ||
    (wp.editor && wp.editor.PluginSidebar);
  if (!PluginSidebar) {
    return;
  }

  var 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" },
    ],
  };

  var LayoutIcon = el(
    "svg",
    {
      xmlns: "http://www.w3.org/2000/svg",
      viewBox: "0 0 24 24",
      width: 24,
      height: 24,
      "aria-hidden": "true",
      focusable: "false",
    },
    el("path", {
      d: "M18 5.5H6c-.8 0-1.5.7-1.5 1.5v10c0 .8.7 1.5 1.5 1.5h12c.8 0 1.5-.7 1.5-1.5V7c0-.8-.7-1.5-1.5-1.5zm0 1.5v2H6V7h12zM6 17v-6.5h12V17H6z",
    })
  );

  function LayoutItem(props) {
    var layout = props.layout;
    var selectedLayout = props.selectedLayout;
    var setSelectedLayout = props.setSelectedLayout;
    return el(
      "div",
      {
        className:
          "brandy-layout-library-layout-item" +
          (selectedLayout.id === layout.id ? " selected" : "") +
          (layout.disabled ? " disabled" : ""),
        onClick: function () {
          if (layout.disabled) return;
          setSelectedLayout(layout);
        },
      },
      el("img", {
        src: layout.image,
        className: "brandy-layout-library-layout-item-image",
      }),
      el(
        "span",
        { className: "brandy-layout-library-layout-item-name" },
        layout.name + (layout.disabled ? " (Coming soon)" : "")
      )
    );
  }

  function LayoutPicker(props) {
    var closeDialog = props.closeDialog;
    var selectedState = useState("");
    var selectedLayout = selectedState[0];
    var setSelectedLayout = selectedState[1];

    var pageTemplateId = useSelect(function (select) {
      return select("core/edit-site") && select("core/edit-site").getEditedPostId();
    }, []);

    var layouts = useMemo(function () {
      return availableLayouts[pageTemplateId] || [];
    }, [pageTemplateId]);

    var changeLayout = function (layout) {
      var allPatterns = select("core/block-editor").__experimentalGetAllowedPatterns();
      var foundPattern = allPatterns.find(function (p) {
        return p.name === layout.id;
      });
      if (!foundPattern) return;
      dispatch("core/block-editor").resetBlocks([]);
      setTimeout(function () {
        var insertionPoint =
          (wp.data.select("core/block-editor").getBlockInsertionPoint() || {})
            .rootClientId || "";
        dispatch("core/block-editor").insertBlocks(
          foundPattern.blocks,
          undefined,
          insertionPoint
        );
      }, 100);
      closeDialog();
    };

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

  function LayoutLibrarySidebar() {
    var pageTemplateId = useSelect(function (select) {
      return select("core/edit-site") && select("core/edit-site").getEditedPostId();
    }, []);

    var isProperPageTemplate = !!availableLayouts[pageTemplateId];

    // Modal mount state is bound DIRECTLY to whether our sidebar is the
    // active one — single source of truth, no useState/useEffect dance.
    // Closing the modal (X / ESC / pick a layout) all route through
    // closeOurSidebar, which flips isOurSidebarActive false → modal
    // unmounts on the same render. No flash, no double-render.
    var isOurSidebarActive = useSelect(function (select) {
      var post = select("core/edit-post");
      var site = select("core/edit-site");
      var name =
        (post && post.getActiveGeneralSidebarName && post.getActiveGeneralSidebarName()) ||
        (site && site.getActiveGeneralSidebarName && site.getActiveGeneralSidebarName());
      return name === SIDEBAR_KEY;
    }, []);

    var showModal = isOurSidebarActive && isProperPageTemplate;

    return el(
      PluginSidebar,
      {
        name: "brandy-layout-library",
        title: __("Brandy Layout Library", "brandy"),
        icon: LayoutIcon,
      },
      el(
        "div",
        { style: { padding: 16 } },
        isProperPageTemplate
          ? el(
              "p",
              { style: { marginTop: 0 } },
              __("Opening Layout Library…", "brandy")
            )
          : el(
              "p",
              { style: { marginTop: 0 } },
              __(
                "Layout Library is available on supported templates: archive-product, home, single-product, about-us.",
                "brandy"
              )
            ),
        showModal &&
          el(
            Modal,
            {
              title: __("Brandy Layout Library", "brandy"),
              onRequestClose: closeOurSidebar,
              isFullScreen: true,
            },
            el(LayoutPicker, { closeDialog: closeOurSidebar })
          )
      )
    );
  }

  registerPlugin("brandy-layout-library", { render: LayoutLibrarySidebar });
})();
