"use strict";
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const styles_lib_components_Box_Box_cjs = require("../Box/Box.cjs");
const parseHighlights = require("autosuggest-highlight/parse/index.js");
const styles_lib_components_Textarea_Highlight_Highlight_cjs = require("./Highlight/Highlight.cjs");
const styles_lib_components_private_Field_Field_cjs = require("../private/Field/Field.cjs");
const styles_lib_components_Accordion_AccordionItem_cjs = require("../Accordion/AccordionItem.cjs");
const styles_lib_components_Textarea_Textarea_css_cjs = require("./Textarea.css.cjs");
const _interopDefaultCompat = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
const parseHighlights__default = /* @__PURE__ */ _interopDefaultCompat(parseHighlights);
const formatRanges = (value, highlightRanges, tone) => {
  if (highlightRanges && value) {
    let lastEnd = 0;
    const validatedAndSortedRanges = highlightRanges.sort((a, b) => a.start > b.start ? 1 : -1).reduce((acc, { end, start }) => {
      const resolvedEnd = end || value.length;
      if (resolvedEnd <= start) {
        return acc;
      }
      const adjustedRange = [];
      if (resolvedEnd > lastEnd) {
        adjustedRange.push({
          // if overlapping, start from end of last range otherwise start from specified range
          start: start < lastEnd ? lastEnd : start,
          end
        });
        lastEnd = resolvedEnd;
      }
      return [...acc, ...adjustedRange];
    }, []);
    return parseHighlights__default.default(
      value,
      validatedAndSortedRanges.map(({ start, end }) => [
        start,
        end || value.length
      ])
    ).reduce((acc, { text, highlight }, i) => {
      if (text) {
        acc.push(
          highlight ? /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Textarea_Highlight_Highlight_cjs.Highlight, { tone, children: text }, i) : text
        );
      }
      return acc;
    }, []);
  }
  return [value];
};
const getCharacterLimitStatus = ({
  characterLimit,
  value
}) => {
  const inputLength = String(value).length;
  if (inputLength < Math.ceil(characterLimit * 0.7 / 10) * 10) {
    return null;
  }
  const diff = characterLimit - inputLength;
  const valid = diff >= 0;
  return /* @__PURE__ */ jsxRuntime.jsx(styles_lib_components_Accordion_AccordionItem_cjs.Text, { size: "small", tone: valid ? "secondary" : "critical", children: diff });
};
const pxToInt = (str) => typeof str === "string" ? parseInt(str.replace("px", ""), 10) : 0;
const calculateLines = (target, lines, lineLimit) => {
  const { paddingBottom, paddingTop, lineHeight } = window.getComputedStyle(target);
  if (!lineHeight.endsWith("px")) {
    return lines;
  }
  const padding = pxToInt(paddingTop) + pxToInt(paddingBottom);
  const currentRows = Math.floor(
    (target.scrollHeight - padding) / pxToInt(lineHeight)
  );
  if (target && target.value === "") {
    return lines;
  }
  return typeof lineLimit === "number" && currentRows > lineLimit ? lineLimit : currentRows;
};
const Textarea = React.forwardRef(
  ({
    value,
    onChange,
    onBlur,
    onFocus,
    onPaste,
    placeholder,
    characterLimit,
    highlightRanges: highlightRangesProp = [],
    lines = 3,
    lineLimit,
    grow = true,
    tone,
    spellCheck,
    ...restProps
  }, ref) => {
    const [rows, setRows] = React.useState(lines);
    const highlightsRef = React.useRef(null);
    const updateScroll = React.useCallback(
      (scrollTop) => {
        if (highlightsRef.current) {
          highlightsRef.current.scrollTop = scrollTop;
        }
      },
      [highlightsRef]
    );
    const inputLength = String(value).length;
    const hasExceededCharacterLimit = characterLimit && inputLength > characterLimit;
    const highlightTone = !hasExceededCharacterLimit && (tone === "critical" || tone === "caution") ? tone : "critical";
    const highlightRanges = hasExceededCharacterLimit ? [{ start: characterLimit }] : highlightRangesProp;
    const hasHighlights = highlightRanges.length > 0;
    return /* @__PURE__ */ jsxRuntime.jsx(
      styles_lib_components_private_Field_Field_cjs.Field,
      {
        ...restProps,
        tone,
        value,
        icon: void 0,
        prefix: void 0,
        secondaryMessage: characterLimit ? getCharacterLimitStatus({
          value,
          characterLimit
        }) : null,
        children: (overlays, { className, borderRadius, background, ...fieldProps }) => /* @__PURE__ */ jsxRuntime.jsxs(
          styles_lib_components_Box_Box_cjs.Box,
          {
            position: "relative",
            width: "full",
            zIndex: 0,
            background,
            borderRadius,
            children: [
              hasHighlights ? /* @__PURE__ */ jsxRuntime.jsx(
                styles_lib_components_Box_Box_cjs.Box,
                {
                  ref: highlightsRef,
                  position: "absolute",
                  overflow: "hidden",
                  pointerEvents: "none",
                  height: "full",
                  "aria-hidden": "true",
                  top: 0,
                  left: 0,
                  className: [styles_lib_components_Textarea_Textarea_css_cjs.highlights, className],
                  ...fieldProps,
                  children: formatRanges(String(value), highlightRanges, highlightTone)
                }
              ) : null,
              /* @__PURE__ */ jsxRuntime.jsx(
                styles_lib_components_Box_Box_cjs.Box,
                {
                  component: "textarea",
                  position: "relative",
                  zIndex: 1,
                  rows,
                  value,
                  onChange: (e) => {
                    if (grow) {
                      setRows(calculateLines(e.currentTarget, lines, lineLimit));
                    }
                    if (typeof onChange === "function") {
                      onChange(e);
                    }
                    if (hasHighlights) {
                      updateScroll(e.currentTarget.scrollTop);
                    }
                  },
                  onBlur,
                  onFocus,
                  onPaste,
                  onScroll: hasHighlights ? (event) => updateScroll(event.currentTarget.scrollTop) : void 0,
                  placeholder: !restProps.disabled ? placeholder : void 0,
                  spellCheck,
                  className: [styles_lib_components_Textarea_Textarea_css_cjs.field, className],
                  ...fieldProps,
                  ref
                }
              ),
              overlays
            ]
          }
        )
      }
    );
  }
);
Textarea.displayName = "Textarea";
exports.Textarea = Textarea;
exports.getCharacterLimitStatus = getCharacterLimitStatus;
