<script setup lang="ts">
import { onMounted, ref } from 'vue'
import FdsIcon from '../../FdsIcon/FdsIcon.vue'
import FdsButtonMinor from '../FdsButtonMinor/FdsButtonMinor.vue'
import type { FdsCopyButtonProps } from './types'

const props = withDefaults(defineProps<FdsCopyButtonProps>(), {
  value: '',
  text: 'Kopiera',
  copiedText: 'Kopierat!',
  timeoutMs: 800,
  disabled: false,
  dataTestid: undefined,
})

const isCopied = ref(false)
let resetTimer: ReturnType<typeof setTimeout> | null = null

async function copyToClipboard(text: string) {
  try {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(text)
      return true
    }
  } catch {
    // ignore and try fallback
  }
  const textarea = document.createElement('textarea')
  textarea.value = text
  textarea.style.position = 'fixed'
  textarea.style.opacity = '0'
  document.body.appendChild(textarea)
  textarea.focus()
  textarea.select()
  let ok = false
  try {
    ok = document.execCommand('copy')
  } catch {
    ok = false
  }
  document.body.removeChild(textarea)
  return ok
}

async function onClick() {
  if (props.disabled) return
  let textToCopy = props.value
  if (props.targetId) {
    const el = document.getElementById(props.targetId)
    if (el) {
      textToCopy = (el as HTMLElement).innerText || (el as HTMLElement).textContent || ''
    }
  }
  if (!textToCopy) return
  const ok = await copyToClipboard(textToCopy)
  if (!ok) return
  isCopied.value = true
  if (resetTimer) clearTimeout(resetTimer)
  resetTimer = setTimeout(() => (isCopied.value = false), props.timeoutMs)
}

onMounted(() => {
  if (resetTimer) {
    clearTimeout(resetTimer)
    resetTimer = null
  }
})
</script>

<template>
  <div v-if="isCopied" class="flex items-center gap-2 h-7">
    <FdsIcon name="bigSuccess" />
    <span>{{ props.copiedText }}</span>
  </div>
  <FdsButtonMinor
    v-else
    type="button"
    :disabled="props.disabled"
    icon="copy"
    :text="isCopied ? props.copiedText : props.text"
    :dataTestid="dataTestid"
    @click="onClick"
  />
</template>
