function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { forwardRef, useRef, useState } from "react";
import { classes } from "../../Combobox.tokens";
import { cx } from "../../../../../utils";
import { ComboboxChip } from "../ComboboxChip/ComboboxChip";
import { useFocusController, Keys } from "../../hooks";
import { StyledArrow, StyledChips, StyledContent, StyledLabel, StyledComboboxInput, StyledComboboxInputHelper, StyledComboboxTarget, StyledText } from "./ComboboxTarget.styles";
var hasChips = classes.hasChips, innerLabelUp = classes.innerLabelUp, arrowInverse = classes.arrowInverse, comboboxTargetArrow = classes.comboboxTargetArrow, comboboxTargeText = classes.comboboxTargeText, comboboxTargetInput = classes.comboboxTargetInput, comboboxTargetLabel = classes.comboboxTargetLabel;
/**
 * Элемент для выпадающего списка
 */ export var ComboboxTarget = /*#__PURE__*/ forwardRef(function(_0, _1) {
    var _ref = [
        _0,
        _1
    ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), values = _ref2.values, search = _ref2.search, label = _ref2.label, placeholder = _ref2.placeholder, opened = _ref2.opened, readOnly = _ref2.readOnly, disabled = _ref2.disabled, enumerationType = _ref2.enumerationType, valueType = _ref2.valueType, size = _ref2.size, closedWithoutChanges = _ref2.closedWithoutChanges, id = _ref2.id, chipsRefs = _ref2.chipsRefs, inputRef = _ref2.inputRef, onChange = _ref2.onChange, onSearch = _ref2.onSearch, onKeyDown = _ref2.onKeyDown, rest = _object_without_properties(_ref2, [
        "values",
        "search",
        "label",
        "placeholder",
        "opened",
        "readOnly",
        "disabled",
        "enumerationType",
        "valueType",
        "size",
        "closedWithoutChanges",
        "id",
        "chipsRefs",
        "inputRef",
        "onChange",
        "onSearch",
        "onKeyDown"
    ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
    var contentRef = useRef(null);
    var inputHelperRef = useRef(null);
    var _useState = _sliced_to_array(useState(false), 2), focused = _useState[0], setFocused = _useState[1];
    var controlledRefs = {
        contentRef: contentRef,
        inputHelperRef: inputHelperRef,
        inputRef: inputRef
    };
    var textContent = values === null || values === void 0 ? void 0 : values.map(function(param) {
        var _param = _sliced_to_array(param, 2), text = _param[1];
        return text;
    }).join(', ');
    var hasValue = values === null || values === void 0 ? void 0 : values.some(function(param) {
        var _param = _sliced_to_array(param, 1), value = _param[0];
        return value;
    });
    var isEnumerationComma = enumerationType === 'comma';
    var isExtraSmall = size === 'xs';
    var isInputNotEmpty = hasValue || search;
    var isInputActive = !hasValue && (opened || focused && !readOnly);
    var hasLabel = label && !isExtraSmall && isEnumerationComma;
    var hasOnlyLabel = !placeholder || label;
    var hasNoAnyTip = !placeholder && !label;
    var placeholderValue = !label && !hasValue || isExtraSmall ? placeholder : undefined;
    var withInnerLabelUp = !isExtraSmall && !hasNoAnyTip && hasOnlyLabel && (isInputActive || hasLabel && isInputNotEmpty) ? innerLabelUp : undefined;
    var withArrowInverse = opened ? arrowInverse : undefined;
    var withHasChips = hasValue && enumerationType === 'chip' ? hasChips : undefined;
    var isLabelVisible = !hasValue && !isExtraSmall || hasLabel;
    var isEnumerationVisible = hasValue && valueType !== 'single';
    var onChipClick = function onChipClick(event) {
        return event.stopPropagation();
    };
    var _useFocusController = useFocusController({
        controlledRefs: controlledRefs,
        opened: opened,
        hasValue: hasValue,
        textContent: textContent,
        search: search,
        values: values,
        valueType: valueType,
        readOnly: readOnly,
        closedWithoutChanges: closedWithoutChanges,
        updateFocused: setFocused,
        updateSearch: onSearch,
        onChipClick: onChipClick
    }), onClickText = _useFocusController.onClickText, onFocusInput = _useFocusController.onFocusInput, onBlurInput = _useFocusController.onBlurInput;
    var onChipClear = function onChipClear(value, text, index) {
        var newValue = values === null || values === void 0 ? void 0 : values.filter(function(param) {
            var _param = _sliced_to_array(param, 2), itemValue = _param[0], itemText = _param[1];
            return !(itemValue === value && itemText === text);
        }).map(function(param) {
            var _param = _sliced_to_array(param, 1), itemValue = _param[0];
            return itemValue;
        });
        chipsRefs === null || chipsRefs === void 0 ? void 0 : chipsRefs.current.splice(index, 1);
        onChange === null || onChange === void 0 ? void 0 : onChange(newValue);
    };
    var onChipKeyDown = function onChipKeyDown(value, text, index, event) {
        var code = event.code;
        if (code === Keys.Tab) {
            event.preventDefault();
        }
        if (code === Keys.Backspace) {
            onChipClear(value, text, index);
        }
    };
    var onKeyDownInput = function onKeyDownInput(event) {
        var _event_currentTarget;
        var code = event.code;
        if (opened && code === Keys.Tab) {
            event.preventDefault();
        }
        if (code === Keys.Backspace && !((_event_currentTarget = event.currentTarget) === null || _event_currentTarget === void 0 ? void 0 : _event_currentTarget.value.length)) {
            var newValue = values === null || values === void 0 ? void 0 : values.map(function(param) {
                var _param = _sliced_to_array(param, 1), itemValue = _param[0];
                return itemValue;
            });
            newValue === null || newValue === void 0 ? void 0 : newValue.pop();
            chipsRefs === null || chipsRefs === void 0 ? void 0 : chipsRefs.current.pop();
            onChange === null || onChange === void 0 ? void 0 : onChange(newValue);
        }
    };
    var onChangeInput = function onChangeInput(event) {
        onSearch === null || onSearch === void 0 ? void 0 : onSearch(event.currentTarget.value);
    };
    var onWheel = function onWheel(event) {
        var deltaY = event.deltaY;
        if (contentRef.current) {
            contentRef.current.scrollLeft += Math.round(deltaY);
        }
    };
    var getRef = function getRef(element, index) {
        if (element && chipsRefs && chipsRefs.current) {
            chipsRefs.current[index] = element;
        }
    };
    // INFO: Нужно очищать на каждый ререндер компонента для актуализации состояния рефов
    if (chipsRefs) {
        chipsRefs.current = [];
    }
    return /*#__PURE__*/ React.createElement(StyledComboboxTarget, _object_spread({
        ref: ref,
        opened: opened,
        readOnly: readOnly,
        disabled: disabled,
        title: textContent,
        "aria-label": label,
        className: cx(withInnerLabelUp, withHasChips),
        onWheel: onWheel,
        onKeyDown: onKeyDown
    }, rest), /*#__PURE__*/ React.createElement(StyledContent, {
        tabIndex: -1,
        ref: contentRef,
        className: withHasChips
    }, isEnumerationVisible && (isEnumerationComma ? /*#__PURE__*/ React.createElement(StyledText, {
        className: comboboxTargeText,
        onClick: onClickText
    }, textContent) : /*#__PURE__*/ React.createElement(StyledChips, null, values === null || values === void 0 ? void 0 : values.map(function(param, index) {
        var _param = _sliced_to_array(param, 2), value = _param[0], text = _param[1];
        return /*#__PURE__*/ React.createElement(ComboboxChip, {
            index: index,
            ref: function ref(element) {
                return getRef(element, index);
            },
            key: "".concat(value, "_").concat(text),
            disabled: disabled,
            readOnly: readOnly,
            value: value,
            text: text,
            onClear: function onClear(v, t) {
                return onChipClear(v, t, index);
            },
            onClick: onChipClick,
            onKeyDown: onChipKeyDown
        });
    }))), /*#__PURE__*/ React.createElement(StyledComboboxInput, {
        ref: inputRef,
        role: "textbox",
        className: comboboxTargetInput,
        value: search,
        placeholder: placeholderValue,
        disabled: disabled,
        readOnly: readOnly,
        onFocus: onFocusInput,
        onBlur: onBlurInput,
        onChange: onChangeInput,
        onKeyDown: onKeyDownInput
    }), valueType === 'multiple' && /*#__PURE__*/ React.createElement(StyledComboboxInputHelper, {
        ref: inputHelperRef
    }, search)), isLabelVisible && /*#__PURE__*/ React.createElement(StyledLabel, {
        className: comboboxTargetLabel,
        htmlFor: id
    }, label), /*#__PURE__*/ React.createElement(StyledArrow, {
        size: "s",
        className: cx(comboboxTargetArrow, withArrowInverse)
    }));
});
