<template>
  <v-tooltip :model-value="!error&&copied" :open-on-hover="false" location="top">
    <template v-slot:activator="{ props }">
      <div class="d-inline-flex align-center" v-bind="props" style="cursor: pointer" @click="copy()">
        <slot>
          <span :style="{maxWidth:width}" style="display: inline-block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ text }}</span>
        </slot>
        <v-btn v-bind="props" v-if="permitted" rounded variant="text" size="small" density="compact" @click="copy()"
               :class="error?'error':copied?'success':''"
               :icon="error?'mdi-close-box-outline':copied?'mdi-check-circle-outline':'mdi-content-copy'"
               :text="showText?text:''"
        />
      </div>
    </template>
    <span>Copied!</span>
  </v-tooltip>
</template>

<script setup lang="ts">
import {ref} from "vue";

const props = defineProps({text:String, showText:{default:false}, width: {default:null}})
const permitted = ref(true)
const copied = ref(false)
const error = ref(false)

navigator.permissions.query({name: "clipboard-write"}).then((permission) => {
  permitted.value = permission.state === "granted" || permission.state === "prompt"
}).catch(()=>null)

function copy() {
  if (!copied.value) {
    navigator.clipboard.writeText(props.text)
        .then(() => {
          copied.value = true
          setTimeout(() => copied.value = false, 3000)
        })
        .catch(() => {
          error.value = true
        })
  }
}

</script>

<style scoped lang="scss">
@use "src/styles/vars" as *;

.error {
  color: $red;
}

.success {
  color: $green;
}
</style>
