/**
 * Brandy Patterns Library — install/activate prompt (theme-only fallback)
 *
 * Loaded by inc/PatternsLibrary.php ONLY when the Brandy Blocks plugin is
 * NOT active. Registers a PluginSidebar with a pinned icon. Click → modal
 * opens with an install/activate prompt. After successful activation,
 * patterns are fetched via the brandy_get_patterns_after_activation AJAX
 * endpoint and rendered with BlockPatternList in the same modal.
 *
 * Plain wp.element + PluginSidebar — no MutationObserver, no DOM injection,
 * no race conditions, no dual-React.
 */
(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 useCallback = wp.element.useCallback;
  var __ = wp.i18n.__;
  var registerPlugin = wp.plugins.registerPlugin;
  var Modal = wp.components.Modal;
  var Button = wp.components.Button;
  var Spinner = wp.components.Spinner;
  var SearchControl = wp.components.SearchControl;
  var BlockPatternList = wp.blockEditor.__experimentalBlockPatternsList;
  var dispatch = wp.data.dispatch;
  var useSelect = wp.data.useSelect;
  var useDispatch = wp.data.useDispatch;
  var noticesStore = wp.notices && wp.notices.store;

  var PluginSidebar =
    (wp.editSite && wp.editSite.PluginSidebar) ||
    (wp.editPost && wp.editPost.PluginSidebar) ||
    (wp.editor && wp.editor.PluginSidebar);
  if (!PluginSidebar) {
    return;
  }

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

  function closeOurSidebar() {
    ["core/edit-post", "core/edit-site"].forEach(function (ns) {
      var d = dispatch(ns);
      if (d && d.closeGeneralSidebar) {
        d.closeGeneralSidebar();
      }
    });
  }

  var PatternsIcon = 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: "M5.85 7.79l3.16 3.16-3.16 3.16L2.69 10.95l3.16-3.16zm5.17 4.95l3.27 3.27-3.27 3.27-3.27-3.27 3.27-3.27zm5.16-4.94l3.16 3.16-3.16 3.16-3.16-3.16 3.16-3.16zM11.02 2.81l3.27 3.27-3.27 3.27-3.27-3.27 3.27-3.27z",
    })
  );

  // ── Patterns browser (rendered after plugin activation) ───────────

  function PatternsLibraryContent(props) {
    var onCloseDialog = props.onCloseDialog;
    var patternsData = props.patternsData;

    var searchState = useState("");
    var searchValue = searchState[0];
    var setSearchValue = searchState[1];
    var categoryState = useState("brandy-call-to-action");
    var selectedCategory = categoryState[0];
    var setSelectedCategory = categoryState[1];

    var storePatternsData = useSelect(
      function (select) {
        if (patternsData) {
          return { patterns: [], patternCategories: [] };
        }
        var blockEditorStore = select("core/block-editor");
        var coreStore = select("core");
        if (!blockEditorStore || !coreStore) {
          return { patterns: [], patternCategories: [] };
        }
        var settings = blockEditorStore.getSettings();
        var allPatterns =
          (blockEditorStore.__experimentalGetAllowedPatterns &&
            blockEditorStore.__experimentalGetAllowedPatterns()) ||
          [];
        if (allPatterns.length === 0 && settings.__experimentalBlockPatterns) {
          allPatterns = settings.__experimentalBlockPatterns;
        }
        if (allPatterns.length === 0) {
          allPatterns =
            (coreStore.getBlockPatterns && coreStore.getBlockPatterns()) || [];
        }
        var brandyPatterns = allPatterns.filter(function (pattern) {
          return (
            pattern.categories &&
            pattern.categories.some(function (cat) {
              return cat.toLowerCase().indexOf("brandy") !== -1;
            })
          );
        });
        return {
          patterns: brandyPatterns,
          patternCategories:
            (settings.__experimentalBlockPatternCategories || []).filter(
              function (cat) {
                return cat.name.toLowerCase().indexOf("brandy") !== -1;
              }
            ),
        };
      },
      [patternsData]
    );

    var patterns =
      (patternsData && patternsData.patterns) || storePatternsData.patterns;
    var patternCategories =
      (patternsData && patternsData.categories) ||
      storePatternsData.patternCategories;

    var filteredPatterns = useMemo(
      function () {
        var filtered = patterns;
        if (selectedCategory !== "all") {
          filtered = filtered.filter(function (pattern) {
            return (
              pattern.categories &&
              pattern.categories.indexOf(selectedCategory) !== -1
            );
          });
        }
        if (searchValue) {
          filtered = filtered.filter(function (pattern) {
            return (
              pattern.title &&
              pattern.title.toLowerCase().indexOf(searchValue.toLowerCase()) !==
                -1
            );
          });
        }
        return filtered.map(function (pattern) {
          var blocks = pattern.blocks;
          if (!blocks && pattern.content && wp.blocks && wp.blocks.parse) {
            try {
              blocks = wp.blocks.parse(pattern.content);
            } catch (e) {
              blocks = [];
            }
          }
          return Object.assign({}, pattern, {
            name: pattern.name || pattern.slug || "pattern-" + Math.random(),
            title: pattern.title || "Untitled Pattern",
            categories: pattern.categories || [],
            content: pattern.content || "",
            description: pattern.description || "",
            blockTypes: pattern.blockTypes || [],
            blocks: blocks || [],
          });
        });
      },
      [patterns, selectedCategory, searchValue]
    );

    var noticesDispatch = noticesStore ? useDispatch(noticesStore) : {};
    var createSuccessNotice = noticesDispatch.createSuccessNotice;
    var blockEditorDispatch = useDispatch("core/block-editor");
    var insertBlocks = blockEditorDispatch.insertBlocks;

    var onClickPattern = useCallback(
      function (pattern, blocks) {
        var insertionPoint =
          (wp.data.select("core/block-editor").getBlockInsertionPoint() || {})
            .rootClientId || "";
        insertBlocks(blocks, undefined, insertionPoint);
        if (createSuccessNotice) {
          createSuccessNotice('Pattern "' + pattern.title + '" inserted.', {
            type: "snackbar",
            id: "inserter-notice",
          });
        }
        onCloseDialog();
      },
      [insertBlocks, createSuccessNotice, onCloseDialog]
    );

    var categoriesList = useMemo(
      function () {
        if (!patternCategories || patternCategories.length === 0) {
          return [
            {
              name: "all",
              label: __("All Brandy Patterns") || "All Brandy Patterns",
            },
          ];
        }
        var cats = patternCategories
          .slice()
          .sort(function (a, b) {
            return (a.name || "").localeCompare(b.name || "");
          })
          .filter(function (cat) {
            return cat.name !== "brandy";
          });
        return cats.concat([
          {
            name: "all",
            label: __("All Brandy Patterns") || "All Brandy Patterns",
          },
        ]);
      },
      [patternCategories]
    );

    return el(
      "div",
      { className: "block-editor-block-patterns-explorer" },
      el(
        "div",
        { className: "block-editor-block-patterns-explorer__sidebar" },
        el(SearchControl, {
          __nextHasNoMarginBottom: true,
          onChange: setSearchValue,
          value: searchValue,
          label: __("Search") || "Search",
          placeholder: __("Search") || "Search",
          className: "block-editor-block-patterns-explorer__search",
        }),
        el(
          "div",
          {
            className:
              "block-editor-block-patterns-explorer__sidebar__categories-list",
          },
          categoriesList.map(function (cat) {
            return el(
              Button,
              {
                __next40pxDefaultSize: true,
                key: cat.name,
                label: cat.label,
                className:
                  "block-editor-block-patterns-explorer__sidebar__categories-list__item",
                isPressed: selectedCategory === cat.name,
                onClick: function () {
                  setSelectedCategory(cat.name);
                },
              },
              cat.label
            );
          })
        )
      ),
      el(
        "div",
        { className: "block-editor-block-patterns-explorer__list" },
        filteredPatterns.length > 0
          ? el(BlockPatternList, {
              blockPatterns: filteredPatterns,
              onClickPattern: onClickPattern,
              isDraggable: false,
            })
          : el(
              "div",
              {
                style: {
                  padding: "40px",
                  textAlign: "center",
                  color: "#757575",
                },
              },
              el(
                "p",
                null,
                "No patterns found. Try refreshing the page or check if Brandy Blocks is properly activated."
              )
            )
      )
    );
  }

  // ── Sidebar host (install prompt → patterns browser) ──────────────

  function PatternsLibrarySidebar() {
    var installingState = useState(false);
    var isInstalling = installingState[0];
    var setIsInstalling = installingState[1];
    var errorState = useState(null);
    var installError = errorState[0];
    var setInstallError = errorState[1];
    var installedState = useState(false);
    var isPluginInstalled = installedState[0];
    var setIsPluginInstalled = installedState[1];
    var loadingState = useState(false);
    var isLoadingPatterns = loadingState[0];
    var setIsLoadingPatterns = loadingState[1];
    var patternsState = useState(null);
    var patternsData = patternsState[0];
    var setPatternsData = patternsState[1];

    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 data = window.brandyPatternsLibrary || {};
    var isPluginAlreadyInstalled = !!data.isBrandyBlocksInstalled;
    var pluginBasename =
      data.brandyBlocksPluginBasename || "brandy-blocks/brandy-blocks.php";

    var loadPatternsLibrary = function () {
      return new Promise(function (resolve) {
        setTimeout(resolve, 1500);
      }).then(function () {
        var formData = new URLSearchParams();
        formData.append("action", "brandy_get_patterns_after_activation");
        formData.append("nonce", data.patternsNonce);
        formData.append("_nocache", Date.now());
        return fetch(data.ajaxUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cache-Control": "no-cache, no-store, must-revalidate",
            Pragma: "no-cache",
          },
          body: formData.toString(),
        })
          .then(function (r) {
            return r.json();
          })
          .then(function (result) {
            if (!result.success) {
              throw new Error(
                (result.data && result.data.message) || "Failed to fetch patterns"
              );
            }
            setPatternsData(result.data);
          })
          .catch(function () {
            setInstallError(
              "Plugin activated but patterns failed to load. Please refresh the page."
            );
          });
      });
    };

    var handleInstallPlugin = function () {
      setIsInstalling(true);
      setInstallError(null);

      var pluginFile = pluginBasename;
      var pluginName = "Brandy Blocks";

      var installStep = isPluginAlreadyInstalled
        ? Promise.resolve(null)
        : (function () {
            var fd = new URLSearchParams();
            fd.append("action", "install-plugin");
            fd.append("slug", "brandy-blocks");
            fd.append("_wpnonce", data.nonce);
            return fetch(data.ajaxUrl, {
              method: "POST",
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              body: fd.toString(),
            })
              .then(function (r) {
                return r.json();
              })
              .then(function (result) {
                if (!result.success) {
                  throw new Error(
                    (result.data && result.data.errorMessage) ||
                      "Failed to install plugin"
                  );
                }
                pluginFile = (result.data && result.data.plugin) || pluginBasename;
                pluginName = (result.data && result.data.pluginName) || "Brandy Blocks";
                return null;
              });
          })();

      installStep
        .then(function () {
          var fd = new URLSearchParams();
          fd.append("action", "activate-plugin");
          fd.append("slug", "brandy-blocks");
          fd.append("plugin", pluginFile);
          fd.append("name", pluginName);
          fd.append("_wpnonce", data.nonce);
          return fetch(data.ajaxUrl, {
            method: "POST",
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            body: fd.toString(),
          });
        })
        .then(function (r) {
          return r.json();
        })
        .then(function (result) {
          if (!result.success) {
            throw new Error(
              (result.data && result.data.errorMessage) || "Failed to activate plugin"
            );
          }
          setIsLoadingPatterns(true);
          return loadPatternsLibrary();
        })
        .then(function () {
          setIsPluginInstalled(true);
          setIsLoadingPatterns(false);
        })
        .catch(function (error) {
          setInstallError(error.message);
        })
        .finally(function () {
          setIsInstalling(false);
        });
    };

    var modalContent = isLoadingPatterns
      ? el(
          "div",
          {
            className: "brandy-patterns-library-loading",
            style: {
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              padding: "40px",
              flexDirection: "column",
              gap: "20px",
            },
          },
          el(Spinner),
          el("p", null, "Loading patterns library...")
        )
      : isPluginInstalled
      ? el(PatternsLibraryContent, {
          onCloseDialog: closeOurSidebar,
          patternsData: patternsData,
        })
      : el(
          "div",
          { className: "brandy-patterns-library-install-prompt" },
          el(
            "p",
            { className: "brandy-patterns-library-dialog-content" },
            el(
              "span",
              {
                className: "brandy-patterns-library-dialog-content-text",
              },
              isPluginAlreadyInstalled
                ? "Please activate Brandy Blocks plugin to use the patterns library."
                : "Please install Brandy Blocks plugin to use the patterns library."
            )
          ),
          el(
            "button",
            {
              type: "button",
              className: "button button-primary",
              onClick: handleInstallPlugin,
              disabled: isInstalling,
              style: { marginTop: "15px" },
            },
            isInstalling
              ? el(
                  "span",
                  null,
                  el(Spinner),
                  isPluginAlreadyInstalled ? " Activating..." : " Installing..."
                )
              : isPluginAlreadyInstalled
              ? "Activate Plugin"
              : "Install & Activate"
          ),
          installError &&
            el(
              "p",
              {
                className: "brandy-patterns-library-error",
                style: { color: "red", marginTop: "10px" },
              },
              installError
            )
        );

    return el(
      PluginSidebar,
      {
        name: "brandy-patterns-library",
        title: __("Brandy Patterns Library", "brandy"),
        icon: PatternsIcon,
      },
      el(
        "div",
        { style: { padding: 16 } },
        el(
          "p",
          { style: { marginTop: 0 } },
          __("Opening Patterns Library…", "brandy")
        ),
        isOurSidebarActive
          ? el(
              Modal,
              {
                title: __("Brandy Patterns Library", "brandy"),
                onRequestClose: closeOurSidebar,
                isFullScreen: isPluginInstalled,
              },
              el(
                "div",
                { className: "brandy-patterns-library-dialog" },
                modalContent
              )
            )
          : null
      )
    );
  }

  registerPlugin("brandy-patterns-library", { render: PatternsLibrarySidebar });
})();
