<template>
  <div role="status" aria-live="polite" :aria-busy="isLoading" :class="`pkt-loader--${inline ? 'inline' : 'box'}`">
    <template v-if="isLoading">
      <div v-if="shouldDisplayLoader" :class="`pkt-loader pkt-loader--${props.size}`" data-testid="pkt-loader">
        <PktIcon
          :name="getVariant(variant)"
          aria-label="loading"
          path="https://punkt-cdn.oslo.kommune.no/latest/animations/"
          :class="`pkt-loader__svg pkt-loader__${variant}`"
        />
        <p v-if="message">{{ message }}</p>
      </div>
    </template>
    <template v-else>
      <slot></slot>
    </template>
  </div>
</template>

<script setup>
import { ref, toRefs } from 'vue'
import PktIcon from '../icon/Icon.vue'

const props = defineProps({
  message: String,
  size: {
    type: String,
    default: 'medium',
    validator: (value) => ['small', 'medium', 'large'].includes(value),
  },
  inline: {
    type: Boolean,
    default: false,
  },
  isLoading: {
    type: Boolean,
    default: true,
  },
  variant: {
    type: String,
    default: 'rainbow',
    validator: (value) => ['blue', 'rainbow', 'shapes'].includes(value),
  },
  delay: {
    type: Number,
    default: 0,
  },
})

const getVariant = (variant) => {
  return variant === 'shapes' ? 'loader' : variant === 'blue' ? 'spinner-blue' : 'spinner'
}

const { delay } = toRefs(props)
let shouldDisplayLoader = ref(delay.value > 0 ? false : true)

delay.value > 0 &&
  setTimeout(() => {
    shouldDisplayLoader.value = true
  }, delay.value)
</script>
