import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useState, useRef } from 'react';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { useField, FieldArray } from 'formik';
import { slugify, isNotPresent, findIndexById, isNotEmpty, noop } from '@bigbinary/neeto-cist';
import Plus from '@bigbinary/neeto-icons/Plus';
import Button from '@bigbinary/neetoui/Button';
import { isEmpty, identity, reject, prop, pluck, clone, insert, move, assocPath, remove, append } from 'ramda';
import { useTranslation, Trans } from 'react-i18next';
import Modal from '@bigbinary/neetoui/Modal';
import Textarea from '@bigbinary/neetoui/Textarea';
import Typography from '@bigbinary/neetoui/Typography';
import { jsxs, jsx } from 'react/jsx-runtime';
import i18next, { t } from 'i18next';
import Editor from '@bigbinary/neeto-editor/Editor';
import Checkbox$1 from '@bigbinary/neetoui/Checkbox';
import Drag from '@bigbinary/neeto-icons/Drag';
import { withT } from '@bigbinary/neeto-commons-frontend/react-utils';
import Copy from '@bigbinary/neeto-icons/Copy';
import Delete from '@bigbinary/neeto-icons/Delete';
import classnames from 'classnames';
import ImageUploader from '@bigbinary/neeto-image-uploader-frontend/ImageUploader';
import Input from '@bigbinary/neetoui/formik/Input';
import Textarea$1 from '@bigbinary/neetoui/formik/Textarea';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import { n } from './inject-css-C2dztUxs.js';
import Edit from '@bigbinary/neeto-icons/Edit';

var BulkOptionModal = function BulkOptionModal(_ref) {
  var isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    handleBulkAdd = _ref.handleBulkAdd,
    bulkAddHelpDocUrl = _ref.bulkAddHelpDocUrl;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useState = useState(""),
    _useState2 = _slicedToArray(_useState, 2),
    optionsString = _useState2[0],
    setOptionsString = _useState2[1];
  var handleSave = function handleSave() {
    handleBulkAdd(optionsString);
    handleClose();
  };
  var handleClose = function handleClose() {
    setOptionsString("");
    onClose();
  };
  return /*#__PURE__*/jsxs(Modal, {
    isOpen: isOpen,
    onClose: handleClose,
    children: [/*#__PURE__*/jsx(Modal.Header, {
      children: /*#__PURE__*/jsx(Typography, {
        style: "h3",
        children: t("neetoMolecules.optionFields.bulkOption.title")
      })
    }), /*#__PURE__*/jsx(Modal.Body, {
      children: /*#__PURE__*/jsx(Textarea, {
        className: "my-2",
        "data-testid": "bulk-add-options-textarea",
        label: t("neetoMolecules.optionFields.bulkOption.label"),
        placeholder: t("neetoMolecules.optionFields.bulkOption.label"),
        rows: 8,
        value: optionsString,
        helpText: /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.optionFields.bulkOption.helpText",
          components: {
            Link: /*#__PURE__*/jsx(Button, {
              className: "text-xs",
              href: bulkAddHelpDocUrl,
              style: "link",
              target: "_blank"
            })
          }
        }),
        onChange: function onChange(e) {
          return setOptionsString(e.target.value);
        }
      })
    }), /*#__PURE__*/jsxs(Modal.Footer, {
      className: "flex items-center gap-x-2",
      children: [/*#__PURE__*/jsx(Button, {
        "data-testid": "bulk-add-options-done-button",
        label: t("neetoMolecules.common.actions.submit"),
        onClick: handleSave
      }), /*#__PURE__*/jsx(Button, {
        "data-testid": "bulk-add-options-cancel-button",
        label: t("neetoMolecules.common.actions.cancel"),
        style: "text",
        onClick: handleClose
      })]
    })]
  });
};

var Checkbox = function Checkbox(_ref) {
  var name = _ref.name,
    optionIndex = _ref.optionIndex;
  var checkboxName = name.replace(".label", ".selected");
  var _useField = useField(checkboxName),
    _useField2 = _slicedToArray(_useField, 3),
    value = _useField2[0].value;
    _useField2[1];
    var setValue = _useField2[2].setValue;
  return /*#__PURE__*/jsx("div", {
    className: "flex h-8 flex-shrink-0 items-center",
    children: /*#__PURE__*/jsx(Checkbox$1, {
      checked: value || false,
      "data-testid": "checkbox-option-".concat(optionIndex),
      onChange: function onChange(e) {
        setValue(e.target.checked);
      }
    })
  });
};

function ownKeys$8(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$8(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$8(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var DragHandle = function DragHandle(props) {
  return /*#__PURE__*/jsx("div", _objectSpread$8(_objectSpread$8({
    className: "neeto-ui-text-gray-500 flex h-8 flex-shrink-0 cursor-grab items-center",
    "data-testid": "drag-handle"
  }, props), {}, {
    children: /*#__PURE__*/jsx(Drag, {
      size: 16,
      strokeWidth: 2
    })
  }));
};

var OptionActions = withT(function (_ref) {
  var t = _ref.t,
    disabled = _ref.disabled,
    _ref$hideCloneOption = _ref.hideCloneOption,
    hideCloneOption = _ref$hideCloneOption === void 0 ? false : _ref$hideCloneOption,
    _ref$hideDeleteOption = _ref.hideDeleteOption,
    hideDeleteOption = _ref$hideDeleteOption === void 0 ? false : _ref$hideDeleteOption,
    optionIndex = _ref.optionIndex,
    id = _ref.id,
    arrayHelpers = _ref.arrayHelpers,
    onClone = _ref.onClone,
    onDelete = _ref.onDelete,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? "" : _ref$className;
  return /*#__PURE__*/jsxs("div", {
    className: "flex items-center gap-1 ".concat(className),
    children: [!hideCloneOption && /*#__PURE__*/jsx(Button, {
      disabled: disabled,
      className: "p-0.5",
      "data-testid": "clone-option-button-".concat(optionIndex),
      icon: Copy,
      size: "small",
      style: "text",
      tooltipProps: {
        content: t("neetoMolecules.common.actions.clone"),
        position: "top",
        touch: ["hold", 500]
      },
      onClick: function onClick() {
        return onClone(id);
      }
    }), !hideDeleteOption && /*#__PURE__*/jsx(Button, {
      disabled: disabled,
      className: "p-0.5",
      "data-testid": "delete-option-button-".concat(optionIndex),
      icon: Delete,
      size: "small",
      style: "text",
      tooltipProps: {
        content: t("neetoMolecules.common.actions.delete"),
        position: "top",
        touch: ["hold", 500]
      },
      onClick: function onClick() {
        return onDelete(id, arrayHelpers);
      }
    })]
  });
});

function ownKeys$7(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$7(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var EditorOption = function EditorOption(_ref) {
  var innerRef = _ref.innerRef,
    draggableProps = _ref.draggableProps,
    dragHandleProps = _ref.dragHandleProps,
    isDraggable = _ref.isDraggable,
    optionIndex = _ref.optionIndex,
    isCheckboxEnabled = _ref.isCheckboxEnabled,
    name = _ref.name,
    disabled = _ref.disabled,
    placeholder = _ref.placeholder,
    shouldFocus = _ref.shouldFocus,
    _onChange = _ref.onChange,
    _onBlur = _ref.onBlur,
    id = _ref.id,
    arrayHelpers = _ref.arrayHelpers,
    hideCloneOption = _ref.hideCloneOption,
    hideDeleteOption = _ref.hideDeleteOption,
    onClone = _ref.onClone,
    onDelete = _ref.onDelete;
  var _useField = useField(name),
    _useField2 = _slicedToArray(_useField, 1),
    field = _useField2[0];
  return /*#__PURE__*/jsx("div", _objectSpread$7(_objectSpread$7({
    ref: innerRef
  }, _objectSpread$7(_objectSpread$7({}, draggableProps), dragHandleProps)), {}, {
    "data-testid": "form-block-options",
    children: /*#__PURE__*/jsxs("div", {
      className: "nf-input-options group relative mb-2 flex items-start gap-1",
      children: [isDraggable && /*#__PURE__*/jsx(DragHandle, _objectSpread$7(_objectSpread$7({}, dragHandleProps), {}, {
        "data-testid": "drag-handle-".concat(optionIndex)
      })), isCheckboxEnabled && /*#__PURE__*/jsx(Checkbox, {
        name: name,
        optionIndex: optionIndex
      }), /*#__PURE__*/jsxs("div", {
        className: "flex w-full items-start gap-2",
        children: [/*#__PURE__*/jsx(Editor, {
          disabled: disabled,
          name: name,
          placeholder: placeholder,
          autoFocus: shouldFocus,
          className: "flex-1",
          "data-testid": "editor-option-".concat(optionIndex),
          initialValue: field.value,
          onChange: function onChange(value) {
            return _onChange({
              id: id,
              value: value
            });
          },
          onBlur: function onBlur(value) {
            _onChange({
              id: id,
              value: value,
              isOnBlur: true
            });
            _onBlur === null || _onBlur === void 0 || _onBlur(id, value);
          }
        }), /*#__PURE__*/jsx("div", {
          className: "absolute end-2 top-2",
          children: /*#__PURE__*/jsx(OptionActions, {
            arrayHelpers: arrayHelpers,
            disabled: disabled,
            hideCloneOption: hideCloneOption,
            hideDeleteOption: hideDeleteOption,
            id: id,
            onClone: onClone,
            onDelete: onDelete,
            optionIndex: optionIndex
          })
        })]
      })]
    })
  }));
};

function ownKeys$6(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$6(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var ImageOption = function ImageOption(_ref) {
  var id = _ref.id,
    name = _ref.name,
    optionIndex = _ref.optionIndex,
    disabled = _ref.disabled,
    placeholder = _ref.placeholder,
    shouldFocus = _ref.shouldFocus,
    onKeyDown = _ref.onKeyDown,
    _onChange = _ref.onChange,
    _onBlur = _ref.onBlur,
    onDelete = _ref.onDelete,
    onClone = _ref.onClone,
    arrayHelpers = _ref.arrayHelpers,
    _ref$hideDeleteOption = _ref.hideDeleteOption,
    hideDeleteOption = _ref$hideDeleteOption === void 0 ? false : _ref$hideDeleteOption,
    _ref$hideCloneOption = _ref.hideCloneOption,
    hideCloneOption = _ref$hideCloneOption === void 0 ? false : _ref$hideCloneOption,
    innerRef = _ref.innerRef,
    draggableProps = _ref.draggableProps,
    dragHandleProps = _ref.dragHandleProps,
    isDraggable = _ref.isDraggable,
    isCheckboxEnabled = _ref.isCheckboxEnabled,
    isEditor = _ref.isEditor;
  var imageFieldName = name.replace(".label", ".image");
  var _useField = useField(name),
    _useField2 = _slicedToArray(_useField, 1),
    field = _useField2[0];
  var _useField3 = useField(imageFieldName),
    _useField4 = _slicedToArray(_useField3, 3);
    _useField4[0];
    var image = _useField4[1].value,
    setValue = _useField4[2].setValue;
  var handleImageChange = function handleImageChange(changedImage) {
    var imageValue = isEmpty(changedImage === null || changedImage === void 0 ? void 0 : changedImage.url) ? null : changedImage;
    setValue(imageValue, false);
    _onChange({
      id: id,
      value: imageValue,
      isOnBlur: false,
      fieldType: "image"
    });
  };
  return /*#__PURE__*/jsx("div", _objectSpread$6(_objectSpread$6({
    ref: innerRef
  }, _objectSpread$6(_objectSpread$6({}, draggableProps), dragHandleProps)), {}, {
    "data-testid": "form-block-options",
    children: /*#__PURE__*/jsxs("div", {
      className: "nf-input-options group relative mb-2 flex items-start gap-1",
      children: [isDraggable && /*#__PURE__*/jsx(DragHandle, _objectSpread$6(_objectSpread$6({}, dragHandleProps), {}, {
        "data-testid": "drag-handle-".concat(optionIndex)
      })), isCheckboxEnabled && /*#__PURE__*/jsx(Checkbox, {
        name: name,
        optionIndex: optionIndex
      }), /*#__PURE__*/jsx("div", {
        className: classnames("flex w-full items-center justify-center", {
          "pointer-events-none opacity-80": disabled
        }),
        children: /*#__PURE__*/jsxs("div", {
          className: "neeto-ui-rounded-lg neeto-ui-border-gray-200 neeto-molecules-option-fields__image-option neeto-ui-bg-white group relative flex w-full flex-col gap-2 border p-2 pe-8",
          children: [/*#__PURE__*/jsx("div", {
            className: "neeto-molecules-option-fields__image-uploader-container flex-shrink-0",
            "data-testid": "picture-choice-option-".concat(optionIndex),
            children: /*#__PURE__*/jsx(ImageUploader, {
              className: "neeto-molecules-option-fields__image-uploader w-full",
              isOptionsDisabled: disabled,
              src: image === null || image === void 0 ? void 0 : image.url,
              uploadConfig: IMAGE_UPLOAD_CONFIG,
              onUploadComplete: handleImageChange
            }, image === null || image === void 0 ? void 0 : image.url)
          }), /*#__PURE__*/jsx("div", {
            className: "w-full",
            children: isEditor ? /*#__PURE__*/jsx(Editor, {
              disabled: disabled,
              name: name,
              placeholder: placeholder,
              autoFocus: shouldFocus,
              className: "flex-1",
              "data-testid": "editor-option-".concat(optionIndex),
              initialValue: field.value,
              onChange: function onChange(value) {
                return _onChange({
                  id: id,
                  value: value
                });
              },
              onBlur: function onBlur(value) {
                _onChange({
                  id: id,
                  value: value,
                  isOnBlur: true
                });
                _onBlur === null || _onBlur === void 0 || _onBlur(id, value);
              }
            }) : /*#__PURE__*/jsx(Input, _defineProperty(_defineProperty({
              disabled: disabled,
              name: name,
              onBlur: _onBlur,
              onKeyDown: onKeyDown,
              placeholder: placeholder,
              autoFocus: shouldFocus,
              "data-testid": "option-input-".concat(optionIndex),
              onFocus: function onFocus(_ref2) {
                var target = _ref2.target;
                return target.select();
              }
            }, "onBlur", function onBlur(event) {
              _onChange({
                id: id,
                value: event.target.value,
                isOnBlur: true
              });
              _onBlur === null || _onBlur === void 0 || _onBlur(id, event.target.value);
              for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                args[_key - 1] = arguments[_key];
              }
              field.onBlur.apply(field, [event].concat(args));
            }), "onChange", function onChange(_ref3) {
              var target = _ref3.target;
              return _onChange({
                id: id,
                value: target.value
              });
            }))
          }), /*#__PURE__*/jsx("div", {
            className: "absolute end-2 top-2",
            children: /*#__PURE__*/jsx(OptionActions, {
              arrayHelpers: arrayHelpers,
              disabled: disabled,
              hideCloneOption: hideCloneOption,
              hideDeleteOption: hideDeleteOption,
              id: id,
              onClone: onClone,
              onDelete: onDelete,
              optionIndex: optionIndex
            })
          })]
        })
      })]
    })
  }));
};

function ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var InputOption = function InputOption(_ref) {
  var shouldFocus = _ref.shouldFocus,
    _ref$hideDeleteOption = _ref.hideDeleteOption,
    hideDeleteOption = _ref$hideDeleteOption === void 0 ? false : _ref$hideDeleteOption,
    _ref$hideCloneOption = _ref.hideCloneOption,
    hideCloneOption = _ref$hideCloneOption === void 0 ? false : _ref$hideCloneOption,
    innerRef = _ref.innerRef,
    draggableProps = _ref.draggableProps,
    dragHandleProps = _ref.dragHandleProps,
    onKeyDown = _ref.onKeyDown,
    onDelete = _ref.onDelete,
    onClone = _ref.onClone,
    _onChange = _ref.onChange,
    optionIndex = _ref.optionIndex,
    disabled = _ref.disabled,
    isTextArea = _ref.isTextArea,
    id = _ref.id,
    isDraggable = _ref.isDraggable,
    name = _ref.name,
    placeholder = _ref.placeholder,
    _onBlur = _ref.onBlur,
    arrayHelpers = _ref.arrayHelpers,
    _ref$isCheckboxEnable = _ref.isCheckboxEnabled,
    isCheckboxEnabled = _ref$isCheckboxEnable === void 0 ? false : _ref$isCheckboxEnable;
  var Component = isTextArea ? Textarea$1 : Input;
  var _useField = useField(name),
    _useField2 = _slicedToArray(_useField, 1),
    field = _useField2[0];
  return /*#__PURE__*/jsx("div", _objectSpread$5(_objectSpread$5({
    ref: innerRef
  }, _objectSpread$5(_objectSpread$5({}, draggableProps), dragHandleProps)), {}, {
    "data-testid": "form-block-options",
    children: /*#__PURE__*/jsxs("div", {
      className: "nf-input-options group relative mb-2 flex items-start gap-1",
      children: [isDraggable && /*#__PURE__*/jsx(DragHandle, _objectSpread$5(_objectSpread$5({}, dragHandleProps), {}, {
        "data-testid": "drag-handle-".concat(optionIndex)
      })), isCheckboxEnabled && /*#__PURE__*/jsx(Checkbox, {
        name: name,
        optionIndex: optionIndex
      }), /*#__PURE__*/jsx("div", {
        className: "flex w-full items-start gap-2",
        children: /*#__PURE__*/jsx(Component, {
          disabled: disabled,
          name: name,
          onKeyDown: onKeyDown,
          placeholder: placeholder,
          autoFocus: shouldFocus,
          className: "flex-1",
          "data-testid": "".concat(isTextArea ? "option-textarea" : "option-input", "-").concat(optionIndex),
          suffix: /*#__PURE__*/jsx(OptionActions, {
            arrayHelpers: arrayHelpers,
            disabled: disabled,
            hideCloneOption: hideCloneOption,
            hideDeleteOption: hideDeleteOption,
            id: id,
            onClone: onClone,
            onDelete: onDelete,
            optionIndex: optionIndex
          }),
          onChange: function onChange(_ref2) {
            var target = _ref2.target;
            return _onChange({
              id: id,
              value: target.value
            });
          },
          onFocus: function onFocus(_ref3) {
            var target = _ref3.target;
            return target.select();
          },
          onBlur: function onBlur(event) {
            _onChange({
              id: id,
              value: event.target.value,
              isOnBlur: true
            });
            _onBlur === null || _onBlur === void 0 || _onBlur(id, event.target.value);
            for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
              args[_key - 1] = arguments[_key];
            }
            field.onBlur.apply(field, [event].concat(args));
          }
        })
      })]
    })
  }));
};

var getOrderedOptions = function getOrderedOptions() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  return options.sort(function (a, b) {
    return a.position - b.position;
  });
};
var filterDeletedRecords = function filterDeletedRecords(options, destroyFlagName) {
  return reject(prop(destroyFlagName), options);
};
var randomId = function randomId() {
  return Math.random().toString(36).substring(2, 13);
};
var getUniqueOptionId = function getUniqueOptionId(option) {
  var _option$id, _option$position, _option$label;
  return option.altId || ((_option$id = option.id) === null || _option$id === void 0 ? void 0 : _option$id.toString()) || ((_option$position = option.position) === null || _option$position === void 0 ? void 0 : _option$position.toString()) || slugify((_option$label = option.label) !== null && _option$label !== void 0 ? _option$label : "");
};
var generatePlaceholder = function generatePlaceholder(itemLabel, count) {
  return "".concat(itemLabel, " ").concat(count + 1);
};
var _generateLabel = function generateLabel(itemLabel, options, count) {
  var labelCount = count || options.length + 1;
  var tempLabel = "".concat(itemLabel, " ").concat(labelCount);
  var isDuplicateLabel = pluck("label", options).includes(tempLabel);
  return isDuplicateLabel ? _generateLabel(itemLabel, options, labelCount + 1) : tempLabel;
};
var resolveFormikValue = function resolveFormikValue(path, values) {
  if (!path || typeof path !== "string") {
    return [];
  }
  return path.replace(/\[|\]/g, ".").split(".").filter(Boolean).reduce(function (acc, key) {
    return acc && acc[key] !== undefined ? acc[key] : undefined;
  }, values);
};
var handleNumberKeyDown = function handleNumberKeyDown(event, onKeyDown) {
  var allowedKeys = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "-"];
  var controlKeys = ["Backspace", "Delete", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Tab", "Enter"];
  if ((event.ctrlKey || event.metaKey) && ["a", "c", "v", "x", "z"].includes(event.key.toLowerCase())) {
    return;
  }
  if (![].concat(allowedKeys, controlKeys).includes(event.key)) {
    event.preventDefault();
  }
  onKeyDown === null || onKeyDown === void 0 || onKeyDown(event);
};
var handleInputBlur = function handleInputBlur(event, _ref) {
  var id = _ref.id,
    inputIndex = _ref.inputIndex,
    onChange = _ref.onChange,
    onBlur = _ref.onBlur,
    field = _ref.field,
    config = _ref.config;
  var value = event.target.value;
  var finalValue = !value && config !== null && config !== void 0 && config.defaultValue ? config.defaultValue : value;
  onChange({
    id: id,
    value: finalValue,
    inputIndex: inputIndex,
    isOnBlur: true
  });
  onBlur === null || onBlur === void 0 || onBlur(id, finalValue, inputIndex);
  field.onBlur(event);
};
var getMultiInputError = function getMultiInputError(isMultiInput, meta) {
  if (!isMultiInput || !meta.error) return null;
  if (Array.isArray(meta.error)) {
    var hasValuesError = meta.error.some(function (optionError) {
      return Array.isArray(optionError.values) && optionError.values.some(identity);
    });
    if (hasValuesError) {
      return t("neetoMolecules.optionFields.allFieldsRequired");
    }
  }
  return null;
};

function ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var MultiInputOption = withT(function (_ref) {
  var shouldFocus = _ref.shouldFocus,
    _ref$hideDeleteOption = _ref.hideDeleteOption,
    hideDeleteOption = _ref$hideDeleteOption === void 0 ? false : _ref$hideDeleteOption,
    _ref$hideCloneOption = _ref.hideCloneOption,
    hideCloneOption = _ref$hideCloneOption === void 0 ? false : _ref$hideCloneOption,
    innerRef = _ref.innerRef,
    draggableProps = _ref.draggableProps,
    dragHandleProps = _ref.dragHandleProps,
    _onKeyDown = _ref.onKeyDown,
    onDelete = _ref.onDelete,
    onClone = _ref.onClone,
    _onChange = _ref.onChange,
    optionIndex = _ref.optionIndex,
    disabled = _ref.disabled,
    id = _ref.id,
    isDraggable = _ref.isDraggable,
    name = _ref.name,
    placeholder = _ref.placeholder,
    _onBlur = _ref.onBlur,
    arrayHelpers = _ref.arrayHelpers,
    _ref$inputConfig = _ref.inputConfig,
    inputConfig = _ref$inputConfig === void 0 ? [] : _ref$inputConfig,
    isCheckboxEnabled = _ref.isCheckboxEnabled;
  return /*#__PURE__*/jsx("div", _objectSpread$4(_objectSpread$4({
    ref: innerRef
  }, _objectSpread$4(_objectSpread$4({}, draggableProps), dragHandleProps)), {}, {
    "data-testid": "form-block-multi-options",
    children: /*#__PURE__*/jsxs("div", {
      className: "nf-multi-input-options group relative mb-2 flex items-center gap-1",
      children: [isDraggable && /*#__PURE__*/jsx(DragHandle, _objectSpread$4(_objectSpread$4({}, dragHandleProps), {}, {
        "data-testid": "drag-handle-".concat(optionIndex)
      })), isCheckboxEnabled && /*#__PURE__*/jsx(Checkbox, {
        name: name,
        optionIndex: optionIndex
      }), /*#__PURE__*/jsx("div", {
        className: "flex flex-1 flex-col gap-2",
        children: /*#__PURE__*/jsx("div", {
          className: "flex gap-2",
          children: inputConfig.map(function (config, inputIndex) {
            var _field$value;
            var inputName = "".concat(name.replace(".label", ""), ".values.").concat(inputIndex);
            var inputType = config.type || INPUT_TYPES.TEXT;
            var isNumberType = inputType === INPUT_TYPES.NUMBER;
            var _useField = useField(inputName),
              _useField2 = _slicedToArray(_useField, 1),
              field = _useField2[0];
            return /*#__PURE__*/jsx("div", {
              className: "flex-1",
              children: /*#__PURE__*/jsx(Input, _objectSpread$4(_objectSpread$4({
                disabled: disabled,
                autoFocus: shouldFocus && inputIndex === 0,
                "data-testid": "multi-option-input-".concat(optionIndex, "-").concat(inputIndex)
              }, isNumberType && {
                min: config.min,
                max: config.max
              }), {}, {
                name: inputName,
                type: inputType,
                value: (_field$value = field.value) !== null && _field$value !== void 0 ? _field$value : config.defaultValue,
                placeholder: config.placeholder || "".concat(placeholder, " ").concat(inputIndex + 1),
                onFocus: function onFocus(_ref2) {
                  var target = _ref2.target;
                  return target.select();
                },
                onBlur: function onBlur(event) {
                  return handleInputBlur(event, {
                    id: id,
                    inputIndex: inputIndex,
                    onChange: _onChange,
                    onBlur: _onBlur,
                    field: field,
                    config: config
                  });
                },
                onChange: function onChange(_ref3) {
                  var target = _ref3.target;
                  return _onChange({
                    id: id,
                    value: target.value,
                    inputIndex: inputIndex
                  });
                },
                onKeyDown: function onKeyDown(event) {
                  return isNumberType ? handleNumberKeyDown(event, _onKeyDown) : _onKeyDown === null || _onKeyDown === void 0 ? void 0 : _onKeyDown(event);
                }
              }))
            }, inputIndex);
          })
        })
      }), /*#__PURE__*/jsx(OptionActions, {
        arrayHelpers: arrayHelpers,
        disabled: disabled,
        hideCloneOption: hideCloneOption,
        hideDeleteOption: hideDeleteOption,
        id: id,
        onClone: onClone,
        onDelete: onDelete,
        optionIndex: optionIndex
      })]
    })
  }));
});

var DEFAULT_OPTION_LABEL = i18next.t("neetoMolecules.optionFields.defaultOption");
var IMAGE_UPLOAD_CONFIG = {
  maxImageSize: 1,
  allowedImageTypes: {
    "image/jpg": [".jpg", ".jpeg"],
    "image/png": [".png"],
    "image/svg": [".svg"]
  }
};
var INPUT_TYPES = {
  TEXT: "text",
  NUMBER: "number"
};
var OPTION_ACTIONS = {
  UPDATE_IMAGE: "update_image",
  UPDATE_VALUES: "update_values",
  UPDATE_LABEL: "update_label",
  DELETE: "delete",
  REORDER: "reorder",
  ADD: "add",
  BULK_ADD: "bulk_add",
  CLONE: "clone"
};
var OPTION_MAP = {
  multiInput: MultiInputOption,
  pictureChoice: ImageOption,
  editor: EditorOption,
  input: InputOption
};

var FormError = function FormError(_ref) {
  var error = _ref.error;
  if (isNotPresent(error) || typeof error !== "string") return null;
  return /*#__PURE__*/jsx(Typography, {
    className: "neeto-ui-input__error",
    "data-testid": "validation-error-container",
    style: "body3",
    children: error
  });
};

function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var attachPosition = function attachPosition(options) {
  return options.map(function (option, index) {
    return _objectSpread$3(_objectSpread$3({}, option), {}, {
      position: index
    });
  });
};
var useOptionFields = function useOptionFields(_ref) {
  var options = _ref.options,
    onChange = _ref.onChange,
    shouldDestroy = _ref.shouldDestroy,
    itemLabel = _ref.itemLabel,
    shouldResetEmptyOptionOnBlur = _ref.shouldResetEmptyOptionOnBlur,
    name = _ref.name,
    destroyFlagName = _ref.destroyFlagName,
    isNewItemsPrefilled = _ref.isNewItemsPrefilled,
    isAddOptionEnabled = _ref.isAddOptionEnabled,
    isPictureChoice = _ref.isPictureChoice,
    isMultiInput = _ref.isMultiInput,
    inputConfig = _ref.inputConfig;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    shouldFocus = _useState2[0],
    setShouldFocus = _useState2[1];
  var editingOptionDetailsRef = useRef({
    id: "",
    value: ""
  });
  var _useField = useField(name),
    _useField2 = _slicedToArray(_useField, 3);
    _useField2[0];
    _useField2[1];
    var helpers = _useField2[2];
  var setValue = helpers.setValue;
  var handleChange = function handleChange(_ref2) {
    var id = _ref2.id,
      value = _ref2.value,
      _ref2$inputIndex = _ref2.inputIndex,
      inputIndex = _ref2$inputIndex === void 0 ? 0 : _ref2$inputIndex,
      _ref2$isOnBlur = _ref2.isOnBlur,
      isOnBlur = _ref2$isOnBlur === void 0 ? false : _ref2$isOnBlur,
      _ref2$fieldType = _ref2.fieldType,
      fieldType = _ref2$fieldType === void 0 ? "label" : _ref2$fieldType;
    var index = findIndexById(id, options);
    var currentOption = options[index];

    // Handle image updates for picture choice (no blur/reset logic needed)
    if (isPictureChoice && fieldType === "image") {
      var _nextOptions = assocPath([index, "image"], value, options);
      setValue(_nextOptions);
      onChange === null || onChange === void 0 || onChange(_nextOptions, OPTION_ACTIONS.UPDATE_IMAGE, index);
      return;
    }

    // Handle multi-input changes
    if (isMultiInput && typeof inputIndex === "number") {
      var currentValues = currentOption.values || [];
      var newValues = clone(currentValues);
      newValues[inputIndex] = value;
      var _nextOptions2 = assocPath([index, "values"], newValues, options);
      setValue(_nextOptions2);
      onChange === null || onChange === void 0 || onChange(_nextOptions2, OPTION_ACTIONS.UPDATE_VALUES, index);
      return;
    }

    // Common blur event handling - ignores onBlur if value is not cleared
    // The value will be reset to initial value if user clicks outside after clearing
    if (isOnBlur && (isNotEmpty(value) || !shouldResetEmptyOptionOnBlur)) {
      return;
    }
    if (editingOptionDetailsRef.current.id !== id) {
      editingOptionDetailsRef.current = {
        id: id,
        value: currentOption.label
      };
    }
    var valueToUpdate = isOnBlur ? editingOptionDetailsRef.current.value : value;

    // Update options with the determined value (always updating label field)
    var nextOptions = assocPath([index, "label"], valueToUpdate, options);
    setValue(nextOptions);
    onChange === null || onChange === void 0 || onChange(nextOptions, OPTION_ACTIONS.UPDATE_LABEL, index);
  };
  var handleDelete = function handleDelete(id, arrayHelpers) {
    var nextOptions;
    var indexToDelete = findIndexById(id, options);
    if (shouldDestroy) {
      nextOptions = assocPath([indexToDelete, destroyFlagName], true, options);
      setValue(nextOptions);
    } else {
      arrayHelpers.remove(indexToDelete);
      nextOptions = attachPosition(remove(indexToDelete, 1, options));
    }
    onChange === null || onChange === void 0 || onChange(nextOptions, OPTION_ACTIONS.DELETE, indexToDelete);
  };
  var handleDragEnd = function handleDragEnd(_ref3) {
    var source = _ref3.source,
      destination = _ref3.destination;
    // When dragged outside of draggable
    if (destination === null) return;
    var deletedOptions = options.filter(prop(destroyFlagName));
    var filteredOptions = filterDeletedRecords(options, destroyFlagName);
    var nextOptions = move(source.index, destination.index, filteredOptions);
    var finalOptions = attachPosition(nextOptions);
    setValue([].concat(_toConsumableArray(deletedOptions), _toConsumableArray(finalOptions)));
    onChange === null || onChange === void 0 || onChange([].concat(_toConsumableArray(deletedOptions), _toConsumableArray(finalOptions)), OPTION_ACTIONS.REORDER);
  };
  var handleAddOption = function handleAddOption() {
    var id = randomId();
    var position = options.length;
    var newOption = _objectSpread$3(_objectSpread$3({
      id: "draft-".concat(id),
      altId: "alt-".concat(id),
      label: isNewItemsPrefilled ? _generateLabel(itemLabel, options) : "",
      position: position
    }, isPictureChoice && {
      image: null
    }), isMultiInput && {
      values: inputConfig.map(function (config) {
        return config.defaultValue || "";
      })
    });
    setShouldFocus(true);
    var nextOptions = append(newOption, options);
    setValue(nextOptions);
    onChange === null || onChange === void 0 || onChange(nextOptions, OPTION_ACTIONS.ADD, position);
  };
  var handleBulkAddOption = function handleBulkAddOption(optionsString) {
    setShouldFocus(true);
    var position = options.length;
    var newOptions = optionsString.trim().split(/\r?\n|,/).filter(isNotEmpty).map(function (option, index) {
      return {
        id: "draft-".concat(randomId()),
        altId: "alt-".concat(randomId()),
        label: option.trim(),
        position: position + index
      };
    });
    var nextOptions = [].concat(_toConsumableArray(options), _toConsumableArray(newOptions));
    setValue(nextOptions);
    onChange === null || onChange === void 0 || onChange(nextOptions, OPTION_ACTIONS.BULK_ADD, position);
  };
  var handleClone = function handleClone(id) {
    var index = findIndexById(id, options);
    var optionToClone = options[index];
    if (!optionToClone) return;
    var newId = randomId();
    var clonedOption = _objectSpread$3(_objectSpread$3({}, optionToClone), {}, {
      id: "draft-".concat(newId),
      altId: "alt-".concat(newId),
      label: isMultiInput ? optionToClone.label : t("neetoMolecules.optionFields.clonedOption", {
        originalLabel: optionToClone.label
      })
    }, isMultiInput && optionToClone.values && {
      values: clone(optionToClone.values)
    });
    setShouldFocus(true);
    var nextOptions = insert(index + 1, clonedOption, options);
    var optionsWithUpdatedPositions = attachPosition(nextOptions);
    setValue(optionsWithUpdatedPositions);
    onChange === null || onChange === void 0 || onChange(optionsWithUpdatedPositions, OPTION_ACTIONS.CLONE, index + 1);
  };
  var handleKeyDown = function handleKeyDown(event) {
    if (event.key !== "Enter") return;
    var form = event.target.form;
    var inputs = Array.from(form.querySelectorAll("input"));
    var currentInput = inputs.indexOf(event.target);
    if (currentInput >= inputs.length - 1) {
      isAddOptionEnabled && handleAddOption();
    } else {
      var _inputs;
      (_inputs = inputs[currentInput + 1]) === null || _inputs === void 0 || _inputs.focus();
      event.preventDefault();
    }
    event.stopPropagation();
  };
  return {
    shouldFocus: shouldFocus,
    handleAddOption: handleAddOption,
    handleBulkAddOption: handleBulkAddOption,
    handleChange: handleChange,
    handleKeyDown: handleKeyDown,
    handleDelete: handleDelete,
    handleDragEnd: handleDragEnd,
    handleClone: handleClone
  };
};

var css = ".neeto-molecules-option-fields__image-uploader img{max-height:100px}";
n(css,{});

function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var BlockOption = withT(function (_ref) {
  var t = _ref.t,
    innerRef = _ref.innerRef,
    _ref$hideDeleteOption = _ref.hideDeleteOption,
    hideDeleteOption = _ref$hideDeleteOption === void 0 ? false : _ref$hideDeleteOption,
    _ref$hideCloneOption = _ref.hideCloneOption,
    hideCloneOption = _ref$hideCloneOption === void 0 ? false : _ref$hideCloneOption,
    draggableProps = _ref.draggableProps,
    dragHandleProps = _ref.dragHandleProps,
    label = _ref.label,
    onEdit = _ref.onEdit,
    onClone = _ref.onClone,
    handleDeleteClick = _ref.handleDeleteClick,
    id = _ref.id,
    isDraggable = _ref.isDraggable,
    optionIndex = _ref.optionIndex,
    arrayHelpers = _ref.arrayHelpers,
    isCheckboxEnabled = _ref.isCheckboxEnabled,
    name = _ref.name;
  return /*#__PURE__*/jsx("div", _objectSpread$2(_objectSpread$2(_objectSpread$2({
    ref: innerRef
  }, draggableProps), dragHandleProps), {}, {
    children: /*#__PURE__*/jsxs("div", {
      className: "neeto-ui-border-gray-400 hover:neeto-ui-bg-gray-200 neeto-ui-rounded-sm shadow-xs group relative mb-2 flex h-10 cursor-pointer items-center gap-2 border p-3 transition-colors duration-300 ease-in-out",
      "data-testid": "address-field-block",
      children: [isDraggable && /*#__PURE__*/jsx(DragHandle, _objectSpread$2(_objectSpread$2({}, dragHandleProps), {}, {
        "data-testid": "drag-handle-".concat(optionIndex)
      })), isCheckboxEnabled && /*#__PURE__*/jsx(Checkbox, {
        name: name,
        optionIndex: optionIndex
      }), /*#__PURE__*/jsx(Typography, {
        className: "flex-grow truncate leading-4",
        "data-testid": "address-text-field",
        style: "body2",
        children: label
      }), /*#__PURE__*/jsxs("div", {
        className: "flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100",
        children: [/*#__PURE__*/jsx(Button, {
          className: "neeto-ui-rounded hover:neeto-ui-bg-gray-400 p-1",
          "data-testid": "address-field-edit-button",
          icon: Edit,
          size: "small",
          style: "text",
          tooltipProps: {
            content: t("neetoMolecules.common.actions.edit"),
            position: "top",
            touch: ["hold", 500]
          },
          onClick: function onClick() {
            return onEdit(id);
          }
        }), /*#__PURE__*/jsx(OptionActions, {
          arrayHelpers: arrayHelpers,
          hideCloneOption: hideCloneOption,
          hideDeleteOption: hideDeleteOption,
          id: id,
          onClone: onClone,
          optionIndex: optionIndex,
          className: "flex items-center gap-2",
          onDelete: handleDeleteClick
        })]
      })]
    })
  }));
});

function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var OptionField = function OptionField(_ref) {
  var option = _ref.option,
    editable = _ref.editable,
    dragHandleProps = _ref.dragHandleProps,
    draggableProps = _ref.draggableProps,
    handleDeleteClick = _ref.handleDeleteClick,
    handleCloneClick = _ref.handleCloneClick,
    hideDeleteOption = _ref.hideDeleteOption,
    hideCloneOption = _ref.hideCloneOption,
    innerRef = _ref.innerRef,
    onEdit = _ref.onEdit,
    draggable = _ref.draggable,
    disabled = _ref.disabled,
    isCheckboxEnabled = _ref.isCheckboxEnabled,
    isPictureChoice = _ref.isPictureChoice,
    isTextArea = _ref.isTextArea,
    isMultiInput = _ref.isMultiInput,
    isEditor = _ref.isEditor,
    inputConfig = _ref.inputConfig,
    shouldFocus = _ref.shouldFocus,
    isEditable = _ref.isEditable,
    itemLabel = _ref.itemLabel,
    handleChange = _ref.handleChange,
    handleKeyDown = _ref.handleKeyDown,
    name = _ref.name,
    optionIndex = _ref.optionIndex,
    onBlur = _ref.onBlur,
    arrayHelpers = _ref.arrayHelpers;
  var commonProps = {
    id: option.id,
    arrayHelpers: arrayHelpers,
    dragHandleProps: dragHandleProps,
    draggableProps: draggableProps,
    hideCloneOption: hideCloneOption,
    hideDeleteOption: hideDeleteOption,
    innerRef: innerRef,
    isCheckboxEnabled: isCheckboxEnabled,
    name: name,
    optionIndex: optionIndex,
    isDraggable: draggable && !disabled,
    onClone: handleCloneClick
  };
  var Component = isMultiInput && OPTION_MAP.multiInput || isPictureChoice && OPTION_MAP.pictureChoice || isEditor && OPTION_MAP.editor || OPTION_MAP.input;
  return editable ? /*#__PURE__*/jsx(Component, _objectSpread$1(_objectSpread$1({}, _objectSpread$1(_objectSpread$1({}, commonProps), {}, {
    inputConfig: inputConfig,
    isEditor: isEditor,
    isTextArea: isTextArea,
    onBlur: onBlur,
    option: option,
    shouldFocus: shouldFocus
  })), {}, {
    disabled: !isEditable || disabled,
    placeholder: generatePlaceholder(itemLabel, optionIndex),
    onChange: handleChange,
    onDelete: handleDeleteClick,
    onKeyDown: handleKeyDown
  })) : /*#__PURE__*/jsx(BlockOption, _objectSpread$1(_objectSpread$1({}, _objectSpread$1(_objectSpread$1({}, commonProps), {}, {
    handleDeleteClick: handleDeleteClick,
    onEdit: onEdit
  })), {}, {
    label: option.label
  }));
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var OptionFields = function OptionFields(_ref) {
  var _field$value;
  var name = _ref.name,
    error = _ref.error,
    onDelete = _ref.onDelete,
    onClone = _ref.onClone,
    onChange = _ref.onChange,
    onBlur = _ref.onBlur,
    _ref$onEdit = _ref.onEdit,
    onEdit = _ref$onEdit === void 0 ? noop : _ref$onEdit,
    _ref$buttonProps = _ref.buttonProps,
    buttonProps = _ref$buttonProps === void 0 ? {} : _ref$buttonProps,
    _ref$minOptions = _ref.minOptions,
    minOptions = _ref$minOptions === void 0 ? 0 : _ref$minOptions,
    _ref$draggable = _ref.draggable,
    draggable = _ref$draggable === void 0 ? false : _ref$draggable,
    _ref$editable = _ref.editable,
    editable = _ref$editable === void 0 ? true : _ref$editable,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$isAddOptionEnabl = _ref.isAddOptionEnabled,
    isAddOptionEnabled = _ref$isAddOptionEnabl === void 0 ? true : _ref$isAddOptionEnabl,
    _ref$isDeleteOptionEn = _ref.isDeleteOptionEnabled,
    isDeleteOptionEnabled = _ref$isDeleteOptionEn === void 0 ? true : _ref$isDeleteOptionEn,
    _ref$isCloneOptionEna = _ref.isCloneOptionEnabled,
    isCloneOptionEnabled = _ref$isCloneOptionEna === void 0 ? false : _ref$isCloneOptionEna,
    _ref$isCheckboxEnable = _ref.isCheckboxEnabled,
    isCheckboxEnabled = _ref$isCheckboxEnable === void 0 ? false : _ref$isCheckboxEnable,
    _ref$isPictureChoice = _ref.isPictureChoice,
    isPictureChoice = _ref$isPictureChoice === void 0 ? false : _ref$isPictureChoice,
    _ref$isTextArea = _ref.isTextArea,
    isTextArea = _ref$isTextArea === void 0 ? false : _ref$isTextArea,
    _ref$isMultiInput = _ref.isMultiInput,
    isMultiInput = _ref$isMultiInput === void 0 ? false : _ref$isMultiInput,
    _ref$isEditor = _ref.isEditor,
    isEditor = _ref$isEditor === void 0 ? false : _ref$isEditor,
    _ref$inputConfig = _ref.inputConfig,
    inputConfig = _ref$inputConfig === void 0 ? [] : _ref$inputConfig,
    _ref$shouldDestroy = _ref.shouldDestroy,
    shouldDestroy = _ref$shouldDestroy === void 0 ? false : _ref$shouldDestroy,
    _ref$destroyFlagName = _ref.destroyFlagName,
    destroyFlagName = _ref$destroyFlagName === void 0 ? "deleted" : _ref$destroyFlagName,
    _ref$shouldResetEmpty = _ref.shouldResetEmptyOptionOnBlur,
    shouldResetEmptyOptionOnBlur = _ref$shouldResetEmpty === void 0 ? true : _ref$shouldResetEmpty,
    _ref$isNewItemsPrefil = _ref.isNewItemsPrefilled,
    isNewItemsPrefilled = _ref$isNewItemsPrefil === void 0 ? true : _ref$isNewItemsPrefil,
    _ref$itemLabel = _ref.itemLabel,
    itemLabel = _ref$itemLabel === void 0 ? DEFAULT_OPTION_LABEL : _ref$itemLabel,
    _ref$bulkActionProps = _ref.bulkActionProps,
    bulkActionProps = _ref$bulkActionProps === void 0 ? {
      enabled: false,
      bulkAddHelpDocUrl: ""
    } : _ref$bulkActionProps;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isBulkOptionModalOpen = _useState2[0],
    setIsBulkOptionModalOpen = _useState2[1];
  var _useField = useField(name),
    _useField2 = _slicedToArray(_useField, 2),
    field = _useField2[0],
    meta = _useField2[1];
  var fieldError = meta.touched ? meta.error : null;
  var multiInputError = getMultiInputError(isMultiInput, meta);
  var options = (_field$value = field.value) !== null && _field$value !== void 0 ? _field$value : [];
  var _useOptionFields = useOptionFields({
      options: options,
      onChange: onChange,
      shouldDestroy: shouldDestroy,
      itemLabel: itemLabel,
      shouldResetEmptyOptionOnBlur: shouldResetEmptyOptionOnBlur,
      destroyFlagName: destroyFlagName,
      name: name,
      isNewItemsPrefilled: isNewItemsPrefilled,
      isAddOptionEnabled: isAddOptionEnabled,
      isPictureChoice: isPictureChoice,
      isMultiInput: isMultiInput,
      inputConfig: inputConfig
    }),
    shouldFocus = _useOptionFields.shouldFocus,
    handleAddOption = _useOptionFields.handleAddOption,
    handleBulkAddOption = _useOptionFields.handleBulkAddOption,
    handleChange = _useOptionFields.handleChange,
    handleKeyDown = _useOptionFields.handleKeyDown,
    handleDelete = _useOptionFields.handleDelete,
    handleDragEnd = _useOptionFields.handleDragEnd,
    handleClone = _useOptionFields.handleClone;

  // Temporarily disables the modifications to options when changed are getting saved to server
  // This condition only needed for server id generated types
  var isEditable = true;
  if (shouldDestroy) isEditable = options.every(prop("id") || error);
  var orderedOptions = getOrderedOptions(options);
  var filteredOptions = orderedOptions.filter(function (_ref2) {
    var deleted = _ref2[destroyFlagName];
    return !deleted;
  });
  var hideDeleteOption = filteredOptions.length <= minOptions || disabled || !isDeleteOptionEnabled;
  var hideCloneOption = disabled || !isCloneOptionEnabled;
  var optionFieldProps = {
    disabled: disabled,
    draggable: draggable,
    editable: editable,
    handleChange: handleChange,
    handleDeleteClick: onDelete !== null && onDelete !== void 0 ? onDelete : handleDelete,
    handleCloneClick: onClone !== null && onClone !== void 0 ? onClone : handleClone,
    handleKeyDown: handleKeyDown,
    hideDeleteOption: hideDeleteOption,
    hideCloneOption: hideCloneOption,
    inputConfig: inputConfig,
    isEditable: isEditable,
    isMultiInput: isMultiInput,
    isPictureChoice: isPictureChoice,
    isTextArea: isTextArea,
    itemLabel: itemLabel,
    onEdit: onEdit,
    onBlur: onBlur,
    shouldFocus: shouldFocus,
    isCheckboxEnabled: isCheckboxEnabled,
    isEditor: isEditor
  };

  // To fix the element positioned incorrectly while dragging when in a pane or modal.
  // https://github.com/hello-pangea/dnd/issues/560#issuecomment-1679201455
  var renderDragClone = function renderDragClone(provided, _, rubric) {
    var draggingIndex = rubric["source"].index;
    var option = filteredOptions[draggingIndex];
    var formikIndex = findIndexById(option.id, options);
    return /*#__PURE__*/jsx(OptionField, _objectSpread(_objectSpread({}, _objectSpread(_objectSpread({}, optionFieldProps), {}, {
      option: option
    })), {}, {
      dragHandleProps: provided.dragHandleProps,
      innerRef: null,
      name: "".concat(name, ".").concat(formikIndex, ".label"),
      optionIndex: draggingIndex,
      draggableProps: _objectSpread(_objectSpread({}, provided.draggableProps), {}, {
        style: _objectSpread(_objectSpread({}, provided.draggableProps.style), {}, {
          zIndex: 999999
        })
      })
    }));
  };
  return /*#__PURE__*/jsxs("form", {
    onSubmit: function onSubmit(e) {
      return e.preventDefault();
    },
    children: [/*#__PURE__*/jsxs(DragDropContext, {
      onDragEnd: handleDragEnd,
      children: [/*#__PURE__*/jsx(Droppable, {
        droppableId: "neeto-molecules-option-fields-".concat(name),
        isDropDisabled: !draggable || disabled,
        renderClone: renderDragClone,
        children: function children(_ref3) {
          var _ref5;
          var innerRef = _ref3.innerRef,
            droppableProps = _ref3.droppableProps,
            placeholder = _ref3.placeholder;
          return /*#__PURE__*/jsxs("div", _objectSpread(_objectSpread({
            ref: innerRef
          }, droppableProps), {}, {
            children: [/*#__PURE__*/jsx(FieldArray, {
              name: name,
              children: function children(arrayHelpers) {
                var options = resolveFormikValue(name, arrayHelpers.form.values);
                return options === null || options === void 0 ? void 0 : options.map(function (option, index) {
                  if (option !== null && option !== void 0 && option[destroyFlagName]) return null;
                  var optionIndex = findIndexById(option.id, filteredOptions);
                  return /*#__PURE__*/jsx(Draggable, {
                    dataKey: getUniqueOptionId(option),
                    draggableId: getUniqueOptionId(option),
                    index: optionIndex,
                    isDragDisabled: !draggable || disabled,
                    children: function children(_ref4) {
                      var innerRef = _ref4.innerRef,
                        draggableProps = _ref4.draggableProps,
                        dragHandleProps = _ref4.dragHandleProps;
                      return /*#__PURE__*/jsx(OptionField, _objectSpread(_objectSpread({}, _objectSpread(_objectSpread({}, optionFieldProps), {}, {
                        arrayHelpers: arrayHelpers,
                        dragHandleProps: dragHandleProps,
                        draggableProps: draggableProps,
                        innerRef: innerRef,
                        option: option,
                        optionIndex: optionIndex
                      })), {}, {
                        name: "".concat(name, ".").concat(index, ".label")
                      }));
                    }
                  }, getUniqueOptionId(option));
                });
              }
            }), placeholder, /*#__PURE__*/jsx(FormError, {
              error: (_ref5 = error !== null && error !== void 0 ? error : multiInputError) !== null && _ref5 !== void 0 ? _ref5 : fieldError
            })]
          }));
        }
      }), /*#__PURE__*/jsxs("div", {
        className: "mt-4 flex items-center justify-between",
        children: [isAddOptionEnabled && /*#__PURE__*/jsx(Button, _objectSpread({
          "data-testid": "add-option-link",
          disabled: !isEditable,
          icon: Plus,
          iconPosition: "left",
          label: t("neetoMolecules.optionFields.addOption"),
          size: "small",
          style: "link",
          onClick: handleAddOption
        }, buttonProps)), bulkActionProps.enabled && !isPictureChoice && !isMultiInput && /*#__PURE__*/jsx(Button, {
          "data-testid": "add-bulk-option-link",
          disabled: !isEditable,
          label: t("neetoMolecules.optionFields.addBulk"),
          size: "small",
          style: "text",
          onClick: function onClick() {
            return setIsBulkOptionModalOpen(true);
          }
        })]
      })]
    }), /*#__PURE__*/jsx(BulkOptionModal, {
      bulkAddHelpDocUrl: bulkActionProps.bulkAddHelpDocUrl,
      handleBulkAdd: handleBulkAddOption,
      isOpen: isBulkOptionModalOpen,
      onClose: function onClose() {
        return setIsBulkOptionModalOpen(false);
      }
    })]
  });
};

export { OptionFields as default };
//# sourceMappingURL=OptionFields.js.map
