<template>
  <div
    class="switch-container"
    :class="{ 'is-checked': modelValue, 'is-disabled': disabled }"
    @click="toggleSwitch"
    :style="{
      backgroundColor: modelValue ? activeColor : inactiveColor,
      width: width + 'px',
      height: height + 'px',
    }">
    <div
      class="switch-circle"
      :style="{
        transform: modelValue ? `translateX(${width - height}px)` : 'translateX(0)',
        width: height * 0.75 + 'px', // 球大小 = 0.75
        height: height * 0.75 + 'px',
        top: height * 0.125 + 'px', // 上下居中 ( (1-0.75)/2 = 0.125 )
        left: height * 0.125 + 'px', // 左右居中起始
      }" />
  </div>
</template>

<script setup>
  const props = defineProps({
    modelValue: Boolean,
    activeColor: {
      type: String,
      default: "#DF384C",
    },
    inactiveColor: {
      type: String,
      default: "#F5F5F5",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    width: {
      type: Number,
      default: 49,
    },
    height: {
      type: Number,
      default: 22,
    },
  });

  const emit = defineEmits(["update:modelValue"]);

  function toggleSwitch() {
    if (props.disabled) return;
    emit("update:modelValue", !props.modelValue);
  }
</script>

<style scoped>
  .switch-container {
    position: relative;
    border-radius: 50px;
    transition: background-color 0.3s;
  }

  .switch-circle {
    position: absolute;
    background-color: #ffffff;
    border-radius: 50%;
    transition: transform 0.3s;
  }

  .is-disabled {
    opacity: 0.4;
  }
</style>
