<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { useViewportBreakpoint } from '../../composables/useViewportBreakpoint'
import { useFdsI18n } from '../../plugin/useFdsI18n'

defineProps<{
  popoverClass?: string
}>()

const { currentBreakpoint, windowWidth, breakpoints } = useViewportBreakpoint()
const { t } = useFdsI18n()

const showBreakpointList = ref(false)
const containerRef = ref<HTMLElement | null>(null)

const toggleBreakpointList = () => {
  showBreakpointList.value = !showBreakpointList.value
}

const handleClickOutside = (event: MouseEvent) => {
  if (containerRef.value && !containerRef.value.contains(event.target as Node)) {
    showBreakpointList.value = false
  }
}

const formatMinWidth = (value: number) => `${value}px`

watch(showBreakpointList, (isOpen) => {
  if (isOpen) {
    document.addEventListener('click', handleClickOutside)
  } else {
    document.removeEventListener('click', handleClickOutside)
  }
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<template>
  <div ref="containerRef" class="flex relative">
    <button
      class="px-2 py-1 rounded text-xs bg-white bg-opacity-20 text-black hover:bg-opacity-30 cursor-pointer"
      :title="`${windowWidth}px`"
      @click="toggleBreakpointList"
    >
      {{ currentBreakpoint }}
    </button>

    <!-- Breakpoint list popover -->
    <div
      v-if="showBreakpointList"
      class="absolute bottom-full left-0 mb-2 rounded-lg shadow-lg p-2 text-xs font-mono whitespace-nowrap z-10"
      :class="popoverClass"
    >
      <div
        v-for="bp in breakpoints"
        :key="bp.key"
        class="flex justify-between gap-4 py-0.5"
        :class="currentBreakpoint === bp.key ? 'font-bold' : 'opacity-60'"
      >
        <span>{{ bp.key }}</span>
        <span>{{ formatMinWidth(bp.min) }}</span>
      </div>
      <div
        class="flex justify-between gap-4 py-0.5 border-t border-current/20 mt-1 pt-1"
        :class="currentBreakpoint === 'base' ? 'font-bold' : 'opacity-60'"
      >
        <span>{{ t('FdsDevMode.baseBreakpoint') }}</span>
        <span>{{ t('FdsDevMode.baseBreakpointRange') }}</span>
      </div>
    </div>
  </div>
</template>
