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

const emit = defineEmits(["phone"]);
const phoneNum = ref("");
const initial = props.record && props.record[props.attr];
phoneNum.value = initial ? String(initial) : "";

watch(phoneNum, (newVal) => {
  // giữ lại CHỈ chữ số
  const digits = newVal.replaceAll(/\D/g, "");

  // sync lại UI nếu user nhập ký tự khác số
  if (digits !== newVal) {
    phoneNum.value = digits;
    return;
  }

  // emit string số hoặc null
  emit("phone", digits.length ? digits : null);
});

watch(
  () => props.record,
  (newRecord) => {
    const v = newRecord && newRecord[props.attr];
    phoneNum.value = v ? String(v) : "";
  },
);
</script>

<template>
  <div class="control has-icons-left">
    <input
      class="input"
      type="text"
      v-model="phoneNum"
      :placeholder="placeholder"
      :disabled="disabled"
      inputmode="numeric"
      maxlength="15"
      autocomplete="tel"
    />
    <span class="icon is-left">
      <Icon
        name="material-symbols:call-outline-rounded"
        :size="20"
      />
    </span>
  </div>
</template>
