<script setup lang="ts">
import { computed } from 'vue'
import type { FdsSpinnerProps } from './types'

const props = withDefaults(
  defineProps<{
    size?: string
    color?: FdsSpinnerProps['color']
    label?: string
    labelPosition?: FdsSpinnerProps['labelPosition']
    dataTestid?: string
  }>(),
  { size: '48px', color: 'inherit', label: '', labelPosition: 'bottom', dataTestid: undefined },
)

const boxStyle = computed(() => ({ width: props.size, height: props.size }))

const colorClass = computed(() => {
  switch (props.color) {
    case 'black':
      return 'text-black'
    case 'white':
      return 'text-white'
    case 'blue':
      return 'text-blue-500'
    case 'inherit':
    default:
      return 'text-inherit'
  }
})

const wrapperClasses = computed(() =>
  props.label
    ? props.labelPosition === 'right'
      ? 'flex items-center gap-2'
      : 'inline-flex flex-col items-center gap-2'
    : 'inline-block',
)

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

<template>
  <div
    :class="wrapperClasses"
    role="status"
    :aria-label="label || 'Laddar'"
    v-bind="rootAttrs"
  >
    <div
      class="relative"
      :style="boxStyle"
    >
      <svg
        class="animate-spin block"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 24 24"
        :class="colorClass"
      >
        <path
          fill="none"
          fill-rule="evenodd"
          stroke="currentColor"
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="1.5"
          d="M22.942 14.523a11.42 11.42 0 01-1.087 2.848m-2.04 2.66a12.161 12.161 0 01-2.456 1.81M12.993.747c1.017.09 2.017.32 2.971.682m2.924 1.636c.81.622 1.528 1.355 2.131 2.178M22.6 8.2a10.5 10.5 0 01.614 2.984M14.25 22.972C8.162 24.215 2.218 20.286.975 14.197-.267 8.108 3.662 2.165 9.75.922"
        />
      </svg>
      <svg
        class="animate-spin-reverse absolute top-0 left-0"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 24 24"
        :class="colorClass"
      >
        <path
          fill="none"
          fill-rule="evenodd"
          stroke="currentColor"
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="1.5"
          d="M12 4.447a7.5 7.5 0 11-7.5 7.5"
        />
      </svg>
    </div>
    <div
      v-if="label"
      :class="labelPosition === 'bottom' ? 'font-bold' : ''"
    >
      {{ label }}
    </div>
  </div>
</template>
