"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.RovingTabIndexItem = void 0;
var _element = require("@wordpress/element");
var _rovingTabIndexContext = require("./roving-tab-index-context");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const RovingTabIndexItem = exports.RovingTabIndexItem = (0, _element.forwardRef)(function UnforwardedRovingTabIndexItem({
  children,
  as: Component,
  ...props
}, forwardedRef) {
  const localRef = (0, _element.useRef)();
  const ref = forwardedRef || localRef;
  // @ts-expect-error - We actually want to throw an error if this is undefined.
  const {
    lastFocusedElement,
    setLastFocusedElement
  } = (0, _rovingTabIndexContext.useRovingTabIndexContext)();
  let tabIndex;
  if (lastFocusedElement) {
    tabIndex = lastFocusedElement === (
    // TODO: The original implementation simply used `ref.current` here, assuming
    // that a forwarded ref would always be an object, which is not necessarily true.
    // This workaround maintains the original runtime behavior in a type-safe way,
    // but should be revisited.
    'current' in ref ? ref.current : undefined) ? 0 : -1;
  }
  const onFocus = event => setLastFocusedElement?.(event.target);
  const allProps = {
    ref,
    tabIndex,
    onFocus,
    ...props
  };
  if (typeof children === 'function') {
    return children(allProps);
  }
  if (!Component) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(Component, {
    ...allProps,
    children: children
  });
});
var _default = exports.default = RovingTabIndexItem;
//# sourceMappingURL=roving-tab-index-item.js.map