<script setup lang="ts">
import { defineAsyncComponent, ref } from "vue";
import type { DomainFactory } from "@/lib/factory";
const CoolDomain = defineAsyncComponent(() => import("./CoolDomain.vue"));
import type { Domain } from "@/types";
import { isDomainAvailable } from "@/lib/whois";

const props = defineProps<{ factory: DomainFactory }>();

const input = ref<string>("");
const domains = ref<Domain[]>([]);
const noDomain = ref<boolean>(false);

function start() {
  noDomain.value = false;
  domains.value.splice(0, domains.value.length);
  if (input.value.length) {
    newDomain();
  }
}

function newDomain() {
  const startInput = input.value;
  props.factory
    .allFromWord(input.value)
    .then((newDomains: Domain[]) => {
      if (input.value === startInput) {
        domains.value.push(...newDomains);
        domains.value.forEach((domain) => void isDomainAvailable(domain));
      }
    })
    .catch(() => {
      if (input.value === startInput && !domains.value.length) {
        noDomain.value = true;
      }
    });
}
</script>

<template>
  <div>
    <div class="pb-6">
      <input
        v-model.trim="input"
        type="text"
        :placeholder="$t('page_input.placeholder')"
        class="input input-xl w-full"
        @keyup.enter="start"
      />
    </div>
    <button class="btn btn-primary" :disabled="!input" @click="start">
      {{ $t("button.generate") }}
    </button>
    <p v-for="(domain, i) in domains" :key="`domain-${i}`" class="pt-3">
      <CoolDomain
        :id="domain.name + domain.searching + domain.available"
        :domain="domain"
      ></CoolDomain>
      <span v-if="domain.searching"
        >&nbsp;<span class="loading loading-dots loading-xs"></span
      ></span>
      <span v-else-if="domain.available"
        >&nbsp;{{ $t("seems") }}
        <a
          :href="`https://tld-list.com/${$i18n.locale}/tld/${domain.tld}`"
          target="_blank"
          class="underline"
          >{{ $t("available") }}</a
        ></span
      ><span v-else>&nbsp;{{ $t("is_unavailable") }}</span>
    </p>
    <p v-if="noDomain" class="pt-6">{{ $t("page_input.not_found") }}.</p>
  </div>
</template>
