<template>
    <span class="reply-timeout">{{ t('已{time}未响应', { time: formattedTime }) }}</span>
</template>

<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';

const props = defineProps<{
    initialSeconds: number;
}>();

const { t } = useI18n();

const seconds = ref(0);
let timer: number | undefined;

const normalizeSeconds = (value: number) => {
    const nextValue = Number(value);
    if (!Number.isFinite(nextValue)) {
        return 0;
    }

    return Math.max(0, Math.floor(nextValue));
};

const stopTimer = () => {
    if (timer !== undefined) {
        window.clearInterval(timer);
        timer = undefined;
    }
};

const startTimer = () => {
    stopTimer();
    seconds.value = normalizeSeconds(props.initialSeconds);

    if (seconds.value <= 0) {
        return;
    }

    timer = window.setInterval(() => {
        seconds.value += 1;
    }, 1000);
};

const formatTime = (totalSeconds: number) => {
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const remainSeconds = totalSeconds % 60;

    if (hours > 0) {
        return `${hours}:${minutes < 10 ? '0' : ''}${minutes}:${remainSeconds < 10 ? '0' : ''}${remainSeconds}`;
    }

    return `${minutes}:${remainSeconds < 10 ? '0' : ''}${remainSeconds}`;
};

const formattedTime = computed(() => formatTime(seconds.value));

watch(
    () => props.initialSeconds,
    () => {
        startTimer();
    },
    { immediate: true },
);

onUnmounted(() => {
    stopTimer();
});
</script>

<style scoped>
.reply-timeout {
    color: #ff4d4f;
    font-size: 12px;
    line-height: 18px;
    white-space: nowrap;
    flex-shrink: 0;
}
</style>