(function (wp) {
  const { registerBlockType } = wp.blocks;
  const { InspectorControls, PanelColorSettings, useBlockProps } = wp.blockEditor;
  const { PanelBody, TextControl, SelectControl } = wp.components;

  registerBlockType("fjord/section-pill", {
    edit: (props) => {
      const { attributes, setAttributes } = props;
      const blockProps = useBlockProps({ className: "fjord-favorites__pill" });

      const style = {};
      if (attributes.backgroundColor) {
        style.background = attributes.backgroundColor;
      }
      if (attributes.textColor) {
        style.color = attributes.textColor;
      }

      const options = [
        { label: "Our Favorites", value: "favorites" },
        { label: "Collections", value: "collections" },
        { label: "About Us", value: "about" },
        { label: "Personalizado", value: "custom" },
      ];

      const presetLabels = {
        favorites: "Our Favorites",
        collections: "Collections",
        about: "About Us",
      };

      const resolvedTitle =
        attributes.preset && attributes.preset !== "custom"
          ? presetLabels[attributes.preset] || "Our Favorites"
          : attributes.title || "Section Title";

      return wp.element.createElement(
        wp.element.Fragment,
        null,
        wp.element.createElement(
          InspectorControls,
          null,
          wp.element.createElement(
            PanelBody,
            { title: "Title", initialOpen: true },
            wp.element.createElement(SelectControl, {
              label: "Preset",
              value: attributes.preset || "favorites",
              options,
              onChange: (value) => setAttributes({ preset: value }),
            }),
            wp.element.createElement(TextControl, {
              label: "Texto personalizado",
              value: attributes.title,
              onChange: (value) => setAttributes({ title: value }),
              disabled: attributes.preset !== "custom",
            })
          ),
          wp.element.createElement(PanelColorSettings, {
            title: "Colors",
            colorSettings: [
              {
                label: "Background",
                value: attributes.backgroundColor,
                onChange: (value) => setAttributes({ backgroundColor: value }),
              },
              {
                label: "Text",
                value: attributes.textColor,
                onChange: (value) => setAttributes({ textColor: value }),
              },
            ],
          })
        ),
        wp.element.createElement(
          "div",
          Object.assign({}, blockProps, { style }),
          wp.element.createElement("h2", null, resolvedTitle)
        )
      );
    },
    save: () => null,
  });
})(window.wp);
