<script setup lang="ts">
import { computed, type Slot } from 'vue'
import { useHasSlot } from '../../../composables/useHasSlots'
import FdsIcon from '../../FdsIcon/FdsIcon.vue'
import type { FdsTableHeadProps } from './types'

const props = withDefaults(defineProps<FdsTableHeadProps>(), {
  align: 'left',
  icon: undefined,
  heading: undefined,
  dataTestid: undefined,
})

const hasSlot = useHasSlot()

const headerClasses = computed(() => [
  'fds-table-head-button appearance-none bg-transparent flex items-center border-none text-left w-full bg-transparent text-gray-800 whitespace-nowrap text-base font-bold leading-5 tracking-normal',
  props.align === 'center' && 'text-center justify-center',
  props.align === 'right' && 'text-right justify-end',
  iconName.value &&
    'text-blue-600! hover:bg-blue_t-200 cursor-pointer focus-visible:outline-dashed focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-blue-500 active:bg-blue_t-300',
])

/* Sending an icon makes the th sortable */
const iconName = computed(() => props.icon)

const emit = defineEmits<{
  (e: 'sort', ev: MouseEvent | KeyboardEvent): void
}>()

const handleSort = (ev: MouseEvent | KeyboardEvent) => {
  emit('sort', ev)
}

const rootAttrs = computed(() => {
  const attrs: Record<string, string> = {}
  if (props.dataTestid) {
    attrs['data-testid'] = props.dataTestid
  }
  return attrs
})

defineSlots<{
  default?: Slot
}>()
</script>

<template>
  <th class="fds-table-head" v-bind="rootAttrs">
    <button
      v-if="iconName"
      :class="headerClasses"
      @click="handleSort"
      @keydown.enter="handleSort"
      @keydown.space.prevent="handleSort"
    >
      <span v-if="hasSlot"><slot /></span>
      <span v-else>{{ heading }}</span>
      <FdsIcon :name="iconName" size="24px" class="fill-blue-500 ml-1" />
    </button>
    <div v-else :class="headerClasses">
      <span v-if="hasSlot"><slot /></span>
      <span v-else>{{ heading }}</span>
    </div>
  </th>
</template>
