import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { memo, useCallback, useRef } from 'react';
import { useAtom } from 'jotai';
import { SelectLabel, SelectWrapper } from '../PayloadSamples/index.js';
import { Container } from '../common/index.js';
import { activeMimeNameAtom } from '../../jotai/app.js';
import { getActiveMediaType } from '../../models/index.js';
import { useTranslate } from '../../hooks/index.js';
function Wrapper({ children, withLabel, innerRef, translate, }) {
    if (!children) {
        return null;
    }
    return withLabel ? (_jsxs(SelectWrapper, { ref: innerRef, children: [_jsx(SelectLabel, { children: translate('openapi.contentType', 'Content type') }), children] })) : (_jsx(Container, { ref: innerRef, children: children }));
}
function MediaTypesSwitchComponent({ content, withLabel, renderSelect, children, }) {
    const translate = useTranslate();
    const [activeMimeName, setActiveMimeName] = useAtom(activeMimeNameAtom);
    const switchMedia = useCallback(({ value }) => {
        /* istanbul ignore next (this can never happen, just to make ts happy, this is callback) */
        if (!content || !ref.current)
            return null;
        const initialOffset = ref.current.getBoundingClientRect().y;
        setActiveMimeName(value);
        requestAnimationFrame(() => {
            /* istanbul ignore next (this can never happen, just to make ts happy, this is callback) */
            if (!ref.current || initialOffset == null)
                return;
            const updatedOffset = ref.current.getBoundingClientRect().y;
            window.scrollBy(0, updatedOffset - initialOffset); // TODO: refactor to use ScrollService (make it singleton)
        });
    }, [content, setActiveMimeName]);
    const ref = useRef(null);
    if (!content || !content.mediaTypes || !content.mediaTypes.length) {
        return null;
    }
    const options = content.mediaTypes.map((mime, idx) => {
        return {
            value: mime.name,
            idx,
        };
    });
    const active = getActiveMediaType(content, activeMimeName);
    return (_jsxs(_Fragment, { children: [_jsx(Wrapper, { innerRef: ref, withLabel: withLabel, translate: translate, children: renderSelect({
                    value: active.name,
                    options,
                    onChange: switchMedia,
                    ariaLabel: 'Content type',
                }) }), children(active)] }));
}
export const MediaTypesSwitch = memo(MediaTypesSwitchComponent);
//# sourceMappingURL=MediaTypesSwitch.js.map