import * as React from 'react';
import { allIcons, Icon } from '../icons';
import join from '../utils/join';
import { useEffect, useRef } from 'react';
export const IconComponent = (props) => {
    const { icon, iconClassName } = props;
    if (!icon) {
        return null;
    }
    const className = !isAdaptableElementIcon(icon)
        ? join(icon.className, iconClassName)
        : iconClassName;
    const divRef = useRef(null);
    useEffect(() => {
        let htmlElement;
        if (isAdaptableElementIcon(icon)) {
            if (typeof icon.element === 'string') {
                const domParser = new DOMParser();
                htmlElement = domParser.parseFromString(icon.element, 'text/html').body
                    .firstChild;
            }
            else {
                htmlElement = icon.element;
                // THe element neets to be cloned.
                // when it is used in more than one plce the element is removed from the DOM
                htmlElement = htmlElement.cloneNode(true);
            }
            divRef.current.insertAdjacentElement('afterend', htmlElement);
        }
        return () => {
            if (isAdaptableElementIcon(icon)) {
                htmlElement?.remove();
            }
        };
    }, [icon]);
    if (isAdaptableSystemIcon(icon) && icon.name in allIcons) {
        return (React.createElement(Icon, { "aria-hidden": "true", name: icon.name, size: icon.size, style: icon.style, className: className }));
    }
    if (isAdaptableCustomIcon(icon)) {
        let width = icon.style?.width ?? 'var(--ab-cmp-icon__width)';
        let height = icon.style?.height ?? 'var(--ab-cmp-icon__height)';
        const iconStyle = icon.style ?? {};
        return React.createElement("img", { src: icon.src, className: className, style: { height, width, ...iconStyle } });
    }
    if (isAdaptableElementIcon(icon)) {
        return (React.createElement("span", { ref: divRef, style: { display: 'none' }, "data-name": "adaptable-icon-placeholder" }));
    }
    return null;
};
export const isAdaptableSystemIcon = (icon) => {
    return typeof icon?.name === 'string';
};
export const isAdaptableCustomIcon = (icon) => {
    return typeof icon?.src === 'string';
};
export const isAdaptableElementIcon = (icon) => {
    return ((typeof HTMLElement === 'function' &&
        icon?.element instanceof HTMLElement) ||
        typeof icon?.element === 'string');
};
export const isAdaptableIcon = (icon) => {
    return isAdaptableSystemIcon(icon) || isAdaptableCustomIcon(icon) || isAdaptableElementIcon(icon);
};
