<script setup>
import { ref } from 'vue'
import { useLoginModal } from '@/composables/useLoginModal'
import { useAuth } from '@/composables/useAuth'

const { isOpen, returnTo, close } = useLoginModal()
const { login } = useAuth()

const documento = ref('')
const carregando = ref(false)
const erro = ref('')

async function entrar() {
    const doc = documento.value.replace(/\D/g, '')
    if (doc.length !== 11 && doc.length !== 14) {
        erro.value = 'Informe um CPF (11 dígitos) ou CNPJ (14 dígitos) válido.'
        return
    }
    erro.value = ''
    carregando.value = true
    try {
        await login(doc, returnTo.value ?? '/portal/painel')
        // login() faz window.location.href — não retorna aqui
    } catch (e) {
        carregando.value = false
        erro.value = e?.data?.statusMessage ?? 'Não foi possível iniciar o login.'
    }
}

function onHide() {
    documento.value = ''
    erro.value = ''
    carregando.value = false
    close()
}
</script>

<template>
    <Dialog
        v-model:visible="isOpen"
        modal
        dismissable-mask
        :draggable="false"
        :closable="true"
        :show-header="false"
        :pt="{
            root: { class: 'w-full max-w-sm mx-4 rounded-2xl overflow-hidden shadow-2xl' },
            mask: { class: 'backdrop-blur-sm' },
        }"
        @hide="onHide"
    >
        <div class="bg-primary px-7 py-6 relative">
            <button
                class="absolute top-3 right-3 w-8 h-8 rounded-full flex items-center justify-center text-white/80 hover:text-white hover:bg-white/15 transition-colors"
                aria-label="Fechar"
                @click="onHide"
            >
                <i class="pi pi-times text-sm" aria-hidden="true" />
            </button>

            <div class="flex items-center gap-3 pr-10">
                <div class="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center" aria-hidden="true">
                    <i class="pi pi-lock text-white text-lg" />
                </div>
                <div>
                    <h2 class="text-white font-bold text-base leading-tight">Faça login para continuar</h2>
                    <p class="text-white/80 text-xs mt-0.5">Acesso seguro ao Portal do Contribuinte</p>
                </div>
            </div>
        </div>

        <div class="px-7 py-6 space-y-5 bg-white dark:bg-slate-800">
            <div>
                <label class="block text-sm font-medium text-slate-700 dark:text-slate-200 mb-1.5">CPF ou CNPJ</label>
                <DocumentoInput v-model="documento" @keyup.enter="entrar" />
                <p v-if="erro" class="mt-1.5 text-xs text-red-600 dark:text-red-400 flex items-center gap-1">
                    <i class="pi pi-exclamation-circle text-xs" aria-hidden="true" />
                    {{ erro }}
                </p>
            </div>

            <Button
                label="Continuar"
                icon="pi pi-arrow-right"
                icon-pos="right"
                class="w-full"
                size="large"
                :loading="carregando"
                :disabled="carregando"
                @click="entrar"
            />

            <div class="text-center space-y-2 pt-1">
                <NuxtLink
                    to="/primeiro-acesso"
                    class="block text-sm text-primary font-medium hover:underline"
                    @click="close"
                >
                    Esqueci minha senha
                </NuxtLink>
                <NuxtLink
                    to="/credenciamento"
                    class="block text-xs text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors"
                    @click="close"
                >
                    Ainda não cadastrado? <span class="text-primary font-semibold">Credenciar-se</span>
                </NuxtLink>
            </div>
        </div>
    </Dialog>
</template>
