"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useFilteredOptionsContext = exports.FilteredOptionsProvider = void 0;
const react_1 = __importStar(require("react"));
const utils_external_1 = require("../../../utils-external");
const helpers_1 = require("../../../utils/helpers");
const hooks_1 = require("../../../utils/hooks");
const Input_context_1 = require("../Input/Input.context");
const selectedOptionsContext_1 = require("../SelectedOptions/selectedOptionsContext");
const combobox_utils_1 = require("../combobox-utils");
const customOptionsContext_1 = require("../customOptionsContext");
const filtered_options_util_1 = __importDefault(require("./filtered-options-util"));
const useVirtualFocus_1 = __importDefault(require("./useVirtualFocus"));
const { Provider: FilteredOptionsContextProvider, useContext: useFilteredOptionsContext, } = (0, helpers_1.createStrictContext)({
    name: "FilteredOptionsContext",
    errorMessage: "useFilteredOptionsContext must be used within a FilteredOptionsProvider",
});
exports.useFilteredOptionsContext = useFilteredOptionsContext;
const FilteredOptionsProvider = ({ children, value: props, }) => {
    const { allowNewValues, filteredOptions: externalFilteredOptions, isListOpen: isExternalListOpen, isLoading, options, } = props;
    const [filteredOptionsRef, setFilteredOptionsRef] = (0, react_1.useState)(null);
    const virtualFocus = (0, useVirtualFocus_1.default)(filteredOptionsRef);
    const { inputProps: { "aria-describedby": partialAriaDescribedBy, id, disabled }, readOnly, value, searchTerm, setValue, setSearchTerm, shouldAutocomplete, setHideCaret, } = (0, Input_context_1.useInputContext)();
    const { maxSelected } = (0, selectedOptionsContext_1.useSelectedOptionsContext)();
    const [isInternalListOpen, setInternalListOpen] = (0, react_1.useState)(false);
    const { customOptions } = (0, customOptionsContext_1.useComboboxCustomOptions)();
    const filteredOptions = (0, react_1.useMemo)(() => {
        if (externalFilteredOptions) {
            return externalFilteredOptions;
        }
        const opts = [...customOptions, ...options];
        return filtered_options_util_1.default.getMatchingValuesFromList(searchTerm, opts);
    }, [customOptions, externalFilteredOptions, options, searchTerm]);
    const previousSearchTerm = (0, hooks_1.usePrevious)(searchTerm);
    const [isMouseLastUsedInputDevice, setIsMouseLastUsedInputDevice] = (0, react_1.useState)(false);
    /**
     * Returns a map of all possible virtual options avaliable in the combobox, including:
     * - Filtered options
     * - Custom options
     * - Add new option
     */
    const allOptionsMap = (0, react_1.useMemo)(() => {
        const initialMap = Object.assign({ [filtered_options_util_1.default.getAddNewOptionId(id)]: allowNewValues
                ? (0, combobox_utils_1.toComboboxOption)(value)
                : undefined }, customOptions.reduce((acc, customOption) => {
            const _id = filtered_options_util_1.default.getOptionId(id, customOption.value);
            acc[_id] = customOption;
            return acc;
        }, {}));
        /* Add the filtered options to the map */
        const mapWithFiltered = filteredOptions.reduce((map, _option) => {
            const _id = filtered_options_util_1.default.getOptionId(id, _option.value);
            map[_id] = _option;
            return map;
        }, initialMap);
        /* Add all options, avoiding duplicates */
        const finalMap = options.reduce((map, _option) => {
            const _id = filtered_options_util_1.default.getOptionId(id, _option.value);
            if (!map[_id]) {
                map[_id] = _option;
            }
            return map;
        }, mapWithFiltered);
        return finalMap;
    }, [allowNewValues, customOptions, id, filteredOptions, options, value]);
    (0, utils_external_1.useClientLayoutEffect)(() => {
        var _a;
        const autoCompleteCandidate = (_a = filtered_options_util_1.default.getFirstValueStartingWith(searchTerm, filteredOptions)) === null || _a === void 0 ? void 0 : _a.label;
        if (shouldAutocomplete &&
            autoCompleteCandidate &&
            ((previousSearchTerm === null || previousSearchTerm === void 0 ? void 0 : previousSearchTerm.length) || 0) < searchTerm.length) {
            setValue(`${searchTerm}${autoCompleteCandidate.substring(searchTerm.length)}`);
        }
    }, [
        filteredOptions,
        previousSearchTerm,
        searchTerm,
        setSearchTerm,
        setValue,
        shouldAutocomplete,
    ]);
    const isListOpen = (0, react_1.useMemo)(() => {
        return isExternalListOpen !== null && isExternalListOpen !== void 0 ? isExternalListOpen : isInternalListOpen;
    }, [isExternalListOpen, isInternalListOpen]);
    const toggleIsListOpen = (0, react_1.useCallback)((newState) => {
        if (disabled || readOnly) {
            return;
        }
        virtualFocus.resetFocus();
        if (newState !== null && newState !== void 0 ? newState : !isInternalListOpen) {
            setHideCaret(maxSelected.isLimitReached);
        }
        setInternalListOpen((oldState) => newState !== null && newState !== void 0 ? newState : !oldState);
    }, [
        virtualFocus,
        maxSelected.isLimitReached,
        isInternalListOpen,
        setHideCaret,
        disabled,
        readOnly,
    ]);
    const isValueNew = (0, react_1.useMemo)(() => Boolean(searchTerm) &&
        !allOptionsMap[filtered_options_util_1.default.getOptionId(id, searchTerm)], [allOptionsMap, id, searchTerm]);
    const ariaDescribedBy = (0, react_1.useMemo)(() => {
        let activeOption = "";
        if (!isLoading && filteredOptions.length === 0 && !allowNewValues) {
            activeOption = filtered_options_util_1.default.getNoHitsId(id);
        }
        else if (value || isLoading) {
            if (shouldAutocomplete && filteredOptions[0]) {
                activeOption = filtered_options_util_1.default.getOptionId(id, filteredOptions[0].value);
            }
            else if (isListOpen && isLoading) {
                activeOption = filtered_options_util_1.default.getIsLoadingId(id);
            }
        }
        const maybeMaxSelectedOptionsId = maxSelected.isLimitReached &&
            filtered_options_util_1.default.getMaxSelectedOptionsId(id);
        return ((0, helpers_1.cl)(activeOption, maybeMaxSelectedOptionsId, partialAriaDescribedBy) ||
            undefined);
    }, [
        isListOpen,
        isLoading,
        maxSelected.isLimitReached,
        value,
        partialAriaDescribedBy,
        shouldAutocomplete,
        filteredOptions,
        id,
        allowNewValues,
    ]);
    const currentOption = (0, react_1.useMemo)(() => { var _a; return allOptionsMap[((_a = virtualFocus.activeElement) === null || _a === void 0 ? void 0 : _a.getAttribute("id")) || -1]; }, [allOptionsMap, virtualFocus]);
    const activeDescendantId = (0, react_1.useMemo)(() => { var _a; return ((_a = virtualFocus.activeElement) === null || _a === void 0 ? void 0 : _a.getAttribute("id")) || undefined; }, [virtualFocus.activeElement]);
    const filteredOptionsState = {
        activeDescendantId,
        allowNewValues,
        setFilteredOptionsRef,
        shouldAutocomplete,
        isListOpen,
        isLoading,
        filteredOptions,
        isMouseLastUsedInputDevice,
        setIsMouseLastUsedInputDevice,
        isValueNew,
        toggleIsListOpen,
        currentOption,
        virtualFocus,
        ariaDescribedBy,
    };
    return (react_1.default.createElement(FilteredOptionsContextProvider, Object.assign({}, filteredOptionsState), children));
};
exports.FilteredOptionsProvider = FilteredOptionsProvider;
//# sourceMappingURL=filteredOptionsContext.js.map