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 ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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, useEffect } from "react";
import cls from "classnames";
import { useForkRef, useOutsideClick } from "../../hooks";
import { getSizeValueFromProp } from "../../utils";
import { processTimeInput, delimiter } from "./utils";
import { base, StyledInput, StyledTimePickerGrid } from "./TimePicker.styles";
import { classes } from "./TimePicker.tokens";
import { FloatingPopover } from "./FloatingPopover";
import { base as sizeCSS } from "./variations/_size/base";
import { base as viewCSS } from "./variations/_view/base";
import { base as hintViewCSS } from "./variations/_hint-view/base";
import { base as hintSizeCSS } from "./variations/_hint-size/base";
import { base as disabledCSS } from "./variations/_disabled/base";
import { base as readonlyCSS } from "./variations/_readonly/base";
import { useKeyNavigation } from "./hooks/useKeyboardNavigation";
export var timePickerRoot = function timePickerRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), className = _ref2.className, // controlled
        outerValue = _ref2.value, _ref_opened = _ref2.opened, opened = _ref_opened === void 0 ? false : _ref_opened, // variations
        view = _ref2.view, size = _ref2.size, _ref_disabled = _ref2.disabled, disabled = _ref_disabled === void 0 ? false : _ref_disabled, _ref_readonly = _ref2.readonly, readonly = _ref_readonly === void 0 ? false : _ref_readonly, stretched = _ref2.stretched, valueError = _ref2.valueError, valueSuccess = _ref2.valueSuccess, // layout
        label = _ref2.label, _ref_labelPlacement = _ref2.labelPlacement, labelPlacement = _ref_labelPlacement === void 0 ? 'outer' : _ref_labelPlacement, keepPlaceholder = _ref2.keepPlaceholder, _ref_required = _ref2.required, required = _ref_required === void 0 ? false : _ref_required, _ref_requiredPlacement = _ref2.requiredPlacement, requiredPlacement = _ref_requiredPlacement === void 0 ? 'right' : _ref_requiredPlacement, _ref_hasRequiredIndicator = _ref2.hasRequiredIndicator, hasRequiredIndicator = _ref_hasRequiredIndicator === void 0 ? false : _ref_hasRequiredIndicator, placeholder = _ref2.placeholder, leftHelper = _ref2.leftHelper, contentLeft = _ref2.contentLeft, contentRight = _ref2.contentRight, textBefore = _ref2.textBefore, textAfter = _ref2.textAfter, autoComplete = _ref2.autoComplete, _ref_hintTrigger = _ref2.// hint
        hintTrigger, hintTrigger = _ref_hintTrigger === void 0 ? 'hover' : _ref_hintTrigger, hintText = _ref2.hintText, _ref_hintView = _ref2.hintView, hintView = _ref_hintView === void 0 ? 'default' : _ref_hintView, _ref_hintSize = _ref2.hintSize, hintSize = _ref_hintSize === void 0 ? 'm' : _ref_hintSize, hintTargetIcon = _ref2.hintTargetIcon, _ref_hintTargetPlacement = _ref2.hintTargetPlacement, hintTargetPlacement = _ref_hintTargetPlacement === void 0 ? 'outer' : _ref_hintTargetPlacement, _ref_hintPlacement = _ref2.hintPlacement, hintPlacement = _ref_hintPlacement === void 0 ? 'auto' : _ref_hintPlacement, hintHasArrow = _ref2.hintHasArrow, _ref_hintOffset = _ref2.hintOffset, hintOffset = _ref_hintOffset === void 0 ? [
            0,
            0
        ] : _ref_hintOffset, hintWidth = _ref2.hintWidth, hintContentLeft = _ref2.hintContentLeft, _ref_frame = _ref2.// popover-container
        frame, frame = _ref_frame === void 0 ? 'document' : _ref_frame, _ref_usePortal = _ref2.usePortal, usePortal = _ref_usePortal === void 0 ? false : _ref_usePortal, _ref_placement = _ref2.placement, placement = _ref_placement === void 0 ? 'bottom-start' : _ref_placement, _ref_closeOnOverlayClick = _ref2.closeOnOverlayClick, closeOnOverlayClick = _ref_closeOnOverlayClick === void 0 ? true : _ref_closeOnOverlayClick, _ref_closeOnEsc = _ref2.closeOnEsc, closeOnEsc = _ref_closeOnEsc === void 0 ? true : _ref_closeOnEsc, disableFlip = _ref2.disableFlip, offset = _ref2.offset, _ref_dropdownAlign = _ref2.// dropdown
        dropdownAlign, dropdownAlign = _ref_dropdownAlign === void 0 ? 'left' : _ref_dropdownAlign, dropdownWidth = _ref2.dropdownWidth, dropdownHeight = _ref2.dropdownHeight, _ref_columnsQuantity = _ref2.columnsQuantity, columnsQuantity = _ref_columnsQuantity === void 0 ? 2 : _ref_columnsQuantity, onToggle = _ref2.onToggle, onFocus = _ref2.onFocus, onChange = _ref2.onChange, rest = _object_without_properties(_ref2, [
            "className",
            "value",
            "opened",
            "view",
            "size",
            "disabled",
            "readonly",
            "stretched",
            "valueError",
            "valueSuccess",
            "label",
            "labelPlacement",
            "keepPlaceholder",
            "required",
            "requiredPlacement",
            "hasRequiredIndicator",
            "placeholder",
            "leftHelper",
            "contentLeft",
            "contentRight",
            "textBefore",
            "textAfter",
            "autoComplete",
            "hintTrigger",
            "hintText",
            "hintView",
            "hintSize",
            "hintTargetIcon",
            "hintTargetPlacement",
            "hintPlacement",
            "hintHasArrow",
            "hintOffset",
            "hintWidth",
            "hintContentLeft",
            "frame",
            "usePortal",
            "placement",
            "closeOnOverlayClick",
            "closeOnEsc",
            "disableFlip",
            "offset",
            "dropdownAlign",
            "dropdownWidth",
            "dropdownHeight",
            "columnsQuantity",
            "onToggle",
            "onFocus",
            "onChange"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        var inputRef = useRef(null);
        var timeGridRootRef = useRef(null);
        var floatingPopoverRef = useRef(null);
        var rootRef = useRef(null);
        var rootForkRef = useForkRef(rootRef, ref);
        var hoursHideTimeoutRef = useRef(null);
        var minutesHideTimeoutRef = useRef(null);
        var secondsHideTimeoutRef = useRef(null);
        var _useState = _sliced_to_array(useState(opened), 2), isInnerOpen = _useState[0], setIsInnerOpen = _useState[1];
        var _useState1 = _sliced_to_array(useState(outerValue || ''), 2), innerTime = _useState1[0], setInnerTime = _useState1[1];
        var _useState2 = _sliced_to_array(useState(null), 2), rootWidth = _useState2[0], setRootWidth = _useState2[1];
        var _useState3 = _sliced_to_array(useState({
            hours: null,
            minutes: null,
            seconds: null,
            currentColumn: null
        }), 2), setActiveTime = _useState3[1];
        var viewValue = outerValue !== null && outerValue !== void 0 ? outerValue : innerTime;
        var format = columnsQuantity === 3 ? 'HH:mm:ss' : 'HH:mm';
        var dropdownWidthValue = dropdownWidth ? getSizeValueFromProp(dropdownWidth, 'rem') : undefined;
        var dropdownHeightValue = dropdownHeight ? getSizeValueFromProp(dropdownHeight, 'rem') : undefined;
        useEffect(function() {
            return function() {
                [
                    hoursHideTimeoutRef,
                    minutesHideTimeoutRef,
                    secondsHideTimeoutRef
                ].forEach(function(timeoutRef) {
                    if (timeoutRef.current) {
                        clearTimeout(timeoutRef.current);
                    }
                });
            };
        }, []);
        useEffect(function() {
            if (!viewValue) {
                return;
            }
            var timeString = viewValue;
            if (format === 'HH:mm' && viewValue.length > 5) {
                timeString = viewValue.substring(0, 5);
            }
            setInnerTime(viewValue);
            var _timeString_split_map = _sliced_to_array(timeString.split(delimiter).map(Number), 3), hh = _timeString_split_map[0], mm = _timeString_split_map[1], ss = _timeString_split_map[2];
            setActiveTime({
                hours: !Number.isNaN(hh) ? hh : null,
                minutes: !Number.isNaN(mm) ? mm : null,
                seconds: format === 'HH:mm:ss' && !Number.isNaN(ss) ? ss : null,
                currentColumn: null
            });
        }, [
            outerValue,
            format
        ]);
        useEffect(function() {
            if (isInnerOpen && (disabled || readonly)) {
                setIsInnerOpen(false);
            }
        }, [
            disabled,
            readonly
        ]);
        useEffect(function() {
            if (rootRef.current) {
                var width = rootRef.current.offsetWidth;
                setRootWidth(width);
            }
        }, [
            dropdownWidth,
            isInnerOpen
        ]);
        var handleToggle = function handleToggle() {
            if (disabled || readonly) return;
            var newState = !isInnerOpen;
            setIsInnerOpen(newState);
            if (newState) {
                setActiveTime(function(prev) {
                    return _object_spread_props(_object_spread({}, prev), {
                        currentColumn: 'hours'
                    });
                });
            }
            onToggle === null || onToggle === void 0 ? void 0 : onToggle(newState);
        };
        useOutsideClick(function() {
            if (!isInnerOpen || !closeOnOverlayClick) {
                return;
            }
            setIsInnerOpen(false);
            onToggle === null || onToggle === void 0 ? void 0 : onToggle(false);
        }, [
            floatingPopoverRef,
            timeGridRootRef
        ]);
        var handleOnChange = function handleOnChange(event) {
            if (!event) {
                return;
            }
            var timeString = event.value;
            if (format === 'HH:mm' && viewValue.length > 5) {
                timeString = viewValue.substring(0, 5);
            }
            setInnerTime(timeString !== null && timeString !== void 0 ? timeString : '');
            setActiveTime({
                hours: !Number.isNaN(event.timeValues.hour) ? event.timeValues.hour : null,
                minutes: !Number.isNaN(event.timeValues.minute) ? event.timeValues.minute : null,
                seconds: format === 'HH:mm:ss' && !Number.isNaN(event.timeValues.second) ? event.timeValues.second : null,
                currentColumn: null
            });
            onChange === null || onChange === void 0 ? void 0 : onChange(event);
        };
        var handleInputChange = function handleInputChange(event) {
            var input = event.target.value;
            var cursorPos = event.target.selectionStart;
            var _processTimeInput = processTimeInput(input, format, cursorPos), innerString = _processTimeInput.innerString, values = _processTimeInput.values, newCursorPosition = _processTimeInput.newCursorPosition;
            setInnerTime(innerString);
            setActiveTime(function(prev) {
                return _object_spread_props(_object_spread({}, prev), {
                    hours: values.hh,
                    minutes: values.mm,
                    seconds: values.ss
                });
            });
            if (onChange) {
                onChange(_object_spread_props(_object_spread({}, event), {
                    target: _object_spread_props(_object_spread({}, event.target), {
                        value: innerString,
                        timeValues: values
                    })
                }));
            }
            requestAnimationFrame(function() {
                if (inputRef.current) {
                    inputRef.current.setSelectionRange(newCursorPosition, newCursorPosition);
                }
            });
        };
        var handleKeyDown = function handleKeyDown(event) {
            if (event.key === 'Enter' && !isInnerOpen) {
                event.preventDefault();
                setIsInnerOpen(true);
                setActiveTime(function(prev) {
                    return _object_spread_props(_object_spread({}, prev), {
                        currentColumn: 'hours'
                    });
                });
                onToggle === null || onToggle === void 0 ? void 0 : onToggle(true);
            }
        };
        var handleOnKeyDown = function handleOnKeyDown(e) {
            onKeyDownNavigation(e);
            handleKeyDown(e);
        };
        var handleTimeGridRootClick = function handleTimeGridRootClick(event) {
            if (disabled || readonly) {
                return;
            }
            if (isInnerOpen && event.target === (timeGridRootRef === null || timeGridRootRef === void 0 ? void 0 : timeGridRootRef.current)) {
                setIsInnerOpen(false);
                if (onToggle) {
                    onToggle(false, event);
                }
            }
        };
        var _useKeyNavigation = useKeyNavigation({
            isCalendarOpen: isInnerOpen,
            format: format,
            maskWithFormat: true,
            delimiter: delimiter,
            closeOnEsc: closeOnEsc,
            onToggle: handleToggle
        }), onKeyDownNavigation = _useKeyNavigation.onKeyDown;
        var getActualWidth = function getActualWidth() {
            var _String;
            if (!rootWidth) {
                return 'fit-content';
            }
            if (dropdownWidthValue === 'fixed' || dropdownWidthValue === undefined) {
                return undefined;
            }
            if (dropdownWidth === 'fullWidth') {
                return "".concat(rootWidth, "px");
            }
            if (((_String = String(dropdownWidth)) === null || _String === void 0 ? void 0 : _String.includes('%')) && typeof dropdownWidth === 'string') {
                var widthValue = rootWidth / 100 * parseFloat(dropdownWidth.replace('%', ''));
                return "".concat(widthValue, "px");
            }
            return String(dropdownWidth || 'fit-content');
        };
        var _obj;
        return /*#__PURE__*/ React.createElement(Root, _object_spread({
            stretched: stretched,
            view: view,
            size: size,
            className: cls(classes.timePickerRoot, className, _define_property({}, classes.timePickerstretched, stretched)),
            disabled: disabled,
            readonly: readonly,
            ref: rootForkRef
        }, hintText && {
            hintView: hintView,
            hintSize: hintSize
        }, rest), /*#__PURE__*/ React.createElement(FloatingPopover, {
            ref: floatingPopoverRef,
            opened: isInnerOpen,
            onToggle: handleToggle,
            offset: offset,
            placement: placement,
            disableFlip: disableFlip,
            portal: usePortal && frame !== 'document' ? frame : undefined,
            target: function target(referenceRef) {
                var _obj;
                return /*#__PURE__*/ React.createElement(StyledInput, _object_spread({
                    ref: inputRef,
                    inputWrapperRef: referenceRef,
                    className: cls((_obj = {}, _define_property(_obj, classes.timePickerError, valueError), _define_property(_obj, classes.timePickerSuccess, valueSuccess), _obj)),
                    value: viewValue,
                    size: size,
                    disabled: disabled,
                    readOnly: readonly,
                    placeholder: placeholder,
                    contentLeft: contentLeft,
                    contentRight: contentRight,
                    textBefore: textBefore,
                    textAfter: textAfter,
                    autoComplete: autoComplete,
                    onChange: handleInputChange,
                    onFocus: onFocus,
                    onKeyDown: handleOnKeyDown,
                    required: required,
                    requiredPlacement: requiredPlacement,
                    hasRequiredIndicator: hasRequiredIndicator,
                    label: label,
                    labelPlacement: labelPlacement,
                    leftHelper: leftHelper,
                    keepPlaceholder: keepPlaceholder
                }, hintText ? {
                    hintText: hintText,
                    hintView: hintView,
                    hintSize: hintSize,
                    hintTrigger: hintTrigger,
                    hintTargetIcon: hintTargetIcon,
                    hintPlacement: hintPlacement,
                    hintHasArrow: hintHasArrow,
                    hintOffset: hintOffset,
                    hintWidth: hintWidth,
                    hintContentLeft: hintContentLeft,
                    hintTargetPlacement: hintTargetPlacement
                } : {
                    hintText: undefined
                }));
            }
        }, /*#__PURE__*/ React.createElement(Root, {
            ref: timeGridRootRef,
            stretched: stretched,
            view: view,
            size: size,
            className: cls(classes.timePickerGridRoot, className, (_obj = {}, _define_property(_obj, classes.timePickerPlacementRight, dropdownAlign === 'right'), _define_property(_obj, classes.timePickerFullWidth, dropdownWidth === 'fullWidth'), _define_property(_obj, classes.timePickerFixed, dropdownWidth !== 'fullWidth'), _obj)),
            disabled: disabled,
            readonly: readonly,
            onClick: handleTimeGridRootClick
        }, /*#__PURE__*/ React.createElement(StyledTimePickerGrid, {
            view: view,
            size: size,
            format: format,
            columns: columnsQuantity,
            innerWidth: getActualWidth(),
            innerHeight: dropdownHeightValue,
            dropdownHeight: "100%",
            dropdownWidth: "fullWidth",
            value: viewValue,
            onChange: handleOnChange,
            disabled: disabled
        }))));
    });
};
export var timePickerConfig = {
    name: 'TimePicker',
    tag: 'div',
    layout: timePickerRoot,
    base: base,
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        },
        hintView: {
            css: hintViewCSS
        },
        hintSize: {
            css: hintSizeCSS
        },
        disabled: {
            css: disabledCSS,
            attrs: true
        },
        readonly: {
            css: readonlyCSS,
            attrs: true
        }
    },
    defaults: {
        size: 'm',
        view: 'default'
    }
};
