import { defineComponent, ref, watch, onMounted, onUnmounted, computed, createElementBlock, openBlock, normalizeClass, unref, createCommentVNode, createElementVNode, normalizeStyle, toDisplayString, Fragment, renderList } from 'vue';
import '../../../utils/index.mjs';
import { countdownEmits, countdownProps } from './countdown.mjs';
import { createNamespace } from '../../../utils/create-namespace.mjs';

"use strict";
const _hoisted_1 = {
  key: 0,
  viewBox: "0 0 24 24",
  fill: "currentColor"
};
var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{ name: "LlCountdown" },
  __name: "countdown",
  props: countdownProps,
  emits: countdownEmits,
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const bem = createNamespace("countdown");
    const UNIT_LABELS = {
      yyyy: "\u5E74",
      MM: "\u6708",
      dd: "\u65E5",
      HH: "\u65F6",
      mm: "\u5206",
      ss: "\u79D2"
    };
    const ALL_UNITS = ["yyyy", "MM", "dd", "HH", "mm", "ss"];
    const UNIT_SECONDS = {
      yyyy: 365 * 24 * 60 * 60,
      MM: 30 * 24 * 60 * 60,
      dd: 24 * 60 * 60,
      HH: 60 * 60,
      mm: 60,
      ss: 1
    };
    const targetTime = ref(0);
    const remainingMs = ref(0);
    const isFinish = ref(false);
    const isRunning = ref(false);
    let timer = null;
    let finishTimer = null;
    const confettiContainer = ref(null);
    const resolveTargetTime = () => {
      if (props.mode === "timer") {
        const v = props.value instanceof Date ? props.value : new Date(props.value);
        return v.getTime();
      }
      return Date.now() + Number(props.value);
    };
    const init = () => {
      if (finishTimer !== null) {
        clearTimeout(finishTimer);
        finishTimer = null;
      }
      targetTime.value = resolveTargetTime();
      remainingMs.value = Math.max(0, targetTime.value - Date.now());
      isFinish.value = false;
    };
    const tick = () => {
      const delta = targetTime.value - Date.now();
      if (delta <= 0) {
        remainingMs.value = 0;
        stopTimer();
        isFinish.value = true;
        if (finishTimer !== null) {
          clearTimeout(finishTimer);
        }
        finishTimer = setTimeout(() => {
          isFinish.value = false;
          finishTimer = null;
        }, 600);
        if (props.showConfetti) {
          createConfetti();
        }
        emits("finish");
      } else {
        remainingMs.value = delta;
      }
    };
    const stopTimer = () => {
      if (timer !== null) {
        clearInterval(timer);
        timer = null;
      }
      isRunning.value = false;
    };
    const createConfetti = () => {
      if (!confettiContainer.value) return;
      const container = confettiContainer.value;
      const { width, height } = container.getBoundingClientRect();
      if (width <= 0 || height <= 0) return;
      const confettiCount = 50;
      const colors = [
        "#b24a2e",
        "#d3a437",
        "#4d956f",
        "#537bd0",
        "#9a4faf",
        "#5fa0aa"
      ];
      for (let i = 0; i < confettiCount; i++) {
        const confetti = document.createElement("div");
        const size = Math.random() * 10 + 4;
        const duration = 2.8 + Math.random() * 0.4;
        const delay = Math.random() * 0.2;
        const centerX = width / 2;
        const centerY = height / 2;
        const angle = Math.random() * Math.PI * 2;
        const distance = Math.min(width, height) * (0.2 + Math.random() * 0.45);
        const rotation = Math.random() * 360;
        const rotateMid = rotation + (Math.random() > 0.5 ? 1 : -1) * (80 + Math.random() * 140);
        const rotateEnd = rotateMid + (Math.random() > 0.5 ? 1 : -1) * (180 + Math.random() * 240);
        const color = colors[Math.floor(Math.random() * colors.length)];
        const isStrip = Math.random() > 0.45;
        const pieceWidth = isStrip ? size * 1.6 : size;
        const pieceHeight = isStrip ? Math.max(3, size * 0.45) : size;
        const opacity = 0.88 + Math.random() * 0.1;
        const fromLeft = Math.random() > 0.5;
        const launchX = width * (fromLeft ? 0.18 : 0.82) + (Math.random() - 0.5) * width * 0.08;
        const launchY = height * 0.88 + (Math.random() - 0.5) * height * 0.06;
        const centerTargetX = centerX - pieceWidth / 2 + (Math.random() - 0.5) * width * 0.08;
        const centerTargetY = centerY - pieceHeight / 2 + (Math.random() - 0.5) * height * 0.08;
        const toCenterX = centerTargetX - launchX;
        const toCenterY = centerTargetY - launchY;
        const explodeX = Math.cos(angle) * distance;
        const explodeY = Math.sin(angle) * distance;
        const finalX = toCenterX + explodeX;
        const finalY = toCenterY + explodeY;
        confetti.style.cssText = `
      position: absolute;
      left: ${launchX}px;
      top: ${launchY}px;
      width: ${pieceWidth}px;
      height: ${pieceHeight}px;
      background-color: ${color};
      border-radius: ${isStrip ? pieceHeight / 2 : 50}%;
      pointer-events: none;
      --ll-confetti-center-x: ${toCenterX}px;
      --ll-confetti-center-y: ${toCenterY}px;
      --ll-confetti-final-x: ${finalX}px;
      --ll-confetti-final-y: ${finalY}px;
      --ll-confetti-rotate-start: ${rotation}deg;
      --ll-confetti-rotate-mid: ${rotateMid}deg;
      --ll-confetti-rotate-end: ${rotateEnd}deg;
      animation: confetti-fall ${duration}s linear ${delay}s forwards;
      transform: rotate(${rotation}deg);
      opacity: ${opacity};
      box-shadow: 0 0 ${Math.max(4, size / 1.9)}px ${color};
    `;
        container.appendChild(confetti);
        setTimeout(
          () => {
            confetti.remove();
          },
          (duration + delay) * 1e3
        );
      }
    };
    const startTimer = () => {
      stopTimer();
      tick();
      isRunning.value = true;
      const interval = props.precision > 0 ? Math.pow(10, 3 - props.precision) : 1e3;
      timer = setInterval(tick, interval);
    };
    const reset = () => {
      stopTimer();
      init();
    };
    const togglePlayPause = () => {
      if (isRunning.value) {
        pause();
      } else {
        start();
      }
    };
    const handleReset = () => {
      reset();
    };
    watch(
      () => props.active,
      (val) => {
        if (val) {
          if (props.mode === "timer") {
            targetTime.value = resolveTargetTime();
            remainingMs.value = Math.max(0, targetTime.value - Date.now());
          } else {
            targetTime.value = Date.now() + remainingMs.value;
          }
          startTimer();
        } else {
          stopTimer();
        }
      }
    );
    watch(
      () => props.value,
      () => {
        stopTimer();
        init();
      }
    );
    onMounted(() => {
      init();
      if (props.active) {
        startTimer();
      }
    });
    onUnmounted(() => {
      stopTimer();
      if (finishTimer !== null) {
        clearTimeout(finishTimer);
      }
    });
    const displayItems = computed(() => {
      const selected = new Set(props.units);
      const totalMs = remainingMs.value;
      const totalSeconds = Math.floor(totalMs / 1e3);
      const subMs = totalMs - totalSeconds * 1e3;
      let remaining = totalSeconds;
      const result = [];
      for (let i = 0; i < ALL_UNITS.length; i++) {
        const unit = ALL_UNITS[i];
        if (!selected.has(unit)) {
          continue;
        }
        const factor = UNIT_SECONDS[unit];
        const val = Math.floor(remaining / factor);
        remaining = remaining % factor;
        if (unit === "ss" && props.precision > 0) {
          const decimal = subMs / 1e3;
          const intPart = String(val).padStart(2, "0");
          const decPart = decimal.toFixed(props.precision).slice(1);
          result.push({
            key: unit,
            value: intPart + decPart,
            label: UNIT_LABELS[unit]
          });
        } else {
          const digits = 2;
          result.push({
            key: unit,
            value: String(val).padStart(digits, "0"),
            label: UNIT_LABELS[unit]
          });
        }
      }
      return result;
    });
    const start = () => {
      if (props.mode === "timer") {
        targetTime.value = resolveTargetTime();
        remainingMs.value = Math.max(0, targetTime.value - Date.now());
      } else {
        targetTime.value = Date.now() + remainingMs.value;
      }
      startTimer();
    };
    const pause = () => {
      stopTimer();
    };
    __expose({ reset, start, pause, isRunning });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(
        "div",
        {
          class: normalizeClass([unref(bem).b(), unref(bem).m(props.theme), isFinish.value ? unref(bem).is("finish") : ""])
        },
        [
          createCommentVNode(" \u793C\u82B1\u5BB9\u5668 "),
          createElementVNode(
            "div",
            {
              ref_key: "confettiContainer",
              ref: confettiContainer,
              class: normalizeClass(unref(bem).e("confetti-container"))
            },
            null,
            2
            /* CLASS */
          ),
          !!props.title ? (openBlock(), createElementBlock(
            "div",
            {
              key: 0,
              class: normalizeClass(unref(bem).e("title")),
              style: normalizeStyle(props.titleStyle)
            },
            toDisplayString(props.title),
            7
            /* TEXT, CLASS, STYLE */
          )) : createCommentVNode("v-if", true),
          createElementVNode(
            "div",
            {
              class: normalizeClass(unref(bem).e("content"))
            },
            [
              (openBlock(true), createElementBlock(
                Fragment,
                null,
                renderList(displayItems.value, (item, index) => {
                  return openBlock(), createElementBlock(
                    Fragment,
                    {
                      key: item.key
                    },
                    [
                      createElementVNode(
                        "div",
                        {
                          class: normalizeClass(unref(bem).e("item"))
                        },
                        [
                          createElementVNode(
                            "span",
                            {
                              class: normalizeClass(unref(bem).e("value"))
                            },
                            toDisplayString(item.value),
                            3
                            /* TEXT, CLASS */
                          ),
                          createElementVNode(
                            "span",
                            {
                              class: normalizeClass(unref(bem).e("label"))
                            },
                            toDisplayString(item.label),
                            3
                            /* TEXT, CLASS */
                          )
                        ],
                        2
                        /* CLASS */
                      ),
                      index < displayItems.value.length - 1 ? (openBlock(), createElementBlock(
                        "span",
                        {
                          key: 0,
                          class: normalizeClass(unref(bem).e("separator"))
                        },
                        " : ",
                        2
                        /* CLASS */
                      )) : createCommentVNode("v-if", true)
                    ],
                    64
                    /* STABLE_FRAGMENT */
                  );
                }),
                128
                /* KEYED_FRAGMENT */
              ))
            ],
            2
            /* CLASS */
          ),
          createCommentVNode(" \u63A7\u5236\u6309\u94AE "),
          props.control ? (openBlock(), createElementBlock(
            "div",
            {
              key: 1,
              class: normalizeClass(unref(bem).e("controls"))
            },
            [
              createElementVNode(
                "button",
                {
                  class: normalizeClass([unref(bem).e("btn"), isRunning.value ? unref(bem).em("btn", "pause") : unref(bem).em("btn", "play")]),
                  onClick: togglePlayPause
                },
                [
                  createCommentVNode(" \u64AD\u653E\u56FE\u6807 "),
                  !isRunning.value ? (openBlock(), createElementBlock("svg", _hoisted_1, [..._cache[0] || (_cache[0] = [
                    createElementVNode(
                      "path",
                      { d: "M8 5v14l11-7z" },
                      null,
                      -1
                      /* CACHED */
                    )
                  ])])) : (openBlock(), createElementBlock(
                    Fragment,
                    { key: 1 },
                    [
                      createCommentVNode(" \u6682\u505C\u56FE\u6807 "),
                      _cache[1] || (_cache[1] = createElementVNode(
                        "svg",
                        {
                          viewBox: "0 0 24 24",
                          fill: "currentColor"
                        },
                        [
                          createElementVNode("path", { d: "M6 19h4V5H6v14zm8-14v14h4V5h-4z" })
                        ],
                        -1
                        /* CACHED */
                      ))
                    ],
                    2112
                    /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
                  ))
                ],
                2
                /* CLASS */
              ),
              createElementVNode(
                "button",
                {
                  class: normalizeClass([unref(bem).e("btn"), unref(bem).em("btn", "reset")]),
                  onClick: handleReset
                },
                [
                  createCommentVNode(" \u91CD\u7F6E\u56FE\u6807 "),
                  _cache[2] || (_cache[2] = createElementVNode(
                    "svg",
                    {
                      viewBox: "0 0 24 24",
                      fill: "currentColor"
                    },
                    [
                      createElementVNode("path", { d: "M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z" })
                    ],
                    -1
                    /* CACHED */
                  ))
                ],
                2
                /* CLASS */
              )
            ],
            2
            /* CLASS */
          )) : createCommentVNode("v-if", true)
        ],
        2
        /* CLASS */
      );
    };
  }
});

export { _sfc_main as default };
//# sourceMappingURL=countdown.vue2.mjs.map
