/**
 * ImageObjectPosition - Block editor focal point controls
 *
 * Adds FocalPointPicker (toolbar popover + sidebar) to image blocks
 * when scale=cover. Stores objectPosition as {x, y} (0-1 range).
 *
 * Supported: core/image, core/post-featured-image, woocommerce/product-image
 */
(function () {
  var el = wp.element.createElement;
  var useState = wp.element.useState;
  var Fragment = wp.element.Fragment;
  var __ = wp.i18n.__;
  var addFilter = wp.hooks.addFilter;
  var createHigherOrderComponent = wp.compose.createHigherOrderComponent;
  var InspectorControls = wp.blockEditor.InspectorControls;
  var BlockControls = wp.blockEditor.BlockControls;
  var PanelBody = wp.components.PanelBody;
  var ToolbarGroup = wp.components.ToolbarGroup;
  var ToolbarButton = wp.components.ToolbarButton;
  var Popover = wp.components.Popover;
  var FocalPointPicker = wp.components.FocalPointPicker;
  var useSelect = wp.data.useSelect;

  var SUPPORTED_BLOCKS = [
    "core/image",
    "core/post-featured-image",
    "woocommerce/product-image",
  ];

  function isSupported(name) {
    return SUPPORTED_BLOCKS.indexOf(name) !== -1;
  }

  // ── Attribute registration ──────────────────────────────────────

  function registerObjectPositionAttribute(settings) {
    if (typeof settings.attributes === "undefined") {
      return settings;
    }
    if (!isSupported(settings.name)) {
      return settings;
    }
    settings.attributes.objectPosition = { type: "object" };
    return settings;
  }

  addFilter(
    "blocks.registerBlockType",
    "brandy/image-object-position-attribute",
    registerObjectPositionAttribute
  );

  // ── Image URL resolution per block type ─────────────────────────

  function useImageUrl(blockName, attributes) {
    // core/image: URL directly available (no useSelect needed)
    var isFeaturedImage = blockName === "core/post-featured-image";

    // Get featured media ID first (re-runs when featured image changes)
    var featuredMediaId = useSelect(
      function (select) {
        if (!isFeaturedImage) return 0;
        try {
          var editorStore = select("core/editor");
          return editorStore
            ? editorStore.getEditedPostAttribute("featured_media") || 0
            : 0;
        } catch (e) {
          return 0;
        }
      },
      [isFeaturedImage]
    );

    // Resolve media URL from ID (re-runs when featuredMediaId changes)
    var featuredUrl = useSelect(
      function (select) {
        if (!isFeaturedImage || !featuredMediaId) return "";
        var media = select("core").getMedia(featuredMediaId);
        return media ? media.source_url : "";
      },
      [isFeaturedImage, featuredMediaId]
    );

    if (blockName === "core/image") {
      return attributes.url || "";
    }

    if (isFeaturedImage) {
      return featuredUrl || "";
    }

    // woocommerce/product-image: no direct URL, picker works without preview
    return "";
  }

  // ── Focal point crosshair icon (SVG) ────────────────────────────

  var focalPointIcon = el(
    "svg",
    {
      xmlns: "http://www.w3.org/2000/svg",
      viewBox: "0 0 24 24",
      width: 24,
      height: 24,
      fill: "none",
      stroke: "currentColor",
      strokeWidth: 1.5,
    },
    // Crosshair lines
    el("line", { x1: 12, y1: 2, x2: 12, y2: 8 }),
    el("line", { x1: 12, y1: 16, x2: 12, y2: 22 }),
    el("line", { x1: 2, y1: 12, x2: 8, y2: 12 }),
    el("line", { x1: 16, y1: 12, x2: 22, y2: 12 }),
    // Center circle
    el("circle", { cx: 12, cy: 12, r: 3 })
  );

  // ── ObjectPositionControls component ────────────────────────────

  function ObjectPositionControls(props) {
    var attributes = props.attributes;
    var setAttributes = props.setAttributes;
    var blockName = props.name;
    var scale = attributes.scale || "";

    // Only show when scale is cover
    if (scale !== "cover") {
      return null;
    }

    var objectPosition = attributes.objectPosition || { x: 0.5, y: 0.5 };
    var popoverState = useState(false);
    var isPopoverOpen = popoverState[0];
    var setIsPopoverOpen = popoverState[1];

    var imageUrl = useImageUrl(blockName, attributes);

    function onChangePosition(value) {
      setAttributes({ objectPosition: value });
    }

    return el(
      Fragment,
      null,
      // Toolbar button with popover
      el(
        BlockControls,
        { group: "other" },
        el(
          ToolbarGroup,
          null,
          el(ToolbarButton, {
            icon: focalPointIcon,
            label: __("Focal Point", "brandy"),
            onClick: function () {
              setIsPopoverOpen(!isPopoverOpen);
            },
            isPressed: isPopoverOpen,
          }),
          isPopoverOpen &&
            el(
              Popover,
              {
                onClose: function () {
                  setIsPopoverOpen(false);
                },
                placement: "bottom",
              },
              el(
                "div",
                {
                  style: {
                    padding: "16px",
                    minWidth: "250px",
                  },
                },
                el(
                  "p",
                  {
                    style: {
                      marginTop: 0,
                      marginBottom: "8px",
                      fontWeight: 600,
                      fontSize: "11px",
                      textTransform: "uppercase",
                    },
                  },
                  __("Object Position", "brandy")
                ),
                el(FocalPointPicker, {
                  url: imageUrl,
                  value: objectPosition,
                  onChange: onChangePosition,
                })
              )
            )
        )
      ),
      // Sidebar control
      el(
        InspectorControls,
        null,
        el(
          PanelBody,
          {
            title: __("Object Position", "brandy"),
            initialOpen: false,
          },
          el(FocalPointPicker, {
            url: imageUrl,
            value: objectPosition,
            onChange: onChangePosition,
          })
        )
      )
    );
  }

  // ── Editor preview style (always rendered, even when deselected) ─

  function EditorPreviewStyle(props) {
    var attributes = props.attributes;
    var clientId = props.clientId;
    var scale = attributes.scale || "";
    var objectPosition = attributes.objectPosition;

    if (scale !== "cover" || !objectPosition) {
      return null;
    }

    var posX = Math.round((objectPosition.x != null ? objectPosition.x : 0.5) * 100);
    var posY = Math.round((objectPosition.y != null ? objectPosition.y : 0.5) * 100);
    var css =
      "#block-" + clientId + " img { object-position: " + posX + "% " + posY + "% !important; }";

    return el("style", null, css);
  }

  // ── BlockEdit HOC ───────────────────────────────────────────────

  var addObjectPositionControls = createHigherOrderComponent(
    function (BlockEdit) {
      return function (props) {
        if (!isSupported(props.name)) {
          return el(BlockEdit, props);
        }

        return el(
          Fragment,
          null,
          el(BlockEdit, props),
          // Style always renders for live preview
          el(EditorPreviewStyle, props),
          // Controls only render when selected
          props.isSelected && el(ObjectPositionControls, props)
        );
      };
    },
    "addObjectPositionControls"
  );

  addFilter(
    "editor.BlockEdit",
    "brandy/image-object-position-controls",
    addObjectPositionControls,
    20
  );
})();
