<template>
  <div class="clock-container">
    <div class="time">{{ currentTime }}</div>
    <div v-if="showDate" class="date">{{ currentDate }}</div>
  </div>
</template>

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

const props = defineProps<{
  showDate?: boolean;
  showSeconds?: boolean;
  use24Hour?: boolean;
}>();

const currentTime = ref('');
const currentDate = ref('');
let timerId: number;

const showDate = computed(() => props.showDate !== false);
const showSeconds = computed(() => props.showSeconds === true);
const use24Hour = computed(() => props.use24Hour !== false);

const buildTimeOptions = (): Intl.DateTimeFormatOptions => {
  const options: Intl.DateTimeFormatOptions = {
    hour: '2-digit',
    minute: '2-digit',
    hour12: !use24Hour.value,
  };
  if (showSeconds.value) {
    options.second = '2-digit';
  }
  return options;
};

const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', buildTimeOptions());
  if (showDate.value) {
    currentDate.value = new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      weekday: 'long',
    }).format(now);
  } else {
    currentDate.value = '';
  }
};

onMounted(() => {
  updateTime();
  timerId = window.setInterval(updateTime, 1000);
});

onUnmounted(() => {
  clearInterval(timerId);
});

watch([showDate, showSeconds, use24Hour], () => {
  updateTime();
});
</script>

<style lang="scss" scoped>

@import '@/styles/tokens.scss';

.clock-container {
  text-align: center;
  margin-bottom: var(--clock-margin-bottom);
  color: $color-text-primary;
  text-shadow: $shadow-md;
}

.time {
  font-size: var(--clock-time-font-size);
  font-weight: 600;
  letter-spacing: var(--clock-letter-spacing);
}

.date {
  font-size: var(--clock-date-font-size);
  color: $color-text-secondary;
  margin-top: var(--clock-date-margin-top);
}
</style>
