"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useToggleItem = useToggleItem;
const react_1 = require("react");
const helpers_1 = require("../../utils/helpers");
const roving_focus_1 = require("../../utils/helpers/roving-focus");
const ToggleGroup_context_1 = require("../ToggleGroup.context");
const TOGGLE_ITEM_SELECTOR = "[data-aksel-toggle-item]:not([data-disabled])";
function useToggleItem({ value, disabled = false, onFocus: _onFocus, onClick, onKeyDown: _onKeyDown, }) {
    const { setSelectedValue, setFocusedValue, selectedValue, focusedValue } = (0, ToggleGroup_context_1.useToggleGroupContext)();
    const isSelected = value === selectedValue;
    const onFocus = () => setFocusedValue(value);
    /**
     * Implements roving-tabindex.
     */
    const onKeyDown = (0, react_1.useCallback)((event) => {
        const container = event.currentTarget.closest("[data-aksel-toggle-group]");
        if (!container) {
            return;
        }
        const current = event.target.closest(TOGGLE_ITEM_SELECTOR);
        const keyMap = {
            ArrowLeft: () => (0, roving_focus_1.rovingFocus)(TOGGLE_ITEM_SELECTOR, container, "prev", current, false),
            ArrowRight: () => (0, roving_focus_1.rovingFocus)(TOGGLE_ITEM_SELECTOR, container, "next", current, false),
            Home: () => (0, roving_focus_1.rovingFocus)(TOGGLE_ITEM_SELECTOR, container, "first"),
            End: () => (0, roving_focus_1.rovingFocus)(TOGGLE_ITEM_SELECTOR, container, "last"),
        };
        const hasModifiers = event.shiftKey || event.ctrlKey || event.altKey || event.metaKey;
        const action = keyMap[event.key];
        if (action && !hasModifiers) {
            event.preventDefault();
            action();
        }
        else if (event.key === "Tab") {
            /**
             * Imperative focus during keydown is risky so we prevent React's batching updates
             * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332
             */
            selectedValue && setTimeout(() => setFocusedValue(selectedValue));
        }
    }, [selectedValue, setFocusedValue]);
    return {
        onClick: (0, helpers_1.composeEventHandlers)(onClick, () => !isSelected && setSelectedValue(value)),
        onFocus: disabled ? undefined : (0, helpers_1.composeEventHandlers)(_onFocus, onFocus),
        onKeyDown: (0, helpers_1.composeEventHandlers)(_onKeyDown, onKeyDown),
        tabIndex: focusedValue === value ? 0 : -1,
        "aria-checked": isSelected,
        "data-selected": isSelected,
        "data-aksel-toggle-item": "",
        role: "radio",
        disabled,
        "data-disabled": disabled ? "" : undefined,
    };
}
//# sourceMappingURL=useToggleItem.js.map