<template>
  <div class="field-container">
    <label>{{ $t('profile.name_label') }}</label>

    <div v-if="authStore.user?.is_google" class="value-locked">
      <p>{{ authStore.user.display_name }}</p>
    </div>

    <div v-else class="editable-wrapper">
      <button 
        v-if="!isEditing" 
        @click="startEditing" 
        class="value-btn"
        :aria-label="$t('profile.edit_name')"
      >
        {{ authStore.user?.display_name }}
      </button>

      <input
        v-else
        ref="inputRef"
        v-model="newName"
        @blur="handleUpdate"
        @keydown.enter="handleUpdate"
        @keydown.esc="cancelEditing"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const isEditing = ref(false)
const newName   = ref(authStore.user?.display_name || '')
const inputRef  = ref<HTMLInputElement | null>(null)

const startEditing = async () => {
  isEditing.value = true
  // On attend que l'input soit rendu pour lui donner le focus
  await nextTick()
  inputRef.value?.focus()
}

const cancelEditing = () => {
  isEditing.value = false
  newName.value = authStore.user?.display_name || ''
}

const handleUpdate = () => {
  if (!isEditing.value) return
  
  // Si le nom a changé et n'est pas vide
  if (newName.value && newName.value !== authStore.user?.display_name) {
    authStore.updateDisplayName(newName.value)
  }
  
  isEditing.value = false
}
</script>

<style scoped lang="scss">
div.field-container {
  margin-block: 1rem;
  display:block
}

div.editable-wrapper{
  display:inline;
}

.value-locked::after {
  content:" 🔒";
}

.value-locked {
  display:inline;
  & p {
    font-weight: 500;
    color: #666;
    display: inline;
    align-items: center;
    gap: 8px;
  }
}

label{
  font-weight:bold;
  display:inline;
}

.value-btn {
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
  text-align: left;
  font-size:1em;
  &:hover{
    color : blueviolet;
  }
}
</style>