import { defineStore } from 'pinia'
import { ref } from 'vue'
import eventApi from '../api/event.api'
import { formatDateTime } from '../lib/dateFormat'
import type { Event } from '../lib/interfaces/event.interface'

type EventWithText = Event & { dateISO: string; dateText: string }
type FollowingEvent = Event & { dateText: string }

export const useEventStore = defineStore('event', () => {
  const nextEvent = ref<EventWithText | null>(null)
  const followingEvents = ref<FollowingEvent[]>([])
  const countdownText = ref('-- : -- : -- : --')

  let countdownInterval: ReturnType<typeof setInterval> | null = null

  function startCountdown(targetISO: string) {
    const targetDate = new Date(targetISO).getTime()

    function update() {
      const distance = targetDate - Date.now()
      if (distance < 0) {
        countdownText.value = 'LIVE NOW!'
        if (countdownInterval) clearInterval(countdownInterval)
        return
      }
      const d = String(Math.floor(distance / 86400000)).padStart(2, '0')
      const h = String(Math.floor((distance % 86400000) / 3600000)).padStart(2, '0')
      const m = String(Math.floor((distance % 3600000) / 60000)).padStart(2, '0')
      const s = String(Math.floor((distance % 60000) / 1000)).padStart(2, '0')
      countdownText.value = `${d}d ${h}h ${m}m ${s}s`
    }

    update()
    countdownInterval = setInterval(update, 1000)
  }

  async function fetch() {
    try {
      const events = await eventApi.index()
      if (events.length > 0) {
        const first = events[0]
        const firstDate = new Date(first.date)
        nextEvent.value = { name: first.name, date: first.date, dateISO: firstDate.toISOString(), dateText: formatDateTime(firstDate) }
        followingEvents.value = events.slice(1).map(e => ({ name: e.name, date: e.date, dateText: formatDateTime(new Date(e.date)) }))
        startCountdown(firstDate.toISOString())
      }
    } catch (e) {
      console.error('Failed to load events:', e)
    }
  }

  function cleanup() {
    if (countdownInterval) {
      clearInterval(countdownInterval)
      countdownInterval = null
    }
  }

  return { nextEvent, followingEvents, countdownText, fetch, cleanup }
})
