<script setup lang="ts">
import HalfStar from "#adata-ui/icons/star/star-half-filled.vue";
import FillStar from "#adata-ui/icons/star/star-filled.vue";
import Star from "#adata-ui/icons/star/star.vue";
import type {SelectEvent, StarMoveEvent} from "./../types";

interface Props {
  fill: number;
  size?: number;
  starId: number;
}

const props = withDefaults(defineProps<Props>(), {
  size: 16,
  fill: 0,
})

const emit = defineEmits<{
  (e: 'star-mouse-move', event: StarMoveEvent): void,
  (e: 'star-selected', event: SelectEvent): void
}>()

const star = computed(() => {
  if (props.fill === 0) {
    return Star
  } else if (props.fill > 0 && props.fill <= 50) {
    return HalfStar
  } else {
    return FillStar
  }
})

const getPosition = (event: MouseEvent) => {
  const starWidth = (92 / 100) * props.size
  const offset = Math.max(event.offsetX, 1)
  const position = Math.round((100 / starWidth) * offset)

  return Math.min(position, 100)
}

const mouseMoving = (event: MouseEvent) => {
  if (event.touchAction !== 'undefined') {
    emit('star-mouse-move', {
      event: event,
      position: getPosition(event),
      id: props.starId
    })
  }
}

const selected = (event: MouseEvent) => {
  emit('star-selected', {
    id: props.starId,
    position: getPosition(event)
  })
}
</script>

<template>
  <div>
    <component
      :is="star"
      class="cursor-pointer"
      :width="size"
      :height="size"
      @mousemove="mouseMoving"
      @click="selected"
    />
  </div>
</template>

<style scoped>

</style>
