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

    <div v-if="authStore.user?.is_google" class="value-locked">
      <p>{{ authStore.user.email }}</p>
    </div>
    
    <div v-else class="editable-wrapper">
      <button
        v-if="!email_toggle"
        @click="toggle_to_input"
      >
        {{ authStore.user?.email }}
      </button>
      <input v-else
        ref="emailInput"
        v-model="email"
        @blur="handleUpdate"
        @keydown.enter="handleUpdate"
        @keydown.esc  ="cancelEditing"
      />
    </div>
  </div>

  <UiModale @close="closeEmailModal" :modalActive="emailModalActive">
    <div class="modal-content">
      <h1>{{ $t('emailUpdate.modale.title') }}</h1>
        <p>{{ $t('emailUpdate.modale.text1') }}</p>
        <p>{{ $t('emailUpdate.modale.text2') }}</p>
        <div class="modale-btns">
          <ButtonBase ref=ConfirmBtn @click="confirmEmailChange">{{ $t('emailUpdate.modale.confBtn') }}</ButtonBase>
          <ButtonBase class="btn" @click="closeEmailModal">{{ $t('emailUpdate.modale.cancelBtn') }}</ButtonBase>
      </div>
    </div>
  </UiModale>
</template>

<script setup lang="ts">
const {locale} = useI18n() 
const authStore = useAuthStore()
const email_toggle = ref(false)
const email = ref(authStore.user?.email)
const emailModalActive = ref(false)
const emailInput  = ref<HTMLInputElement | null>(null)
const ConfirmBtn  = ref<HTMLInputElement | null>(null)
const toggle_to_input = async ()=>{
  email_toggle.value = true  
  // On attend que Vue passe email_toggle à true et affiche l'input dans le DOM
  await nextTick()
  
  // Maintenant l'input existe, on peut lui donner le focus
  emailInput.value?.focus()
}

const handleUpdate = async ()=>{
  if (email.value !== authStore.user?.email){
    emailModalActive.value = true
    await nextTick()
    ConfirmBtn.value?.focus()
  }
  email_toggle.value = false
}

const cancelEditing = () => {
  email_toggle.value = false
  email.value = authStore.user?.email || ''
}

//* Fonctions de taitement email */
const closeEmailModal = () =>{
  emailModalActive.value = false
  email.value = authStore.user?.email
}

const confirmEmailChange = () => {
  emailModalActive.value = false
  if (email.value){
    authStore.emailChange(email.value, locale.value)
  }
}

</script>

<style 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;
}

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