<template>
  <div class="copy-container">
    <div class="label h700 caps" v-if="label">
      {{ label }}
    </div>

    <div class="wrapper d-flex align-items-center">
      <p class="h600 grow">
        {{ copyText }}
      </p>

      <div
        id="copy-btn"
        class="icon fill-blue"
        data-clipboard-action="copy"
        :data-clipboard-text="copyText"
        @click="setCopied"
      >
        <SpIcon name="sp-copy" />
      </div>
    </div>

    <p v-if="copied" class="copied h700">{{ $t("common.copied") }}</p>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import Clipboard from "clipboard";
export default defineComponent({
  props: {
    label: {
      type: String,
      default: "",
    },
    copyText: {
      type: String,
      required: true,
      default: "Copy Text",
    },
  },
  setup(props) {
    const clipboard = ref<any>(null);
    const copied = ref<boolean>(false);
    const timeoutId = ref<any>(null);

    onMounted((): void => {
      clipboard.void = new Clipboard("#copy-btn");
    });

    const setCopied = (): void => {
      clearTimeout(timeoutId.value);

      copied.value = true;
      timeoutId.value = setTimeout(() => {
        copied.value = false;
      }, 3000);
    };

    return {
      ...props,
      setCopied,
      clipboard,
      copied,
      timeoutId,
    };
  },
});
</script>
