<div x-data="authRedirect()" class="authredirect-page py-8 max-w-xl mx-auto">
  <h1 class="text-2xl font-semibold mb-6">Sign in or continue as guest</h1>
  <template x-if="errorMessage">
    <div class="mb-4 p-3 bg-red-100 text-red-700" x-text="errorMessage"></div>
  </template>
  <form @submit.prevent="login">
    <div class="mb-4">
      <label class="block mb-1">Email</label>
      <input type="email" x-model="username" required class="border p-2 w-full"/>
    </div>
    <div class="mb-6">
      <label class="block mb-1">Password</label>
      <input type="password" x-model="password" required class="border p-2 w-full"/>
    </div>
    <button type="submit" class="bg-blue-600 text-white py-2 px-4 rounded" :disabled="isLoading">
      <template x-if="!isLoading">Login</template>
      <template x-if="isLoading">Logging in…</template>
    </button>
  </form>
  <div class="mt-6">
    <button @click="continueGuest" class="underline text-blue-600">Continue as Guest</button>
  </div>
</div>
<script>
function authRedirect() {
  return {
    username: '',
    password: '',
    isLoading: false,
    errorMessage: '',
    login() {
      this.isLoading = true;
      fetch('/customer/ajax/login', {
        method: 'POST',
        body: new URLSearchParams({
          'login[username]': this.username,
          'login[password]': this.password
        }),
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
      .then(res => res.json())
      .then(data => {
        if (data.errors) {
          this.errorMessage = data.message || 'Login failed';
        } else {
          window.location.href = '/checkout';
        }
      })
      .catch(() => this.errorMessage = 'Something went wrong')
      .finally(() => this.isLoading = false);
    },
    continueGuest() {
      window.location.href = '/checkout';
    }
  };
}
</script>
