<template>
  <div
    v-if="displayCoords"
    class="absolute bottom-2 right-2 z-[501] rounded-lg px-3 py-2 font-mono text-base bg-base-100/95 backdrop-blur-sm border border-base-300/50 shadow cursor-pointer select-none transition-all hover:border-primary/50 hover:bg-base-100 flex items-center gap-2"
    aria-label="Current grid position and zoom — click to copy share link"
    :title="copied ? 'Copied!' : 'Click to copy share link'"
    role="button"
    tabindex="0"
    @click="copyShareUrl"
    @keydown.enter="copyShareUrl"
    @keydown.space.prevent="copyShareUrl"
  >
    <span class="relative">
      {{ mapid }} · {{ displayCoords.x }}, {{ displayCoords.y }} · z{{ displayCoords.z }}
      <span
        v-if="copied"
        class="absolute -top-6 left-1/2 -translate-x-1/2 whitespace-nowrap rounded bg-primary px-2 py-1 text-xs font-sans text-primary-content shadow"
      >
        Copied!
      </span>
    </span>
    <icons-icon-copy class="size-4 shrink-0 opacity-70" aria-hidden="true" />
  </div>
</template>

<script setup lang="ts">
const props = defineProps<{
  mapid: number
  displayCoords: { x: number; y: number; z: number } | null
}>()

const { fullUrl } = useAppPaths()
const copied = ref(false)
let copyTimeout: ReturnType<typeof setTimeout> | null = null

function copyShareUrl() {
  if (!props.displayCoords) return
  const path = `grid/${props.mapid}/${props.displayCoords.x}/${props.displayCoords.y}/${props.displayCoords.z}`
  const url = fullUrl(path)
  if (import.meta.client && navigator.clipboard?.writeText) {
    navigator.clipboard.writeText(url).then(() => {
      copied.value = true
      useToast().success('Link copied')
      if (copyTimeout) clearTimeout(copyTimeout)
      copyTimeout = setTimeout(() => {
        copied.value = false
        copyTimeout = null
      }, 2000)
    })
  }
}
</script>
