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

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

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

        this.errorMessage = '';
        this.isSubmitting = true;

        try {
            const response = await fetch('/api/login_check', {
                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 || 'Anmeldung 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 : 'Anmeldung 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 '/';
    }
}));
