import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useContext } from 'react';
import styled, { css } from 'styled-components';
import { meetsContrastGuidelines, mix, readableColor, transparentize } from 'polished';
import { calculateForegroundColor, isSolidColor, readableHue } from '../../styles';
import * as warnSolidIcon from '../Icon/icons/warn-solid.icon';
import { registerIcon } from '../Icon';
import { useConsolidatedRef, useElement, useI18n, useUID } from '../../hooks';
import Tooltip from '../Tooltip';
import { defaultThemeProp } from '../../theme';
import { tryCatch } from '../../utils';
import Count, { StyledCount } from '../Badges/Count';
import BareButton from '../Button/BareButton';
import HiddenText from '../HiddenText';
import TabsContext from './TabsContext';
import { StyledErrorIcon } from './Tabs.styles';
registerIcon(warnSolidIcon);
const activeStyle = (color) => css `
  ::after {
    display: block;
    background-color: ${color};
  }
`;
const getHorizontalUnselectedHoverStyle = ({ detached, level, opacity, color }) => level && level > 1 && !detached
    ? css `
        ::before {
          content: '';
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          border-radius: inherit;
          background-color: currentColor;
          opacity: ${opacity};
        }
      `
    : css `
        background-color: ${color};
        border-start-start-radius: ${detached ? 0 : 'calc(0.5rem * 0.5)'};
        border-start-end-radius: ${detached ? 0 : 'calc(0.5rem * 0.5)'};
      `;
const getHorizontalStyles = ({ selected, level, theme }) => {
    const color = theme.components.button.color;
    const foreground = theme.base.palette['foreground-color'];
    const { detached: tabsDetached } = theme.components.tabs;
    const secondaryColor = tabsDetached
        ? theme.base.palette['primary-background']
        : theme.base.palette['secondary-background'];
    const lightenedColor = tryCatch(() => transparentize(0.3, color)) ?? '';
    // If the secondary color is not a solid color, use the readable color as the fallback background.
    const fallbackBackground = isSolidColor(secondaryColor) ? secondaryColor : readableColor(color);
    const backgroundUsable = tryCatch(() => meetsContrastGuidelines(color, fallbackBackground).AA);
    const usableColor = backgroundUsable ? color : readableHue(color, fallbackBackground);
    const hoverBackgroundColor = tabsDetached
        ? tryCatch(() => transparentize(0.95, foreground))
        : tryCatch(() => mix(0.9, fallbackBackground, usableColor));
    const activeBackgroundColor = tabsDetached
        ? theme.base.palette['secondary-background']
        : tryCatch(() => mix(0.8, fallbackBackground, usableColor));
    const { spacing } = theme.base;
    let activeTabColor = theme.base.palette.interactive;
    if (!meetsContrastGuidelines(activeTabColor, fallbackBackground).AA) {
        activeTabColor = readableHue(activeTabColor, fallbackBackground);
    }
    return css `
    align-items: center;
    display: flex;
    flex-direction: row;
    height: calc(4 * ${spacing});
    padding: 0 calc(1.5 * ${spacing});
    border: none;
    text-decoration: none;

    @media (pointer: coarse) {
      height: ${theme.base['hit-area']['finger-min']};
    }

    span:first-of-type {
      color: ${selected ? color : foreground};
      display: inline-block;

      ::before {
        content: attr(data-content) / '';
        display: block;
        font-weight: bold;
        height: 0;
        overflow: hidden;
        visibility: hidden;
      }
    }

    &:first-child {
      margin-left: 0;
    }
    ::after {
      background: ${selected ? color : lightenedColor};
      display: ${selected ? 'block' : 'none'};
      content: '';
      position: absolute;
      height: 0.125rem;
      bottom: 0;
      left: calc(1.5 * ${spacing});
      right: calc(1.5 * ${spacing});
    }

    ${!selected
        ? css `
          @media (hover: hover) {
            &:not(:disabled):hover {
              text-decoration: none;
              ${getHorizontalUnselectedHoverStyle({
            detached: tabsDetached,
            level,
            opacity: 0.1,
            color: hoverBackgroundColor
        })}
            }

            &:not(:disabled):active {
              text-decoration: none;
              ${getHorizontalUnselectedHoverStyle({
            detached: tabsDetached,
            level,
            opacity: 0.2,
            color: activeBackgroundColor
        })}
            }
          }
        `
        : css `
          ${level &&
            level > 1 &&
            css `
            background-color: ${theme.base.palette['primary-background']};
          `}
        `}

    &:focus,
    &:not([disabled]):focus {
      border-radius: calc(0.5rem * 0.5);
      box-shadow: ${theme.base.shadow['focus-inset']};
      text-decoration: none;
      ::after {
        display: none;
      }
    }

    @media (pointer: coarse) {
      min-block-size: ${theme.base['hit-area'].finger};
    }

    ${StyledCount} {
      margin-inline-start: calc(0.5 * ${spacing});
    }

    ${tabsDetached &&
        css `
      &[aria-selected='true'],
      &:focus,
      &:not([disabled]):focus {
        color: ${activeTabColor};
        span:first-of-type {
          color: ${activeTabColor};
        }
        background: ${activeBackgroundColor};
      }
      &:hover:not(:disabled):not([aria-selected='true']) {
        background: ${hoverBackgroundColor};
        border-radius: 0;
        color: ${foreground};
        span:first-of-type {
          color: ${foreground};
        }
      }
    `}
  `;
};
const getVerticalStyles = ({ selected, theme }) => {
    const { detached: tabsDetached } = theme.components.tabs;
    const borderColor = theme.base.palette['border-line'];
    const interactive = theme.base.palette.interactive;
    const foreground = theme.base.palette['foreground-color'];
    const secondary = theme.base.palette['secondary-background'];
    const lightenedColor = tryCatch(() => transparentize(tabsDetached ? 0.95 : 0.5, tabsDetached ? foreground : interactive)) ?? '';
    const { spacing } = theme.base;
    const activeTabBg = tabsDetached ? secondary : transparentize(0.75, interactive);
    const activeTabColor = tabsDetached
        ? interactive
        : calculateForegroundColor(activeTabBg, foreground);
    return css `
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-style: solid;
    color: ${foreground};
    border-width: 0.0625rem 0;
    border-color: ${tabsDetached ? 'transparent' : borderColor};
    height: calc(5.5 * ${spacing});
    margin-top: -0.0625rem;
    padding: 0 calc(2 * ${spacing});
    text-decoration: none;

    &:first-child {
      border-top: 0.0625rem solid ${tabsDetached ? 'transparent' : borderColor};
    }
    ::after {
      content: '';
      position: absolute;
      display: ${selected ? 'block' : 'none'};
      top: 0;
      bottom: 0;
      ${tabsDetached ? 'left: 0;' : 'right: 0;'}
      width: 0.25rem;
      background: ${interactive};
    }
    &:hover&:not(:disabled) {
      ${activeStyle(lightenedColor)}
      text-decoration: none;
    }

    &:focus,
    &:not([disabled]):focus {
      ${activeStyle(interactive)}
      box-shadow: inset 0 0 0 0.0625rem ${interactive};
      text-decoration: none;
    }

    ${tabsDetached &&
        css `
      border-radius: calc(0.5 * ${theme.base['border-radius']});
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      margin: calc(0.125 * ${spacing}) calc(2 * ${spacing});

      &:not([disabled]):focus,
      &[aria-selected='true'] {
        background: ${activeTabBg};
        color: ${activeTabColor};
      }
      &:hover&:not(:disabled):not([aria-selected='true']) {
        background: ${lightenedColor};
      }
    `}
  `;
};
export const StyledTab = styled(BareButton)(({ theme, tabType, selected, level }) => css `
    position: relative;
    background: none;
    cursor: pointer;
    white-space: nowrap;

    ${selected &&
    css `
      font-weight: bold;
    `}

    & + & {
      margin-inline-start: 0;
    }

    &:focus {
      outline: none;
    }

    &:disabled {
      cursor: not-allowed;
      opacity: ${theme.base['disabled-opacity']};
    }

    ${tabType === 'horizontal'
    ? getHorizontalStyles({ theme, selected, level })
    : getVerticalStyles({ theme, selected })}

    ${StyledErrorIcon} {
      margin-inline-end: calc(0.5 * ${theme.base.spacing});
    }
  `);
StyledTab.defaultProps = defaultThemeProp;
const Tab = forwardRef(function Tab({ selected, content, count, type, disabled, errors, ...restProps }, ref) {
    const t = useI18n();
    const [tabEl, setTabEl] = useElement();
    const tabRef = useConsolidatedRef(ref, setTabEl);
    const { level } = useContext(TabsContext);
    const countDescID = useUID();
    const errorDescID = useUID();
    const commaDescID = useUID();
    const describedBy = [];
    if (typeof count === 'number') {
        describedBy.push(countDescID);
    }
    if (typeof count === 'number' && errors) {
        describedBy.push(commaDescID);
    }
    if (errors) {
        describedBy.push(errorDescID);
    }
    return (_jsxs(StyledTab, { ref: tabRef, selected: selected, tabType: type, disabled: disabled, level: level, "aria-describedby": describedBy.length > 0 ? describedBy.join(' ') : undefined, ...restProps, children: [_jsxs("span", { children: [!!errors && (_jsxs(_Fragment, { children: [_jsx(StyledErrorIcon, { name: 'warn-solid' }), _jsx(Tooltip, { target: tabEl, hideDelay: 'none', showDelay: 'none', describeTarget: false, children: t('tab_error_tooltip', [content]) }), _jsx(HiddenText, { id: errorDescID, children: t('tab_error_description') })] })), _jsx("span", { "data-content": content, children: content })] }), typeof count === 'number' && _jsx(Count, { id: countDescID, children: count }), typeof count === 'number' && errors && _jsx(HiddenText, { id: commaDescID, children: "," })] }));
});
export default Tab;
//# sourceMappingURL=Tab.js.map