import Alpine from 'alpinejs';
import { storeTokens } from './game';

Alpine.data('register', () => ({
    email: '',
    password: '',
    passwordConfirm: '',
    isSubmitting: false,
    errorMessage: '',

    async submit() {
        if (this.isSubmitting) return;

        this.errorMessage = '';

        if (this.password.length < 8) {
            this.errorMessage = 'Das Passwort muss mindestens 8 Zeichen haben.';
            return;
        }

        if (this.password !== this.passwordConfirm) {
            this.errorMessage = 'Die Passwörter stimmen nicht überein.';
            return;
        }

        this.isSubmitting = true;

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

            const payload = await response.json().catch(() => ({}));
            if (!response.ok) {
                throw new Error(payload?.message || 'Registrierung fehlgeschlagen.');
            }

            const token = String(payload?.token || '');
            if (token === '') {
                throw new Error('Server hat kein Token geliefert.');
            }

            storeTokens(token, payload?.refresh_token || '');
            window.location.href = this.getRedirectTarget();
        } catch (error) {
            this.errorMessage = error instanceof Error ? error.message : 'Registrierung fehlgeschlagen.';
        } finally {
            this.isSubmitting = false;
        }
    },

    getRedirectTarget() {
        const nextField = document.getElementById('auth-next');
        const next = String(nextField?.value || '').trim();

        if (next !== '' && next.startsWith('/')) {
            return next;
        }

        return '/';
    }
}));
