"use client";
import {
  useFormContext
} from "../__chunks/BQYVKXYL.js";
import {
  useButton
} from "../__chunks/HMKTUWOU.js";
import "../__chunks/PZ3OL7I2.js";
import "../__chunks/U6HHPQDW.js";
import "../__chunks/SWN3JYXT.js";
import "../__chunks/SMPCIMZM.js";
import {
  createElement,
  createHook,
  forwardRef
} from "../__chunks/GWSL6KNJ.js";
import {
  useEvent
} from "../__chunks/KPHZR4MB.js";
import "../__chunks/YXGXYGQX.js";

// src/form/form-remove.tsx
import { isTextField } from "@ariakit/core/utils/dom";
import { invariant } from "@ariakit/core/utils/misc";
var TagName = "button";
function findNextOrPreviousField(items, name, index) {
  const fields = items == null ? void 0 : items.filter(
    (item) => item.type === "field" && item.name.startsWith(name)
  );
  const regex = new RegExp(`^${name}\\.(\\d+)`);
  const nextField = fields == null ? void 0 : fields.find((field) => {
    const fieldIndex = field.name.replace(regex, "$1");
    return Number.parseInt(fieldIndex, 10) > index;
  });
  if (nextField) return nextField;
  return fields == null ? void 0 : fields.reverse().find((field) => {
    const fieldIndex = field.name.replace(regex, "$1");
    return Number.parseInt(fieldIndex, 10) < index;
  });
}
function findPushButton(items, name) {
  return items == null ? void 0 : items.find((item) => item.type === "button" && item.name === name);
}
var useFormRemove = createHook(
  function useFormRemove2({
    store,
    name: nameProp,
    index,
    autoFocusOnClick = true,
    ...props
  }) {
    const context = useFormContext();
    store = store || context;
    invariant(
      store,
      process.env.NODE_ENV !== "production" && "FormRemove must be wrapped in a Form component."
    );
    const name = `${nameProp}`;
    const onClickProp = props.onClick;
    const onClick = useEvent((event) => {
      var _a;
      onClickProp == null ? void 0 : onClickProp(event);
      if (event.defaultPrevented) return;
      if (!store) return;
      store.removeValue(name, index);
      if (!autoFocusOnClick) return;
      const { items } = store.getState();
      const item = findNextOrPreviousField(items, name, index);
      const element = item == null ? void 0 : item.element;
      if (element) {
        element.focus();
        if (isTextField(element)) {
          element.select();
        }
      } else {
        const pushButton = findPushButton(items, name);
        (_a = pushButton == null ? void 0 : pushButton.element) == null ? void 0 : _a.focus();
      }
    });
    props = {
      ...props,
      onClick
    };
    props = useButton(props);
    return props;
  }
);
var FormRemove = forwardRef(function FormRemove2(props) {
  const htmlProps = useFormRemove(props);
  return createElement(TagName, htmlProps);
});
export {
  FormRemove,
  useFormRemove
};
