/**
 * Grid Responsive Layout — shared constants + grid layout controls.
 * Spanning controls are in spanning-controls.js (loaded separately).
 */

function isGridBlock(name) {
  return (
    name === "core/group" ||
    name === "core/post-template" ||
    name === "woocommerce/product-collection"
  );
}

var defaultResponsiveLayout = {
  enabled: false,
  tablet: { columnType: "manual", value: "2" },
  mobile: { columnType: "manual", value: "1" },
};

var defaultResponsiveSpanning = {
  enabled: false,
  tablet: { columnSpan: 1, rowSpan: 1 },
  mobile: { columnSpan: 1, rowSpan: 1 },
};

/* ── Grid Layout: register attribute ── */

function addGridAttributes(settings, name) {
  if (typeof settings.attributes === "undefined") return settings;
  if (!isGridBlock(name)) return settings;
  settings.attributes = Object.assign(settings.attributes, {
    responsiveLayout: { type: "object", default: defaultResponsiveLayout },
  });
  return settings;
}

wp.hooks.addFilter(
  "blocks.registerBlockType",
  "brandy/grid-attribute",
  addGridAttributes
);

/* ── Grid Layout: editor controls HOC ── */

var gridResponsiveLayoutControls = wp.compose.createHigherOrderComponent(
  function (BlockEdit) {
    return function (props) {
      var Fragment = wp.element.Fragment;
      var useMemo = wp.element.useMemo;
      var useCallback = wp.element.useCallback;
      var BlockControls = wp.blockEditor.BlockControls;
      var ToolbarGroup = wp.components.ToolbarGroup;
      var ToolbarButton = wp.components.ToolbarButton;
      var isSelected = props.isSelected;
      var attributes = props.attributes;
      var setAttributes = props.setAttributes;
      var name = props.name;
      var responsiveLayout =
        attributes.responsiveLayout ?? defaultResponsiveLayout;
      var __ = wp.i18n.__;
      var previewDevice = wp.data.useSelect(function (select) {
        return (
          (
            select("core/edit-post") ?? select("core/edit-site")
          )?.__experimentalGetPreviewDeviceType() ?? ""
        ).toLowerCase();
      });

      var isEnabled = responsiveLayout.enabled ?? false;
      var isGridLayout =
        isGridBlock(name) &&
        (attributes.layout?.type === "grid" ||
          attributes.displayLayout?.type === "flex");
      var isResponsivePreview = previewDevice !== "desktop";
      var shouldActivate = isGridLayout && isResponsivePreview;

      // Detect if block uses displayLayout (Product Collection) vs layout (core/group)
      var usesDisplayLayout = !!(attributes.displayLayout && attributes.displayLayout.type === "flex");

      // Hooks must be called unconditionally (React rules of hooks)
      var wrappedAttributes = useMemo(function () {
        if (!shouldActivate || !isEnabled) return attributes;
        var deviceSettings =
          responsiveLayout[previewDevice] ?? responsiveLayout.tablet;
        var columnCount =
          deviceSettings.columnType === "manual"
            ? parseInt(deviceSettings.value)
            : null;

        if (usesDisplayLayout) {
          // Product Collection: feed back via displayLayout.columns
          return Object.assign({}, attributes, {
            displayLayout: Object.assign({}, attributes.displayLayout, {
              columns: columnCount ?? attributes.displayLayout.columns,
            }),
          });
        }

        return Object.assign({}, attributes, {
          layout: Object.assign({}, attributes.layout, {
            columnCount: columnCount,
            minimumColumnWidth:
              deviceSettings.columnType === "auto"
                ? deviceSettings.value
                : null,
          }),
        });
      }, [shouldActivate, isEnabled, previewDevice, responsiveLayout, attributes.layout, attributes.displayLayout, usesDisplayLayout]);

      var wrappedSetAttributes = useCallback(function (newAttrs) {
        // Intercept displayLayout changes (Product Collection)
        if (usesDisplayLayout && newAttrs.displayLayout) {
          var mergedDL = Object.assign({}, attributes.displayLayout, newAttrs.displayLayout);
          var otherAttrs = Object.assign({}, newAttrs);
          delete otherAttrs.displayLayout;

          if (!mergedDL.columns) {
            setAttributes(
              Object.assign({}, otherAttrs, {
                responsiveLayout: defaultResponsiveLayout,
              })
            );
          } else {
            var updatedLayout = Object.assign({}, responsiveLayout, {
              enabled: true,
            });
            updatedLayout[previewDevice] = {
              columnType: "manual",
              value: String(mergedDL.columns),
            };
            setAttributes(
              Object.assign({}, otherAttrs, {
                responsiveLayout: updatedLayout,
              })
            );
          }
          return;
        }

        // Intercept layout changes (core/group, core/post-template)
        if (newAttrs.layout) {
          var merged = Object.assign({}, attributes.layout, newAttrs.layout);
          var hasValue = merged.minimumColumnWidth || merged.columnCount;
          var otherAttrs2 = Object.assign({}, newAttrs);
          delete otherAttrs2.layout;

          if (!hasValue) {
            setAttributes(
              Object.assign({}, otherAttrs2, {
                responsiveLayout: defaultResponsiveLayout,
              })
            );
          } else {
            var columnType = merged.minimumColumnWidth ? "auto" : "manual";
            var value = merged.minimumColumnWidth
              ? merged.minimumColumnWidth
              : String(merged.columnCount ?? 3);
            var updatedLayout2 = Object.assign({}, responsiveLayout, {
              enabled: true,
            });
            updatedLayout2[previewDevice] = {
              columnType: columnType,
              value: value,
            };
            setAttributes(
              Object.assign({}, otherAttrs2, {
                responsiveLayout: updatedLayout2,
              })
            );
          }
          return;
        }
        setAttributes(newAttrs);
      }, [setAttributes, attributes.layout, attributes.displayLayout, responsiveLayout, previewDevice, usesDisplayLayout]);

      var onReset = useCallback(function () {
        setAttributes({ responsiveLayout: defaultResponsiveLayout });
      }, [setAttributes]);

      if (!shouldActivate) {
        return React.createElement(BlockEdit, props);
      }

      var children = [
        React.createElement(
          BlockEdit,
          Object.assign({}, props, {
            attributes: wrappedAttributes,
            setAttributes: wrappedSetAttributes,
          })
        ),
      ];

      if (isSelected && isEnabled) {
        children.push(
          React.createElement(
            BlockControls,
            null,
            React.createElement(
              ToolbarGroup,
              null,
              React.createElement(
                ToolbarButton,
                { onClick: onReset },
                __("Reset responsive")
              )
            )
          )
        );
      }

      return React.createElement(Fragment, null, ...children);
    };
  },
  "GridResponsiveLayoutControls"
);

wp.hooks.addFilter(
  "editor.BlockEdit",
  "brandy/grid-settings-controls",
  gridResponsiveLayoutControls
);

/* ── Grid Layout: editor preview style HOC ── */

var addGridResponsiveLayoutStyle = wp.compose.createHigherOrderComponent(
  function (BlockListBlock) {
    return function (props) {
      var useMemo = wp.element.useMemo;
      var attributes = props.attributes;
      var responsiveLayout =
        attributes.responsiveLayout ?? defaultResponsiveLayout;

      // Memoize style computation to avoid new objects on every render
      var mergedWrapperProps = useMemo(function () {
        var wrapperProps = props.wrapperProps ?? {};
        if (!responsiveLayout.enabled) return wrapperProps;

        var className = (wrapperProps.className || "") + " is-responsive-grid-layout";
        var style = Object.assign({}, wrapperProps.style ?? {}, {
          "--responsive-grid-layout-tablet-columns":
            responsiveLayout.tablet.columnType === "manual"
              ? "repeat(" + responsiveLayout.tablet.value + ", 1fr)"
              : "repeat(auto-fill, minmax(min(" +
                responsiveLayout.tablet.value +
                ", 100%), 1fr))",
          "--responsive-grid-layout-mobile-columns":
            responsiveLayout.mobile.columnType === "manual"
              ? "repeat(" + responsiveLayout.mobile.value + ", 1fr)"
              : "repeat(auto-fill, minmax(min(" +
                responsiveLayout.mobile.value +
                ", 100%), 1fr))",
        });
        return Object.assign({}, wrapperProps, { className: className, style: style });
      }, [responsiveLayout, props.wrapperProps]);

      return React.createElement(
        BlockListBlock,
        Object.assign({}, props, { wrapperProps: mergedWrapperProps })
      );
    };
  },
  "addGridResponsiveLayoutStyle"
);

wp.hooks.addFilter(
  "editor.BlockListBlock",
  "brandy/grid-responsive-layout-settings",
  addGridResponsiveLayoutStyle
);
