<template>
  <div v-if="textValue" ref="button-copy-text" :class="ui.root({ class: [props.class, props.ui?.root] })">
    <UButton
      v-if="to"
      :to="to"
      :class="ui.text({ class: props.ui?.text })"
      :external="external"
      :target="target"
      variant="link"
      color="info"
    >
      <slot>{{ textValue }}</slot>
    </UButton>
    <span v-else :class="ui.text({ class: props.ui?.text })">
      <slot>{{ textValue }}</slot>
    </span>

    <UTooltip
      v-if="showAction"
      :text="tooltipText"
      :content="{ side: 'top' }"
      disable-hoverable-content
      disable-closing-trigger
    >
      <UButton
        :class="ui.button({ class: props.ui?.button })"
        :icon="copied ? appConfig.ui.icons.check : appConfig.ui.icons.copy"
        variant="link"
        size="sm"
        :color="copied ? 'success' : 'neutral'"
        @click="copy(textValue)"
      />
    </UTooltip>
  </div>
</template>

<script>
import theme from "#build/cms/button-copy-text";
import { useAppConfig } from "#imports";
import { useClipboard, useElementHover } from "@vueuse/core";
import { computed, useTemplateRef } from "vue";
import { tv } from "../tv";
</script>

<script setup>
const props = defineProps({
  text: { type: [String, Number, null], required: false },
  showAction: { type: Boolean, required: false, default: true },
  alwaysShowTooltip: { type: Boolean, required: false },
  to: { type: null, required: false },
  class: { type: null, required: false },
  ui: { type: null, required: false },
  target: { type: [String, Object, null], required: false },
  external: { type: Boolean, required: false },
  label: { type: String, required: false }
});
const appConfig = useAppConfig();
const { copy, copied } = useClipboard();
const tooltipText = computed(() => copied.value ? "\u0421\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D\u043E" : "\u0421\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C");
const copyTextRef = useTemplateRef("button-copy-text");
const isHovered = useElementHover(copyTextRef);
const textValue = computed(() => {
  const text = props.label ?? props.text;
  return typeof text === "number" ? text.toString() : text;
});
const ui = computed(() => tv({ extend: tv(theme), ...appConfig.cms?.buttonCopyText || {} })({
  buttonInvisible: !isHovered.value && !props.alwaysShowTooltip,
  to: !!props.to
}));
</script>
