<script setup lang="ts">
import { computed, useAttrs } from 'vue'
import FdsSpinner from '../../FdsSpinner/FdsSpinner.vue'
import type { FdsListHeadingProps } from './types'
import { classValueToString } from '../../../helpers/classValueToString'
import { useFdsI18n } from '../../../plugin/useFdsI18n'

defineOptions({
  inheritAttrs: false,
})

const props = withDefaults(defineProps<FdsListHeadingProps>(), {
  loading: false,
  dataTestid: undefined,
})

const attrs = useAttrs()
const { t } = useFdsI18n()

const consumerClass = computed(() => classValueToString(attrs.class))

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

const separatorText = () => t('FdsListHeading.separator')

const headingText = computed(() => {
  // If total is falsy, show "0 separator unfiltered text"
  if (!props.total) {
    let result = '0'
    if (props.unfiltered) {
      result += ` ${separatorText()} ${props.unfiltered}`
    }
    if (props.text) {
      result += ` ${props.text}`
    }
    return result
  }

  // If no text, just show total
  if (!props.text) return String(props.total)

  // If unfiltered exists and differs from total, show "total separator unfiltered text"
  if (props.unfiltered && props.total !== props.unfiltered) {
    return `${props.total} ${separatorText()} ${props.unfiltered} ${props.text}`
  }

  // Default: show "total text"
  return `${props.total} ${props.text}`
})

const handleLoadingText = () => {
  if (props.loadingText && props.loadingText.length > 0) {
    return props.loadingText
  }
  return t('FdsListHeading.loading')
}

const wrapperClasses = computed(() => {
  const baseClasses = 'inline-block mb-3 h-7 font-bold text-xl'
  return [baseClasses, consumerClass.value].filter(Boolean).join(' ')
})
</script>

<template>
  <div :class="wrapperClasses" v-bind="rootAttrs">
    <FdsSpinner
      v-if="loading"
      size="24px"
      color="blue"
      :label="handleLoadingText()"
      label-position="right"
    />
    <h3
      v-else
      class="heading font-heading text-xl m-0"
    >
      {{ headingText }}
    </h3>
  </div>
</template>
