import * as React from 'react';
import { Flex } from '../Flex';
import clsx from 'clsx';
import { useRef } from 'react';
import contains from '../utils/contains';
export const ToggleGroupContext = React.createContext({
    toggleButtons: [],
    activeIndex: -1,
});
export const ToggleGroup = (props) => {
    const ref = useRef(null);
    const [context, setContext] = React.useState({
        toggleButtons: [],
        activeIndex: 0,
    });
    const setActiveIndex = React.useCallback((index) => {
        setContext((prev) => ({
            ...prev,
            activeIndex: index,
        }));
    }, []);
    return (React.createElement(ToggleGroupContext.Provider, { value: context },
        React.createElement(Flex, { ref: ref, tabIndex: 0, className: clsx('ab-Toggle-Group twa:shadow-sm', 'twa:bg-primary twa:text-text-on-primary', 'twa:rounded-standard twa:overflow-hidden', 'twa:inline-flex twa:w-fit', 'twa:focus:outline-0', 
            // make the shadow of child Toggle buttons invisible when the group is not focused
            'twa:not-focus-within:[--ab-focus-light__box-shadow:none]', 'twa:not-focus-within:[--ab-focus__box-shadow:none]'), onMouseDown: (event) => {
                const index = context.toggleButtons.findIndex((btn) => contains(btn.node, event.target));
                if (index !== -1) {
                    setActiveIndex(index);
                }
            }, onKeyDown: (event) => {
                const { toggleButtons, activeIndex } = context;
                if (event.key === ' ') {
                    event.preventDefault();
                    event.stopPropagation();
                    const activeButton = toggleButtons[activeIndex];
                    if (!activeButton) {
                        return;
                    }
                    activeButton.toggle();
                    return;
                }
                if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
                    event.preventDefault();
                    event.stopPropagation();
                    const node = ref.current;
                    if (!node) {
                        return;
                    }
                    const dir = event.key === 'ArrowLeft' ? -1 : 1;
                    let nextIndex = activeIndex + dir;
                    if (nextIndex < 0) {
                        nextIndex = toggleButtons.length - 1;
                    }
                    else if (nextIndex > toggleButtons.length - 1) {
                        nextIndex = 0;
                    }
                    setActiveIndex(nextIndex);
                }
            } }, props.children)));
};
