<script setup>
import { ref, computed, watch } from "vue";
import { parse } from "@twemoji/parser";
import { useState, useRuntimeConfig } from "#imports";
const props = defineProps({
  text: { type: String, required: true },
  mode: { type: String, required: false }
});
const config = useRuntimeConfig().public.twemoji;
const renderMode = computed(() => props.mode !== void 0 ? props.mode : config.mode);
const twemojify = useState(`twemojify:${renderMode.value}`, () => ({}));
const parsedText = ref(props.text);
const vs16RegExp = /\uFE0F/g;
const removeVS16s = (text) => text.replace(vs16RegExp, "");
const replaceEmojis = (emoji, indices) => {
  if (!twemojify.value[emoji]) return parsedText.value;
  return parsedText.value.replace(props.text.slice(...indices), twemojify.value[emoji]);
};
const loadTwemojify = async () => {
  const emojis = parse(props.text, { assetType: renderMode.value });
  for (const { url, indices, text: emoji } of emojis) {
    if (!url) {
      if (vs16RegExp.test(emoji)) {
        parsedText.value = removeVS16s(parsedText.value);
      }
      continue;
    }
    if (twemojify.value[emoji]) {
      parsedText.value = replaceEmojis(emoji, indices);
      continue;
    }
    if (renderMode.value === "png") {
      twemojify.value[emoji] = `<img src="${url}" class="twemojify" />`;
    } else {
      if (import.meta.client) {
        const expiry = localStorage.getItem(`twemoji-expiry`);
        if (config.cache && config.cache.maxAge > 0) {
          if (Date.now() > Number(expiry)) {
            localStorage.removeItem(`twemojify-${emoji}`);
            localStorage.setItem(`twemoji-expiry`, String(Date.now() + config.cache.maxAge * 1e3));
          }
          const cached = localStorage.getItem(`twemojify-${emoji}`);
          if (cached) {
            twemojify.value[emoji] = cached;
            parsedText.value = replaceEmojis(emoji, indices);
            continue;
          }
        }
      }
      const svgFetch = await $fetch(url, { responseType: "text" }).then((res) => res).catch(() => "");
      const svgBody = svgFetch.replace(/<\/*svg[^>]*>/g, "");
      const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" class="twemojify">${svgBody}</svg>`;
      twemojify.value[emoji] = svg;
      if (import.meta.client) {
        if (config.cache && config.cache.maxAge > 0) {
          localStorage.setItem(`twemojify-${emoji}`, svg);
        }
      }
    }
    parsedText.value = replaceEmojis(emoji, indices);
  }
};
watch(() => props, async () => {
  await loadTwemojify();
}, { deep: true });
await loadTwemojify();
</script>

<template>
  <span v-html="parsedText" />
</template>
