<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import { useNewsStore } from '@/stores/news'

dayjs.extend(utc)
dayjs.extend(timezone)

const tehranTime = ref('')
const store = useNewsStore()
let interval: ReturnType<typeof setInterval>

const updateClocks = () => {
  tehranTime.value = dayjs().tz('Asia/Tehran').format('HH:mm:ss')
}

onMounted(() => {
  updateClocks()
  interval = setInterval(updateClocks, 1000)
  store.fetchEverything({ q: 'iran' })
})

onUnmounted(() => {
  clearInterval(interval)
})
</script>

<template>
  <div class="container">
    <div class="clock">
      <div class="time">Tehran time: {{ tehranTime }}</div>
    </div>
  </div>

  <main>
    <p v-if="store.loading">Loading...</p>
    <p v-else-if="store.error">{{ store.error }}</p>
    <ul v-else>
      <li v-for="article in store.articles" :key="article.url">
        <a :href="article.url" target="_blank">{{ article.title }}</a>
      </li>
    </ul>
  </main>
</template>
