<template>
  <div class="toggle-field-row">
    <span class="toggle-field-label">{{ label }}</span>
    <button
      type="button"
      :class="['toggle-btn', { active: modelValue }]"
      :aria-pressed="modelValue"
      :disabled="disabled"
      @click="$emit('update:modelValue', !modelValue)"
    >
      <span class="toggle-knob" />
    </button>
    <button
      v-if="description"
      type="button"
      class="toggle-expand-btn"
      :aria-expanded="expanded"
      @click.stop="expanded = !expanded"
      :aria-label="expanded ? 'Collapse info' : 'Show info'"
    >
      <span class="toggle-chevron" :class="{ open: expanded }">›</span>
    </button>
  </div>
  <p v-if="description && expanded" class="toggle-desc-text">{{ description }}</p>
  <p v-if="error" class="toggle-error">{{ error }}</p>
</template>

<script setup lang="ts">
import { ref } from 'vue'

defineProps<{
  label: string
  modelValue: boolean
  disabled?: boolean
  description?: string
  error?: string
}>()

defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const expanded = ref(false)
</script>

<style scoped>
.toggle-field-row {
  display: flex;
  align-items: center;
  gap: 0.6rem;
}

.toggle-field-label {
  flex: 1;
  font-size: 0.95rem;
  color: var(--form-label, #444);
}

.toggle-expand-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--text-muted, #888);
  padding: 0 0.15rem;
  font-size: 1.2rem;
  line-height: 1;
  display: flex;
  align-items: center;
}

.toggle-chevron {
  display: inline-block;
  transition: transform 0.2s;
}

.toggle-chevron.open {
  transform: rotate(90deg);
}

.toggle-desc-text {
  font-size: 0.83rem;
  color: var(--text-muted, #666);
  margin: 0.3rem 0 0;
  line-height: 1.4;
}

.toggle-error {
  font-size: 0.9rem;
  color: var(--error, #e53e3e);
  margin: 0.2rem 0 0;
}

.toggle-btn {
  flex-shrink: 0;
  width: 44px;
  height: 24px;
  border-radius: 12px;
  border: none;
  background: var(--form-input-border, #ccc);
  cursor: pointer;
  position: relative;
  transition: background 0.2s;
  padding: 0;
}

.toggle-btn.active {
  background: var(--btn-primary, #4a90e2);
}

.toggle-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.toggle-knob {
  display: block;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: white;
  position: absolute;
  top: 3px;
  left: 3px;
  transition: left 0.2s;
  pointer-events: none;
}

.toggle-btn.active .toggle-knob {
  left: 23px;
}
</style>
