<div class="authredirect-login-page" x-data="loginForm()" x-init="init()">
    <form @submit.prevent="submit" class="form">
        <div class="form-group">
            <label for="email">Email</label>
            <input x-model="email" id="email" name="username" type="email" class="input" required />
            <template x-if="errors.email">
                <p class="text-red-600 text-sm" x-text="errors.email"></p>
            </template>
        </div>
        <div class="form-group mt-4">
            <label for="password">Password</label>
            <input x-model="password" id="password" name="password" type="password" class="input" required />
            <template x-if="errors.password">
                <p class="text-red-600 text-sm" x-text="errors.password"></p>
            </template>
        </div>
        <div class="mt-4">
            <button type="submit" class="btn btn-primary btn-size-lg justify-center w-full">Log In</button>
        </div>
        <template x-if="errors.general">
            <p class="text-red-600 text-sm mt-2" x-text="errors.general"></p>
        </template>
    </form>

    <script>
        function loginForm() {
            return {
                email: '',
                password: '',
                errors: {},
                init() {
                    this.errors = {};
                },
                async submit() {
                    this.errors = {};
                    if (!this.email.includes('@')) {
                        this.errors.email = 'Invalid email format';
                        return;
                    }
                    if (!this.password) {
                        this.errors.password = 'Password is required';
                        return;
                    }
                    try {
                        const response = await fetch('/authredirect/ajax/login', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                username: this.email,
                                password: this.password
                            })
                        });
                        const result = await response.json();
                        if (result.success) {
                            window.location.href = '/checkout#shipping';
                        } else {
                            this.errors.general = result.message || 'Login failed';
                        }
                    } catch (e) {
                        this.errors.general = 'An error occurred. Please try again.';
                    }
                }
            }
        }
    </script>
</div>
