<template>
  <label
    :class="[
      {'ui-toggle--checked': modelValue},
      {'ui-toggle--disabled': disabled},
      {'--left': left}
    ]"
    class="ui-toggle"
    aria-label="Toggle"
  >
    <input
      :checked="modelValue"
      :value="modelValue"
      class="ui-toggle__input _visually-hidden"
      type="checkbox"
      @change="$emit('update:modelValue', $event.target?.checked)"
    >
    <span
      v-if="$slots.default"
      class="ui-toggle__text"
    >
      <slot/>
    </span>
  </label>
</template>

<script setup lang="ts">
defineProps<{
  modelValue: boolean
  disabled?: boolean
  left?: boolean
}>();

defineEmits<{
  (e: 'update:modelValue', value?: boolean): void
}>();
</script>

<style lang="scss">
$control-width: 36px;
$control-height: 20px;
$padding: 2px;
$toggler-size: 16px;

.ui-toggle {
  display: flex;
  align-items: center;
  position: relative;
  user-select: none;

  @media (hover: hover) {
    cursor: pointer;

    &:is(:hover, :focus-visible) {
      opacity: 0.9;
    }
  }
}

.ui-toggle::before,
.ui-toggle::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  transform: translate(0, -50%);
}

.ui-toggle.--left::before {
  left: auto;
  right: 0;
}

/* Трек уехал к правому краю лейбла — ручку считаем от него же (без слота 100% = 0). */
.ui-toggle.--left::after {
  left: calc(100% - #{$control-width} + #{$padding});
}

.ui-toggle::before {
  width: $control-width;
  height: $control-height;
  border-radius: $radius-full;
  background-color: $toggle-bg;
}

.ui-toggle.ui-toggle--checked::before {
  background: $toggle-bg--active;
}

.ui-toggle::after {
  left: $padding;
  width: $toggler-size;
  height: $toggler-size;
  border-radius: 50%;
  background-color: $toggle-handle;
  transition: var(--transition) transform;
}

.ui-toggle.ui-toggle--checked::after {
  background-color: $toggle-handle--active;;
  transform: translate(calc(($control-width - $toggler-size) - $padding * 2), -50%);
}

.ui-toggle.ui-toggle--disabled {
  color: $toggle-text--disabled;
  pointer-events: none;
}

.ui-toggle.ui-toggle--disabled::after {
  background-color: $toggle-handle--disabled;
}

.ui-toggle__text {
  padding-left: calc($control-width + 8px);
}

.ui-toggle.--left .ui-toggle__text {
  padding-left: 0;
  padding-right: calc($control-width + 8px);
}
</style>
