<template>
  <div v-if="loaded"
    class="l-fixed l-right-3 l-bottom-3 l-left-3 md:l-left-auto l-max-w-lg l-z-50">
    <PopupCard
      :review="currentReview"
      :theme="theme"
      @close="closeReview"
    />
  </div>
</template>

<script setup="{ emit }">
import { onMounted, computed, ref } from 'vue'
import PopupCard from './PopupCard.vue'
import useReviews from '@/api/reviews'
import useWidgetSettings from '@/api/widget-settings'

const props = defineProps({
  apiKey: {
    type: String,
    required: true,
  },
  apiUrl: {
    type: String,
  }
})

const emit = defineEmits(['close'])

const { getPopupSettings, theme } = useWidgetSettings()
const { getReviews, reviews, totalReviews } = useReviews()

const currentReviewIndex = ref(0)
const currentReview = ref(null)
const loading = ref(true)
const loaded = ref(false)

const baseApiUrl = computed(() => props.apiUrl ?? import.meta.env.VITE_API_URL)

const closeReview = () => {
  currentReview.value = null
  setTimeout(nextReview, (Math.random() * 6000 | 0) + 6000)
}

const nextReview = () => {
  if (currentReviewIndex.value < totalReviews.value - 1) {
    currentReviewIndex.value++
    currentReview.value = reviews.value[currentReviewIndex.value]
  }
}

onMounted(async () => {
  loading.value = true
  const themeData = await getPopupSettings(props.apiKey, baseApiUrl.value)

  theme.value = themeData
  try {
    await getReviews(1, props.apiKey, baseApiUrl.value)
    loaded.value = true
  } finally {
    loading.value = false
  }
})

</script>