import { css } from "@emotion/css"
import { memo, useMemo } from "react"
import { RuleType } from "~/shared/models/enums.generated"
import type { TreeItem } from "./index"

function getFavicon(url: string) {
  url = url.replace(/@/g, "%40")
  if (url.startsWith(`chrome://inspect`)) {
    return defaultFavicon
  }
  return `chrome://favicon/size/512/${url}`
}

export function getFirstDomainRule(rules: TreeItem["rules"]) {
  return rules.find(rule => rule.type === RuleType.Domain && !rule.exclude)?.value
}

function getURL(rules: TreeItem["rules"]) {
  const domain = getFirstDomainRule(rules)
  if (domain) {
    return `https://${domain}`
  }

  const url = rules.find(r => r.type === RuleType.URLPrefix || r.type === RuleType.URL)
    ?.value

  if (url) {
    return url
  }
}

export const Favicon = memo<{ item: TreeItem }>(({ item }) => {
  const { rules, icon } = item
  const url = useMemo(() => getURL(rules), [rules])

  if (!url) {
    return defaultFavicon
  }

  const src = icon ?? getFavicon(url)

  return typeof src === "string" ? (
    <img
      alt="Favicon"
      className={css`
        border-radius: 2px;
        width: 16px;
        height: 16px;
        margin-right: 4px;
      `}
      src={src}
    />
  ) : (
    src
  )
})

const defaultFavicon = (
  <svg
    focusable="false"
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    className={css`
      width: 20px;
      margin-left: -1px;
      margin-right: 2px;
    `}
  >
    <path
      d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"
      fill="#0060f0"
    />
  </svg>
)
