import { defineStore } from 'pinia'
import { ref } from 'vue'
import youtubeApi from '../api/youtube.api'

export const useYoutubeStore = defineStore('youtube', () => {
  const state = ref<'loading' | 'loaded' | 'error' | 'no-config'>('loading')
  const videoId = ref('')
  const title = ref('')
  const publishDate = ref('')
  const viewCount = ref('')
  const error = ref('')

  function formatDate(iso: string): string {
    const d = new Date(iso)
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
  }

  function formatViews(n: number): string {
    if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M views'
    if (n >= 1_000) return Math.round(n / 1_000) + 'K views'
    return n + ' views'
  }

  async function fetchLatest() {
    state.value = 'loading'
    try {
      const video = await youtubeApi.latestVideo()
      if (!video) {
        state.value = 'no-config'
        return
      }
      videoId.value = video.id
      title.value = video.title
      publishDate.value = formatDate(video.publishDate)
      viewCount.value = video.viewCount ? formatViews(Number(video.viewCount)) : ''
      state.value = 'loaded'
    } catch (err: any) {
      error.value = 'Error loading video: ' + err.message
      state.value = 'error'
    }
  }

  return { state, videoId, title, publishDate, viewCount, error, fetchLatest }
})
