<template>
  <LoginModal v-if="modal_visible" @submit="on_submit" @cancel="on_cancel" />

  <BulmaButton
    v-bind="$attrs"
    :icon="'fa-solid fa-toggle-' + (store.is_admin ? 'on' : 'off')"
    :busy="is_busy"
    text="Admin"
    @click.left="on_click"
  />
</template>

<script setup lang="ts">
import { APIError } from "@/lib/api_error";
import { Credentials } from "@/lib/model";
import { advent22Store } from "@/lib/store";

import BulmaButton from "./bulma/Button.vue";
import LoginModal from "./LoginModal.vue";

let modal_visible = false;
let is_busy = false;
const store = advent22Store();

function on_click() {
  if (store.is_admin) {
    store.logout();
  } else {
    // show login modal
    is_busy = true;
    modal_visible = true;
  }
}

function on_submit(creds: Credentials) {
  modal_visible = false;

  store
    .login(creds)
    .catch((error) => APIError.alert(error))
    .finally(() => (is_busy = false));
}

function on_cancel() {
  modal_visible = false;
  is_busy = false;
}
</script>
