<script setup lang="ts">
import { ref, onMounted, onBeforeMount } from "vue";
import { isDomainAvailable } from "./lib/whois";
import { DomainFactory } from "./lib/factory";

enum State {
  Loading,
  Ready,
  Generating,
  Fetching,
  Error,
}

function getLang() {
  return document.location.hash === "#french" ? "french" : "english";
}

const visible = ref<boolean>(false);
const factory = ref<DomainFactory>(new DomainFactory());
const domain = ref<string | null>(null);
const domainAvailable = ref<boolean>(false);
const lang = ref<string>(getLang());
const state = ref<State>(State.Loading);

function newDomain() {
  if (!factory.value.error) {
    state.value = State.Generating;
    factory.value
      .next(lang.value)
      .then((value) => {
        domain.value = value;
        checkAvailability();
      })
      .catch((err: unknown) => {
        state.value = State.Error;
        throw err;
      });
  }
}

function checkAvailability() {
  if (domain.value) {
    const promiseDomain = domain.value;
    state.value = State.Fetching;
    isDomainAvailable(promiseDomain)
      .then((available) => {
        if (domain.value !== promiseDomain) {
          return; // domain changed
        }
        domainAvailable.value = available;
        if (!available) {
          newDomain();
        } else {
          state.value = State.Ready;
        }
      })
      .catch((err: unknown) => {
        state.value = State.Error;
        throw err;
      });
  }
}

function getTextClass() {
  if (!domain.value || domain.value.length < 15) {
    return "text-5xl";
  }
  if (domain.value.length < 20) {
    return "text-4xl";
  }
  if (domain.value.length < 25) {
    return "text-3xl";
  }
  if (domain.value.length < 30) {
    return "text-2xl";
  }
  return "text-xl";
}

onBeforeMount(async () => {
  await factory.value.init();
  newDomain();
  state.value = State.Ready;
});
onMounted(() => {
  setTimeout(() => {
    visible.value = true;
  });
  setInterval(() => {
    const newLang = getLang();
    if (newLang !== lang.value) {
      lang.value = newLang;
      newDomain();
    }
  }, 100);
});
</script>

<template>
  <div :style="{ display: visible ? 'inherit' : 'none' }">
    <div class="card bg-base-100 w-xl max-w-svw shrink-0 shadow-2xl">
      <div class="card-body overflow-hidden">
        <h1 class="font-bold" :class="getTextClass()">
          <span
            v-if="state !== State.Loading && domain"
            class="inline-block me-2"
          >
            <div v-if="state === State.Fetching" class="status status-xl"></div>
            <div
              v-else-if="domainAvailable"
              class="inline-grid *:[grid-area:1/1]"
            >
              <div class="status status-xl status-success animate-ping"></div>
              <div class="status status-xl status-success"></div>
            </div>
            <div v-else class="inline-grid *:[grid-area:1/1]">
              <div class="status status-xl status-error animate-ping"></div>
              <div class="status status-xl status-error"></div>
            </div>
          </span>
          <span
            v-if="!domain"
            class="loading loading-spinner loading-xl"
          ></span>
          <span v-else>{{ domain }}</span>
        </h1>
        <p v-if="state === State.Loading" class="py-6">
          <span v-if="lang === 'french'"
            >Chargement de la Cool Domain Factory™</span
          >
          <span v-else>Loading the Cool Domain Factory™</span>
          <span class="loading loading-dots loading-xs"></span>
        </p>
        <p v-else-if="state === State.Generating" class="py-6">
          <span v-if="lang === 'french'">Création d'un domaine cool</span>
          <span v-else>Generating a new cool domain</span>
          <span class="loading loading-dots loading-xs"></span>
        </p>
        <p v-else-if="state === State.Fetching" class="py-6">
          <span v-if="lang === 'french'">Vérification de la disponibilité</span>
          <span v-else>Checking domain availability</span>
          <span class="loading loading-dots loading-xs"></span>
        </p>
        <div v-else-if="state === State.Ready && domainAvailable" class="py-6">
          <span v-if="lang === 'french'"
            >Ce domaine semble
            <a
              :href="`https://tld-list.com/fr/tld/${domain?.split('.')[1]}`"
              target="_blank"
              class="underline"
              >disponible</a
            >
            !</span
          >
          <span v-else
            >This domain seems
            <a
              :href="`https://tld-list.com/tld/${domain?.split('.')[1]}`"
              target="_blank"
              class="underline"
              >available</a
            >!</span
          >
        </div>
        <div v-else-if="state === State.Ready && !domainAvailable" class="py-6">
          <span v-if="lang === 'french'">Ce domaine n'est pas disponible.</span>
          <span v-else>This domain is not available.</span>
        </div>
        <div v-else-if="state === State.Error" class="py-6">
          <span v-if="lang === 'french'"
            >Une erreur est survenue, merci de recharger la page.</span
          >
          <span v-else>An error has occured, please reload the page.</span>
        </div>
        <button
          :disabled="
            state === State.Loading ||
            state === State.Generating ||
            state === State.Error
          "
          class="btn btn-primary"
          @click="newDomain"
        >
          <span v-if="lang === 'french'">Nouveau domaine</span>
          <span v-else>New domain</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.footer {
  opacity: 50%;
}
</style>
