'use client';
"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.MultipleSelect = exports.MultipleSelectItem = exports.MultipleSelectGroup = exports.MultipleSelectContent = exports.MultipleSelectEmpty = exports.MultipleSelectValue = exports.MultipleSelectTrigger = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importDefault(require("react"));
const SelectPrimitive = __importStar(require("@radix-ui/react-select"));
const lucide_react_1 = require("lucide-react");
const badge_1 = require("../badge");
const utils_1 = require("../../../lib/utils");
const separator_1 = require("../separator");
const cmdk_1 = require("cmdk");
const use_click_away_1 = require("../../../hooks/use-click-away");
const MultipleSelectContext = react_1.default.createContext({
    value: [],
    onValueChange: (values) => values,
    handleChange: (value) => value,
    handleClear: () => { },
    setOpen: () => { },
    setOnScrollbar: () => { },
    options: {},
    addOption: (option) => option,
    inputRef: react_1.default.createRef()
});
const useMultipleSelect = () => {
    const context = react_1.default.useContext(MultipleSelectContext);
    if (!context) {
        throw new Error('useMultipleSelect must be used within a MultipleSelectProvider');
    }
    return context;
};
exports.MultipleSelectTrigger = react_1.default.forwardRef(({ className, children, readOnly }, ref) => {
    const _ref = react_1.default.useRef(null);
    const { open, setOpen, onScrollbar, disabled, value, inputRef, handleClear } = useMultipleSelect();
    react_1.default.useImperativeHandle(ref, () => _ref.current);
    (0, use_click_away_1.useClickAway)(_ref, () => {
        // Should not close when clicking on the scrollbar
        if (onScrollbar) {
            return;
        }
        setOpen(false);
        inputRef.current?.blur();
    });
    return ((0, jsx_runtime_1.jsxs)("div", { ref: _ref, className: (0, utils_1.cn)('bg-background ring-offset-background placeholder:text-shadcn-400 focus:ring-ring border-shadcn-400 flex flex-row rounded-md border text-sm focus:ring-2 focus:ring-offset-0 focus:outline-hidden focus-visible:outline-hidden md:text-sm [&>span]:line-clamp-1', {
            'h-10': value.length === 0,
            'min-h-10': value.length > 0,
            'cursor-text': !disabled && !readOnly && value.length !== 0,
            'bg-shadcn-100 cursor-not-allowed opacity-50': disabled
        }, readOnly && [
            'data-read-only:cursor-default',
            'data-read-only:select-text',
            'data-read-only:bg-muted',
            'data-read-only:opacity-50',
            'data-read-only:pointer-events-none',
            'data-read-only:focus:outline-hidden',
            'data-read-only:focus:ring-0'
        ], className), "data-read-only": readOnly ? '' : undefined, onClick: (e) => {
            // Redirect focus to the input field when clicking on the container
            if (disabled || readOnly) {
                e.preventDefault();
                return;
            }
            if (open) {
                inputRef?.current?.blur();
            }
            else {
                inputRef?.current?.focus();
            }
            setOpen(!open);
        }, children: [(0, jsx_runtime_1.jsx)("div", { className: "flex grow flex-wrap gap-1 px-3 py-2", children: children }), (0, jsx_runtime_1.jsxs)("div", { className: "flex flex-1 items-center justify-end", children: [(0, jsx_runtime_1.jsx)("button", { type: "button", className: (0, utils_1.cn)((disabled || readOnly || value.length < 1) && 'hidden'), children: (0, jsx_runtime_1.jsx)(lucide_react_1.X, { className: "text-muted-foreground mx-2 h-4 cursor-pointer", onClick: (event) => {
                                event.stopPropagation();
                                handleClear();
                            } }) }), (0, jsx_runtime_1.jsx)(separator_1.Separator, { orientation: "vertical", className: (0, utils_1.cn)('flex h-full min-h-6', (disabled || readOnly || value.length < 1) && 'hidden') }), (0, jsx_runtime_1.jsx)(SelectPrimitive.Icon, { children: (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronDown, { className: (0, utils_1.cn)('mx-3 my-2 h-4 w-4 cursor-pointer opacity-50', readOnly && 'hidden') }) })] })] }));
});
exports.MultipleSelectTrigger.displayName = 'MultipleSelectTrigger';
exports.MultipleSelectValue = react_1.default.forwardRef(({ className, ...props }, ref) => {
    const { value, disabled, handleChange, options, showValue, inputRef } = useMultipleSelect();
    react_1.default.useImperativeHandle(ref, () => inputRef.current);
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [options &&
                value?.map((value) => ((0, jsx_runtime_1.jsxs)(badge_1.Badge, { variant: "secondary", className: (0, utils_1.cn)('data-disabled:bg-muted-foreground data-fixed:bg-muted-foreground data-disabled:text-muted data-fixed:text-muted data-disabled:hover:bg-muted-foreground data-fixed:hover:bg-muted-foreground'), children: [showValue ? value : options[value], (0, jsx_runtime_1.jsx)("button", { type: "button", className: (0, utils_1.cn)('ring-offset-background focus:ring-ring ml-1 rounded-full outline-hidden focus:ring-2 focus:ring-offset-2', disabled && 'hidden'), children: (0, jsx_runtime_1.jsx)(lucide_react_1.X, { className: "text-muted-foreground hover:text-foreground h-3 w-3", onClick: (event) => {
                                    event.stopPropagation();
                                    handleChange(value);
                                } }) })] }, value))), (0, jsx_runtime_1.jsx)(cmdk_1.Command.Input, { ...props, ref: inputRef, disabled: disabled, className: (0, utils_1.cn)('placeholder:text-muted-foreground bg-transparent outline-hidden focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 disabled:placeholder:opacity-0', className) })] }));
});
exports.MultipleSelectValue.displayName = 'MultipleSelectValue';
exports.MultipleSelectEmpty = react_1.default.forwardRef(({ className, ...props }, forwardedRef) => {
    const render = (0, cmdk_1.useCommandState)((state) => state.filtered.count === 0);
    if (!render)
        return null;
    return ((0, jsx_runtime_1.jsx)("div", { ref: forwardedRef, className: (0, utils_1.cn)('py-6 text-center text-sm', className), "cmdk-empty": "", role: "presentation", ...props }));
});
exports.MultipleSelectEmpty.displayName = 'MultipleSelectEmpty';
exports.MultipleSelectContent = react_1.default.forwardRef(({ className, position = 'popper', children, onMouseEnter, onMouseLeave, ...props }, ref) => {
    const { open, addOption, setOnScrollbar } = useMultipleSelect();
    // Since this component is not going to be rendered in the DOM until open is true,
    // we need to register the options when the component mounts
    // and when the children change.
    react_1.default.useEffect(() => {
        react_1.default.Children.forEach(react_1.default.Children.toArray(children), (child) => {
            if (react_1.default.isValidElement(child) &&
                child.props.value) {
                addOption({ [child.props.value]: child.props.children });
            }
        });
    }, [children]);
    if (!open) {
        return null;
    }
    return ((0, jsx_runtime_1.jsx)("div", { className: "relative", children: (0, jsx_runtime_1.jsx)(cmdk_1.Command.List, { ref: ref, className: (0, utils_1.cn)('bg-popover text-popover-foreground animate-in absolute top-1 z-50 max-h-96 w-full min-w-32 overflow-x-hidden overflow-y-auto rounded-md border shadow-md outline-hidden', position === 'popper' &&
                'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1', className), ...props, onMouseEnter: (e) => {
                onMouseEnter?.(e);
                setOnScrollbar(true);
            }, onMouseLeave: (e) => {
                onMouseLeave?.(e);
                setOnScrollbar(false);
            }, children: (0, jsx_runtime_1.jsx)(exports.MultipleSelectGroup, { children: children }) }) }));
});
exports.MultipleSelectContent.displayName = 'MultipleSelectContent';
exports.MultipleSelectGroup = react_1.default.forwardRef(({ className, ...props }, ref) => ((0, jsx_runtime_1.jsx)(cmdk_1.Command.Group, { ref: ref, className: (0, utils_1.cn)('text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium', className), ...props })));
exports.MultipleSelectGroup.displayName = 'MultipleSelectGroup';
exports.MultipleSelectItem = react_1.default.forwardRef(({ className, value, onClick: _onClick, onSelect, children, ...props }, ref) => {
    const { handleChange } = useMultipleSelect();
    return ((0, jsx_runtime_1.jsx)(cmdk_1.Command.Item, { ref: ref, value: value, keywords: typeof children === 'string' ? [children] : undefined, className: (0, utils_1.cn)('data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0', className), ...props, onMouseDown: (e) => {
            e.preventDefault();
            e.stopPropagation();
        }, onSelect: (value) => {
            handleChange(value);
            onSelect?.(value);
        }, children: children }));
});
exports.MultipleSelectItem.displayName = 'MultipleSelectItem';
exports.MultipleSelect = react_1.default.forwardRef(({ value, defaultValue, onValueChange, className, showValue, disabled, onKeyDown, children, onChange: _onChange, ...props }, ref) => {
    const _ref = react_1.default.useRef(null);
    const [open, setOpen] = react_1.default.useState(false);
    const inputRef = react_1.default.useRef(null);
    const [onScrollbar, setOnScrollbar] = react_1.default.useState(false);
    const safeValue = Array.isArray(value) ? value : [];
    const safeDefault = Array.isArray(defaultValue) ? defaultValue : [];
    const [selected, setSelected] = react_1.default.useState(safeDefault.length > 0 ? safeDefault : safeValue);
    const [options, addOption] = react_1.default.useReducer((prev, state) => ({
        ...prev,
        ...state
    }), {});
    react_1.default.useImperativeHandle(ref, () => _ref.current);
    const handleClear = () => {
        setSelected([]);
        onValueChange?.([]);
    };
    const handleChange = react_1.default.useCallback((value) => {
        if (!value) {
            return;
        }
        const newSelected = selected.includes(value)
            ? selected.filter((item) => item !== value)
            : [...selected, value];
        setSelected(newSelected);
        onValueChange?.(newSelected);
    }, [selected, onValueChange]);
    const handleKeyDown = react_1.default.useCallback((e) => {
        const input = inputRef.current;
        if (input) {
            if (e.key === 'Delete' || e.key === 'Backspace') {
                if (input.value === '' && selected.length > 0) {
                    handleChange(selected[selected.length - 1]);
                }
            }
            // This is not a default behavior of the <input /> field
            if (e.key === 'Escape') {
                e.stopPropagation();
                input.blur();
            }
        }
    }, [selected, handleChange]);
    // Keeps the selected value in sync with the value prop
    react_1.default.useEffect(() => {
        if (Array.isArray(value)) {
            setSelected(value);
        }
    }, [value]);
    return ((0, jsx_runtime_1.jsx)(MultipleSelectContext.Provider, { value: {
            value: selected,
            onValueChange: setSelected,
            showValue,
            disabled,
            handleChange,
            handleClear,
            onScrollbar,
            setOnScrollbar,
            open,
            setOpen,
            options,
            addOption,
            inputRef
        }, children: (0, jsx_runtime_1.jsx)(cmdk_1.Command, { ref: _ref, className: (0, utils_1.cn)('text-foreground flex h-auto w-full flex-col overflow-visible rounded-md bg-transparent', className), "aria-disabled": disabled, ...props, onKeyDown: (e) => {
                handleKeyDown(e);
                onKeyDown?.(e);
            }, children: children }) }));
});
exports.MultipleSelect.displayName = 'MultipleSelect';
