"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/AddressLookup/AddressLookup.tsx
var AddressLookup_exports = {};
__export(AddressLookup_exports, {
  AddressLookup: () => AddressLookup
});
module.exports = __toCommonJS(AddressLookup_exports);
var import_icons2 = require("@simplybusiness/icons");
var import_react11 = require("react");

// src/components/Combobox/Combobox.tsx
var import_mobius_hooks3 = require("@simplybusiness/mobius-hooks");
var import_dedupe11 = __toESM(require("classnames/dedupe"));
var import_react10 = require("react");

// src/hooks/useBreakpoint/useBreakpoint.tsx
var import_mobius_hooks = require("@simplybusiness/mobius-hooks");
var import_react = require("react");
var DEFAULT_BREAKPOINTS = [
  { size: "xs", value: 320 },
  { size: "sm", value: 480 },
  { size: "md", value: 670 },
  { size: "lg", value: 960 },
  { size: "xl", value: 1200 },
  { size: "xxl", value: 1320 }
];
var PASSIVE = { passive: true };
var getBreakpoint = (breakpoints, windowWidth) => {
  const closest = breakpoints.findIndex(
    (breakpoint) => breakpoint.value >= windowWidth + 1
  );
  const smallest = breakpoints[0];
  const largest = breakpoints[breakpoints.length - 1];
  const match = breakpoints[closest - 1];
  if (closest === 0) return smallest;
  if (closest === -1) return largest;
  return match;
};
var useBreakpoint = (customBreakpoints) => {
  const isClientSide = (0, import_mobius_hooks.useIsClient)();
  const breakpoints = customBreakpoints || DEFAULT_BREAKPOINTS;
  const defaultBreakpoint = breakpoints[0];
  const [windowWidth, setWindowWidth] = (0, import_react.useState)(
    typeof globalThis?.window !== "undefined" ? window.innerWidth : defaultBreakpoint.value
  );
  (0, import_mobius_hooks.useWindowEvent)("resize", () => setWindowWidth(window.innerWidth), PASSIVE);
  const debouncedWidth = (0, import_mobius_hooks.useDebouncedValue)(windowWidth, 200);
  const currentBreakpoint = (0, import_react.useMemo)(
    () => !isClientSide || breakpoints.length === 0 ? defaultBreakpoint : getBreakpoint(breakpoints, debouncedWidth),
    [isClientSide, breakpoints, defaultBreakpoint, debouncedWidth]
  );
  const up = (0, import_react.useCallback)(
    (size) => {
      const sizeIndex = breakpoints.findIndex((item) => item.size === size);
      if (sizeIndex === -1) {
        return false;
      }
      const currentIndex = breakpoints.findIndex(
        (item) => item.size === currentBreakpoint.size
      );
      return currentIndex >= sizeIndex;
    },
    [currentBreakpoint, breakpoints]
  );
  const down = (0, import_react.useCallback)(
    (size) => {
      const sizeIndex = breakpoints.findIndex((item) => item.size === size);
      if (sizeIndex === -1) {
        return true;
      }
      const currentIndex = breakpoints.findIndex(
        (item) => item.size === currentBreakpoint.size
      );
      return currentIndex <= sizeIndex;
    },
    [currentBreakpoint, breakpoints]
  );
  return {
    breakpoint: currentBreakpoint,
    up,
    down
  };
};

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

// src/hooks/useLabel/useLabel.tsx
var import_react2 = require("react");
function useLabel({
  id: providedId,
  label,
  "aria-label": ariaLabel,
  "aria-labelledby": ariaLabelledby,
  labelElementType = "label"
}) {
  let labelProps = {};
  let fieldProps = {};
  const hasWarnedAboutMissingLabels = (0, import_react2.useRef)(false);
  const fallbackId = (0, import_react2.useId)();
  const id = providedId || fallbackId;
  const labelId = (0, import_react2.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_react3 = require("react");
function useTextField(props) {
  const {
    isDisabled = false,
    isReadOnly = false,
    isRequired = false,
    inputElementType = "input"
  } = props;
  const { labelProps, fieldProps } = useLabel(props);
  const descriptionId = (0, import_react3.useId)();
  const descriptionProps = { id: descriptionId };
  const errorMessageId = (0, import_react3.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/TextField/TextField.tsx
var import_dedupe8 = __toESM(require("classnames/dedupe"));
var import_react6 = require("react");

// 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_react4 = 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_react4.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_react5 = require("react");
var adornmentWithClassName = (component, validationClasses, className) => {
  if (!component) return null;
  const typedComponent = component;
  return (0, import_react5.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_react6.memo)(TextFieldInner);
TextField.displayName = "TextField";

// src/components/VisuallyHidden/VisuallyHidden.tsx
var import_jsx_runtime8 = require("react/jsx-runtime");
function VisuallyHidden(props) {
  const {
    className,
    children,
    elementType: Component = "div",
    ...otherProps
  } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
    Component,
    {
      className,
      style: {
        border: 0,
        clip: "rect(0 0 0 0)",
        clipPath: "inset(50%)",
        height: "1px",
        margin: "-1px",
        overflow: "hidden",
        padding: 0,
        position: "absolute",
        width: "1px",
        whiteSpace: "nowrap"
      },
      ...otherProps,
      children
    }
  );
}

// src/components/Combobox/Listbox.tsx
var import_dedupe10 = __toESM(require("classnames/dedupe"));

// src/components/Combobox/Option.tsx
var import_react7 = require("react");
var import_dedupe9 = __toESM(require("classnames/dedupe"));

// src/components/Combobox/utils.tsx
function isOptionGroup(options) {
  if (!options) return false;
  return typeof options[0] === "object" && "options" in options[0] && options[0].options !== void 0 && "heading" in options[0] && options[0].heading !== void 0;
}
var getOptionValue = (option) => typeof option === "string" ? option : option?.value;
var getOptionLabel = (option) => typeof option === "string" ? option : option?.label;
function filterOptions(options, inputValue) {
  if (isOptionGroup(options)) {
    return options.map((optionGroup) => ({
      ...optionGroup,
      options: optionGroup.options.filter(
        (option) => getOptionLabel(option).toLowerCase().includes(inputValue.toLowerCase())
      )
    })).filter((optionGroup) => optionGroup.options.length > 0);
  }
  return options.filter(
    (option) => getOptionLabel(option).toLowerCase().includes(inputValue.toLowerCase())
  );
}
var buildOptionTestId = (prefix, value) => `${prefix}-${value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "")}`;

// src/components/Combobox/Option.tsx
var import_jsx_runtime9 = require("react/jsx-runtime");
var Option = ({
  option,
  isHighlighted,
  onOptionSelect,
  optionComponent: OptionComponent,
  optionTestIdPrefix,
  id
}) => {
  const optionRef = (0, import_react7.useRef)(null);
  const optionValue = getOptionValue(option) || "";
  const testId = buildOptionTestId(
    optionTestIdPrefix || "combobox-option",
    optionValue
  );
  (0, import_react7.useEffect)(() => {
    if (isHighlighted && optionRef.current && optionRef.current.scrollIntoView) {
      optionRef.current.scrollIntoView({ block: "nearest" });
    }
  }, [isHighlighted]);
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
    "li",
    {
      ref: optionRef,
      role: "option",
      "data-testid": testId,
      id,
      "aria-selected": isHighlighted,
      onMouseDown: () => onOptionSelect(option),
      className: (0, import_dedupe9.default)("mobius-combobox__option", "has-pii", {
        "mobius-combobox__option--is-highlighted": isHighlighted
      }),
      children: OptionComponent ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(OptionComponent, { option, isHighlighted }) : getOptionLabel(option)
    },
    getOptionValue(option)
  );
};

// src/components/Combobox/Listbox.tsx
var import_jsx_runtime10 = require("react/jsx-runtime");
var getOptionKey = (option, index, groupIndex) => {
  let key;
  if (typeof option === "object" && option.id) key = option.id;
  else if (typeof option === "object") key = `${option.value}::${option.label}`;
  else if (typeof option === "string") key = option;
  else key = String(index);
  return groupIndex !== void 0 ? `${groupIndex}:${key}` : key;
};
var Listbox = ({
  id,
  isOpen = false,
  options,
  highlightedIndex,
  highlightedGroupIndex,
  onOptionSelect,
  optionComponent,
  optionTestIdPrefix
}) => {
  const classes = (0, import_dedupe10.default)("mobius-combobox__list", {
    "mobius-combobox__list--hidden": !isOpen
  });
  function getOptionId(option, groupIndex, index) {
    if (typeof option === "object" && "id" in option && typeof option.id === "string") {
      return option.id;
    }
    return isOptionGroup(options) ? `${id}-option-${groupIndex}-${index}` : `${id}-option-${index}`;
  }
  if (!isOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { role: "listbox", id, className: classes });
  }
  if (options && options.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { role: "listbox", id, className: classes, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "mobius-combobox__no-options", children: "No options" }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { role: "listbox", id, className: classes, children: isOptionGroup(options) ? options.map((option, groupIndex) => /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
    "ul",
    {
      role: "group",
      "aria-labelledby": `${id}-group-${groupIndex}`,
      className: "mobius-combobox__group",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
          "li",
          {
            role: "presentation",
            id: `${id}-group-${groupIndex}`,
            className: "mobius-combobox__group-label",
            children: option.heading
          }
        ),
        option.options.map((groupOption, index) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
          Option,
          {
            option: groupOption,
            isHighlighted: highlightedIndex === index && highlightedGroupIndex === groupIndex,
            onOptionSelect,
            optionComponent,
            optionTestIdPrefix,
            id: getOptionId(groupOption, groupIndex, index)
          },
          getOptionKey(groupOption, index, groupIndex)
        ))
      ]
    },
    option.heading
  )) : typeof options !== "undefined" ? options.map((option, index) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
    Option,
    {
      option,
      isHighlighted: highlightedIndex === index,
      onOptionSelect,
      optionComponent,
      optionTestIdPrefix,
      id: getOptionId(option, 0, index)
    },
    getOptionKey(option, index)
  )) : null });
};

// src/components/Combobox/useComboboxHighlight.tsx
var import_react8 = require("react");
function useComboboxHighlight(options) {
  const [highlightedIndex, setHighlightedIndex] = (0, import_react8.useState)(
    options && options.length ? 0 : -1
  );
  const [highlightedGroupIndex, setHighlightedGroupIndex] = (0, import_react8.useState)(0);
  function highlightNextOption() {
    const isGroup = isOptionGroup(options);
    if (!options) {
      return;
    }
    if (isGroup) {
      const group = options[highlightedGroupIndex];
      if (highlightedIndex === group.options.length - 1) {
        if (highlightedGroupIndex === options.length - 1) {
          return;
        }
        setHighlightedIndex(0);
        setHighlightedGroupIndex(highlightedGroupIndex + 1);
      } else {
        setHighlightedIndex(highlightedIndex + 1);
      }
    } else {
      if (highlightedIndex === options.length - 1) {
        return;
      }
      setHighlightedIndex(highlightedIndex + 1);
    }
  }
  function highlightPreviousOption() {
    const isGroup = isOptionGroup(options);
    if (highlightedIndex === 0 && highlightedGroupIndex === 0) {
      return;
    }
    if (isGroup) {
      if (highlightedIndex === 0) {
        const prevGroupIndex = highlightedGroupIndex - 1;
        const prevGroup = options[prevGroupIndex];
        setHighlightedGroupIndex(prevGroupIndex);
        setHighlightedIndex(prevGroup.options.length - 1);
      } else {
        setHighlightedIndex(highlightedIndex - 1);
      }
    } else {
      setHighlightedIndex(highlightedIndex - 1);
    }
  }
  function highlightFirstOption() {
    setHighlightedIndex(0);
    setHighlightedGroupIndex(0);
  }
  function highlightLastOption() {
    const isGroup = isOptionGroup(options);
    if (!options) {
      return;
    }
    if (isGroup) {
      const lastGroupIndex = options.length - 1;
      const lastGroup = options[lastGroupIndex];
      setHighlightedGroupIndex(lastGroupIndex);
      setHighlightedIndex(lastGroup.options.length - 1);
    } else {
      setHighlightedIndex(options.length - 1);
    }
  }
  const clearHighlight = () => {
    setHighlightedIndex(
      typeof options === "undefined" || options.length ? 0 : -1
    );
    setHighlightedGroupIndex(0);
  };
  return {
    highlightedIndex,
    highlightedGroupIndex,
    highlightPreviousOption,
    highlightNextOption,
    highlightFirstOption,
    highlightLastOption,
    clearHighlight
  };
}

// src/components/Combobox/useComboboxOptions.ts
var import_mobius_hooks2 = require("@simplybusiness/mobius-hooks");
var import_react9 = require("react");
function useComboboxOptions({
  options,
  asyncOptions,
  delay = 300,
  minSearchLength = 3,
  inputValue = "",
  skipNextDebounceRef,
  onSearched
}) {
  const [filteredOptions, setFilteredOptions] = (0, import_react9.useState)(void 0);
  const debouncedInputValue = (0, import_mobius_hooks2.useDebouncedValue)(
    inputValue,
    // Don't debounce synchronous options
    options ? 0 : delay
  );
  const [isLoading, setIsLoading] = (0, import_react9.useState)(false);
  const [error2, setError] = (0, import_react9.useState)(null);
  const asyncOptionsRef = (0, import_react9.useRef)(asyncOptions);
  asyncOptionsRef.current = asyncOptions;
  const onSearchedRef = (0, import_react9.useRef)(onSearched);
  onSearchedRef.current = onSearched;
  (0, import_react9.useEffect)(() => {
    const controller = new AbortController();
    const { signal } = controller;
    const fetchOptions = async () => {
      setIsLoading(true);
      setError(null);
      try {
        if (asyncOptionsRef.current) {
          if (debouncedInputValue.length < minSearchLength) {
            setFilteredOptions(void 0);
            return;
          }
          const result = await asyncOptionsRef.current(debouncedInputValue, {
            signal
          });
          setFilteredOptions(result);
          onSearchedRef.current?.(debouncedInputValue);
        } else if (options) {
          setFilteredOptions(filterOptions(options, debouncedInputValue));
        } else {
          setError(new Error("No options provided"));
        }
      } catch (e) {
        if (e instanceof DOMException && e.name === "AbortError") {
          return;
        }
        setError(e);
      } finally {
        setIsLoading(false);
      }
    };
    if (!skipNextDebounceRef?.current) {
      void fetchOptions();
    } else {
      skipNextDebounceRef.current = false;
    }
    return () => {
      controller.abort();
    };
  }, [
    debouncedInputValue,
    options,
    delay,
    minSearchLength,
    skipNextDebounceRef
  ]);
  function updateFilteredOptions(newOptions) {
    setIsLoading(true);
    return newOptions.then(setFilteredOptions).catch(setError).finally(() => setIsLoading(false));
  }
  return {
    filteredOptions,
    updateFilteredOptions,
    isLoading,
    error: error2,
    isError: error2 != null
  };
}

// src/components/Combobox/Combobox.tsx
var import_Combobox = require("@simplybusiness/mobius/src/components/Combobox/Combobox.css");
var import_jsx_runtime11 = require("react/jsx-runtime");
var ComboboxInner = ({
  ref,
  ...props
}) => {
  const {
    id,
    defaultValue,
    value,
    options,
    asyncOptions,
    delay,
    minSearchLength,
    onSelected,
    className,
    placeholder,
    icon,
    onBlur,
    onFocus,
    onChange,
    // onSearched, // unused prop, consider removing
    optionComponent,
    optionTestIdPrefix,
    errorMessage,
    ...otherProps
  } = props;
  const skipNextDebounceRef = (0, import_react10.useRef)(false);
  const fallbackRef = (0, import_react10.useRef)(null);
  const [inputValue, setInputValue] = (0, import_react10.useState)(defaultValue || "");
  const [isOpen, setIsOpen] = (0, import_react10.useState)(false);
  const [isChanging, setIsChanging] = (0, import_react10.useState)(false);
  const { filteredOptions, updateFilteredOptions, isLoading, error: error2 } = useComboboxOptions({
    options,
    asyncOptions,
    inputValue,
    delay,
    minSearchLength,
    skipNextDebounceRef
  });
  const [validationError, setValidationError] = (0, import_react10.useState)(
    error2?.message || errorMessage
  );
  const {
    highlightedIndex,
    highlightedGroupIndex,
    highlightNextOption,
    highlightPreviousOption,
    highlightFirstOption,
    highlightLastOption,
    clearHighlight
  } = useComboboxHighlight(filteredOptions);
  const inputRef = ref || fallbackRef;
  const listboxId = (0, import_react10.useId)();
  const statusId = (0, import_react10.useId)();
  const blurTimeoutRef = (0, import_react10.useRef)(null);
  const userInteractedRef = (0, import_react10.useRef)(false);
  const justSelectedRef = (0, import_react10.useRef)(false);
  const { down } = useBreakpoint();
  const isMobile = down("md");
  (0, import_react10.useEffect)(() => {
    setValidationError(error2?.message || errorMessage);
  }, [error2, errorMessage]);
  const getEmptyValue = () => {
    const firstOption = filteredOptions ? isOptionGroup(filteredOptions) ? filteredOptions[0]?.options[0] : filteredOptions[0] : options ? isOptionGroup(options) ? options[0]?.options[0] : options[0] : void 0;
    if (typeof firstOption === "string") {
      return "";
    }
    return { label: "", value: "" };
  };
  const handleFocus = (e) => {
    onFocus?.(e);
    if (!filteredOptions || filteredOptions.length === 0) return;
    if (blurTimeoutRef.current) {
      clearTimeout(blurTimeoutRef.current);
      blurTimeoutRef.current = null;
    }
    const isNaturalFocus = userInteractedRef.current || e.relatedTarget !== null;
    if (userInteractedRef.current) {
      userInteractedRef.current = false;
    }
    if (justSelectedRef.current && !isNaturalFocus) {
      return;
    }
    if (isNaturalFocus) {
      setIsOpen(true);
      justSelectedRef.current = false;
    }
  };
  (0, import_react10.useEffect)(() => {
    if (!inputRef || typeof inputRef === "function") return;
    const inputElement = inputRef.current;
    if (!inputElement) return;
    const handleMouseDown = () => {
      userInteractedRef.current = true;
    };
    inputElement.addEventListener("mousedown", handleMouseDown);
    return () => {
      inputElement.removeEventListener("mousedown", handleMouseDown);
    };
  }, [inputRef]);
  (0, import_mobius_hooks3.useOnUnmount)(() => {
    if (blurTimeoutRef.current) {
      clearTimeout(blurTimeoutRef.current);
    }
  });
  const handleInputChange = (e) => {
    const newValue = e.target.value;
    setInputValue(newValue);
    setValidationError(void 0);
    justSelectedRef.current = false;
    setIsChanging(true);
    if (!asyncOptions) {
      setIsOpen(true);
    }
    clearHighlight();
    onChange?.(e);
  };
  const handleOptionSelect = (option) => {
    const val = getOptionValue(option);
    if (!val && val !== "") return;
    if (typeof option === "object" && "callback" in option && option.callback && typeof option.callback === "function") {
      justSelectedRef.current = true;
      setTimeout(() => {
        if (inputRef && typeof inputRef !== "function" && inputRef.current) {
          inputRef.current.focus();
        }
      }, 0);
      const callbackPromise = option.callback();
      updateFilteredOptions(callbackPromise);
      callbackPromise.then(() => {
        setIsOpen(true);
        setIsChanging(true);
      }).catch(() => {
      });
      return;
    }
    skipNextDebounceRef.current = true;
    justSelectedRef.current = true;
    setIsChanging(false);
    setValidationError(void 0);
    setIsOpen(false);
    setInputValue(val);
    onSelected?.(option);
  };
  const getFirstOption = () => {
    if (!filteredOptions) return void 0;
    if (isOptionGroup(filteredOptions)) {
      return filteredOptions[0]?.options[0];
    }
    return filteredOptions[0];
  };
  const getHighlightedOption = () => {
    if (!filteredOptions) return void 0;
    if (highlightedIndex === -1) return void 0;
    if (isOptionGroup(filteredOptions)) {
      const group = filteredOptions[highlightedGroupIndex];
      return group?.options[highlightedIndex];
    }
    return filteredOptions[highlightedIndex];
  };
  const getHighlightedOptionId = () => {
    const option = getHighlightedOption();
    if (!option) return void 0;
    if (isOptionGroup(filteredOptions)) {
      return `${listboxId}-option-${highlightedGroupIndex}-${highlightedIndex}`;
    }
    return `${listboxId}-option-${highlightedIndex}`;
  };
  const handleBlur = (e) => {
    if (!justSelectedRef.current) {
      const typedText = inputValue.trim();
      const typedTextLower = typedText.toLowerCase();
      const highlightedOption = getHighlightedOption();
      const label = getOptionLabel(highlightedOption);
      if (typedTextLower === label?.toLowerCase()) {
        setTimeout(() => {
          handleOptionSelect(highlightedOption);
        }, 0);
      } else if (typedText === "") {
        setTimeout(() => {
          handleOptionSelect(getEmptyValue());
        }, 0);
      } else {
        setValidationError(
          errorMessage || "Please select an option from the list"
        );
        setTimeout(() => {
          setInputValue("");
        }, 0);
      }
    }
    blurTimeoutRef.current = setTimeout(() => {
      onBlur?.(e);
      setIsOpen(false);
      setIsChanging(false);
    }, 150);
  };
  const handleKeyDown = (e) => {
    switch (e.key) {
      case "ArrowDown":
        e.preventDefault();
        justSelectedRef.current = false;
        setIsOpen(true);
        highlightNextOption();
        break;
      case "ArrowUp":
        e.preventDefault();
        justSelectedRef.current = false;
        setIsOpen(true);
        highlightPreviousOption();
        break;
      case "Home":
        e.preventDefault();
        justSelectedRef.current = false;
        setIsOpen(true);
        highlightFirstOption();
        break;
      case "End":
        e.preventDefault();
        justSelectedRef.current = false;
        setIsOpen(true);
        highlightLastOption();
        break;
      case "Enter":
        e.preventDefault();
        if (isOpen) {
          const selectedOption = getHighlightedOption() || getFirstOption();
          if (selectedOption) {
            handleOptionSelect(selectedOption);
          }
        }
        break;
      case "Escape":
        e.preventDefault();
        setInputValue("");
        setIsOpen(false);
        clearHighlight();
        break;
      default:
    }
  };
  (0, import_react10.useEffect)(() => {
    if (value) {
      setInputValue(value);
    }
  }, [value]);
  (0, import_react10.useEffect)(() => {
    if (asyncOptions && isChanging) {
      setIsOpen(!!filteredOptions && filteredOptions.length > 0);
    }
  }, [filteredOptions, asyncOptions, isChanging]);
  const classes = (0, import_dedupe11.default)(
    "mobius mobius-combobox",
    {
      "mobius-combobox--is-expanded": isOpen,
      "mobius-combobox--is-loading": isLoading,
      "mobius-combobox--is-mobile": isMobile
    },
    className
  );
  const getStatusMessage = () => {
    if (isLoading) return "Loading options";
    if (!filteredOptions || filteredOptions.length === 0) {
      return isChanging ? "No options found" : "";
    }
    const count = isOptionGroup(filteredOptions) ? filteredOptions.reduce((sum, group) => sum + group.options.length, 0) : filteredOptions.length;
    return isOpen && isChanging ? `${count} option${count === 1 ? "" : "s"} available` : "";
  };
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { id, "data-testid": "mobius-combobox__wrapper", className: classes, children: [
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      VisuallyHidden,
      {
        role: "status",
        "aria-live": "polite",
        id: statusId,
        elementType: "div",
        className: "mobius-combobox__status",
        children: getStatusMessage()
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      TextField,
      {
        ...otherProps,
        className: "mobius-combobox__input",
        role: "combobox",
        value: inputValue,
        placeholder,
        onFocus: handleFocus,
        onBlur: handleBlur,
        onKeyDown: handleKeyDown,
        onChange: handleInputChange,
        autoComplete: "off",
        "aria-describedby": isLoading ? statusId : void 0,
        "aria-autocomplete": "list",
        "aria-haspopup": "listbox",
        "aria-controls": isOpen ? listboxId : void 0,
        "aria-expanded": isOpen,
        "aria-activedescendant": highlightedIndex === -1 ? void 0 : getHighlightedOptionId(),
        prefixInside: icon,
        ref: inputRef,
        errorMessage: errorMessage || validationError || error2?.message
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      Listbox,
      {
        id: listboxId,
        isOpen,
        isLoading,
        options: filteredOptions,
        highlightedIndex,
        highlightedGroupIndex,
        onOptionSelect: handleOptionSelect,
        optionComponent,
        optionTestIdPrefix
      }
    )
  ] });
};
var Combobox = ComboboxInner;

// src/components/AddressLookup/utils.ts
function isLoqateErrorResponse(response) {
  return Array.isArray(response) && response.some((item) => "Error" in item);
}

// src/components/AddressLookup/AddressLookup.tsx
var import_jsx_runtime12 = require("react/jsx-runtime");
function optionsFromResponse({ Items }, addressLookupService) {
  if (!Items || !Array.isArray(Items)) {
    throw Error("No address found");
  }
  if (isLoqateErrorResponse(Items)) {
    throw Error(Items[0].Description);
  }
  return Items.map((item) => ({
    id: item.Id,
    label: `${item.Text}, ${item.Description}`,
    value: item.Text,
    // Add a callback to trigger secondary search
    // if the address type is not "Address"
    callback: item.Type === "Address" ? void 0 : async () => {
      const result = await addressLookupService.findById(item.Id);
      return optionsFromResponse(result, addressLookupService);
    }
  }));
}
var AddressLookup = ({
  ref,
  addressLookupService,
  onAddressSelected,
  onOptionsDisplayed,
  onError,
  errorMessage,
  ...otherProps
}) => {
  const [error2, _setError] = (0, import_react11.useState)(null);
  const setError = (0, import_react11.useCallback)(
    (newError) => {
      if (newError != null) onError?.(newError);
      _setError(newError);
    },
    [onError]
  );
  const asyncOptions = (0, import_react11.useCallback)(
    async (searchTerm) => {
      try {
        const response = await addressLookupService.search(searchTerm);
        setError(null);
        const options = optionsFromResponse(response, addressLookupService);
        onOptionsDisplayed?.();
        return options;
      } catch (e) {
        setError(e);
        return [];
      }
    },
    [addressLookupService, setError, onOptionsDisplayed]
  );
  const handleSelected = (selected) => {
    setError(null);
    const isEmpty = typeof selected === "string" ? selected === "" : !selected.id && !selected.value;
    if (isEmpty) {
      return Promise.resolve();
    }
    if (typeof selected === "string" || !selected.id) {
      setError(new Error("Selected option missing id"));
      return Promise.resolve();
    }
    return addressLookupService.get(selected.id).then(onAddressSelected).catch(setError);
  };
  const realErrorMessage = error2 && "An error occurred" || errorMessage;
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
    Combobox,
    {
      ...otherProps,
      ref,
      onSelected: handleSelected,
      asyncOptions,
      errorMessage: realErrorMessage,
      icon: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Icon, { icon: import_icons2.search })
    }
  );
};
AddressLookup.displayName = "AddressLookup";
//# sourceMappingURL=AddressLookup.js.map
