<template>
  <img
    v-if="src || (!src && !hideWhenNoSrc)"
    :class="[
      cn.b(),
      cn.is('circle', circle),
      cn.is('fallback', isFallback),
      cn.is('empty', !src),
    ]"
    :src="src"
    :alt="code"
    draggable="false"
  >
</template>

<script>
/** FROM -> TO */
</script>

<script setup>
// TODO: Typescript
import { computed, toRef } from 'vue'
import useClassname from '../../composables/use-classname'
import AVAILABLE_COINS from './available-coins.json'

const props = defineProps({
  code: {
    type: String,
    required: true,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  circle: {
    type: Boolean,
    default: false,
  },
  fallbackImg: {
    type: String,
    default: undefined,
  },
  hideWhenNoSrc: {
    type: Boolean,
    default: false,
  },
})

const DIRECT_ALIASES = {
  toncoin: 'ton',
  bnb: 'btcbep20',
  ftm: 'fantom',
  matic: 'polygon',
  avaxc: 'avax',
  bsc: 'btcbep20',
  btctest: 'btc',
  lend: 'polygon',
  rub: 'abrub',
  poly: 'polygon',
  usdterc20: 'usdtomni',
}

const REGEX_ALIASES = {
  'acrub': /^acc/,
  'usdtomni': /^usdt/,
  'wirerub': /^wire/,
  'eth': /^eth/,
  'usd coin': /^usdc/,
  'btcbep20': /^bnb/,
  'tusd': /^tusd/,
  'tcsbrub': /^tcs/,
  'shib': /^shib/,
  'dai': /^dai/,
  'cake': /^cake/,
}

const cn = useClassname('ui-coin')

const fallbackImg = toRef(props, 'fallbackImg')

const name = computed(() => props.code.toLowerCase())
const notAvailable = computed(() => !AVAILABLE_COINS.includes(name.value))

const alias = computed(() => {
  if (!notAvailable.value)
    return null

  const direct = DIRECT_ALIASES[name.value]

  if (direct)
    return direct

  for (const [target, pattern] of Object.entries(REGEX_ALIASES)) {
    if (pattern.test(name.value))
      return target
  }

  return null
})

const isFallback = computed(
  () => notAvailable.value && !alias.value && fallbackImg.value,
)

const src = computed(() => {
  if (!name.value || (notAvailable.value && !alias.value))
    return fallbackImg.value

  const code = alias.value ?? name.value

  return `/coins/${code}.svg`
})
</script>

<style lang="scss">
@use 'styles';
</style>
