<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { forgotPassword, login, register, resetPassword } from "../api";
import { useAuthStore } from "../ui/stores/authStore";
import { usePlayerFactionStore } from "../ui/stores/playerFactionStore";

type AuthPane = "login" | "register" | "forgot" | "reset";

const authStore = useAuthStore();
const playerFactionStore = usePlayerFactionStore();

const pane = ref<AuthPane>("login");
const errorMessage = ref("");
const infoMessage = ref("");
const returnedResetToken = ref("");

const loginForm = reactive({
  email: "",
  password: "",
});

const registerForm = reactive({
  email: "",
  password: "",
});

const forgotForm = reactive({
  email: "",
});

const resetForm = reactive({
  token: "",
  newPassword: "",
});

const paneTitle = computed(() => {
  switch (pane.value) {
    case "register":
      return "Create your pilot account";
    case "forgot":
      return "Recover access";
    case "reset":
      return "Choose a new password";
    default:
      return "Sign in to the command bridge";
  }
});

async function submitLogin() {
  await execute(async () => {
    const session = await login(loginForm);
    authStore.setSession(session);
    playerFactionStore.setPlayerFaction(null);
  });
}

async function submitRegister() {
  await execute(async () => {
    await register(registerForm);
    playerFactionStore.setPlayerFaction(null);
    infoMessage.value = "Account created. Sign in to enter the universe.";
    pane.value = "login";
    loginForm.email = registerForm.email;
    registerForm.password = "";
  });
}

async function submitForgot() {
  await execute(async () => {
    const response = await forgotPassword(forgotForm);
    returnedResetToken.value = response.resetToken ?? "";
    if (response.resetToken) {
      resetForm.token = response.resetToken;
      resetForm.newPassword = "";
      infoMessage.value = "Development reset token generated below. Continue directly to reset password.";
      pane.value = "reset";
      return;
    }

    infoMessage.value = "If the account exists, a password reset message has been issued.";
  });
}

async function submitReset() {
  await execute(async () => {
    await resetPassword(resetForm);
    returnedResetToken.value = "";
    infoMessage.value = "Password updated. Sign in with the new password.";
    pane.value = "login";
    resetForm.token = "";
    resetForm.newPassword = "";
  });
}

function switchPane(nextPane: AuthPane) {
  pane.value = nextPane;
  errorMessage.value = "";
  infoMessage.value = "";
}

async function execute(action: () => Promise<void>) {
  errorMessage.value = "";
  infoMessage.value = "";
  authStore.setBusy(true);
  try {
    await action();
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "Request failed.";
  } finally {
    authStore.setBusy(false);
  }
}
</script>

<template>
  <div class="auth-landing">
    <div class="auth-landing__backdrop" />

    <div class="auth-landing__hero">
      <h1>Take command in a persistent universe.</h1>
      <p>
        Take your destiny into your own hands. Explore the frontier, forge alliances, expand your reach, and make enemies in a living space sim that keeps moving with or without you.
      </p>
      <div class="auth-card">
        <div class="auth-card__tabs">
          <button type="button" :class="{ 'is-active': pane === 'login' }" @click="switchPane('login')">Login</button>
          <button type="button" :class="{ 'is-active': pane === 'register' }" @click="switchPane('register')">Register</button>
          <button type="button" :class="{ 'is-active': pane === 'forgot' }" @click="switchPane('forgot')">Forgot</button>
        </div>

        <h2>{{ paneTitle }}</h2>

        <form v-if="pane === 'login'" class="auth-card__form" @submit.prevent="submitLogin">
          <input v-model.trim="loginForm.email" type="text" autocomplete="username" placeholder="Email or login">
          <input v-model="loginForm.password" type="password" autocomplete="current-password" placeholder="Password">
          <button type="submit" :disabled="authStore.busy">{{ authStore.busy ? "Signing in..." : "Sign in" }}</button>
          <button type="button" class="auth-card__link" @click="switchPane('forgot')">Forgot password?</button>
        </form>

        <form v-else-if="pane === 'register'" class="auth-card__form" @submit.prevent="submitRegister">
          <input v-model.trim="registerForm.email" type="email" autocomplete="email" placeholder="Email">
          <input v-model="registerForm.password" type="password" autocomplete="new-password" placeholder="Password">
          <button type="submit" :disabled="authStore.busy">{{ authStore.busy ? "Creating..." : "Create account" }}</button>
        </form>

        <form v-else-if="pane === 'forgot'" class="auth-card__form" @submit.prevent="submitForgot">
          <input v-model.trim="forgotForm.email" type="email" autocomplete="email" placeholder="Email">
          <button type="submit" :disabled="authStore.busy">{{ authStore.busy ? "Submitting..." : "Send reset link" }}</button>
        </form>

        <form v-else class="auth-card__form" @submit.prevent="submitReset">
          <input v-model.trim="resetForm.token" type="text" autocomplete="off" placeholder="Reset token">
          <input v-model="resetForm.newPassword" type="password" autocomplete="new-password" placeholder="New password">
          <button type="submit" :disabled="authStore.busy">{{ authStore.busy ? "Updating..." : "Reset password" }}</button>
          <button type="button" class="auth-card__link" @click="switchPane('login')">Back to login</button>
        </form>

        <div v-if="returnedResetToken" class="auth-card__token">
          <div class="auth-card__token-label">Development reset token</div>
          <code>{{ returnedResetToken }}</code>
        </div>

        <div v-if="infoMessage" class="auth-card__message auth-card__message--info">
          {{ infoMessage }}
        </div>
        <div v-if="errorMessage" class="auth-card__message auth-card__message--error">
          {{ errorMessage }}
        </div>

        <div class="auth-card__footer">
          <button
            v-if="pane !== 'reset'"
            type="button"
            class="auth-card__link"
            @click="switchPane('reset')"
          >
            Have a reset token?
          </button>
        </div>
      </div>

      <div class="auth-landing__notes">
        <div>Local account auth is active on this dev machine.</div>
        <div>Google, Microsoft, and other providers can plug into the same identity model later.</div>
      </div>
    </div>
  </div>
</template>
