<script setup lang="ts">
import { computed, toRef, useAttrs } from 'vue'

import { useTexturedDeck } from '@/composables/useTexturedDeck'
import type { TexturedDeckValue } from '@/composables/useTexturedDeck'
import { DeckTexture } from '@/enums'
import config from '@/config'

defineOptions({
  name: 'TexturedDeck'
})

export interface TexturedDeckProps {
  /**
   * Name of the texture file ('silk', 'brick', 'rock', 'sand', 'crack', 'carbon')
   */
  modelValue?: TexturedDeckValue
  /**
   * CSS background-size property (cover, contain, auto, 50%, 50% auto, ...)
   */
  size?: string
  /**
   * Tag/Component to use as root tag.
   */
  tag?: string | object
  /**
   * Either or note we should use the black version of the texture
   */
  black?: boolean
  /**
   * Host where to find the textures (without tailing slash)
   */
  backgroundBaseUrl?: string
}

const props = withDefaults(defineProps<TexturedDeckProps>(), {
  modelValue: DeckTexture.Brick,
  size: 'cover',
  tag: 'div',
  black: false,
  backgroundBaseUrl: () => config.get('textured-deck.background-base-url', window.location.origin)
})

const attrs = useAttrs()

const { style } = useTexturedDeck({
  modelValue: toRef(props, 'modelValue'),
  size: toRef(props, 'size'),
  black: toRef(props, 'black'),
  backgroundBaseUrl: toRef(props, 'backgroundBaseUrl')
})

// NOTE: latent behaviour preserved — every prop (modelValue, size, black,
// backgroundBaseUrl) is forwarded onto the root element as an attribute, on
// top of Vue's automatic attribute fallthrough. The `tag` prop is dropped so
// it does not surface as an attribute on the rendered element.
const inheritedProps = computed((): object => {
  return { ...attrs, ...props, tag: undefined }
})
</script>

<template>
  <component
    :is="tag"
    :style="style"
    v-bind="inheritedProps"
    class="textured-deck"
  >
    <slot />
  </component>
</template>

<style lang="scss" scoped>
.textured-deck {
  background: #000 no-repeat center center;
  background-size: cover;
  color: #fff;
}
</style>
