<script setup lang="ts">
import { ref, computed, nextTick, watch, onMounted, PropType, withDefaults } from 'vue'
import { currentIndexNum } from './'
const index = currentIndexNum.value
const props = withDefaults(
  defineProps<{
    toastText: string
    toastMovingTime?: number
    toastType?: 'success' | 'error'
  }>(),
  {
    toastMovingTime: 3,
    toastType: 'success',
  }
)
let timer: NodeJS.Timeout | null = null
const toastMove = ref(false)
onMounted(() => {
  toastMove.value = true
  timer = setTimeout(() => {
    toastMove.value = false
  }, props.toastMovingTime * 1000)
})

// トーストの表示時間をpropsの値から文字列の秒数に変換
const toastFadeTime = ref(`${String(props.toastMovingTime / 2)}s`)
function closeToast() {
  if (toastMove.value) {
    clearTimeout(timer!)
    toastMove.value = false
  }
}

const color = computed(() => {
  return props.toastType === 'success' ? 'var(--c-primary)' : 'var(--c-toast-warning)'
})
</script>

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

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

.toast-move,
.toast-enter-active,
.toast-leave-active
  transition: all v-bind(toastFadeTime) ease

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

.toast-leave-to
  opacity: 0
  transform: translateY(109px)
  transition: all v-bind(toastFadeTime) ease

.toast-leave-from
  opacity: 1
  transform: translateY(109px)
  transition: all v-bind(toastFadeTime) ease
</style>
