<template>
  <h1>Compte</h1>
  <ul>
    <li>
      <p v-if="user.name">Nom : {{ user.name }}</p>
    </li>
    <li :class="{ 'is-editing': isEditingEmail }">
      <input
        v-if="isEditingEmail"
        @input="updateEmail"
        type="email"
        v-model="email"
        id="username"
        placeholder="mail@exemple.com"
        autocomplete="username"
        class="w-full rounded-md border border-grey-200 px-16 py-12"
        :class="{ invalid: emailRegex.test(email) }"
        required
      />
      <p v-else>Email : {{ user.email }}</p>
      <button v-if="isEditingEmail" class="btn | w-full">enregistrer</button>
      <button v-else @click="isEditingEmail = true" class="btn | w-full">
        modifier
      </button>
    </li>
    <li :class="{ 'is-editing': isEditingEmail }">
      <input
        @input="updatePassword"
        type="password"
        v-model="password"
        id="password"
        class="w-full rounded-md border border-grey-200 px-16 py-12"
        :class="{ invalid: password.length < 8 }"
        required
      />
    </li>
    <li>
      <p>Client : {{ user.client.name }}</p>
    </li>
    <li v-if="user.hasOwnProperty('projects')">
      <p>Nombre de projets : {{ Object.values(user.projects).length }}</p>
    </li>
  </ul>
</template>
<script setup>
import { storeToRefs } from 'pinia';
import { useUserStore } from '../stores/user';
import { ref, watch } from 'vue';

const { user } = storeToRefs(useUserStore());

const email = ref('');
const isEditingEmail = ref(false);
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

const password = ref('');

function updateEmail(event) {
  email.value = event.target.value;
}
</script>

<style scoped>
input.invalid:focus-visible {
  outline: 2px solid #ef8d8d;
}
</style>
