<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from "vue";
import { useNamespace, useLocale } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import {
  countdownProps,
  countdownEmits,
  createFormatContext,
  formatCountdown,
  isTargetTimestamp
} from "./countdown";
defineOptions({
  name: "YhCountdown"
});
const props = defineProps(countdownProps);
const emit = defineEmits(countdownEmits);
const ns = useNamespace("countdown");
const { t } = useLocale();
const { themeStyle } = useComponentTheme(
  "countdown",
  computed(() => props.themeOverrides)
);
const status = ref("pending");
const remain = ref(getInitialRemain());
const startTime = ref(0);
const pausedRemain = ref(remain.value);
const hasWarned = ref(false);
const rafId = ref(null);
const prevUpdateTime = ref(0);
const formatContext = computed(() => createFormatContext(remain.value));
const displayText = computed(() => formatCountdown(props.format, formatContext.value));
const shouldShowDays = computed(() => {
  if (props.showDays === true) return true;
  if (props.showDays === false) return false;
  return formatContext.value.days > 0;
});
const isWarning = computed(() => {
  if (!props.warningThreshold) return false;
  return remain.value > 0 && remain.value <= props.warningThreshold;
});
const isFinished = computed(() => status.value === "finished");
const rootClass = computed(() => [
  ns.b(),
  ns.is("finished", isFinished.value),
  ns.is("warning", isWarning.value),
  ns.is("paused", status.value === "paused"),
  ns.is("flip", props.flipAnimation),
  ns.is("monospace", props.useMonospaceFont)
]);
const valueStyleComputed = computed(() => {
  if (typeof props.valueStyle === "string") {
    return props.valueStyle;
  }
  return props.valueStyle;
});
function getInitialRemain() {
  const serverOffset = props.serverTimeOffset ?? 0;
  const now = Date.now() + serverOffset;
  const value = props.value;
  if (isTargetTimestamp(value)) {
    let target = value instanceof Date ? value.getTime() : value;
    if (props.timezoneOffset !== void 0 && props.timezoneOffset !== null) {
      const localOffset = -(/* @__PURE__ */ new Date()).getTimezoneOffset();
      const tzAdjustment = (props.timezoneOffset - localOffset) * 60 * 1e3;
      target = target - tzAdjustment;
    }
    return Math.max(0, target - now);
  }
  return Math.max(0, value instanceof Date ? value.getTime() : value);
}
function tick() {
  if (status.value !== "running") return;
  const now = performance.now();
  const elapsed = now - startTime.value;
  const newRemain = Math.max(0, pausedRemain.value - elapsed);
  const shouldUpdate = now - prevUpdateTime.value >= props.interval || newRemain === 0 || Math.floor(remain.value / props.precision) !== Math.floor(newRemain / props.precision);
  if (shouldUpdate) {
    remain.value = newRemain;
    prevUpdateTime.value = now;
    emit("change", formatContext.value);
    if (props.warningThreshold && !hasWarned.value && isWarning.value) {
      hasWarned.value = true;
      emit("warning", formatContext.value);
    }
  }
  if (newRemain <= 0) {
    finish();
    return;
  }
  rafId.value = requestAnimationFrame(tick);
}
function start() {
  if (status.value === "running") return;
  if (status.value === "pending" || status.value === "finished") {
    pausedRemain.value = getInitialRemain();
    hasWarned.value = false;
  }
  remain.value = pausedRemain.value;
  if (remain.value <= 0) {
    finish();
    return;
  }
  startTime.value = performance.now();
  prevUpdateTime.value = startTime.value;
  status.value = "running";
  emit("start");
  emit("statusChange", "running");
  rafId.value = requestAnimationFrame(tick);
}
function pause() {
  if (status.value !== "running") return;
  if (rafId.value) {
    cancelAnimationFrame(rafId.value);
    rafId.value = null;
  }
  const elapsed = performance.now() - startTime.value;
  pausedRemain.value = Math.max(0, pausedRemain.value - elapsed);
  remain.value = pausedRemain.value;
  status.value = "paused";
  emit("pause");
  emit("statusChange", "paused");
}
function resume() {
  if (status.value !== "paused") return;
  startTime.value = performance.now();
  prevUpdateTime.value = startTime.value;
  status.value = "running";
  emit("resume");
  emit("statusChange", "running");
  rafId.value = requestAnimationFrame(tick);
}
function reset() {
  if (rafId.value) {
    cancelAnimationFrame(rafId.value);
    rafId.value = null;
  }
  pausedRemain.value = getInitialRemain();
  remain.value = pausedRemain.value;
  hasWarned.value = false;
  status.value = "pending";
  emit("reset");
  emit("statusChange", "pending");
  if (props.autoStart) {
    start();
  }
}
function finish() {
  if (rafId.value) {
    cancelAnimationFrame(rafId.value);
    rafId.value = null;
  }
  remain.value = 0;
  status.value = "finished";
  emit("finish");
  emit("statusChange", "finished");
}
function getRemain() {
  return remain.value;
}
function getStatus() {
  return status.value;
}
watch(
  () => props.value,
  () => {
    reset();
  }
);
onMounted(() => {
  if (props.autoStart && remain.value > 0) {
    start();
  } else if (remain.value <= 0) {
    status.value = "finished";
    emit("finish");
    emit("statusChange", "finished");
  }
});
onUnmounted(() => {
  if (rafId.value) {
    cancelAnimationFrame(rafId.value);
    rafId.value = null;
  }
});
defineExpose({
  start,
  pause,
  resume,
  reset,
  getRemain,
  getStatus
});
const digits = computed(() => {
  const ctx = formatContext.value;
  const result = [];
  if (shouldShowDays.value) {
    result.push({ key: "days", value: ctx.DD, label: props.labels?.days || t("countdown.days") });
  }
  if (props.showHours) {
    result.push({ key: "hours", value: ctx.HH, label: props.labels?.hours || t("countdown.hours") });
  }
  if (props.showMinutes) {
    result.push({
      key: "minutes",
      value: ctx.mm,
      label: props.labels?.minutes || t("countdown.minutes")
    });
  }
  if (props.showSeconds) {
    result.push({
      key: "seconds",
      value: ctx.ss,
      label: props.labels?.seconds || t("countdown.seconds")
    });
  }
  if (props.showMilliseconds) {
    result.push({
      key: "milliseconds",
      value: ctx.SSS,
      label: props.labels?.milliseconds || t("countdown.milliseconds")
    });
  }
  return result;
});
</script>

<template>
  <div v-if="keepAliveOnFinish || status !== 'finished'" :class="rootClass" :style="themeStyle">
    <!-- 标题 -->
    <slot name="prefix">
      <span v-if="title" :class="ns.e('title')">{{ title }}</span>
    </slot>

    <!-- 主体内容 -->
    <div :class="ns.e('content')">
      <!-- 默认插槽：完全自定义渲染 -->
      <slot
        :current="formatContext"
        :remaining="remain"
        :formatted="displayText"
        :status="status"
        :is-warning="isWarning"
        :is-finished="isFinished"
      >
        <!-- 翻牌模式 -->
        <template v-if="flipAnimation">
          <template v-for="(digit, idx) in digits" :key="digit.key">
            <!-- 分隔符 -->
            <span v-if="idx > 0" :class="ns.e('separator')">
              <slot name="separator">{{ separator }}</slot>
            </span>

            <div :class="ns.e('block')">
              <div :class="ns.e('flip-card')">
                <slot :name="`${digit.key}-cell`" :value="digit.value">
                  <span :class="ns.e('value')" :style="valueStyleComputed">
                    {{ digit.value }}
                  </span>
                </slot>
              </div>
              <span v-if="digit.label" :class="ns.e('label')">{{ digit.label }}</span>
            </div>
          </template>
        </template>

        <!-- 常规模式 -->
        <template v-else>
          <span :class="ns.e('value')" :style="valueStyleComputed">
            <slot name="value" :text="displayText">{{ displayText }}</slot>
          </span>
        </template>
      </slot>
    </div>

    <!-- 后缀 -->
    <slot name="suffix">
      <span v-if="suffix" :class="ns.e('suffix')">{{ suffix }}</span>
    </slot>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-countdown {
  --yh-countdown-font-size: 24px;
  --yh-countdown-value-color: var(--yh-text-color-primary);
  --yh-countdown-label-color: var(--yh-text-color-secondary);
  --yh-countdown-separator-color: var(--yh-text-color-placeholder);
  --yh-countdown-warning-color: var(--yh-color-danger);
  --yh-countdown-finished-color: var(--yh-color-success);
  --yh-countdown-bg: transparent;
  --yh-countdown-block-bg: var(--yh-fill-color-light);
  --yh-countdown-block-shadow: var(--yh-shadow-sm);
  --yh-countdown-block-radius: var(--yh-radius-md);
  --yh-countdown-block-padding-y: 12px;
  --yh-countdown-block-padding-x: 16px;
  --yh-countdown-block-padding: var(--yh-countdown-block-padding-y)
    var(--yh-countdown-block-padding-x);
  --yh-countdown-gap: 8px;
  --yh-countdown-font-family: var(--yh-font-family);
  --yh-countdown-monospace-font:
    'JetBrains Mono', 'SF Mono', 'Roboto Mono', 'Fira Code', 'Consolas', monospace;
  display: inline-flex;
  align-items: center;
  gap: var(--yh-countdown-gap);
  font-family: var(--yh-countdown-font-family);
  background: var(--yh-countdown-bg);
  line-height: 1;
}
.yh-countdown.is-monospace .yh-countdown__value {
  font-family: var(--yh-countdown-monospace-font);
  font-variant-numeric: tabular-nums;
  letter-spacing: -0.02em;
}

.yh-countdown__title {
  font-size: 14px;
  font-weight: 500;
  color: var(--yh-countdown-label-color);
  margin-right: 4px;
  white-space: nowrap;
}

.yh-countdown__content {
  display: inline-flex;
  align-items: center;
  gap: var(--yh-countdown-gap);
}

.yh-countdown__value {
  font-size: var(--yh-countdown-font-size);
  font-weight: 700;
  color: var(--yh-countdown-value-color);
  transition: color 0.3s ease, transform 0.3s ease;
  line-height: 1;
}

.yh-countdown__separator {
  font-size: calc(var(--yh-countdown-font-size) * 0.8);
  font-weight: 600;
  color: var(--yh-countdown-separator-color);
  margin: 0 2px;
  opacity: 0.7;
  animation: countdown-blink 1s infinite;
  transition: margin-top 0.3s ease;
}

.yh-countdown__block {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.yh-countdown__flip-card {
  background: var(--yh-countdown-block-bg);
  border-radius: var(--yh-countdown-block-radius);
  padding: var(--yh-countdown-block-padding);
  box-shadow: var(--yh-countdown-block-shadow);
  position: relative;
  overflow: hidden;
  min-width: 52px;
  text-align: center;
}
.yh-countdown__flip-card::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, rgba(0, 0, 0, 0.06) 20%, rgba(0, 0, 0, 0.06) 80%, transparent 100%);
  pointer-events: none;
}

.yh-countdown__label {
  font-size: 11px;
  font-weight: 500;
  color: var(--yh-countdown-label-color);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  white-space: nowrap;
}

.yh-countdown__suffix {
  font-size: 14px;
  font-weight: 500;
  color: var(--yh-countdown-label-color);
  margin-left: 4px;
  white-space: nowrap;
}

.yh-countdown.is-flip .yh-countdown__content {
  align-items: flex-start;
}

.yh-countdown.is-flip .yh-countdown__separator {
  margin-top: calc(0.15 * var(--yh-countdown-font-size) + var(--yh-countdown-block-padding-y));
}

.yh-countdown.is-flip .yh-countdown__flip-card {
  perspective: 400px;
}
.yh-countdown.is-flip .yh-countdown__flip-card .yh-countdown__value {
  display: block;
  transform-style: preserve-3d;
  backface-visibility: hidden;
}

.yh-countdown.is-warning .yh-countdown__value {
  color: var(--yh-countdown-warning-color);
  animation: countdown-pulse 0.5s infinite alternate;
}
.yh-countdown.is-warning .yh-countdown__flip-card {
  box-shadow: var(--yh-countdown-block-shadow), 0 0 0 2px var(--yh-color-danger-light-5);
}

.yh-countdown.is-finished .yh-countdown__value {
  color: var(--yh-countdown-finished-color);
}
.yh-countdown.is-finished .yh-countdown__separator {
  animation: none;
  opacity: 0.5;
}

.yh-countdown.is-paused .yh-countdown__value {
  opacity: 0.6;
}
.yh-countdown.is-paused .yh-countdown__separator {
  animation: none;
}
.yh-countdown.is-paused .yh-countdown__flip-card {
  opacity: 0.7;
}

@keyframes countdown-blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.3;
  }
}
@keyframes countdown-pulse {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(1.02);
  }
}
@keyframes countdown-flip-down {
  0% {
    transform: rotateX(0deg);
  }
  100% {
    transform: rotateX(-90deg);
  }
}
@keyframes countdown-flip-up {
  0% {
    transform: rotateX(90deg);
  }
  100% {
    transform: rotateX(0deg);
  }
}
</style>
