<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
    modelValue: { type: String, default: '' },
    disabled: { type: Boolean, default: false },
})
const emit = defineEmits(['update:modelValue'])

const wrapper = ref(null)
const input = ref(props.modelValue)

watch(() => props.modelValue, (v) => { input.value = v })

const apenasDigitos = computed(() => input.value.replace(/\D/g, ''))
const isCnpj = computed(() => apenasDigitos.value.length > 11)

const valorFormatado = computed(() => {
    const d = apenasDigitos.value
    if (d.length <= 11) {
        return d
            .replace(/(\d{3})(\d)/, '$1.$2')
            .replace(/(\d{3})(\d)/, '$1.$2')
            .replace(/(\d{3})(\d{1,2})$/, '$1-$2')
    }
    return d
        .replace(/(\d{2})(\d)/, '$1.$2')
        .replace(/(\d{3})(\d)/, '$1.$2')
        .replace(/(\d{3})(\d)/, '$1/$2')
        .replace(/(\d{4})(\d{1,2})$/, '$1-$2')
})

const placeholder = computed(() => isCnpj.value ? '00.000.000/0000-00' : '000.000.000-00')

function onInput(e) {
    const raw = e.target.value.replace(/\D/g, '').slice(0, 14)
    input.value = raw
    emit('update:modelValue', raw)
}

function focus() {
    wrapper.value?.querySelector('input')?.focus()
}

defineExpose({ focus })
</script>

<template>
    <div ref="wrapper" class="relative">
        <InputText
            :value="valorFormatado"
            :placeholder="placeholder"
            :disabled="disabled"
            inputmode="numeric"
            autocomplete="username"
            class="w-full text-lg tracking-wide"
            size="large"
            aria-label="CPF ou CNPJ"
            aria-required="true"
            @input="onInput"
        />
        <span
            v-if="disabled"
            class="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-slate-400 font-medium flex items-center gap-1 pointer-events-none"
        >
            <i class="pi pi-lock text-[10px]" aria-hidden="true" />
            {{ isCnpj ? 'CNPJ' : 'CPF' }}
        </span>
        <span
            v-else-if="apenasDigitos.length > 0"
            class="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-slate-400 font-medium pointer-events-none"
        >
            {{ isCnpj ? 'CNPJ' : 'CPF' }}
        </span>
    </div>
</template>
