import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useLayoutEffect, useRef, useState, useCallback, memo, useMemo } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { Button } from '@redocly/theme/components/Button/Button';
import { OverflowMenuVerticalIcon } from '@redocly/theme/icons/OverflowMenuVerticalIcon/OverflowMenuVerticalIcon';
import { LanguageDropdown } from './LanguageDropdown.js';
import { languageAtom, layoutAtom } from '../../jotai/app.js';
import { LanguageListContainer, LanguageListItem, Container } from './styled.js';
import { LanguageItem } from './LanguageItem.js';
import { DROPDOWN_TRIGGER_WIDTH, ITEM_WIDTH } from './constants.js';
import { LanguageListSkeleton } from '../common/Skeleton/LanguageListSkeleton.js';
import { useTelemetry } from '../../hooks/index.js';
function LanguageListComponent({ languages, activeLanguage }) {
    const [visibleItems, setVisibleItems] = useState([]);
    const [hiddenItems, setHiddenItems] = useState([]);
    const telemetry = useTelemetry();
    const containerRef = useRef(null);
    const layout = useAtomValue(layoutAtom);
    const setLanguage = useSetAtom(languageAtom);
    const setLanguageSendTelemetry = (selectedItem) => {
        telemetry.send({
            type: 'openapi_docs.select_language.clicked',
            payload: { language: selectedItem },
        });
    };
    const onSelectLanguage = (selectedItem) => {
        setLanguage(selectedItem);
        setLanguageSendTelemetry(selectedItem);
    };
    const handleSetActiveLanguage = (selectedItem) => {
        const selectedItemIndex = hiddenItems.findIndex((item) => item.key === selectedItem);
        if (selectedItemIndex !== -1) {
            const newHiddenItems = [...hiddenItems];
            const newVisibleItems = [...visibleItems];
            swapItems(newVisibleItems, newHiddenItems, selectedItemIndex);
            setVisibleItems(newVisibleItems);
            setHiddenItems(newHiddenItems);
            setLanguageSendTelemetry(selectedItem);
            setLanguage(selectedItem);
        }
    };
    const updateItemsVisibility = useCallback(() => {
        const containerWidth = containerRef?.current?.offsetWidth;
        if (!containerWidth)
            return;
        const { newVisibleItems, newHiddenItems } = calculateVisibleAndHiddenItems(containerWidth, [
            ...languages,
        ]);
        const selectedItemIndex = newHiddenItems.findIndex((item) => item.key === activeLanguage);
        if (selectedItemIndex !== -1) {
            swapItems(newVisibleItems, newHiddenItems, selectedItemIndex);
        }
        setVisibleItems(newVisibleItems);
        setHiddenItems(newHiddenItems);
    }, [activeLanguage, languages]);
    useLayoutEffect(() => {
        updateItemsVisibility();
        window.addEventListener('resize', updateItemsVisibility);
        return () => {
            window.removeEventListener('resize', updateItemsVisibility);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [layout, activeLanguage]);
    const justifyContent = useMemo(() => (visibleItems.length >= 5 || hiddenItems.length ? 'space-between' : 'start'), [hiddenItems.length, visibleItems.length]);
    return (_jsxs(Container, { ref: containerRef, children: [_jsxs(LanguageListContainer, { "$justifyContent": justifyContent, children: [!visibleItems.length && _jsx(LanguageListSkeleton, {}), visibleItems.map((item) => (_jsx(LanguageListItem, { onClick: () => onSelectLanguage(item.key), active: activeLanguage === item.key, children: _jsx(LanguageItem, { item: item, withIcon: true }) }, item.key)))] }), hiddenItems.length ? (_jsx(LanguageDropdown, { activeTab: activeLanguage, samples: hiddenItems, onChange: handleSetActiveLanguage, trigger: _jsx(Button, { icon: _jsx(OverflowMenuVerticalIcon, {}), variant: "text", style: { height: '100%' } }), withArrow: false, withCheckmark: false, width: 156 })) : null] }));
}
export const LanguageList = memo(LanguageListComponent);
function calculateVisibleAndHiddenItems(containerWidth, items) {
    let totalWidth = 0;
    const newVisibleItems = [];
    const newHiddenItems = [];
    items.forEach((item, idx) => {
        const isLastItem = idx === items.length - 1;
        // We won't display dropdown if the last item will fit in the container
        const dropdownTriggerWidth = isLastItem && newHiddenItems.length === 0 ? 0 : DROPDOWN_TRIGGER_WIDTH;
        if (containerWidth && totalWidth + ITEM_WIDTH + dropdownTriggerWidth <= containerWidth) {
            newVisibleItems.push(item);
            totalWidth += ITEM_WIDTH;
        }
        else {
            newHiddenItems.push(item);
        }
    });
    return { newVisibleItems, newHiddenItems };
}
function swapItems(newVisibleItems, newHiddenItems, selectedItemIndex) {
    const lastVisibleItems = newVisibleItems[newVisibleItems.length - 1];
    if (lastVisibleItems) {
        newVisibleItems[newVisibleItems.length - 1] = newHiddenItems[selectedItemIndex];
        newHiddenItems[selectedItemIndex] = lastVisibleItems;
    }
}
//# sourceMappingURL=LanguageList.js.map