<template>
    <HeaderPublic />
    <div class="cadastro-container d-flex align-items-center justify-content-center min-vh-100 p-3">
        <div class="cadastro-card p-5 shadow-lg rounded-4 bg-white">
            
            <div class="text-center mb-4">
                <img src="@/assets/CtrlCash-blue.png" alt="CtrlCash Logo" width="150" class="mb-3">
                <h2 class="fw-bold text-primary-dark">Abra Sua Conta</h2>
                <p class="text-secondary-dark">Preencha os campos para iniciar seu controle financeiro.</p>
            </div>

            <form @submit.prevent="handleCadastro">
                <div class="mb-3">
                    <label for="nome" class="form-label fw-medium text-primary-dark">Nome Completo</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-person-fill"></i></span>
                        <input type="text" class="form-control" id="nome" v-model="cadastroForm.name" required placeholder="Seu nome">
                    </div>
                </div>

                <div class="mb-3">
                    <label for="email" class="form-label fw-medium text-primary-dark">E-mail</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-envelope-fill"></i></span>
                        <input type="email" class="form-control" id="email" v-model="cadastroForm.email" required placeholder="seu.email@exemplo.com">
                    </div>
                </div>
                
                <div class="mb-3">
                    <label for="password" class="form-label fw-medium text-primary-dark">Crie Sua Senha</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
                        <input type="password" class="form-control" id="password" v-model="cadastroForm.password" required placeholder="Mínimo 6 caracteres">
                    </div>
                </div>
                
                <div class="mb-4">
                    <label for="confirmPassword" class="form-label fw-medium text-primary-dark">Confirmar Senha</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
                        <input type="password" class="form-control" id="confirmPassword" v-model="confirmPassword" required placeholder="Repita a senha">
                    </div>
                </div>

                <!-- Mensagens -->
                <div v-if="error" class="alert alert-danger">
                    {{ error }}
                </div>
                <div v-if="success" class="alert alert-success">
                    {{ success }}
                </div>
                
                <button type="submit" class="btn btn-primary-feature w-100 fw-bold py-2 shadow-sm" :disabled="loading">
                    <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                    {{ loading ? 'Cadastrando...' : 'Criar Minha Conta CtrlCash' }}
                </button>
            </form>

        </div>
    </div>
</template>

<script setup>
    import { ref } from 'vue';
    import { useRouter } from 'vue-router';
    import HeaderPublic from '@/components/HeaderPublic.vue';

    const router = useRouter();
    const loading = ref(false);
    const error = ref('');
    const success = ref('');

    const cadastroForm = ref({
        name: '',
        email: '',
        password: ''
    });
    const confirmPassword = ref('');

    const handleCadastro = async () => {
        loading.value = true;
        error.value = '';
        success.value = '';

        // Validações
        if (cadastroForm.value.password !== confirmPassword.value) {
            error.value = "As senhas não coincidem!";
            loading.value = false;
            return;
        }

        if (cadastroForm.value.password.length < 6) {
            error.value = "A senha deve ter pelo menos 6 caracteres";
            loading.value = false;
            return;
        }

        try {
            const response = await fetch('/api/auth/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(cadastroForm.value)
            });

            const data = await response.json();

            if (response.ok) {
                success.value = 'Cadastro realizado com sucesso! Redirecionando...';
                
                // Auto-login após cadastro
                setTimeout(() => {
                    localStorage.setItem('user', JSON.stringify(data.user));
                    localStorage.setItem('isAuthenticated', 'true');
                    router.push('/dashboard');
                }, 2000);
            } else {
                error.value = data.error || 'Erro ao cadastrar';
            }
        } catch (err) {
            console.error('Erro:', err);
            error.value = 'Erro de conexão com o servidor';
        } finally {
            loading.value = false;
        }
    };
</script>

<style scoped>
    .text-primary-dark { color: #1A3B5E !important; }
    .text-secondary-dark { color: #6c757d !important; }
    
    .cadastro-container { background-color: #F8F9FA; }
    .cadastro-card { max-width: 450px; width: 100%; }
    
    .btn-primary-feature {
        background-color: #1A3B5E;
        border-color: #1A3B5E;
        color: white;
        transition: background-color 0.2s;
    }
    .btn-primary-feature:hover:not(:disabled) {
        background-color: #29517b;
        border-color: #29517b;
    }
    .btn-primary-feature:disabled {
        opacity: 0.6;
    }

    .form-control:focus {
        border-color: #1A3B5E;
        box-shadow: 0 0 0 0.25rem rgba(26, 59, 94, 0.25);
    }
    .input-group-text {
        background-color: #e9ecef;
        border-right: none;
        color: #1A3B5E;
    }
</style>