import styled from "@emotion/styled"

const failed = new Set<string>()

function onError({ currentTarget: img }: { currentTarget: any }) {
  if (img.getAttribute("src") !== "#") {
    failed.add(img.getAttribute("src"))
    img.src =
      "data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
    img.style.background = "linear-gradient(#F8F8F8, #EEE)"
  }
}

const EmptyIcon = styled.span`
  background: linear-gradient(#f8f8f8, #eee);
  border-radius: 3px;
  border: 1px solid #e9e9e9;
  display: inline-block;
  height: 20px;
  margin-bottom: -5px;
  margin-left: -2px;
  margin-right: 7px;
  width: 20px;
`

const Favicon = styled.img`
  display: inline-block;
  margin-right: 10px;
`.withComponent((props: JSX.IntrinsicElements["img"]) => (
  <img
    className={props.className}
    src={props.src!}
    onError={onError}
    onClick={props.onClick}
  />
))

const Icon = ({
  src,
  className,
  onClick,
}: {
  src?: string
  className?: string
  onClick?(): void
}) =>
  src && !failed.has(src) ? (
    <Favicon className={className} src={src} onClick={onClick} />
  ) : (
    <EmptyIcon className={className} data-src={src} onClick={onClick} />
  )

export { Icon as Favicon }
