// packages/block-library/src/tab-panel/edit.js
import { __ } from "@wordpress/i18n";
import {
  useBlockProps,
  useInnerBlocksProps,
  store as blockEditorStore
} from "@wordpress/block-editor";
import { useSelect, useDispatch } from "@wordpress/data";
import { useMemo, useEffect } from "@wordpress/element";
import Controls from "./controls.mjs";
import { jsx, jsxs } from "react/jsx-runtime";
var TEMPLATE = [
  [
    "core/paragraph",
    {
      placeholder: __("Type / to choose a block")
    }
  ]
];
function Edit({ clientId, context, isSelected }) {
  const activeTabIndex = context["core/tabs-activeTabIndex"];
  const editorActiveTabIndex = context["core/tabs-editorActiveTabIndex"];
  const effectiveActiveIndex = editorActiveTabIndex ?? activeTabIndex;
  const { blockIndex, hasInnerBlocksSelected, tabsClientId } = useSelect(
    (select) => {
      const {
        getBlockRootClientId,
        getBlockIndex,
        hasSelectedInnerBlock
      } = select(blockEditorStore);
      const tabPanelsClientId = getBlockRootClientId(clientId);
      const _tabsClientId = getBlockRootClientId(tabPanelsClientId);
      const _blockIndex = getBlockIndex(clientId);
      const _hasInnerBlocksSelected = hasSelectedInnerBlock(
        clientId,
        true
      );
      return {
        blockIndex: _blockIndex,
        hasInnerBlocksSelected: _hasInnerBlocksSelected,
        tabsClientId: _tabsClientId
      };
    },
    [clientId]
  );
  const { updateBlockAttributes, __unstableMarkNextChangeAsNotPersistent } = useDispatch(blockEditorStore);
  useEffect(() => {
    const isTabSelected = isSelected || hasInnerBlocksSelected;
    if (isTabSelected && tabsClientId && effectiveActiveIndex !== blockIndex) {
      __unstableMarkNextChangeAsNotPersistent();
      updateBlockAttributes(tabsClientId, {
        editorActiveTabIndex: blockIndex
      });
    }
  }, [
    isSelected,
    hasInnerBlocksSelected,
    tabsClientId,
    effectiveActiveIndex,
    blockIndex,
    updateBlockAttributes,
    __unstableMarkNextChangeAsNotPersistent
  ]);
  const isActiveTab = effectiveActiveIndex === blockIndex;
  const isDefaultTab = activeTabIndex === blockIndex;
  const isSelectedTab = useMemo(() => {
    if (isSelected || hasInnerBlocksSelected) {
      return true;
    }
    if (isActiveTab) {
      return true;
    }
    return false;
  }, [isSelected, hasInnerBlocksSelected, isActiveTab]);
  const blockProps = useBlockProps({
    hidden: !isSelectedTab,
    tabIndex: isSelectedTab ? 0 : -1
  });
  const innerBlocksProps = useInnerBlocksProps(blockProps, {
    template: TEMPLATE
  });
  return /* @__PURE__ */ jsxs("section", { ...innerBlocksProps, children: [
    /* @__PURE__ */ jsx(
      Controls,
      {
        tabsClientId,
        blockIndex,
        isDefaultTab
      }
    ),
    isSelectedTab && innerBlocksProps.children
  ] });
}
export {
  Edit as default
};
//# sourceMappingURL=edit.mjs.map
