<template>
  <div class="flex items-start gap-2 pt-0.5 mb-2" :class="props.showReverse ? 'flex-row-reverse' : 'flex-row'">
    <span class="text-xs text-[#4E5969]">{{ props.msg?.messageRole === MessageRole.AI ? 'NIANXX' : '我' }}</span>
    <span class="text-xs text-[#86909C]">{{ formattedTime }}</span>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { ChatMessage, MessageRole } from '../model/ChatModel'

interface Props {
  msg?: ChatMessage
  showReverse?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showReverse: false
})

const formattedTime = computed(() => {
  const tsRaw = props.msg?.timestamp
  if (tsRaw == null) return ''
  let ts = Number(tsRaw)
  if (isNaN(ts)) return ''

  const pad = (n: number) => String(n).padStart(2, '0')

  // Heuristic:
  // - If ts < 1e9, treat as a duration in seconds and convert to dd-hh-mm (legacy)
  // - If ts looks like an epoch (seconds or ms) format to YYYY年MM月DD日 HH:mm:ss
  if (ts < 1e9) {
    const totalSeconds = Math.floor(ts)
    const days = Math.floor(totalSeconds / 86400)
    const hours = Math.floor((totalSeconds % 86400) / 3600)
    const minutes = Math.floor((totalSeconds % 3600) / 60)
    return `${String(days).padStart(2, '0')}-${pad(hours)}-${pad(minutes)}`
  }

  // epoch handling: convert seconds -> ms when appropriate
  if (ts < 1e12) ts = ts * 1000
  const d = new Date(ts)
  if (isNaN(d.getTime())) return ''
  const Y = d.getFullYear()
  const M = pad(d.getMonth() + 1)
  const D = pad(d.getDate())
  const h = pad(d.getHours())
  const m = pad(d.getMinutes())
  const s = pad(d.getSeconds())

  // If the timestamp is the same calendar day as today, show only time HH:mm:ss
  const now = new Date()
  const sameDay = now.getFullYear() === d.getFullYear()
    && now.getMonth() === d.getMonth()
    && now.getDate() === d.getDate()

  if (sameDay) {
    return `${h}:${m}:${s}`
  }

  // otherwise show YYYY-MM-DD HH:mm:ss
  return `${Y}-${M}-${D} ${h}:${m}:${s}`
})

</script>