<template>
  <div class="sport-date-filter-container">
    <div class="filter-left">
      <el-segmented
          v-model="activeDate"
          :options="displayOptions"
          class="dark-segmented"
          @change="handleSegmentedChange"
      >
        <template #default="{ item }">
          <div class="segment-item">
            {{ item.label }}
          </div>
        </template>
      </el-segmented>
    </div>

    <div class="filter-right">
      <el-date-picker
          v-model="activeDate"
          type="date"
          :placeholder="t('选择日期')"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
          class="dark-date-picker"
          :clearable="false"
          :teleported="false"
          @change="handlePickerChange"
      >
        <template #prefix>
          <el-icon class="calendar-icon"><Calendar /></el-icon>
        </template>
      </el-date-picker>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Calendar } from '@element-plus/icons-vue';

const { t } = useI18n();

const props = defineProps({
  // 赛事状态: 0=未开始(未来), 1=进行中(仅今天), 2=已完场(过去)
  state: {
    type: Number,
    required: true
  },
  // 快捷选项展示的天数 (预留配置口，默认 7 天)
  daysCount: {
    type: Number,
    default: 7
  }
});

// 新增 update:date 用于 Vue3 的 v-model 双向静默绑定
const emit = defineEmits(['change', 'update:date']);

// 当前选中的日期 (YYYY-MM-DD)
const activeDate = ref('');

// 辅助方法：获取 YYYY-MM-DD 格式
const getLocalYYYYMMDD = (date) => {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
};

// 辅助方法：生成显示的文本 (例如: 03/29 周日)
const getDisplayLabel = (dateObj, isToday = false) => {
  if (isToday) return t('今天');
  const m = String(dateObj.getMonth() + 1).padStart(2, '0');
  const d = String(dateObj.getDate()).padStart(2, '0');
  const weeks = [t('周日'), t('周一'), t('周二'), t('周三'), t('周四'), t('周五'), t('周六')];
  const w = weeks[dateObj.getDay()];
  return `${m}/${d} ${w}`;
};

// 基础的 N 天快捷选项
const baseOptions = computed(() => {
  const options = [];
  const today = new Date();

  // 方向：未开始(0)往后加，已完场(2)往前减
  const direction = props.state === 2 ? -1 : 1;

  // 如果是进行中(1)，通常只能看今天的盘
  const count = props.state === 1 ? 1 : props.daysCount;

  for (let i = 0; i < count; i++) {
    const targetDate = new Date(today);
    targetDate.setDate(today.getDate() + (i * direction));

    options.push({
      label: getDisplayLabel(targetDate, i === 0),
      value: getLocalYYYYMMDD(targetDate)
    });
  }
  return options;
});

// 最终展示的选项（融合了 DatePicker 选出的不在快捷列表里的自定义日期）
const displayOptions = computed(() => {
  const options = [...baseOptions.value];
  if (activeDate.value) {
    const exists = options.some(opt => opt.value === activeDate.value);
    // 如果用户通过日期选择器选了一个不在前 N 天里的日子，把它追加到末尾以便高亮显示
    if (!exists) {
      // 兼容 iOS
      const safeDateStr = activeDate.value.replace(/-/g, '/');
      const customDate = new Date(safeDateStr);
      options.push({
        label: getDisplayLabel(customDate, false),
        value: activeDate.value
      });
    }
  }
  return options;
});

// DatePicker 的禁用逻辑
const disabledDate = (time) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 抹平时间差，只比对日期

  if (props.state === 0) {
    // 状态0 (未开始)：只能选今天及以后，禁用今天之前
    return time.getTime() < today.getTime();
  } else if (props.state === 2) {
    // 状态2 (已完场)：只能选今天及以前，禁用今天之后
    return time.getTime() > today.getTime() + 24 * 3600 * 1000 - 1;
  } else {
    // 状态1 (进行中)：只能看今天
    return time.getTime() < today.getTime() || time.getTime() > today.getTime() + 24 * 3600 * 1000 - 1;
  }
};

// 核心修改点：增加 isPassive 标记
const initToday = (isPassive = false) => {
  const todayStr = getLocalYYYYMMDD(new Date());
  activeDate.value = todayStr;
  
  // 偷偷把值同步给父组件的 currentDate，但不叫醒父组件去请求接口
  emit('update:date', todayStr);
  
  // 只有用户主动操作时，才触发 change 让父组件去查接口
  if (!isPassive) {
    emit('change', todayStr);
  }
};

// 监听状态改变：从"未开始"切到"已完场"等，被动重置时间为今天
watch(() => props.state, () => {
  initToday(true); // 传入 true，表示被动触发，不要发 change
});

// 初始化
onMounted(() => {
  initToday(true); // 首次加载，父组件自己会查接口，这里也静默同步即可
});

// 事件触发
const handleSegmentedChange = (val) => {
  emit('update:date', val);
  emit('change', val);
};

const handlePickerChange = (val) => {
  emit('update:date', val);
  emit('change', val);
};
</script>

<style scoped lang="scss">
$main-color: #f8b932;
$card-bg: var(--el-bg-color-overlay);
$border-color: var(--el-border-color-lighter);

.sport-date-filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: $card-bg;
  border-radius: 6px;
  padding: 6px 12px;
  // margin-bottom: 8px; /* 与下方的赛事列表留出间隙 */
  border: 1px solid $border-color;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);

  /* 容器查询适配：如果屏幕太小，可允许换行 */
  flex-wrap: wrap;
  gap: 8px;

  .filter-left {
    flex: 1;
    min-width: 300px;
    overflow-x: auto;

    /* 隐藏滚动条让它看起来更干净 */
    &::-webkit-scrollbar { display: none; }
    scrollbar-width: none;
  }

  .filter-right {
    flex-shrink: 0;
  }
}

/* 深度定制分段控制器以匹配你的暗黑电竞风 */
.dark-segmented {
  --el-border-radius-base: 6px;
  background-color: var(--el-fill-color-darker);
  padding: 2px;

  :deep(.el-segmented__item) {
    min-width: 80px;
    padding: 0 12px;
    color: var(--el-text-color-regular);
    transition: all 0.3s;
    font-size: 13px;
    font-weight: 500;

    &:hover {
      color: $main-color;
    }
  }

  :deep(.el-segmented__item.is-selected) {
    background-color: var(--el-color-primary-light-9);
    color: #fff;
    font-weight: bold;
    box-shadow: 0 1px 4px rgba(0,0,0,0.2);
    border-radius: 4px;
  }

  .segment-item {
    line-height: 28px;
    white-space: nowrap;
  }
}

/* 深度定制右侧 DatePicker */
.dark-date-picker {
  width: 140px !important;

  :deep(.el-input__wrapper) {
    background-color: var(--el-fill-color-darker);
    box-shadow: none !important;
    border: 1px solid var(--el-border-color-darker);
    height: 32px;
    border-radius: 6px;
    padding: 0 8px;
    transition: all 0.3s;

    &:hover, &.is-focus {
      border-color: $main-color;
    }
  }

  :deep(.el-input__inner) {
    color: $main-color;
    font-weight: bold;
    font-size: 13px;
    font-family: DIN, monospace;
    text-align: center;
  }

  .calendar-icon {
    color: var(--el-text-color-secondary);
  }
}
</style>
