<template>
  <div :class="['input-wrap', { 'input-wrap--error': !!error, 'input-wrap--filled': !!modelValue }]">
    <input
      :id="inputId"
      v-bind="$attrs"
      :value="modelValue"
      :type="type"
      class="input-wrap__field"
      placeholder=" "
      @input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
      @blur="emit('blur', $event)"
    />
    <label :for="inputId" class="input-wrap__label">{{ label }}</label>
    <p v-if="error" :id="`${inputId}-error`" class="input-wrap__error" role="alert">
      {{ error }}
    </p>
  </div>
</template>

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

const props = withDefaults(defineProps<{
  modelValue?: string
  label: string
  type?: string
  error?: string
  id?: string
}>(), {
  modelValue: '',
  type: 'text',
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
  blur: [event: FocusEvent]
}>()

const inputId = computed(() => props.id ?? `input-${Math.random().toString(36).slice(2)}`)
</script>

<style scoped lang="scss">
.input-wrap {
  position: relative;
  width: 100%;

  &__field {
    width: 100%;
    min-height: 56px;
    padding: 22px var(--space-4) 8px;
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    background: var(--color-surface);
    color: var(--color-text);
    font-family: var(--font-family);
    font-size: var(--text-base);
    transition: border-color var(--duration-fast);

    &::placeholder {
      color: transparent;
    }

    &:focus {
      outline: none;
      border-color: var(--color-primary);
    }

    &:not(:placeholder-shown) ~ .input-wrap__label,
    &:focus ~ .input-wrap__label {
      top: 8px;
      font-size: var(--text-xs);
      color: var(--color-primary);
      transform: none;
    }
  }

  &__label {
    position: absolute;
    left: var(--space-4);
    top: 50%;
    transform: translateY(-50%);
    color: var(--color-text-muted);
    font-size: var(--text-base);
    pointer-events: none;
    transition: top var(--duration-fast), font-size var(--duration-fast), color var(--duration-fast), transform var(--duration-fast);
  }

  &--error &__field {
    border-color: var(--color-destructive);
  }

  &__error {
    margin-top: var(--space-1);
    padding-left: var(--space-4);
    font-size: var(--text-sm);
    color: var(--color-destructive);
  }
}
</style>
