// packages/block-library/src/tab-panel/remove-tab-toolbar-control.js
import {
  BlockControls,
  store as blockEditorStore
} from "@wordpress/block-editor";
import { ToolbarGroup, ToolbarButton } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { useDispatch, useSelect } from "@wordpress/data";
import { jsx } from "react/jsx-runtime";
function RemoveTabToolbarControl({ tabsClientId }) {
  const {
    removeBlock,
    updateBlockAttributes,
    selectBlock,
    __unstableMarkNextChangeAsNotPersistent
  } = useDispatch(blockEditorStore);
  const {
    activeTabPanelClientId,
    tabCount,
    editorActiveTabIndex,
    tabListClientId
  } = useSelect(
    (select) => {
      if (!tabsClientId) {
        return {
          activeTabPanelClientId: null,
          tabCount: 0,
          editorActiveTabIndex: 0,
          tabListClientId: null
        };
      }
      const { getBlocks, getBlockAttributes } = select(blockEditorStore);
      const tabsAttributes = getBlockAttributes(tabsClientId);
      const activeIndex = tabsAttributes?.editorActiveTabIndex ?? tabsAttributes?.activeTabIndex ?? 0;
      const innerBlocks = getBlocks(tabsClientId);
      const tabPanels = innerBlocks.find(
        (block) => block.name === "core/tab-panels"
      );
      const tabList = innerBlocks.find(
        (block) => block.name === "core/tab-list"
      );
      const tabPanelBlocks = tabPanels?.innerBlocks || [];
      const activeTabPanel = tabPanelBlocks[activeIndex];
      return {
        activeTabPanelClientId: activeTabPanel?.clientId || null,
        tabCount: tabPanelBlocks.length,
        editorActiveTabIndex: activeIndex,
        tabListClientId: tabList?.clientId || null
      };
    },
    [tabsClientId]
  );
  const removeTab = () => {
    if (!activeTabPanelClientId || tabCount <= 1) {
      return;
    }
    const newActiveIndex = editorActiveTabIndex >= tabCount - 1 ? tabCount - 2 : editorActiveTabIndex;
    __unstableMarkNextChangeAsNotPersistent();
    updateBlockAttributes(tabsClientId, {
      editorActiveTabIndex: newActiveIndex
    });
    removeBlock(activeTabPanelClientId, false);
    if (tabListClientId) {
      selectBlock(tabListClientId);
    }
  };
  const isDisabled = tabCount <= 1 || !activeTabPanelClientId;
  return /* @__PURE__ */ jsx(BlockControls, { group: "other", children: /* @__PURE__ */ jsx(ToolbarGroup, { children: /* @__PURE__ */ jsx(
    ToolbarButton,
    {
      className: "components-toolbar__control",
      onClick: removeTab,
      text: __("Remove tab"),
      disabled: isDisabled
    }
  ) }) });
}
export {
  RemoveTabToolbarControl as default
};
//# sourceMappingURL=remove-tab-toolbar-control.mjs.map
