<template>
  <span class="vm-date-text">{{ text }}</span>
</template>

<script setup lang="ts">
import { computed } from 'vue'
defineOptions({ name: 'vm-date-text' })

const props = withDefaults(
  defineProps<{
    modelValue?: string | number | Date | null
    format?: string
  }>(),
  { format: 'YYYY-MM-DD HH:mm:ss' },
)

function pad(n: number) {
  return String(n).padStart(2, '0')
}

const text = computed(() => {
  if (props.modelValue == null || props.modelValue === '') return '—'
  const d = new Date(props.modelValue)
  if (Number.isNaN(d.getTime())) return String(props.modelValue)
  const map: Record<string, string> = {
    YYYY: String(d.getFullYear()),
    MM: pad(d.getMonth() + 1),
    DD: pad(d.getDate()),
    HH: pad(d.getHours()),
    mm: pad(d.getMinutes()),
    ss: pad(d.getSeconds()),
  }
  return props.format.replace(/YYYY|MM|DD|HH|mm|ss/g, (k) => map[k] || k)
})
</script>

<style lang="scss" scoped>
.vm-date-text {
  font-size: 13px;
  color: var(--foreground);
}
</style>
