<template>
  <div
    class="bg-[#8cecff]/[0.24] py-[4px] rounded-[8px] my-[12px]_mt-[12px]_mb-[6px] min-w-[325px] shadow-[0_2px_4px_rgba(0,0,0,0.1)]">
    <div class="flex">
      <div v-for="(item, index) in dates" :key="index"
        class="flex-1 flex flex-col items-center justify-center py-[6px] rounded-[8px]"
        :class="{ 'bg-[#0ccd58]': index === activeIndex }" @click="selectDate(index)">
        <span :class="['text-[12px]', index === activeIndex ? 'text-[#fff]' : 'text-[#333]']">{{ item.label }}</span>
        <span :class="['text-[14px]', index === activeIndex ? 'text-[#fff]' : 'text-[#555] font-bold']">
          {{ item.date }}
        </span>
      </div>

      <!-- 日历按钮 -->
      <div
        class="flex-1 flex flex-col items-center justify-center py-[6px] rounded-[8px] bg-white rounded-r-[8px] -my-[4px]"
        @click="openCalendar">
        <img src="https://oss.nianxx.cn/mp/static/booking_calendar.png" class="w-[16px] h-[16px]" />
        <span class="text-[11px] text-[#666] mt-[2px]">{{ t("home.quickBooking.calendarTitle") }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits, computed } from "vue";
import { useI18n } from "vue-i18n";
import { emitter } from '@/utils/events.ts'

const emit = defineEmits(["update:date"]); // 声明事件
const { t } = useI18n();

const activeIndex = ref(2); // 默认今天
const relativeDayLabels = computed(() => [
  t("home.quickBooking.relativeDays.twoDaysAgo"),
  t("home.quickBooking.relativeDays.yesterday"),
  t("home.quickBooking.relativeDays.today"),
  t("home.quickBooking.relativeDays.tomorrow"),
  t("home.quickBooking.relativeDays.dayAfterTomorrow"),
]);

const dates = computed(() => {
  const today = new Date();
  const labels = relativeDayLabels.value;
  const list = [];
  for (let i = -2; i <= 2; i++) {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    const month = d.getMonth() + 1;
    const day = d.getDate();
    list.push({
      label: labels[i + 2],
      date: `${month}/${day}`,
      fullDate: `${d.getFullYear()}-${String(month).padStart(2, "0")}-${String(
        day
      ).padStart(2, "0")}`,
    });
  }
  return list;
});

const selectDate = (index) => {
  activeIndex.value = index;
  emit("update:date", dates.value[index]); // 传回父组件
};

const openCalendar = () => {
  emitter.emit("selectCalendarDate", (date) => {
    emit("update:date", { fullDate: date });
    emitter.off("selectCalendarDate");
  });
};

</script>
