<script setup lang="ts">
import { computed } from 'vue'
import { formatAsOf } from '../formatters/financial'

const props = defineProps<{
  asOf: string
  staleAfterMinutes: number
  now: string
  source?: string
  revision?: number
  refreshable?: boolean
}>()
const emit = defineEmits<{ refresh: [] }>()

const ageMinutes = computed(() => Math.max(0, (new Date(props.now).getTime() - new Date(props.asOf).getTime()) / 60_000))
const stale = computed(() => ageMinutes.value > props.staleAfterMinutes)
</script>

<template>
  <button v-if="props.refreshable" type="button" :aria-label="stale ? '데이터 지연, 새로 고침' : '데이터 최신, 새로 고침'" :data-status="stale ? 'stale' : 'fresh'" :title="props.source ? `출처: ${props.source}` : undefined" @click="emit('refresh')">
    <span aria-hidden="true">↻</span> {{ stale ? 'STALE' : 'FRESH' }} · {{ formatAsOf(props.asOf) }}<span v-if="props.revision !== undefined"> · rev {{ props.revision }}</span>
  </button>
  <span v-else :aria-label="stale ? '데이터 지연' : '데이터 최신'" :data-status="stale ? 'stale' : 'fresh'" :title="props.source ? `출처: ${props.source}` : undefined">
    {{ stale ? 'STALE' : 'FRESH' }} · {{ formatAsOf(props.asOf) }}<span v-if="props.revision !== undefined"> · rev {{ props.revision }}</span>
  </span>
</template>
