import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from 'react';
import { useAtom } from 'jotai';
import { Segmented } from '@redocly/theme/components/Segmented/Segmented';
import { isUndefined } from '@redocly/theme/core/openapi';
import { Dropdown } from '../Dropdown/index.js';
import { operationStore } from '../../../jotai/operation.js';
const LIMIT_FOR_SEGMENTED = 5;
function SchemaSelectionComponent({ options, onChange, pointer, schema, defaultOneOfIdx, }) {
    const [store, setOperationStore] = useAtom(operationStore(pointer));
    const activeOneOfIdx = store.activeOneOf[schema.pointer] ?? defaultOneOfIdx;
    const activeValue = options[activeOneOfIdx]?.value;
    const [isAnyItemTruncated, setIsAnyItemTruncated] = useState(false);
    const segmentedRef = useRef(null);
    useEffect(() => {
        if (!segmentedRef.current)
            return;
        const checkTruncation = () => {
            const items = segmentedRef.current?.querySelectorAll('button[role="tab"]');
            const isTruncated = Array.from(items || []).some((item) => {
                return item.offsetWidth < item.scrollWidth;
            });
            if (isTruncated !== isAnyItemTruncated) {
                setIsAnyItemTruncated(isTruncated);
            }
        };
        checkTruncation();
        window.addEventListener('resize', checkTruncation);
        return () => window.removeEventListener('resize', checkTruncation);
    }, [isAnyItemTruncated, options]);
    const handleSelectedChange = useCallback(({ value }) => {
        if (value !== undefined) {
            if (onChange) {
                onChange(value);
            }
            else {
                setOperationStore({
                    activeExampleName: schema.oneOf?.[value]?.title,
                    activeOneOf: { [schema.pointer]: value },
                    requestValues: { body: null },
                });
            }
        }
    }, [onChange, schema.oneOf, schema.pointer, setOperationStore]);
    if (isUndefined(activeValue)) {
        return null;
    }
    return options.length > LIMIT_FOR_SEGMENTED || isAnyItemTruncated ? (_jsx(Dropdown, { options: options, value: activeValue, onChange: handleSelectedChange })) : (_jsx(Segmented, { ref: segmentedRef, value: activeValue, onChange: handleSelectedChange, options: options, size: "small", "data-testid": "segmented-schema" }));
}
export const SchemaSelection = SchemaSelectionComponent;
//# sourceMappingURL=SchemaSelection.js.map