"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/DateField/index.tsx
var DateField_exports = {};
__export(DateField_exports, {
  DateField: () => DateField,
  MIN_MAX_ERROR: () => MIN_MAX_ERROR,
  convertToDateFormat: () => convertToDateFormat,
  isValidDate: () => isValidDate
});
module.exports = __toCommonJS(DateField_exports);

// src/components/DateField/DateField.tsx
var import_dedupe9 = __toESM(require("classnames/dedupe"));
var import_react6 = require("react");

// src/utils/mergeRefs.ts
function mergeRefs(refs) {
  return (value) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref != null) {
        ref.current = value;
      }
    });
  };
}

// src/components/TextField/TextField.tsx
var import_dedupe8 = __toESM(require("classnames/dedupe"));
var import_react5 = require("react");

// src/utils/spaceDelimitedList.ts
function spaceDelimitedList(list) {
  return list.filter(Boolean).join(" ") || void 0;
}

// src/hooks/useLabel/useLabel.tsx
var import_react = require("react");
function useLabel({
  id: providedId,
  label,
  "aria-label": ariaLabel,
  "aria-labelledby": ariaLabelledby,
  labelElementType = "label"
}) {
  let labelProps = {};
  let fieldProps = {};
  const hasWarnedAboutMissingLabels = (0, import_react.useRef)(false);
  const fallbackId = (0, import_react.useId)();
  const id = providedId || fallbackId;
  const labelId = (0, import_react.useId)();
  if (label) {
    ariaLabelledby = ariaLabelledby ? `${labelId} ${ariaLabelledby}` : labelId;
    labelProps = {
      id: labelId,
      htmlFor: labelElementType === "label" ? id : void 0
    };
  } else if (!ariaLabelledby && !ariaLabel && !hasWarnedAboutMissingLabels.current) {
    hasWarnedAboutMissingLabels.current = true;
    console.warn(
      "If you do not provide a visible label, you must specify an aria-label or aria-labelledby attribute for accessibility"
    );
  }
  fieldProps = {
    id,
    "aria-label": ariaLabel,
    "aria-labelledby": ariaLabelledby
  };
  return {
    labelProps,
    fieldProps
  };
}

// src/hooks/useTextField/useTextField.tsx
var import_react2 = require("react");
function useTextField(props) {
  const {
    isDisabled = false,
    isReadOnly = false,
    isRequired = false,
    inputElementType = "input"
  } = props;
  const { labelProps, fieldProps } = useLabel(props);
  const descriptionId = (0, import_react2.useId)();
  const descriptionProps = { id: descriptionId };
  const errorMessageId = (0, import_react2.useId)();
  const errorMessageProps = { id: errorMessageId };
  const ariaDescribedBy = spaceDelimitedList([
    props.description && descriptionId,
    props.errorMessage && errorMessageId,
    props["aria-describedby"]
  ]);
  return {
    descriptionProps,
    errorMessageProps,
    labelProps,
    inputProps: {
      defaultValue: props.defaultValue,
      value: props.value,
      onChange: props.onChange,
      disabled: isDisabled,
      readOnly: isReadOnly,
      required: isRequired,
      "aria-required": isRequired === true ? true : void 0,
      "aria-invalid": props.isInvalid,
      "aria-describedby": ariaDescribedBy,
      "aria-errormessage": props["aria-errormessage"],
      role: props.role,
      type: inputElementType === "input" ? props.type : void 0,
      pattern: inputElementType === "input" ? props.pattern : void 0,
      autoComplete: props.autoComplete,
      maxLength: props.maxLength,
      minLength: props.minLength,
      name: props.name,
      placeholder: props.placeholder,
      inputMode: props.inputMode,
      // Clipboard events
      onCopy: props.onCopy,
      onCut: props.onCut,
      onPaste: props.onPaste,
      // Composition events
      onCompositionEnd: props.onCompositionEnd,
      onCompositionStart: props.onCompositionStart,
      onCompositionUpdate: props.onCompositionUpdate,
      // Selection events
      onSelect: props.onSelect,
      // Input events
      onBeforeInput: props.onBeforeInput,
      onInput: props.onInput,
      // Focus events
      onFocus: props.onFocus,
      onBlur: props.onBlur,
      ...fieldProps
    }
  };
}

// src/hooks/useValidationClasses/useValidationClasses.ts
var useValidationClasses = (props) => {
  const { isInvalid } = props;
  if (isInvalid) {
    return "--is-invalid";
  }
  if (isInvalid === false) {
    return "--is-valid";
  }
  return "";
};

// src/components/ErrorMessage/ErrorMessage.tsx
var import_icons = require("@simplybusiness/icons");
var import_dedupe4 = __toESM(require("classnames/dedupe"));

// src/components/Icon/Icon.tsx
var import_dedupe = __toESM(require("classnames/dedupe"));
var import_Icon = require("@simplybusiness/mobius/src/components/Icon/Icon.css");
var import_jsx_runtime = require("react/jsx-runtime");
var ICON_PREFIX = "mobius-icon";
var capitaliseFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);
function Icon({
  ref,
  icon,
  className,
  size = "xs",
  color,
  fixedWidth,
  spin,
  spinReverse,
  title,
  ...otherProps
}) {
  if (!icon) {
    throw new Error("Must specify icon object");
  }
  const classes = (0, import_dedupe.default)(
    "mobius",
    "mobius-icon",
    `svg-inline--${ICON_PREFIX}`,
    `--size-${size}`,
    className,
    {
      [`${ICON_PREFIX}-fw`]: fixedWidth,
      [`${ICON_PREFIX}-spin`]: spin || spinReverse,
      [`${ICON_PREFIX}-spin-reverse`]: spinReverse
    }
  );
  const { iconName, width, height, svgPathData } = icon;
  const formattedIconName = iconName.split("-").join(" ");
  const defaultTitle = `${capitaliseFirstLetter(formattedIconName)} icon`;
  const titleText = title || defaultTitle;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
    "svg",
    {
      ref,
      focusable: "false",
      "data-icon": iconName,
      className: classes,
      role: "img",
      xmlns: "http://www.w3.org/2000/svg",
      viewBox: `0 0 ${width} ${height}`,
      style: { color },
      ...otherProps,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("title", { children: titleText }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { fill: "currentColor", d: svgPathData })
      ]
    }
  );
}

// src/components/TextOrHTML/TextOrHTML.tsx
var import_dedupe3 = __toESM(require("classnames/dedupe"));
var import_react3 = require("react");

// src/components/Text/Text.tsx
var import_dedupe2 = __toESM(require("classnames/dedupe"));
var import_Text = require("@simplybusiness/mobius/src/components/Text/Text.css");
var import_jsx_runtime2 = require("react/jsx-runtime");
var getElementType = (variant, elementType) => {
  if (elementType) {
    return elementType;
  }
  if (variant && ["h1", "h2", "h3", "h4"].includes(variant)) {
    return variant;
  }
  return "p";
};
var Text = ({ ref, elementType, ...props }) => {
  const { variant, className, spacing, ...otherProps } = props;
  const Element = getElementType(variant, elementType);
  const variantType = variant || Element;
  const classes = (0, import_dedupe2.default)(
    "mobius",
    "mobius-text",
    { [`--is-${variantType}`]: variantType },
    { [`--has-line-height-${spacing}`]: spacing },
    className
  );
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Element, { ref, ...otherProps, className: classes });
};
Text.displayName = "Text";

// src/components/TextOrHTML/TextOrHTML.tsx
var import_jsx_runtime3 = require("react/jsx-runtime");
var BLOCK_TAG = /<(div|p|ul|ol|li|h[1-6]|table|tr|td|th|blockquote|pre|hr|dl|dt|dd)[\s>/]/i;
var containsBlockHTML = (text) => BLOCK_TAG.test(text);
var containsHTML = (text) => /<[a-z/]/i.test(text) || /&(?:#\d+|#x[\da-f]+|[a-z]\w*);/i.test(text);
var buildTextClasses = (textProps, htmlClassName) => {
  const { variant, elementType, spacing, className } = textProps;
  const variantType = variant || getElementType(variant, elementType);
  return (0, import_dedupe3.default)(
    "mobius",
    "mobius-text",
    { [`--is-${variantType}`]: variantType },
    { [`--has-line-height-${spacing}`]: spacing },
    className,
    htmlClassName
  );
};
var TextOrHTML = ({
  ref,
  text,
  htmlClassName,
  htmlElementType,
  textWrapper = false,
  autoDetect = false,
  ...textProps
}) => {
  const hasBlockContent = autoDetect && containsBlockHTML(text);
  const dangerousHTML = (0, import_react3.useMemo)(() => ({ __html: text }), [text]);
  if (autoDetect && !hasBlockContent) {
    const { variant, spacing, elementType, className, ...domProps } = textProps;
    const Element = getElementType(variant, elementType);
    const classes = buildTextClasses(textProps, htmlClassName);
    return containsHTML(text) ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
      Element,
      {
        ref,
        ...domProps,
        className: classes,
        dangerouslySetInnerHTML: dangerousHTML
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Element, { ref, ...domProps, className: classes, children: text });
  }
  const DangerousComponent = htmlElementType ?? (hasBlockContent ? "div" : "span");
  const dangerousElement = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
    DangerousComponent,
    {
      className: htmlClassName,
      dangerouslySetInnerHTML: dangerousHTML
    }
  );
  if (textWrapper) {
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { ref, ...textProps, children: dangerousElement });
  }
  return dangerousElement;
};
TextOrHTML.displayName = "TextOrHTML";

// src/components/ErrorMessage/ErrorMessage.tsx
var import_ErrorMessage = require("@simplybusiness/mobius/src/components/ErrorMessage/ErrorMessage.css");
var import_jsx_runtime4 = require("react/jsx-runtime");
var ErrorMessage = ({
  id,
  errorMessage,
  className
}) => {
  const classes = (0, import_dedupe4.default)("mobius", "mobius-error-message", className);
  if (!errorMessage) return null;
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { id, className: classes, "data-testid": "ErrorMessage", role: "alert", children: [
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
      Icon,
      {
        icon: import_icons.error,
        className: "mobius-error-message__icon",
        "aria-hidden": "true"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
      TextOrHTML,
      {
        elementType: "span",
        className: "mobius-error-message__text",
        text: errorMessage
      }
    )
  ] });
};
ErrorMessage.displayName = "ErrorMessage";

// src/components/Label/Label.tsx
var import_dedupe5 = __toESM(require("classnames/dedupe"));
var import_Label = require("@simplybusiness/mobius/src/components/Label/Label.css");
var import_jsx_runtime5 = require("react/jsx-runtime");
var Label = ({ ref, ...props }) => {
  const { elementType: Element = "label", children, ...otherProps } = props;
  const classes = (0, import_dedupe5.default)("mobius", "mobius-label", props.className);
  otherProps.className = classes;
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Element, { ref, ...otherProps, className: classes, children });
};
Label.displayName = "Label";

// src/components/Stack/Stack.tsx
var import_dedupe6 = __toESM(require("classnames/dedupe"));
var import_Stack = require("@simplybusiness/mobius/src/components/Stack/Stack.css");
var import_jsx_runtime6 = require("react/jsx-runtime");
var Stack = ({ ref, ...props }) => {
  const { elementType: Element = "div", gap, ...otherProps } = props;
  const classes = (0, import_dedupe6.default)(
    "mobius",
    "mobius-stack",
    {
      [`--gap-${gap}`]: gap
    },
    otherProps.className
  );
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Element, { ref, ...otherProps, className: classes });
};
Stack.displayName = "Stack";

// src/components/TextField/adornmentWithClassName.ts
var import_dedupe7 = __toESM(require("classnames/dedupe"));
var import_react4 = require("react");
var adornmentWithClassName = (component, validationClasses, className) => {
  if (!component) return null;
  const typedComponent = component;
  return (0, import_react4.cloneElement)(typedComponent, {
    className: (0, import_dedupe7.default)(
      typedComponent.props.className,
      validationClasses,
      className
    )
  });
};

// src/components/TextField/TextField.tsx
var import_TextField = require("@simplybusiness/mobius/src/components/TextField/TextField.css");
var import_jsx_runtime7 = require("react/jsx-runtime");
var TextFieldInner = ({ ref, ...props }) => {
  const {
    isDisabled,
    type = "text",
    isInvalid,
    className,
    label,
    errorMessage,
    children,
    isRequired,
    prefixInside,
    prefixOutside,
    suffixInside,
    suffixOutside,
    autoComplete,
    isReadOnly,
    ...otherProps
  } = props;
  const resolvedAutoComplete = autoComplete ?? (type === "email" ? "email" : type === "tel" ? "tel" : void 0);
  const { inputProps, labelProps, errorMessageProps } = useTextField({
    ...props,
    autoComplete: resolvedAutoComplete,
    "aria-errormessage": errorMessage
  });
  const hidden = type === "hidden";
  const validationClasses = useValidationClasses({ isInvalid });
  const textfieldClasses = {
    "--is-disabled": isDisabled,
    "--is-required": typeof isRequired === "boolean" && isRequired,
    "--is-optional": typeof isRequired === "boolean" && !isRequired,
    "--is-hidden": hidden,
    [className || ""]: true
  };
  const sharedClasses = (0, import_dedupe8.default)(validationClasses, textfieldClasses);
  const labelClasses = (0, import_dedupe8.default)(
    {
      "--is-disabled": isDisabled
    },
    validationClasses
  );
  const containerClasses = (0, import_dedupe8.default)(
    "mobius",
    "mobius-text-field",
    sharedClasses
  );
  const inputClasses = (0, import_dedupe8.default)(
    "mobius",
    "mobius-text-field__input",
    sharedClasses
  );
  const inputWrapperClasses = (0, import_dedupe8.default)(
    "mobius-text-field__input-wrapper",
    sharedClasses
  );
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Stack, { gap: "xs", className: containerClasses, children: [
    label && !hidden && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Label, { ...labelProps, className: labelClasses, children: label }),
    /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "mobius-text-field__inner-container", children: [
      adornmentWithClassName(
        prefixOutside,
        labelClasses,
        "mobius-text-field__prefix-outside"
      ),
      /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: inputWrapperClasses, children: [
        adornmentWithClassName(
          prefixInside,
          labelClasses,
          "mobius-text-field__prefix-inside"
        ),
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
          "input",
          {
            ...otherProps,
            ...inputProps,
            ref,
            type,
            className: inputClasses
          }
        ),
        adornmentWithClassName(
          suffixInside,
          labelClasses,
          "mobius-text-field__suffix-inside"
        )
      ] }),
      adornmentWithClassName(
        suffixOutside,
        labelClasses,
        "mobius-text-field__suffix-outside"
      )
    ] }),
    children && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "mobius-text-field__children", children }),
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ErrorMessage, { ...errorMessageProps, errorMessage })
  ] });
};
var TextField = (0, import_react5.memo)(TextFieldInner);
TextField.displayName = "TextField";

// src/components/DateField/validation.ts
var convertToDateFormat = (date, format) => {
  const dateParts = date.split(/[-/]/);
  const formatParts = format ? format.split(/[-/]/) : ["yyyy", "mm", "dd"];
  const dateObj = {};
  const formattedDate = [];
  for (let i = 0; i < formatParts.length; i++) {
    dateObj[formatParts[i]] = dateParts[i] ? parseInt(dateParts[i], 10) : 0;
  }
  formattedDate.push(dateObj["yyyy"]?.toString() || "0000");
  formattedDate.push(
    (dateObj["mm"] < 10 ? "0" : "") + (dateObj["mm"]?.toString() || "00")
  );
  formattedDate.push(
    (dateObj["dd"] < 10 ? "0" : "") + (dateObj["dd"]?.toString() || "00")
  );
  return formattedDate.join("-");
};
var isValidDate = (date, format = "yyyy-mm-dd") => {
  if (!date) return true;
  const standardDate = convertToDateFormat(date, format);
  const [yearStr, monthStr, dayStr] = standardDate.split("-");
  const year = parseInt(yearStr, 10);
  const month = parseInt(monthStr, 10);
  const day = parseInt(dayStr, 10);
  if (month < 1 || month > 12) {
    return false;
  }
  const daysInMonth = new Date(year, month, 0).getDate();
  return day > 0 && day <= daysInMonth;
};

// src/components/DateField/DateField.tsx
var import_jsx_runtime8 = require("react/jsx-runtime");
var MIN_MAX_ERROR = '"min" value should not be greater than "max" value.';
var DateField = ({ ref, ...props }) => {
  const {
    min,
    max,
    format,
    className,
    errorMessage,
    defaultValue,
    value,
    ...otherProps
  } = props;
  const [error2, setError] = (0, import_react6.useState)(errorMessage);
  const [isInvalid, setIsInvalid] = (0, import_react6.useState)(void 0);
  const localRef = (0, import_react6.useRef)(null);
  const classes = (0, import_dedupe9.default)("mobius-date-field", className);
  const formattedMin = min ? convertToDateFormat(min, format) : void 0;
  const formattedMax = max ? convertToDateFormat(max, format) : void 0;
  const formattedDefaultValue = defaultValue ? convertToDateFormat(defaultValue, format) : void 0;
  const formattedValue = value ? convertToDateFormat(value, format) : void 0;
  const setInvalidState = (error3) => {
    setError(error3);
    setIsInvalid(true);
  };
  const setValidState = () => {
    setError(props.errorMessage);
    setIsInvalid(false);
  };
  (0, import_react6.useEffect)(() => {
    if (!isValidDate(min, format)) {
      setInvalidState(`Invalid min date: ${min}`);
      return;
    }
    if (!isValidDate(max, format)) {
      setInvalidState(`Invalid max date: ${max}`);
      return;
    }
    if (min && max) {
      const minDate = new Date(min);
      const maxDate = new Date(max);
      if (minDate > maxDate) {
        setInvalidState(MIN_MAX_ERROR);
      } else {
        setValidState();
      }
    } else {
      setValidState();
    }
  }, [min, max, format]);
  const validate = () => {
    const isValidInput = localRef.current?.checkValidity();
    if (!isValidInput) {
      setInvalidState("Invalid date input");
    } else {
      setValidState();
    }
  };
  const handleBlur = (event) => {
    validate();
    otherProps.onBlur?.(event);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
    TextField,
    {
      ref: mergeRefs([localRef, ref]),
      className: classes,
      type: "date",
      min: formattedMin,
      max: formattedMax,
      errorMessage: errorMessage ?? error2,
      isInvalid,
      defaultValue: formattedDefaultValue,
      value: formattedValue,
      onBlur: handleBlur,
      ...otherProps
    }
  );
};
DateField.displayName = "DateField";
//# sourceMappingURL=index.js.map
