import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useState, useEffect, useMemo } from 'react';
import styled, { css } from 'styled-components';
import createDOMPurify from 'dompurify';
import { StyledPopover } from '../Popover';
import { defaultThemeProp } from '../../theme';
import { calculateFontSize } from '../../styles';
import { withTestIds } from '../../utils';
import { useTestIds } from '../../hooks';
import { getHTMLTestIds } from './HTML.test-ids';
const DOMPurify = createDOMPurify();
export const listStyles = css `
  ul,
  ol {
    padding-inline-start: 2.5rem;
  }

  li {
    margin: 0.5rem 0;
  }

  ul li {
    ul {
      margin-inline-start: 1rem;
      list-style-type: circle;
    }

    ul ul {
      margin-inline-start: 2rem;
      list-style-type: square;
    }

    ul ul ul {
      margin-inline-start: 3rem;
      list-style-type: disc;
    }
  }

  ol li {
    ol {
      margin-inline-start: 1rem;
      list-style-type: lower-alpha;
    }

    ol ol {
      margin-inline-start: 2rem;
      list-style-type: lower-roman;
    }

    ol ol ol {
      margin-inline-start: 3rem;
      list-style-type: decimal;
    }
  }
`;
export const getTableStyles = (theme) => css `
  border-collapse: collapse;

  td {
    border: 0.0625rem solid ${theme.base.palette['border-line']};
    min-width: 6.25rem;
  }

  tr:first-child {
    td:first-child {
      border-top-left-radius: 0.125rem;
    }

    td:last-child {
      border-top-right-radius: 0.125rem;
    }
  }

  tr:last-child {
    td:first-child {
      border-bottom-left-radius: 0.125rem;
    }

    td:last-child {
      border-bottom-right-radius: 0.125rem;
    }
  }
`;
export const getHtmlStyles = (theme) => {
    const { base: { 'font-size': baseFontSize, 'font-scale': baseFontScale, palette }, components: { text } } = theme;
    const fontSize = calculateFontSize(baseFontSize, baseFontScale);
    return `
    ${listStyles}
    table {
      ${getTableStyles(theme)}
    }
    img {
      max-width: 100%;
      height: auto;
      border-radius: 0.25rem;
    }
    a {
      color: ${palette.interactive};
    }
    pre {
      white-space: break-spaces;
    }
    p {
      min-height: ${fontSize[text.primary['font-size']]};
    }
    h1 {
      font-size: ${fontSize[text.h1['font-size']]};
      font-weight: ${text.h1['font-weight']};
      min-height: ${fontSize[text.h1['font-size']]};
    }
    h2 {
      font-size: ${fontSize[text.h2['font-size']]};
      font-weight: ${text.h2['font-weight']};
      min-height: ${fontSize[text.h2['font-size']]};
    }
    h3 {
      font-size: ${fontSize[text.h3['font-size']]};
      font-weight: ${text.h3['font-weight']};
      min-height: ${fontSize[text.h3['font-size']]};
    }
    h4 {
      font-size: ${fontSize[text.h4['font-size']]};
      font-weight: ${text.h4['font-weight']};
      min-height: ${fontSize[text.h4['font-size']]};
    }
    h5 {
      font-size: ${fontSize[text.h5['font-size']]};
      font-weight: ${text.h5['font-weight']};
      min-height: ${fontSize[text.h5['font-size']]};
    }
    h6 {
      font-size: ${fontSize[text.h6['font-size']]};
      font-weight: ${text.h6['font-weight']};
      min-height: ${fontSize[text.h6['font-size']]};
    }
  `;
};
export const StyledHTML = styled.div(({ theme }) => {
    return css `
    width: 100%;
    overflow-x: auto;
    overflow-wrap: break-word;
    contain: paint;
    ${getHtmlStyles(theme)}

    ${StyledPopover} ul {
      ul {
        padding-inline-start: 0;
      }
      ol {
        padding-inline-start: 0;
      }
    }

    ${StyledPopover} li {
      margin: 0;
    }
  `;
});
StyledHTML.defaultProps = defaultThemeProp;
if (DOMPurify.isSupported) {
    const targetBlankSet = new WeakSet();
    DOMPurify.addHook('beforeSanitizeAttributes', node => {
        // Can be passed text nodes
        if (!(node instanceof HTMLElement || node instanceof SVGElement))
            return;
        node.removeAttribute('class');
        if (node.tagName === 'A' &&
            node.hasAttribute('href') &&
            node.getAttribute('target') === '_blank') {
            targetBlankSet.add(node);
        }
    });
    DOMPurify.addHook('afterSanitizeAttributes', node => {
        if (node.tagName === 'A' && node.hasAttribute('href')) {
            const href = node.getAttribute('href');
            let fullURL;
            try {
                fullURL = new URL(href, window.location.href);
            }
            catch (e) {
                return;
            }
            if (window.location.origin !== fullURL.origin) {
                node.setAttribute('target', '_blank');
                node.setAttribute('rel', 'noopener');
            }
            else if (targetBlankSet.has(node)) {
                node.setAttribute('target', '_blank');
                targetBlankSet.delete(node);
            }
        }
    });
}
const HTML = forwardRef(function HTML({ testId, content, customTags, ...restProps }, ref) {
    const [mounted, setMounted] = useState(false);
    const sanitizedHtml = useMemo(() => {
        // Don't render content on the server at all.
        return mounted && DOMPurify.isSupported
            ? DOMPurify.sanitize(content, {
                FORBID_TAGS: ['style'],
                CUSTOM_ELEMENT_HANDLING: {
                    tagNameCheck: customTags ? tagName => customTags.includes(tagName) : undefined
                }
            })
            : '';
    }, [content, customTags, mounted]);
    const testIds = useTestIds(testId, getHTMLTestIds);
    useEffect(() => {
        setMounted(true);
    }, []);
    return (_jsx(StyledHTML, { "data-testid": testIds.root, ...restProps, dangerouslySetInnerHTML: { __html: sanitizedHtml }, ref: ref }));
});
export default withTestIds(HTML, getHTMLTestIds);
//# sourceMappingURL=HTML.js.map