<script setup>
import { computed, ref, nextTick } from "vue";
import { useNamespace, useFormItem } from "@yh-ui/hooks";
import { useConfig } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { switchProps, switchEmits } from "./switch";
defineOptions({
  name: "YhSwitch"
});
const props = defineProps(switchProps);
const emit = defineEmits(switchEmits);
const ns = useNamespace("switch");
const { form, validate } = useFormItem();
const { themeStyle } = useComponentTheme(
  "switch",
  computed(() => props.themeOverrides)
);
const { globalSize } = useConfig();
const inputRef = ref();
const isChecked = computed(() => props.modelValue === props.activeValue);
const isDisabled = computed(() => {
  return props.disabled || form?.disabled === true;
});
const isInteractive = computed(() => {
  return !isDisabled.value && !props.loading;
});
const actualWidth = computed(() => {
  if (!props.width) return void 0;
  return typeof props.width === "number" ? `${props.width}px` : props.width;
});
const handleClick = () => {
  if (!isInteractive.value) return;
  handleChange();
};
const handleChange = async () => {
  const { beforeChange } = props;
  const newValue = isChecked.value ? props.inactiveValue : props.activeValue;
  if (!beforeChange) {
    updateValue(newValue);
    return;
  }
  try {
    const result = beforeChange();
    const shouldChange = result instanceof Promise ? await result : result;
    if (shouldChange !== false) {
      updateValue(newValue);
    }
  } catch {
  }
};
const updateValue = (val) => {
  emit("update:modelValue", val);
  emit("change", val);
  if (props.validateEvent) {
    validate("change");
  }
  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.checked = isChecked.value;
    }
  });
};
const focus = () => {
  inputRef.value?.focus();
};
const switchStyle = computed(() => ({
  ...themeStyle.value,
  "--yh-switch-width": actualWidth.value
}));
const switchClass = computed(() => [
  ns.b(),
  ns.m(props.size || globalSize.value || "default"),
  ns.is("disabled", isDisabled.value),
  ns.is("checked", isChecked.value),
  ns.is("loading", props.loading)
]);
const coreStyle = computed(() => {
  const style = {};
  if (actualWidth.value) {
    style.width = actualWidth.value;
  }
  return style;
});
defineExpose({
  focus,
  checked: isChecked
});
</script>

<template>
  <div
    :class="switchClass"
    :style="switchStyle"
    role="switch"
    :aria-checked="isChecked"
    :aria-disabled="isDisabled"
    @click="handleClick"
  >
    <input
      ref="inputRef"
      :class="ns.e('input')"
      type="checkbox"
      :id="props.id"
      :name="props.name"
      :disabled="!isInteractive"
      :checked="isChecked"
      :tabindex="props.tabindex"
      :aria-label="props.ariaLabel"
      @change.stop
      @keydown.enter="handleClick"
    />

    <!-- 左侧标签（非内嵌模式） -->
    <span
      v-if="!props.inlinePrompt && (props.inactiveIcon || props.inactiveText)"
      :class="[ns.e('label'), ns.e('label--left'), ns.is('active', !isChecked)]"
    >
      <slot name="inactive">
        <component v-if="props.inactiveIcon" :is="props.inactiveIcon" :class="ns.e('icon')" />
        <span v-else-if="props.inactiveText">{{ props.inactiveText }}</span>
      </slot>
    </span>

    <!-- 开关核心 -->
    <span :class="ns.e('core')" :style="coreStyle">
      <!-- 内嵌内容 -->
      <div v-if="props.inlinePrompt" :class="ns.e('inner')">
        <template v-if="isChecked">
          <slot name="active">
            <component v-if="props.activeIcon" :is="props.activeIcon" :class="ns.e('icon')" />
            <span v-else-if="props.activeText" :class="ns.e('inner-text')">
              {{ props.activeText.substring(0, 3) }}
            </span>
          </slot>
        </template>
        <template v-else>
          <slot name="inactive">
            <component v-if="props.inactiveIcon" :is="props.inactiveIcon" :class="ns.e('icon')" />
            <span v-else-if="props.inactiveText" :class="ns.e('inner-text')">
              {{ props.inactiveText.substring(0, 3) }}
            </span>
          </slot>
        </template>
      </div>

      <!-- 滑块（action） -->
      <div :class="ns.e('action')">
        <!-- Loading 图标 -->
        <svg
          v-if="props.loading"
          :class="ns.e('loading-icon')"
          viewBox="0 0 1024 1024"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            fill="currentColor"
            d="M512 64a32 32 0 0 1 32 32v192a32 32 0 0 1-64 0V96a32 32 0 0 1 32-32zm0 640a32 32 0 0 1 32 32v192a32 32 0 1 1-64 0V736a32 32 0 0 1 32-32zm448-192a32 32 0 0 1-32 32H736a32 32 0 1 1 0-64h192a32 32 0 0 1 32 32zm-640 0a32 32 0 0 1-32 32H96a32 32 0 0 1 0-64h192a32 32 0 0 1 32 32zM195.2 195.2a32 32 0 0 1 45.248 0L376.32 331.008a32 32 0 0 1-45.248 45.248L195.2 240.448a32 32 0 0 1 0-45.248zm452.544 452.544a32 32 0 0 1 45.248 0L828.8 783.552a32 32 0 0 1-45.248 45.248L647.744 692.992a32 32 0 0 1 0-45.248zM828.8 195.264a32 32 0 0 1 0 45.184L692.992 376.32a32 32 0 0 1-45.248-45.248l135.808-135.808a32 32 0 0 1 45.248 0zm-452.544 452.48a32 32 0 0 1 0 45.248L240.448 828.8a32 32 0 0 1-45.248-45.248l135.808-135.808a32 32 0 0 1 45.248 0z"
          />
        </svg>
        <!-- 自定义 action 图标 -->
        <template v-else>
          <slot v-if="isChecked" name="active-action">
            <component v-if="props.activeActionIcon" :is="props.activeActionIcon" />
          </slot>
          <slot v-else name="inactive-action">
            <component v-if="props.inactiveActionIcon" :is="props.inactiveActionIcon" />
          </slot>
        </template>
      </div>
    </span>

    <!-- 右侧标签（非内嵌模式） -->
    <span
      v-if="!props.inlinePrompt && (props.activeIcon || props.activeText)"
      :class="[ns.e('label'), ns.e('label--right'), ns.is('active', isChecked)]"
    >
      <slot name="active">
        <component v-if="props.activeIcon" :is="props.activeIcon" :class="ns.e('icon')" />
        <span v-else-if="props.activeText">{{ props.activeText }}</span>
      </slot>
    </span>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-switch {
  --yh-switch-on-color: var(--yh-color-primary);
  --yh-switch-off-color: var(--yh-border-color);
  --yh-switch-width: 40px;
  --yh-switch-height: 20px;
  --yh-switch-button-size: 16px;
  --yh-switch-font-size: var(--yh-font-size-base, 14px);
  display: inline-flex;
  align-items: center;
  position: relative;
  font-size: var(--yh-switch-font-size);
  line-height: var(--yh-switch-height);
  height: var(--yh-switch-height);
  vertical-align: middle;
  cursor: pointer;
}
.yh-switch__input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
  margin: 0;
}

.yh-switch__label {
  transition: var(--yh-transition-base);
  height: var(--yh-switch-height);
  display: inline-block;
  font-size: inherit;
  font-weight: 500;
  cursor: pointer;
  vertical-align: middle;
  color: var(--yh-text-color-primary);
  white-space: nowrap;
}
.yh-switch__label--left {
  margin-right: 10px;
}

.yh-switch__label--right {
  margin-left: 10px;
}

.yh-switch__label.is-active {
  color: var(--yh-color-primary);
}

.yh-switch__core {
  margin: 0;
  display: inline-block;
  position: relative;
  width: var(--yh-switch-width);
  height: var(--yh-switch-height);
  border: 1px solid var(--yh-switch-off-color);
  outline: none;
  border-radius: calc(var(--yh-switch-height) / 2);
  box-sizing: border-box;
  background: var(--yh-switch-off-color);
  cursor: pointer;
  transition: border-color var(--yh-duration-base), background-color var(--yh-duration-base);
  vertical-align: middle;
}
.yh-switch__inner {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 4px 0 20px;
  transition: all var(--yh-duration-base);
  box-sizing: border-box;
  overflow: hidden;
}
.yh-switch__inner-text {
  font-size: 12px;
  color: var(--yh-color-primary-text, #fff);
  white-space: nowrap;
  user-select: none;
}

.yh-switch__action {
  position: absolute;
  top: 1px;
  left: 1px;
  border-radius: var(--yh-radius-circle);
  transition: all var(--yh-duration-base);
  width: var(--yh-switch-button-size);
  height: var(--yh-switch-button-size);
  background-color: var(--yh-bg-color, #ffffff);
  display: flex;
  justify-content: center;
  align-items: center;
  color: var(--yh-switch-off-color);
  z-index: 1;
}
.yh-switch__loading-icon {
  width: calc(var(--yh-switch-button-size) * 0.75);
  height: calc(var(--yh-switch-button-size) * 0.75);
  animation: rotating 2s linear infinite;
}

.yh-switch.is-checked .yh-switch__core {
  border-color: var(--yh-switch-on-color);
  background-color: var(--yh-switch-on-color);
}
.yh-switch.is-checked .yh-switch__core .yh-switch__inner {
  padding: 0 20px 0 4px;
}
.yh-switch.is-checked .yh-switch__core .yh-switch__action {
  left: calc(100% - var(--yh-switch-button-size) - 1px);
  color: var(--yh-switch-on-color);
}

.yh-switch.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.yh-switch.is-disabled .yh-switch__core {
  cursor: not-allowed;
}

.yh-switch {
  /* 尺寸变体 */
}
.yh-switch--large {
  --yh-switch-width: 50px;
  --yh-switch-height: 24px;
  --yh-switch-button-size: 20px;
  --yh-switch-font-size: var(--yh-font-size-md, 16px);
}

.yh-switch--small {
  --yh-switch-width: 30px;
  --yh-switch-height: 16px;
  --yh-switch-button-size: 12px;
  --yh-switch-font-size: var(--yh-font-size-xs, 12px);
}
</style>
