<template>
    <div class="resend-verify-area pt-120 pb-120">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-6 col-md-8">
                    <div class="resend-form-wrap shadow-lg p-5 rounded bg-white">
                        <div class="header text-center mb-4">
                            <h2 class="mb-2">Doğrulama E-postası Gönder</h2>
                            <p class="text-muted">
                                E-posta adresinizi girin, doğrulama bağlantısını tekrar gönderelim.
                            </p>
                        </div>

                        <form @submit.prevent="handleResend">
                            <div class="mb-3">
                                <label for="email" class="form-label">E-posta Adresi</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                    <input type="email" class="form-control" id="email" v-model="email"
                                        placeholder="E-posta adresinizi girin" required>
                                </div>
                                <div v-if="error" class="text-danger small mt-1">{{ error }}</div>
                            </div>

                            <!-- Turnstile Component -->
                            <ClientOnly>
                                <div class="mb-4 d-flex justify-content-center">
                                    <NuxtTurnstile v-model="turnstileToken" />
                                </div>
                            </ClientOnly>

                            <button type="submit" class="btn btn-primary w-100 py-2" :disabled="loading">
                                <span v-if="loading" class="spinner-border spinner-border-sm me-2" role="status"
                                    aria-hidden="true"></span>
                                {{ loading ? 'Gönderiliyor...' : 'Gönder' }}
                            </button>
                        </form>

                        <div class="text-center mt-4">
                            <NuxtLink to="/auth/login" class="text-decoration-none">
                                <i class="fas fa-arrow-left me-1"></i> Giriş sayfasına dön
                            </NuxtLink>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { z } from 'zod'; // Import z directly if not exported from validations, or use from validations if available
import Swal from 'sweetalert2';

definePageMeta({
    middleware: 'guest-only',
    auth: { unauthenticatedOnly: true, navigateAuthenticatedTo: '/' }
});

const config = useRuntimeConfig();
const email = ref('');
const error = ref('');
const loading = ref(false);
const turnstileToken = ref('');

const emailSchema = z.string().email({ message: 'Geçerli bir e-posta adresi giriniz' });

const validate = () => {
    const result = emailSchema.safeParse(email.value);
    if (!result.success) {
        error.value = result.error.errors[0].message;
        return false;
    }
    error.value = '';
    return true;
};

const handleResend = async () => {
    if (!validate()) return;

    if (!turnstileToken.value) {
        Swal.fire({
            icon: 'warning',
            title: 'Güvenlik Kontrolü',
            text: 'Lütfen Turnstile güvenlik kontrolünü tamamlayın.',
            timer: 3000,
            toast: true,
            position: 'top-end',
            showConfirmButton: false
        });
        return;
    }

    loading.value = true;

    try {
        const apiUrl = config.public.NUXT_PUBLIC_API_BASE || 'http://127.0.0.1:8080';

        const response = await fetch(`${apiUrl}/api/v1/auth/resend-verification`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                email: email.value
            })
        });

        if (response.ok) {
            Swal.fire({
                icon: 'success',
                title: 'Başarılı!',
                text: 'Doğrulama bağlantısı e-posta adresinize gönderildi.',
                confirmButtonText: 'Tamam'
            });
            email.value = ''; // Reset form
            turnstileToken.value = ''; // Reset token ideally, but might need manual reset
        } else {
            const data = await response.json();
            Swal.fire({
                icon: 'error',
                title: 'Hata',
                text: data.message || data.error || 'İşlem başarısız oldu.',
            });
        }
    } catch (err) {
        console.error(err);
        Swal.fire({
            icon: 'error',
            title: 'Hata',
            text: 'Sunucu ile iletişim hatası.',
        });
    } finally {
        loading.value = false;
    }
};
</script>

<style scoped>
.resend-verify-area {
    background-color: #f8f9fa;
    min-height: 80vh;
    display: flex;
    align-items: center;
}

.resend-form-wrap {
    border-top: 5px solid #0d6efd;
}
</style>
