const RESPONSIVE_CONDITIONS_PRIORITY = 100;

/**
 * WP 7.0+ bridge helpers (isHiddenForDevice, toggleHidden) live in
 * script-helpers.js, enqueued as a hard dep of this file. Pull the API into
 * locals for readability.
 */
const { isHiddenForDevice, toggleHidden } =
  window.BrandyResponsiveConditionsHelpers || {};

/** Register attributes on all blocks */
function addResponsiveConditionsAttribute(settings) {
  if (typeof settings.attributes === "undefined") {
    return settings;
  }
  settings.attributes = Object.assign(settings.attributes, {
    hideOnDesktop: {
      type: "boolean",
      default: false,
      attribute: "data-hide-on-desktop",
    },
    hideOnTablet: {
      type: "boolean",
      default: false,
      attribute: "data-hide-on-tablet",
    },
    hideOnMobile: {
      type: "boolean",
      default: false,
      attribute: "data-hide-on-mobile",
    },
  });
  return settings;
}

wp.hooks.addFilter(
  "blocks.registerBlockType",
  "brandy/responsive-conditions-attribute",
  addResponsiveConditionsAttribute
);

/** SVG icon helper */
function rcSvg(paths) {
  return React.createElement(
    "svg",
    {
      xmlns: "http://www.w3.org/2000/svg",
      viewBox: "0 0 24 24",
      width: 24,
      height: 24,
      fill: "currentColor",
    },
    ...paths.map((d) => React.createElement("path", { d }))
  );
}

/** Device icons — visible state */
const RC_ICONS = {
  desktop: rcSvg(["M4 5h16v10H4V5zm2 2v6h12V7H6zm-2 12h16v-1H4v1z"]),
  tablet: rcSvg(["M7 3h10a1 1 0 011 1v16a1 1 0 01-1 1H7a1 1 0 01-1-1V4a1 1 0 011-1zm1 2v14h8V5H8zm4 13a1 1 0 100-2 1 1 0 000 2z"]),
  mobile: rcSvg(["M9 3h6a1 1 0 011 1v16a1 1 0 01-1 1H9a1 1 0 01-1-1V4a1 1 0 011-1zm1 2v14h4V5h-4zm2 13a1 1 0 100-2 1 1 0 000 2z"]),
};

/** Device icons — hidden state (with diagonal slash) */
const RC_ICONS_HIDDEN = {
  desktop: rcSvg([
    "M4 5h16v10H4V5zm2 2v6h12V7H6zm-2 12h16v-1H4v1z",
    "M3.7 2.3a1 1 0 00-1.4 1.4l18 18a1 1 0 001.4-1.4l-18-18z",
  ]),
  tablet: rcSvg([
    "M7 3h10a1 1 0 011 1v16a1 1 0 01-1 1H7a1 1 0 01-1-1V4a1 1 0 011-1zm1 2v14h8V5H8zm4 13a1 1 0 100-2 1 1 0 000 2z",
    "M3.7 2.3a1 1 0 00-1.4 1.4l18 18a1 1 0 001.4-1.4l-18-18z",
  ]),
  mobile: rcSvg([
    "M9 3h6a1 1 0 011 1v16a1 1 0 01-1 1H9a1 1 0 01-1-1V4a1 1 0 011-1zm1 2v14h4V5h-4zm2 13a1 1 0 100-2 1 1 0 000 2z",
    "M3.7 2.3a1 1 0 00-1.4 1.4l18 18a1 1 0 001.4-1.4l-18-18z",
  ]),
};

const RC_DEVICES = [
  { key: "hideOnDesktop", device: "desktop", label: "Desktop" },
  { key: "hideOnTablet", device: "tablet", label: "Tablet" },
  { key: "hideOnMobile", device: "mobile", label: "Mobile" },
];

/** Toolbar with 3 device visibility toggle buttons */
const ResponsiveConditionsControls = wp.compose.createHigherOrderComponent(
  (BlockEdit) => {
    return (props) => {
      const { Fragment } = wp.element;
      const { ToolbarButton, ToolbarGroup } = wp.components;
      const { BlockControls } = wp.blockEditor;
      const { __ } = wp.i18n;
      const { attributes, setAttributes, isSelected } = props;

      return React.createElement(
        Fragment,
        null,
        React.createElement(BlockEdit, props),
        isSelected &&
          React.createElement(
            BlockControls,
            null,
            React.createElement(
              ToolbarGroup,
              null,
              RC_DEVICES.map((d) => {
                const isHidden = isHiddenForDevice(attributes, d.key);
                return React.createElement(ToolbarButton, {
                  key: d.key,
                  icon: isHidden
                    ? RC_ICONS_HIDDEN[d.device]
                    : RC_ICONS[d.device],
                  label: isHidden
                    ? __(`Show on ${d.label}`, "brandy")
                    : __(`Hide on ${d.label}`, "brandy"),
                  isPressed: isHidden,
                  onClick: () =>
                    toggleHidden(setAttributes, attributes, d.key, !isHidden),
                });
              })
            )
          )
      );
    };
  },
  "ResponsiveConditionsControls"
);

wp.hooks.addFilter(
  "editor.BlockEdit",
  "brandy/responsive-conditions-controls",
  ResponsiveConditionsControls,
  RESPONSIVE_CONDITIONS_PRIORITY
);

/** Add data attributes to saved block HTML */
function addResponsiveConditionsProps(props, blockType, attributes) {
  const { hideOnDesktop, hideOnTablet, hideOnMobile } = attributes;
  if (hideOnDesktop) {
    Object.assign(props, { "data-hide-on-desktop": "true" });
  }
  if (hideOnTablet) {
    Object.assign(props, { "data-hide-on-tablet": "true" });
  }
  if (hideOnMobile) {
    Object.assign(props, { "data-hide-on-mobile": "true" });
  }
  return props;
}

wp.hooks.addFilter(
  "blocks.getSaveContent.extraProps",
  "brandy/responsive-conditions-props",
  addResponsiveConditionsProps,
  RESPONSIVE_CONDITIONS_PRIORITY
);

/** Editor indicator showing which devices are hidden */
const AddResponsiveConditionsStyle = wp.compose.createHigherOrderComponent(
  (BlockListBlock) => {
    return (props) => {
      const { attributes } = props;

      const hideOns = [];
      if (isHiddenForDevice(attributes, "hideOnDesktop")) hideOns.push("Desktop");
      if (isHiddenForDevice(attributes, "hideOnTablet")) hideOns.push("Tablet");
      if (isHiddenForDevice(attributes, "hideOnMobile")) hideOns.push("Mobile");

      const wrapperProps = {
        ...(props.wrapperProps ?? {}),
        ...(hideOns.length > 0
          ? { "data-hide-ons": hideOns.join(", ") }
          : {}),
      };

      return React.createElement(BlockListBlock, {
        ...props,
        wrapperProps,
      });
    };
  },
  "AddResponsiveConditionsStyle"
);

wp.hooks.addFilter(
  "editor.BlockListBlock",
  "brandy/responsive-conditions-style",
  AddResponsiveConditionsStyle,
  RESPONSIVE_CONDITIONS_PRIORITY
);
