<template>
  <q-card-section class="code-section no-padding q-mb-xl">
    <div class="q-mb-xs text-left text-text">
      <span class="fontmedium">
        {{ $t('auth.validation_code') }}
      </span>
    </div>

    <div
      class="code-boxes-wrapper"
      @click="focusCodeInput"
    >
      <div
        v-for="i in 6"
        :key="i"
        :class="{ 'code-box--active': code.length === i - 1 }"
        class="code-box"
      >
        <span
          v-if="code[i - 1]"
          class="text-text"
        >
          {{ code[i - 1] }}
        </span>

        <span
          v-else
          class="text-text-light"
        >
          {{ placeholder }}
        </span>
      </div>
    </div>

    <q-input
      ref="codeInputRef"
      v-model="code"
      class="code-hidden-input"
      hide-bottom-space
      inputmode="numeric"
      lazy-rules
      mask="######"
      no-error-icon
      :rules="[inputRules.required]"
    />
  </q-card-section>
</template>

<script setup>
import { ref } from 'vue';
import { useInputRules } from 'src/composables/useInputRules';

const code = defineModel('code', {
  required: true,
  type: String,
});

const { inputRules } = useInputRules();

const codeInputRef = ref(null);

const placeholder = 'x';

const focusCodeInput = () => {
  codeInputRef.value?.$el.querySelector('input')?.focus();
};
</script>

<style lang="scss" scoped>
.code-boxes-wrapper {
  display: flex;
  width: 100%;
  gap: clamp(4px, 2vw, 10px);
  justify-content: center;
  cursor: text;

  .code-box {
    flex: 0 1 44px;
    min-width: 0;
    max-width: 44px;
    aspect-ratio: 1;
    border: 2px solid #e4e4e4;
    background-color: #f9fafb;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    color: var(--q-text);
    transition: border-color 0.2s ease;

    &--active {
      border-color: var(--q-primary);
    }
  }
}

.code-section {
  width: 100%;
  min-width: 0;
  overflow: hidden;
}

.code-hidden-input {
  position: absolute;
  opacity: 0;
  pointer-events: none;
  width: 0;
  height: 0;
  overflow: hidden;
}
</style>
