<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <slot v-if="state === 'visible'" name="default" />
  <span v-else>***</span>
  <BulmaButton
    :class="`is-small is-${record.color} ml-2`"
    :icon="['fas', record.icon]"
    :busy="state === 'pending'"
    @click="on_click"
  />
</template>

<script setup lang="ts">
import { computed, ref } from "vue";

import BulmaButton from "./Button.vue";

const emit = defineEmits<{
  (event: "show"): void;
  (event: "hide"): void;
}>();

type State = "hidden" | "pending" | "visible";
const state = ref<State>("hidden");

const state_map: Record<State, { color: string; icon: string; next: State }> = {
  hidden: { color: "primary", icon: "eye-slash", next: "pending" },
  pending: { color: "warning", icon: "eye-slash", next: "visible" },
  visible: { color: "danger", icon: "eye", next: "hidden" },
} as const;
const record = computed(() => state_map[state.value] ?? state_map.hidden);

let pending_timeout: number | undefined;

function on_click(): void {
  state.value = record.value.next;

  if (state.value === "hidden") {
    emit("hide");
  }

  if (state.value === "pending") {
    pending_timeout = window.setTimeout(() => (state.value = "hidden"), 2500);
  } else {
    window.clearTimeout(pending_timeout);
  }

  if (state.value === "visible") {
    emit("show");
  }
}
</script>
