import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, forwardRef, useMemo, useImperativeHandle, useRef, Fragment } from 'react';
import Button from '../Button';
import { focusHeadingOrContainer, withTestIds } from '../../utils';
import { useConsolidatedRef, useI18n, useTestIds, useTheme } from '../../hooks';
import Flex from '../Flex';
import Text from '../Text';
import Grid from '../Grid';
import ExpandCollapse, { ExpandCollapseButton } from '../ExpandCollapse';
import { Count } from '../Badges';
import Icon, { registerIcon } from '../Icon';
import * as timesIcon from '../Icon/icons/times.icon';
import * as caretRightIcon from '../Icon/icons/caret-right.icon';
import * as warnSolidIcon from '../Icon/icons/warn-solid.icon';
import * as diamondMinusIcon from '../Icon/icons/diamond-solid.icon';
import * as informationSolidIcon from '../Icon/icons/information-solid.icon';
import * as checkSolidIcon from '../Icon/icons/check-solid.icon';
import * as aiIcon from '../Icon/icons/polaris-solid.icon';
import VisuallyHiddenText from '../VisuallyHiddenText';
import HTML from '../HTML';
import { getBannerTestIds } from './Banner.test-ids';
import { StyledBanner, StyledBannerStatus, StyledBannerMessageList, StyledBannerMessage, StyledBannerMessageLabel } from './Banner.styles';
registerIcon(timesIcon, caretRightIcon, warnSolidIcon, diamondMinusIcon, informationSolidIcon, checkSolidIcon, aiIcon);
// FIXME: Temporarily re-exporting for backward compatibility.
export { StyledBanner, StyledBannerMessageList };
const BannerMessageItem = forwardRef(function BannerMessageItem({ testId, label, description, action, ...restProps }, ref) {
    const testIds = useTestIds(testId, getBannerTestIds);
    const labelArray = Array.isArray(label) ? label : [label];
    return (_jsxs(StyledBannerMessage, { ...restProps, ref: ref, children: [_jsx(StyledBannerMessageLabel, { "data-testid": testIds.messageLabel, children: labelArray.map((item, idx) => typeof item === 'string' ? (
                // eslint-disable-next-line react/no-array-index-key
                _jsx(Fragment, { children: item }, idx)) : (
                // eslint-disable-next-line react/no-array-index-key
                _jsx(Button, { variant: 'link', href: item.href, onClick: item.onClick, children: item.text }, idx))) }), description && (_jsxs(_Fragment, { children: [' ', _jsx(Text, { "data-testid": testIds.messageDescription, variant: 'secondary', children: description })] })), action && (_jsxs(_Fragment, { children: [' ', _jsx(Text, { variant: 'secondary', children: _jsx(Button, { "data-testid": testIds.messageAction, variant: 'link', href: action.href, onClick: action.onClick, ...action, children: action.text }) })] }))] }));
});
const prepareMessages = (messages, testId) => {
    return messages.flatMap(msg => {
        if (typeof msg === 'string') {
            return [_jsx(BannerMessageItem, { label: msg })];
        }
        if (msg.items && msg.items.length > 0) {
            const { items, ...restMsg } = msg;
            const subMessages = prepareMessages(items, testId);
            return [_jsx(BannerMessageItem, { ...restMsg, testId: testId }), subMessages];
        }
        return [_jsx(BannerMessageItem, { ...msg, testId: testId })];
    });
};
export default withTestIds(forwardRef(function Banner({ testId, variant, headingText, headingTag = 'h3', messages = [], content, onDismiss, handle, ...restProps }, ref) {
    const testIds = useTestIds(testId, getBannerTestIds);
    const messagesToRender = useMemo(() => prepareMessages(messages, testId), [messages]);
    const firstMessageHasChildren = messages.length > 0 &&
        typeof messages[0] === 'object' &&
        Array.isArray(messages[0].items) &&
        messages[0].items.length > 0;
    const count = messages.length;
    const t = useI18n();
    const theme = useTheme();
    const [collapsed, setCollapsed] = useState(false);
    const bannerRef = useConsolidatedRef(ref);
    const expandCollapseBtnRef = useRef(null);
    const showHeader = headingText !== undefined || (content ? count !== 0 : count !== 1 || firstMessageHasChildren);
    const expandable = showHeader && (count !== 0 || !!content);
    const showCount = count > 0;
    let heading = headingText;
    let icon;
    let role;
    let ariaLive;
    switch (variant) {
        case 'urgent':
            heading ??= t('error');
            icon = 'warn-solid';
            role = 'alert';
            ariaLive = 'assertive';
            break;
        case 'warning':
            heading ??= t('warning');
            icon = 'diamond-minus';
            role = 'alert';
            ariaLive = 'assertive';
            break;
        case 'success':
            heading ??= t('success');
            icon = theme.base['icon-set'] === 'budicon' ? 'check-solid' : 'check';
            role = 'none';
            ariaLive = 'polite';
            break;
        case 'ai':
            heading ??= t('ai_generated');
            icon = 'polaris-solid';
            role = 'none';
            ariaLive = 'polite';
            break;
        case 'info':
        default:
            heading ??= t('information');
            icon = 'information-solid';
            role = 'none';
            ariaLive = 'polite';
            break;
    }
    useImperativeHandle(handle, () => ({
        focus: () => {
            // Empty timeout ensures that the banner will take focus after any other programmatic focus events
            setTimeout(() => {
                if (expandCollapseBtnRef.current) {
                    expandCollapseBtnRef.current.focus();
                }
                else if (bannerRef.current) {
                    focusHeadingOrContainer(bannerRef.current, heading);
                }
            });
        }
    }), []);
    const iconRegion = (_jsx(Flex, { as: StyledBannerStatus, container: { alignItems: 'center' }, variant: variant, children: _jsx(Icon, { name: icon }) }));
    const dismissButton = onDismiss ? (_jsx(Button, { "data-testid": testIds.dismiss, onClick: onDismiss, label: t('dismiss'), "aria-label": t('banner_dismiss_button_label_a11y'), variant: 'simple', icon: true, children: _jsx(Icon, { name: 'times' }) })) : null;
    return (_jsx(Grid, { "data-testid": testIds.root, ...restProps, as: StyledBanner, container: showHeader
            ? { cols: 'minmax(0, 1fr)' }
            : { cols: 'min-content minmax(0, 1fr) auto', gap: 1, alignItems: 'start' }, role: role, "aria-live": ariaLive, headingTag: headingTag, variant: variant, ref: bannerRef, children: !showHeader ? (_jsxs(_Fragment, { children: [iconRegion, _jsx(VisuallyHiddenText, { as: headingTag, children: `${heading} ${showCount ? count : ''}` }), _jsx(Flex, { item: { alignSelf: 'center', grow: 1 }, as: content ? undefined : 'ul', children: (() => {
                        if (content) {
                            return _jsx(HTML, { content: content });
                        }
                        if (typeof messages[0] === 'string') {
                            return _jsx(BannerMessageItem, { testId: testId, label: messages[0], as: 'li' });
                        }
                        return _jsx(BannerMessageItem, { ...messages[0], testId: testId, as: 'li' });
                    })() }), dismissButton] })) : (_jsxs(Flex, { container: { direction: 'column', justify: 'center' }, children: [_jsxs(Grid, { container: {
                        cols: expandable ? 'auto 1fr auto' : '1fr auto',
                        areas: expandable ? '"toggle heading dismiss"' : '"heading dismiss"',
                        gap: 0.5,
                        alignItems: 'start'
                    }, children: [_jsxs(Grid, { container: { cols: 'min-content auto', gap: 1 }, item: { area: 'heading', alignSelf: 'center' }, children: [iconRegion, _jsxs(Grid, { "data-testid": testIds.heading, container: {
                                        cols: `fit-content(100%) ${showCount ? 'max-content' : ''}`,
                                        gap: 0.5,
                                        alignItems: 'center'
                                    }, as: Text, forwardedAs: headingTag, variant: 'h3', children: [heading, " ", showCount && _jsx(Count, { children: count })] })] }), expandable && (_jsx(Grid, { item: { area: 'toggle' }, children: _jsx(ExpandCollapseButton, { "data-testid": testIds.expandCollapse, onToggle: () => {
                                    setCollapsed(cur => !cur);
                                }, label: t(collapsed ? 'expand' : 'collapse'), "aria-label": t(collapsed ? 'expand_noun' : 'collapse_noun', [heading]), "aria-expanded": !collapsed, iconOnly: true, ref: expandCollapseBtnRef, expanded: !collapsed }) })), _jsx(Grid, { item: { area: 'dismiss' }, children: dismissButton })] }), expandable && (_jsx(ExpandCollapse, { collapsed: collapsed, children: _jsxs(Flex, { container: {
                            direction: 'column',
                            gap: 1,
                            pad: [1, 2]
                        }, children: [messagesToRender.length > 0 ? (_jsx(StyledBannerMessageList, { items: messagesToRender })) : null, content && _jsx(HTML, { content: content })] }) }))] })) }));
}), getBannerTestIds);
//# sourceMappingURL=Banner.js.map