<script setup>
const props = defineProps({
  record: Object,
  attr: String,
  disabled: Boolean,
  placeholder: {
    type: String,
    default: "",
  },
});

const { $copy, $empty, $errEmail } = useNuxtApp();
const emit = defineEmits(["email"]);
const email = ref(props.record?.[props.attr] ? $copy(props.record[props.attr]) : undefined);
const error = ref(false);

watch(
  () => props.record?.[props.attr],
  (v) => {
    email.value = v ? $copy(v) : undefined;
  },
);

function doCheck() {
  if ($empty(email.value)) {
    email.value = undefined;
    error.value = false;
    return emit("email", null);
  }
  error.value = !!$errEmail(email.value);
  emit("email", email.value);
}
</script>

<template>
  <div class="control has-icons-left">
    <input
      :class="['input', error && 'is-danger', disabled && 'has-text-black']"
      type="text"
      v-model="email"
      @keyup="doCheck"
      :placeholder="placeholder"
      :disabled="disabled"
    />
    <span class="icon is-left">
      <Icon
        name="material-symbols:mail-outline-rounded"
        :size="20"
      />
    </span>
  </div>
</template>
