import React from 'react';
import styled from 'styled-components';

import type { CDNIconProps } from '@redocly/theme/icons/types';

import { getCssColorVariable } from '@redocly/theme/core/utils';
import { ICONS_CDN_URL } from '@redocly/theme/core/constants';

const Icon = (props: CDNIconProps) => {
  const { name, type, pack, mode, color, ...rest } = props;
  const cdnUrl = ICONS_CDN_URL[pack || 'font-awesome'];
  const typeSegment = pack === 'code' ? '' : type ? type + '/' : 'regular/';

  const styleProps =
    mode === 'background'
      ? {
          backgroundImage: `url(${cdnUrl}/${typeSegment}${name}.svg)`,
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'center',
          backgroundSize: 'contain',
        }
      : {
          backgroundColor: color ? getCssColorVariable(color) : 'currentColor',
          maskImage: `url(${cdnUrl}/${typeSegment}${name}.svg)`,
          maskRepeat: 'no-repeat',
          maskPosition: 'center',
          maskSize: 'contain',
        };

  return (
    <svg
      {...rest}
      style={{
        ...styleProps,
        display: 'inline-block',
        verticalAlign: 'middle',
      }}
    />
  );
};

export const CDNIcon = styled(Icon).attrs({
  'data-component-name': 'icons/CDNIcon/CDNIcon',
})`
  height: ${({ size }) => size || 'var(--icon-height, 1em)'};
  width: ${({ size }) => size || 'var(--icon-width, 1em)'};
`;
