import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, forwardRef, Fragment, useMemo, useImperativeHandle, useRef } from 'react';
import styled, { css } from 'styled-components';
import { getContrast } from 'polished';
import { defaultThemeProp } from '../../theme';
import Button, { StyledButton } from '../Button';
import { focusHeadingOrContainer, tryCatch, withTestIds } from '../../utils';
import { useConsolidatedRef, useDirection, useI18n, useTestIds } from '../../hooks';
import Flex from '../Flex';
import Text, { StyledText } from '../Text';
import Grid from '../Grid';
import ExpandCollapse from '../ExpandCollapse';
import { Count } from '../Badges';
import Icon, { StyledIcon, 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 checkIcon from '../Icon/icons/check.icon';
import * as aiIcon from '../Icon/icons/polaris-solid.icon';
import VisuallyHiddenText from '../VisuallyHiddenText';
import { UnorderedList } from '../List';
import { readableColor } from '../../styles';
import { getBannerTestIds } from './Banner.test-ids';
registerIcon(timesIcon, caretRightIcon, warnSolidIcon, diamondMinusIcon, informationSolidIcon, checkIcon, aiIcon);
export const StyledBanner = styled.div(({ headingTag, theme }) => {
    return css `
      border-radius: var(--border-radius, ${theme.components.card['border-radius']});
      min-inline-size: 100%;
      inline-size: 0;

      &:has(${headingTag}:focus) {
        box-shadow: ${theme.base.shadow.focus};
      }

      ${headingTag}${StyledText} {
        word-break: break-word;
      }
    `;
});
StyledBanner.defaultProps = defaultThemeProp;
export const StyledBannerStatus = styled.div(({ variant, theme }) => {
    const { background } = theme.components.banner[variant];
    const color = tryCatch(() => getContrast(background, theme.base.palette['primary-background']) >= 3
        ? theme.base.palette['primary-background']
        : readableColor(background));
    return css `
    background-color: ${background};
    color: ${color};
    border-start-start-radius: inherit;
    border-end-start-radius: inherit;
    border: 0.0625rem solid ${theme.base.palette['border-line']};
    border-inline-end: none;
    font-size: 1.25rem;
  `;
});
StyledBannerStatus.defaultProps = defaultThemeProp;
export const StyledBannerHeader = styled.div(({ theme }) => {
    const { rtl } = useDirection();
    return css `
    min-height: 2.125rem;

    ${StyledButton}[aria-expanded] {
      ${StyledIcon} {
        transition: rotate ${theme.base.animation.speed} ${theme.base.animation.timing.ease};
      }

      &[aria-expanded='true'] ${StyledIcon} {
        rotate: 90deg;
      }

      &[aria-expanded='false'] ${StyledIcon} {
        rotate: ${rtl ? 180 : 0}deg;
      }
    }
  `;
});
StyledBannerHeader.defaultProps = defaultThemeProp;
export const StyledBannerContent = styled.div(({ expandable, theme }) => {
    return css `
    background: ${theme.components.card.background};
    padding-block: calc(0.5 * ${theme.base.spacing});
    padding-inline-start: calc(${expandable ? 0.5 : 2} * ${theme.base.spacing});
    padding-inline-end: calc(0.5 * ${theme.base.spacing});
    border: 0.0625rem solid ${theme.base.palette['border-line']};
    border-inline-start: none;
    border-start-end-radius: inherit;
    border-end-end-radius: inherit;
  `;
});
StyledBannerContent.defaultProps = defaultThemeProp;
export const StyledBannerMessageList = styled(UnorderedList)(({ theme }) => css `
    padding-block-end: calc(0.5 * ${theme.base.spacing});
    padding-inline-start: calc(5 * ${theme.base.spacing});
    padding-inline-end: calc(2 * ${theme.base.spacing});
  `);
StyledBannerMessageList.defaultProps = defaultThemeProp;
export const StyledBannerMessage = styled.span `
  overflow-wrap: break-word;
  list-style: none;
`;
StyledBannerMessage.defaultProps = defaultThemeProp;
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("span", { "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) {
            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 = 'h2', messages, 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 [collapsed, setCollapsed] = useState(count > 2);
    const bannerRef = useConsolidatedRef(ref);
    const expandCollapseBtnRef = useRef(null);
    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 = '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);
                }
            });
        }
    }), []);
    return (_jsxs(Grid, { "data-testid": testIds.root, ...restProps, as: StyledBanner, container: { cols: '2rem minmax(0, 1fr)' }, role: role, "aria-live": ariaLive, headingTag: headingTag, ref: bannerRef, children: [_jsx(Flex, { as: StyledBannerStatus, container: { justify: 'center', alignItems: 'start', pad: [1.5, 0] }, variant: variant, children: _jsx(Icon, { name: icon }) }), count === 1 && !firstMessageHasChildren && headingText === undefined ? (_jsxs(Flex, { container: { alignItems: 'start' }, as: StyledBannerContent, children: [_jsx(VisuallyHiddenText, { as: headingTag, children: `${heading} ${count}` }), _jsx(Flex, { item: { alignSelf: 'center', grow: 1 }, as: 'ul', children: typeof messages[0] === 'string' ? (_jsx(BannerMessageItem, { testId: testId, label: messages[0], as: 'li' })) : (_jsx(BannerMessageItem, { ...messages[0], testId: testId, as: 'li' })) }), 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' }) }))] })) : (_jsxs(StyledBannerContent, { expandable: true, children: [_jsxs(Grid, { as: StyledBannerHeader, container: { cols: 'auto 1fr auto', areas: '"toggle heading dismiss"', gap: 0.5 }, children: [_jsxs(Grid, { "data-testid": testIds.heading, container: {
                                    cols: 'fit-content(100%) max-content',
                                    gap: 0.5,
                                    alignItems: 'center'
                                }, item: { area: 'heading', alignSelf: 'center' }, as: Text, forwardedAs: headingTag, variant: 'h2', children: [heading, " ", _jsx(Count, { children: count })] }), _jsx(Grid, { item: { area: 'toggle', alignSelf: 'center' }, children: _jsx(Button, { "data-testid": testIds.expandCollapse, onClick: () => {
                                        setCollapsed(cur => !cur);
                                    }, label: t(collapsed ? 'expand' : 'collapse'), "aria-label": t(collapsed ? 'expand_noun' : 'collapse_noun', [heading]), "aria-expanded": !collapsed, variant: 'simple', icon: true, ref: expandCollapseBtnRef, children: _jsx(Icon, { name: 'caret-right' }) }) }), _jsx(Grid, { item: { area: 'dismiss', alignSelf: 'center' }, children: 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' }) })) })] }), _jsx(ExpandCollapse, { collapsed: collapsed, children: _jsx(StyledBannerMessageList, { items: messagesToRender }) })] }))] }));
}), getBannerTestIds);
//# sourceMappingURL=Banner.js.map