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

const emit = defineEmits<{
  (e: 'update:toastSwitch', value: boolean): void
}>()

const props = defineProps({
  /**
   * トーストのオンオフはv-modelと連動
   */
  toastSwitch: { type: Boolean, default: false, required: true },
  /**
   * トースト内に表示させる文字列
   */
  toastText: { type: String, default: '登録完了' },
  /**
   * トーストを表示、非表示の時間
   */
  toastMovingTime: { type: Number, default: 4 }
})

const isToastOnStatus = computed(() => {
  if (toastMove.value === true) {
    return setTimeout(() => {
      ;(toastMove.value = false), props.toastMovingTime * 1000
    })
  } else {
    return
  }
})

//親コンポーネントからv-modelのBoolean値を元に表示、非表示を切り替える
const toastMove = computed({
  get: () => props.toastSwitch,
  set: value => {
    emit('update:toastSwitch', value)
  }
})

// トーストの表示時間をpropsの値から文字列の秒数に変換
const toastFadeTime = ref<string>()
toastFadeTime.value = `${String(props.toastMovingTime)}s`
</script>

<template>
  <div>
    <Teleport to="body">
      <div>
        <Transition name="toast">
          <div class="_toast" v-if="isToastOnStatus">
            <div class="_toast_text">{{ toastText }}</div>
          </div>
        </Transition>
      </div>
    </Teleport>
  </div>
</template>

<style lang="sass" scoped>
._toast
  height: 109px
  width: 238px
  background-color: var(--c-primary)
  position: fixed
  right:0
  bottom:0
  z-index: 100
  display: grid
  place-items: center
._toast_text
  color: var(--c-text-color)
  text-align: center

.toast-enter
  opacity: 0
  transform: translateY(100px)

.toast-enter-active
  animation: movein v-bind(toastFadeTime)
  animation-timing-function: ease-in


.toast-leave-active
  animation: movein v-bind(toastFadeTime) reverse
  animation-timing-function: ease-in


@keyframes movein
  0%
    opacity: 0
    transform: translateY(100px)
  50%
    opacity: 1
    transform: translateY(0px)
  80%
    opacity: 1
    transform: translateY(0px)
  100%
    opacity: 0
    transform: translateY(100px)
</style>
