<template>
  <TextField
    v-model="model"
    :name="name"
    :label="label"
    :placeholder="placeholder"
    :error="error"
    :vibration="vibration"
    :disabled="disabled"
    :type="visible ? 'text' : 'password'"
  >
    <template #appendIcon>
      <button
        type="button"
        class="password-field__toggle"
        :aria-label="visible ? 'پنهان کردن رمز' : 'نمایش رمز'"
        @click="visible = !visible"
      >
        <SvgIcon :name="visible ? 'eye-slash' : 'eye'" :size="22" color="var(--color-thd-gray)" />
      </button>
    </template>
  </TextField>
</template>

<script setup>
import { ref, watch } from 'vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import TextField from '@/components/form/TextField.vue'

const props = defineProps({
  modelValue: { type: String, default: '' },
  name: { type: String, default: 'password' },
  label: { type: String, default: 'رمز عبور' },
  placeholder: { type: String, default: '' },
  error: { type: String, default: '' },
  vibration: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue'])

const visible = ref(false)
const model = ref(props.modelValue)

watch(model, (v) => emit('update:modelValue', v))
watch(
  () => props.modelValue,
  (v) => {
    if (v !== model.value) model.value = v
  }
)
</script>

<style lang="scss" scoped>
.password-field__toggle {
  border: none;
  background: transparent;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;

  &:hover {
    opacity: 0.7;
  }
}
</style>
