<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { completePlayerOnboarding, fetchRaces } from "../api";
import type { RaceSnapshot } from "../contractsRaces";
import { useAuthStore } from "../ui/stores/authStore";
import { usePlayerFactionStore } from "../ui/stores/playerFactionStore";

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

const busy = ref(false);
const loadingRaces = ref(false);
const errorMessage = ref("");
const raceOptions = ref<RaceSnapshot[]>([]);
const form = reactive({
  name: "",
  raceId: "",
});

const canSubmit = computed(() =>
  form.name.trim().length >= 2 && form.raceId.trim().length > 0 && !busy.value && !loadingRaces.value,
);

onMounted(async () => {
  loadingRaces.value = true;
  errorMessage.value = "";
  try {
    raceOptions.value = (await fetchRaces()).sort((left, right) => left.name.localeCompare(right.name));
    if (!form.raceId && raceOptions.value.length > 0) {
      form.raceId = raceOptions.value[0].id;
    }
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "Unable to load race options.";
  } finally {
    loadingRaces.value = false;
  }
});

async function submit() {
  if (!canSubmit.value) {
    return;
  }

  busy.value = true;
  errorMessage.value = "";
  try {
    const snapshot = await completePlayerOnboarding({
      name: form.name.trim(),
      raceId: form.raceId,
    });
    playerFactionStore.setPlayerFaction(snapshot);
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "Unable to create your pilot.";
  } finally {
    busy.value = false;
  }
}

function signOut() {
  authStore.clearSession();
  playerFactionStore.setPlayerFaction(null);
}
</script>

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

    <div class="auth-landing__hero">
      <h1>Create your pilot</h1>
      <p>
        This account has access to the universe, but it does not have an in-game identity yet. Choose a name and an origin faction, then you will start with a single basic ship.
      </p>
      <div class="auth-card">
        <h2>First Login Setup</h2>

        <form class="auth-card__form" @submit.prevent="submit">
          <input
            v-model.trim="form.name"
            type="text"
            autocomplete="nickname"
            maxlength="48"
            placeholder="Pilot name"
          >
          <select v-model="form.raceId" :disabled="loadingRaces || busy">
            <option value="" disabled>Select a race</option>
            <option
              v-for="race in raceOptions"
              :key="race.id"
              :value="race.id"
            >
              {{ race.name }}
            </option>
          </select>
          <button type="submit" :disabled="!canSubmit">
            {{ busy ? "Entering universe..." : "Create pilot" }}
          </button>
        </form>

        <div v-if="loadingRaces" class="auth-card__message auth-card__message--info">
          Loading faction options...
        </div>
        <div v-if="errorMessage" class="auth-card__message auth-card__message--error">
          {{ errorMessage }}
        </div>

        <div class="auth-card__footer">
          <button type="button" class="auth-card__link" @click="signOut">
            Sign out
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
