<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/views/pages/auth/ResetPasswordPage.vue
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';

import Password from 'primevue/password';
import { useToast } from 'primevue/usetoast';

import { supabase } from '@/lib/supabase/client';

const toast = useToast();
const router = useRouter();

const newPassword = ref('');
const confirmPassword = ref('');
const loading = ref(false);
const done = ref(false);

// estado do link de recovery
const recoveryReady = ref(false);
const linkInvalid = ref(false);

function isStrongEnough(p) {
    return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(p || '');
}

const strengthOk = computed(() => isStrongEnough(newPassword.value));
const matchOk = computed(() => !!confirmPassword.value && newPassword.value === confirmPassword.value);

const canSubmit = computed(() => recoveryReady.value && strengthOk.value && matchOk.value && !loading.value);

// barra de força: 0–4
const strengthScore = computed(() => {
    const p = newPassword.value;
    if (!p) return 0;
    let s = 0;
    if (p.length >= 8) s++;
    if (/[A-Z]/.test(p)) s++;
    if (/[a-z]/.test(p)) s++;
    if (/\d/.test(p)) s++;
    return s;
});

const strengthLabel = computed(() => {
    if (!newPassword.value) return '';
    const labels = ['', 'Muito fraca', 'Fraca', 'Boa', 'Forte'];
    return labels[strengthScore.value] || 'Forte';
});

const strengthColor = computed(() => {
    const colors = ['', 'bg-red-500', 'bg-yellow-500', 'bg-blue-500', 'bg-emerald-500'];
    return colors[strengthScore.value] || 'bg-emerald-500';
});

let unsubscribeFn = null;

async function syncRecoveryState() {
    try {
        const { data, error } = await supabase.auth.getSession();
        if (error) throw error;
        if (data?.session) {
            recoveryReady.value = true;
        } else {
            linkInvalid.value = true;
        }
    } catch {
        linkInvalid.value = true;
    }
}

onMounted(async () => {
    await syncRecoveryState();

    const { data: listener } = supabase.auth.onAuthStateChange((event) => {
        if (event === 'PASSWORD_RECOVERY' || event === 'SIGNED_IN') {
            recoveryReady.value = true;
            linkInvalid.value = false;
        }
        if (event === 'SIGNED_OUT') {
            recoveryReady.value = false;
        }
    });

    unsubscribeFn = () => listener?.subscription?.unsubscribe();
});

onBeforeUnmount(() => {
    try {
        unsubscribeFn?.();
    } catch {}
});

function goLogin() {
    router.replace('/auth/login');
}

async function submit() {
    if (!recoveryReady.value) {
        toast.add({ severity: 'warn', summary: 'Link inválido', detail: 'Solicite um novo e-mail de redefinição.', life: 3500 });
        return;
    }
    if (!matchOk.value) {
        toast.add({ severity: 'warn', summary: 'Confirmação', detail: 'As senhas não conferem.', life: 3000 });
        return;
    }
    if (!strengthOk.value) {
        toast.add({ severity: 'warn', summary: 'Senha fraca', detail: 'Use no mínimo 8 caracteres com maiúscula, minúscula e número.', life: 4000 });
        return;
    }

    loading.value = true;
    try {
        const { error } = await supabase.auth.updateUser({ password: newPassword.value });
        if (error) throw error;

        done.value = true;
        try {
            await supabase.auth.signOut({ scope: 'global' });
        } catch {}
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Não foi possível redefinir a senha.', life: 4500 });
    } finally {
        loading.value = false;
    }
}
</script>

<template>
    <div class="min-h-screen w-full flex">
        <!-- ===== ESQUERDA: Painel de segurança ===== -->
        <div class="hidden lg:flex lg:w-1/2 relative overflow-hidden flex-col">
            <!-- Fundo gradiente -->
            <div class="absolute inset-0 bg-gradient-to-br from-indigo-600 via-violet-600 to-purple-700" />

            <!-- Grade decorativa -->
            <div class="absolute inset-0 opacity-[0.08]" style="background-image: linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px); background-size: 48px 48px" />

            <!-- Orbs -->
            <div class="absolute -top-40 -left-40 h-[32rem] w-[32rem] rounded-full bg-white/10 blur-3xl pointer-events-none" />
            <div class="absolute bottom-0 right-0 h-80 w-80 rounded-full bg-violet-300/20 blur-3xl pointer-events-none" />

            <div class="relative z-10 flex flex-col h-full p-10 xl:p-14">
                <!-- Brand -->
                <div class="flex items-center gap-3">
                    <div class="grid h-10 w-10 place-items-center rounded-xl bg-white/20 backdrop-blur-sm border border-white/20 shadow-lg">
                        <i class="pi pi-heart-fill text-white text-sm" />
                    </div>
                    <span class="text-white font-bold text-lg tracking-tight">Agência PSI</span>
                </div>

                <!-- Conteúdo central -->
                <div class="flex-1 flex flex-col justify-center space-y-8">
                    <div class="grid h-16 w-16 place-items-center rounded-2xl bg-white/15 backdrop-blur-sm border border-white/20 shadow-lg">
                        <i class="pi pi-lock text-white text-2xl" />
                    </div>

                    <div class="space-y-3">
                        <h2 class="text-3xl xl:text-4xl font-bold text-white leading-tight">Crie uma senha<br />que você não vai<br />esquecer.</h2>
                        <p class="text-base text-white/70 leading-relaxed max-w-sm">Escolha algo único e seguro. Uma boa senha protege seus dados e os de seus pacientes.</p>
                    </div>

                    <!-- Dicas -->
                    <ul class="space-y-3">
                        <li class="flex items-start gap-3 text-sm text-white/70">
                            <span class="mt-1 h-1.5 w-1.5 rounded-full bg-emerald-400 shrink-0" />
                            Mínimo de 8 caracteres
                        </li>
                        <li class="flex items-start gap-3 text-sm text-white/70">
                            <span class="mt-1 h-1.5 w-1.5 rounded-full bg-indigo-300 shrink-0" />
                            Combine letras maiúsculas, minúsculas e números
                        </li>
                        <li class="flex items-start gap-3 text-sm text-white/70">
                            <span class="mt-1 h-1.5 w-1.5 rounded-full bg-fuchsia-300 shrink-0" />
                            Não reutilize a mesma senha de outros serviços
                        </li>
                        <li class="flex items-start gap-3 text-sm text-white/70">
                            <span class="mt-1 h-1.5 w-1.5 rounded-full bg-amber-300 shrink-0" />
                            Exemplo seguro: <span class="font-semibold text-white/90">"Noite#Calma7"</span>
                        </li>
                    </ul>
                </div>

                <!-- Rodapé esquerdo -->
                <div class="flex items-center justify-between text-xs text-white/40">
                    <span>Agência PSI</span>
                    <span>Acesso seguro</span>
                </div>
            </div>
        </div>

        <!-- ===== DIREITA: Formulário ===== -->
        <div class="flex-1 lg:w-1/2 flex flex-col min-h-screen bg-[var(--surface-ground)] overflow-y-auto relative">
            <!-- Halos sutis -->
            <div class="pointer-events-none absolute inset-0">
                <div class="absolute top-10 right-10 h-64 w-64 rounded-full blur-3xl bg-indigo-400/5" />
                <div class="absolute bottom-10 left-10 h-56 w-56 rounded-full blur-3xl bg-violet-400/5" />
            </div>

            <div class="relative flex flex-col flex-1 justify-center px-6 py-10 sm:px-10 lg:px-12 xl:px-16 w-full max-w-lg mx-auto">
                <!-- Mobile: Brand -->
                <div class="flex lg:hidden items-center gap-2 mb-8">
                    <div class="grid h-8 w-8 place-items-center rounded-lg bg-indigo-500/10 border border-indigo-500/20">
                        <i class="pi pi-heart-fill text-indigo-500 text-xs" />
                    </div>
                    <span class="text-[var(--text-color)] font-bold text-base tracking-tight">Agência PSI</span>
                </div>

                <!-- ── Estado: SUCESSO ── -->
                <template v-if="done">
                    <div class="text-center space-y-6">
                        <div class="mx-auto grid h-20 w-20 place-items-center rounded-full bg-emerald-500/10 border border-emerald-500/20">
                            <i class="pi pi-check text-emerald-500 text-3xl" />
                        </div>
                        <div>
                            <h1 class="text-2xl font-bold text-[var(--text-color)]">Senha redefinida!</h1>
                            <p class="mt-2 text-sm text-[var(--text-color-secondary)] leading-relaxed">Sua senha foi atualizada com sucesso.<br />Faça login novamente para continuar.</p>
                        </div>
                        <Button label="Ir para o login" icon="pi pi-sign-in" class="w-full" @click="goLogin" />
                    </div>
                </template>

                <!-- ── Estado: LINK INVÁLIDO ── -->
                <template v-else-if="linkInvalid">
                    <div class="text-center space-y-6">
                        <div class="mx-auto grid h-20 w-20 place-items-center rounded-full bg-red-500/10 border border-red-500/20">
                            <i class="pi pi-times text-red-500 text-3xl" />
                        </div>
                        <div>
                            <h1 class="text-2xl font-bold text-[var(--text-color)]">Link inválido</h1>
                            <p class="mt-2 text-sm text-[var(--text-color-secondary)] leading-relaxed">Este link expirou ou já foi utilizado.<br />Solicite um novo e-mail de redefinição.</p>
                        </div>
                        <Button label="Voltar para o login" icon="pi pi-arrow-left" severity="secondary" outlined class="w-full" @click="goLogin" />
                    </div>
                </template>

                <!-- ── Estado: FORMULÁRIO ── -->
                <template v-else>
                    <!-- Cabeçalho -->
                    <div class="mb-7">
                        <h1 class="text-3xl font-bold text-[var(--text-color)] leading-tight">Redefinir senha</h1>
                        <p class="mt-1.5 text-sm text-[var(--text-color-secondary)]">Escolha uma senha nova e segura para sua conta.</p>
                    </div>

                    <form class="space-y-5" @submit.prevent="submit">
                        <!-- Nova senha -->
                        <div>
                            <label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">Nova senha</label>
                            <Password v-model="newPassword" placeholder="Mínimo 8 caracteres" toggleMask :feedback="false" class="w-full" inputClass="w-full" :disabled="loading" />

                            <!-- Barra de força -->
                            <div v-if="newPassword" class="mt-2 space-y-1">
                                <div class="flex gap-1">
                                    <div v-for="i in 4" :key="i" class="h-1 flex-1 rounded-full transition-all duration-300" :class="i <= strengthScore ? strengthColor : 'bg-[var(--surface-border)]'" />
                                </div>
                                <span
                                    class="text-xs"
                                    :class="{
                                        'text-red-500': strengthScore === 1,
                                        'text-yellow-500': strengthScore === 2,
                                        'text-blue-500': strengthScore === 3,
                                        'text-emerald-500': strengthScore === 4
                                    }"
                                >
                                    {{ strengthLabel }}
                                </span>
                            </div>
                            <p v-else class="mt-1.5 text-xs text-[var(--text-color-secondary)]">Dica: combine letras, números e símbolos.</p>
                        </div>

                        <!-- Confirmar senha -->
                        <div>
                            <label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">Confirmar senha</label>
                            <Password v-model="confirmPassword" placeholder="Repita a nova senha" toggleMask :feedback="false" class="w-full" inputClass="w-full" :disabled="loading" />
                            <div v-if="confirmPassword" class="mt-1.5 flex items-center gap-1.5 text-xs" :class="matchOk ? 'text-emerald-500' : 'text-yellow-500'">
                                <i :class="matchOk ? 'pi pi-check' : 'pi pi-times'" />
                                {{ matchOk ? 'As senhas conferem.' : 'As senhas não conferem.' }}
                            </div>
                        </div>

                        <!-- Botão -->
                        <Button type="submit" label="Atualizar senha" icon="pi pi-check" class="w-full" :loading="loading" :disabled="!canSubmit" />
                    </form>

                    <!-- Rodapé -->
                    <div class="mt-8 pt-6 border-t border-[var(--surface-border)]">
                        <button type="button" class="flex items-center gap-2 text-sm text-[var(--text-color-secondary)] hover:text-[var(--text-color)] transition-colors" @click="goLogin">
                            <i class="pi pi-arrow-left text-xs" />
                            Voltar para o login
                        </button>

                        <p class="mt-4 text-xs text-[var(--text-color-secondary)] leading-relaxed">Se você não solicitou essa redefinição, ignore o e-mail e certifique-se de que sua conta está segura.</p>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>
