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

const authStore = useAuthStore();
const playerFactionStore = usePlayerFactionStore();
const { session, busy, availablePlayerIdentities, effectivePlayerId } = storeToRefs(authStore);

const mode = ref<"login" | "register">("login");
const email = ref("");
const password = ref("");
const errorMessage = ref("");
const identityBusy = ref(false);
const identityError = ref("");
const forgotPasswordOpen = ref(false);
const forgotPasswordState = reactive({
  email: "",
});

const selectedIdentityId = computed({
  get: () => effectivePlayerId.value ?? "",
  set: (value: string) => {
    void switchIdentity(value || null);
  },
});

const canAccessGm = computed(() => authStore.canAccessGm);
const activeIdentitySummary = computed(() =>
  availablePlayerIdentities.value.find((entry) => entry.userId === (effectivePlayerId.value ?? session.value?.userId ?? "")) ?? null,
);

async function submit() {
  errorMessage.value = "";
  authStore.setBusy(true);
  try {
    if (mode.value === "login") {
      const snapshot = await login({ email: email.value, password: password.value });
      authStore.setSession(snapshot);
      playerFactionStore.setPlayerFaction(null);
      password.value = "";
      forgotPasswordOpen.value = false;
    } else {
      await register({ email: email.value, password: password.value });
      playerFactionStore.setPlayerFaction(null);
      errorMessage.value = "";
      mode.value = "login";
      password.value = "";
    }
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "Authentication failed.";
  } finally {
    authStore.setBusy(false);
  }
}

function logout() {
  authStore.clearSession();
  playerFactionStore.setPlayerFaction(null);
  errorMessage.value = "";
  password.value = "";
}

async function refreshPlayerContext() {
  if (!authStore.isAuthenticated) {
    playerFactionStore.setPlayerFaction(null);
    return;
  }

  try {
    playerFactionStore.setPlayerFaction(await fetchPlayerFaction());
  } catch {
    playerFactionStore.setPlayerFaction(null);
  }
}

async function loadPlayerIdentities() {
  if (!authStore.isAuthenticated || !authStore.canAccessGm) {
    authStore.setAvailablePlayerIdentities([]);
    return;
  }

  identityBusy.value = true;
  identityError.value = "";
  try {
    authStore.setAvailablePlayerIdentities(await fetchPlayerIdentities());
  } catch (error) {
    identityError.value = error instanceof Error ? error.message : "Unable to load player identities.";
    authStore.setAvailablePlayerIdentities([]);
  } finally {
    identityBusy.value = false;
  }
}

async function switchIdentity(nextPlayerId: string | null) {
  authStore.setEffectivePlayerId(nextPlayerId);
  identityBusy.value = true;
  identityError.value = "";
  try {
    await refreshPlayerContext();
  } catch (error) {
    identityError.value = error instanceof Error ? error.message : "Unable to switch current identity.";
  } finally {
    identityBusy.value = false;
  }
}

watch(
  () => session.value?.userId ?? null,
  async () => {
    await loadPlayerIdentities();
    await refreshPlayerContext();
  },
  { immediate: true },
);
</script>

<template>
  <div class="pointer-events-auto rounded-2xl border border-white/10 bg-[rgba(11,14,20,0.9)] px-4 py-4 text-[color:var(--viewer-text)] shadow-[0_18px_60px_rgba(0,0,0,0.35)] backdrop-blur">
    <template v-if="session">
      <div class="flex items-start justify-between gap-3">
        <div>
          <div class="text-xs uppercase tracking-[0.22em] text-white/45">Identity</div>
          <div class="mt-1 text-sm font-semibold">{{ session.email }}</div>
          <div class="mt-1 text-xs text-white/55">Player {{ session.userId.slice(0, 8) }}</div>
          <div v-if="canAccessGm" class="mt-3">
            <div class="text-[10px] uppercase tracking-[0.18em] text-white/45">Current Identity</div>
            <select
              v-model="selectedIdentityId"
              class="mt-1 w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none transition focus:border-white/30"
              :disabled="identityBusy"
            >
              <option value="">GM Self</option>
              <option
                v-for="identity in availablePlayerIdentities"
                :key="identity.userId"
                :value="identity.userId"
              >
                {{ identity.email }}{{ identity.playerFactionLabel ? ` · ${identity.playerFactionLabel}` : "" }}
              </option>
            </select>
            <div class="mt-1 text-[11px] text-white/50">
              Acting as
              {{ activeIdentitySummary?.email ?? session.email }}
              <span v-if="activeIdentitySummary?.playerFactionLabel"> · {{ activeIdentitySummary.playerFactionLabel }}</span>
            </div>
            <div v-if="identityError" class="mt-2 text-[11px] text-[#ffd8cf]">{{ identityError }}</div>
          </div>
          <div v-if="session.roles.length > 0" class="mt-2 flex flex-wrap gap-1.5">
            <span
              v-for="role in session.roles"
              :key="role"
              class="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] text-white/65"
            >
              {{ role }}
            </span>
          </div>
        </div>
        <button
          type="button"
          class="rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs transition hover:bg-white/10"
          @click="logout"
        >
          Sign out
        </button>
      </div>
    </template>
    <template v-else>
      <div class="flex items-center justify-between gap-3">
        <div>
          <div class="text-xs uppercase tracking-[0.22em] text-white/45">Pilot Access</div>
          <div class="mt-1 text-sm font-semibold">{{ mode === "login" ? "Sign in" : "Create account" }}</div>
        </div>
        <button
          type="button"
          class="rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs transition hover:bg-white/10"
          @click="mode = mode === 'login' ? 'register' : 'login'"
        >
          {{ mode === "login" ? "Register" : "Login" }}
        </button>
      </div>

      <form class="mt-3 flex flex-col gap-2.5" @submit.prevent="submit">
        <input
          v-model.trim="email"
          type="email"
          autocomplete="email"
          placeholder="Email"
          class="rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none transition placeholder:text-white/35 focus:border-white/30"
        >
        <input
          v-model="password"
          type="password"
          :autocomplete="mode === 'login' ? 'current-password' : 'new-password'"
          placeholder="Password"
          class="rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none transition placeholder:text-white/35 focus:border-white/30"
        >
        <button
          type="submit"
          class="rounded-xl bg-[#ff7458] px-3 py-2 text-sm font-semibold text-black transition hover:bg-[#ff8c74] disabled:cursor-not-allowed disabled:opacity-50"
          :disabled="busy"
        >
          {{ busy ? "Working..." : mode === "login" ? "Sign in" : "Create account" }}
        </button>
      </form>

      <button
        type="button"
        class="mt-2 text-xs text-white/55 underline-offset-4 transition hover:text-white/80 hover:underline"
        @click="forgotPasswordOpen = !forgotPasswordOpen"
      >
        Forgot password?
      </button>

      <div v-if="forgotPasswordOpen" class="mt-2 rounded-xl border border-dashed border-white/10 bg-black/15 px-3 py-2 text-xs text-white/60">
        <div class="font-medium text-white/72">Reset flow not implemented yet.</div>
        <div class="mt-1">Backend support is still missing for forgot-password and reset-token delivery.</div>
        <input
          v-model.trim="forgotPasswordState.email"
          type="email"
          autocomplete="email"
          placeholder="Email for future reset flow"
          class="mt-2 w-full rounded-lg border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none transition placeholder:text-white/35 focus:border-white/30"
        >
      </div>

      <div v-if="errorMessage" class="mt-2 rounded-xl border border-[#ff7458]/25 bg-[rgba(255,116,88,0.12)] px-3 py-2 text-xs text-[#ffd8cf]">
        {{ errorMessage }}
      </div>
    </template>
  </div>
</template>
