/**
 * Spanning responsive controls — attribute registration, editor HOC, preview style.
 * Depends on script.js for shared constants (defaultResponsiveSpanning).
 */

/* ── Spanning: register attribute ── */

function addSpanningAttributes(settings) {
  if (typeof settings?.attributes === "undefined") return settings;
  settings.attributes = Object.assign(settings.attributes, {
    responsiveSpanning: { type: "object", default: defaultResponsiveSpanning },
  });
  return settings;
}

wp.hooks.addFilter(
  "blocks.registerBlockType",
  "brandy/spanning-attribute",
  addSpanningAttributes
);

/* ── Spanning: editor controls HOC ── */

var spanningResponsiveLayoutControls = wp.compose.createHigherOrderComponent(
  function (BlockEdit) {
    return function (props) {
      var Fragment = wp.element.Fragment;
      var useState = wp.element.useState;
      var useCallback = wp.element.useCallback;
      var BlockControls = wp.blockEditor.BlockControls;
      var ToolbarGroup = wp.components.ToolbarGroup;
      var ToolbarButton = wp.components.ToolbarButton;
      var Popover = wp.components.Popover;
      var NumberControl = wp.components.__experimentalNumberControl;
      var Flex = wp.components.Flex;
      var FlexItem = wp.components.FlexItem;
      var isSelected = props.isSelected;
      var attributes = props.attributes;
      var setAttributes = props.setAttributes;
      var __unstableParentLayout = props.__unstableParentLayout;
      var responsiveSpanning =
        attributes.responsiveSpanning ?? defaultResponsiveSpanning;
      var __ = wp.i18n.__;
      var previewDevice = wp.data.useSelect(function (select) {
        return (
          (
            select("core/edit-post") ?? select("core/edit-site")
          )?.__experimentalGetPreviewDeviceType() ?? ""
        ).toLowerCase();
      });

      var openState = useState(false);
      var isOpen = openState[0];
      var setIsOpen = openState[1];

      var isEnabled = responsiveSpanning.enabled ?? false;
      var isGridChild = __unstableParentLayout?.type === "grid";
      var isDesktop = previewDevice === "desktop";
      var shouldActivate = isGridChild && isSelected;

      var desktopColumnSpan = attributes.style?.layout?.columnSpan ?? 1;
      var desktopRowSpan = attributes.style?.layout?.rowSpan ?? 1;

      var columnSpan, rowSpan;
      if (isDesktop || !shouldActivate) {
        columnSpan = desktopColumnSpan;
        rowSpan = desktopRowSpan;
      } else {
        columnSpan = isEnabled
          ? (responsiveSpanning[previewDevice]?.columnSpan ?? desktopColumnSpan)
          : desktopColumnSpan;
        rowSpan = isEnabled
          ? (responsiveSpanning[previewDevice]?.rowSpan ?? desktopRowSpan)
          : desktopRowSpan;
      }

      // Hooks called unconditionally (React rules of hooks)
      var onChangeColumnSpan = useCallback(function (v) {
        var val = parseInt(v) || 1;
        if (isDesktop) {
          setAttributes({
            style: Object.assign({}, attributes.style, {
              layout: Object.assign({}, attributes.style?.layout ?? {}, {
                columnSpan: val,
              }),
            }),
          });
        } else {
          var updated = Object.assign({}, responsiveSpanning, {
            enabled: true,
          });
          updated[previewDevice] = {
            columnSpan: val,
            rowSpan:
              responsiveSpanning[previewDevice]?.rowSpan ?? desktopRowSpan,
          };
          setAttributes({ responsiveSpanning: updated });
        }
      }, [setAttributes, isDesktop, attributes.style, responsiveSpanning, previewDevice, desktopRowSpan]);

      var onChangeRowSpan = useCallback(function (v) {
        var val = parseInt(v) || 1;
        if (isDesktop) {
          setAttributes({
            style: Object.assign({}, attributes.style, {
              layout: Object.assign({}, attributes.style?.layout ?? {}, {
                rowSpan: val,
              }),
            }),
          });
        } else {
          var updated = Object.assign({}, responsiveSpanning, {
            enabled: true,
          });
          updated[previewDevice] = {
            columnSpan:
              responsiveSpanning[previewDevice]?.columnSpan ??
              desktopColumnSpan,
            rowSpan: val,
          };
          setAttributes({ responsiveSpanning: updated });
        }
      }, [setAttributes, isDesktop, attributes.style, responsiveSpanning, previewDevice, desktopColumnSpan]);

      var onReset = useCallback(function () {
        setAttributes({ responsiveSpanning: defaultResponsiveSpanning });
        setIsOpen(false);
      }, [setAttributes, setIsOpen]);

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

      // Popover content
      var popoverChildren = [
        React.createElement(
          "p",
          {
            style: {
              fontSize: "11px",
              textTransform: "uppercase",
              fontWeight: 500,
              color: "#757575",
              margin: "0 0 12px",
            },
          },
          isDesktop
            ? __("Spanning")
            : __("Responsive Spanning") + " (" + previewDevice + ")"
        ),
        React.createElement(
          Flex,
          { gap: 2 },
          React.createElement(
            FlexItem,
            null,
            React.createElement(NumberControl, {
              __next40pxDefaultSize: true,
              onChange: onChangeColumnSpan,
              min: 1,
              max: 12,
              step: 1,
              value: columnSpan,
              label: __("Column span"),
            })
          ),
          React.createElement(
            FlexItem,
            null,
            React.createElement(NumberControl, {
              __next40pxDefaultSize: true,
              onChange: onChangeRowSpan,
              min: 1,
              max: 12,
              step: 1,
              value: rowSpan,
              label: __("Row span"),
            })
          )
        ),
      ];

      if (!isDesktop && isEnabled) {
        popoverChildren.push(
          React.createElement(ToolbarButton, {
            icon: "undo",
            label: __("Reset responsive spanning"),
            onClick: onReset,
            style: { marginTop: "8px" },
          })
        );
      }

      // Toolbar
      var toolbarChildren = [
        React.createElement(
          ToolbarButton,
          {
            onClick: function () {
              setIsOpen(!isOpen);
            },
            isPressed: isOpen,
          },
          "Col: " + columnSpan + " \u00D7 Row: " + rowSpan
        ),
      ];

      if (isOpen) {
        toolbarChildren.push(
          React.createElement(
            Popover,
            {
              placement: "bottom-start",
              onClose: function () {
                setIsOpen(false);
              },
            },
            React.createElement(
              "div",
              { style: { padding: "16px", minWidth: "200px" } },
              ...popoverChildren
            )
          )
        );
      }

      return React.createElement(
        Fragment,
        null,
        React.createElement(BlockEdit, props),
        React.createElement(
          BlockControls,
          null,
          React.createElement(ToolbarGroup, null, ...toolbarChildren)
        )
      );
    };
  },
  "SpanningResponsiveLayoutControls"
);

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

/* ── Spanning: editor preview style HOC ── */

var addSpanningResponsiveLayoutStyle = wp.compose.createHigherOrderComponent(
  function (BlockListBlock) {
    return function (props) {
      var useMemo = wp.element.useMemo;
      var attributes = props.attributes;
      var responsiveSpanning =
        attributes.responsiveSpanning ?? defaultResponsiveSpanning;

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

        var className = (wrapperProps.className || "") + " has-responsive-spanning";
        var style = Object.assign({}, wrapperProps.style ?? {}, {
          "--responsive-spanning-column-tablet":
            responsiveSpanning.tablet.columnSpan,
          "--responsive-spanning-row-tablet": responsiveSpanning.tablet.rowSpan,
          "--responsive-spanning-column-mobile":
            responsiveSpanning.mobile.columnSpan,
          "--responsive-spanning-row-mobile": responsiveSpanning.mobile.rowSpan,
        });
        return Object.assign({}, wrapperProps, { className: className, style: style });
      }, [responsiveSpanning, props.wrapperProps]);

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

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