<script lang="ts">
  import { goto } from "$app/navigation";
  import { page } from "$app/state";
  import { PUBLIC_BACKEND_API_HOST } from "$env/static/public";
  import { onMount } from "svelte";

  let token = page.params.token;
  let errorMessage: string | undefined = $state(undefined);
  let success: boolean | undefined = $state(undefined);

  onMount(async () => {
    try {
      const res = await fetch(`${PUBLIC_BACKEND_API_HOST}/api/v1/user/verify-email`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token })
      });

      let data = await res.json();

      if (!res.ok) {
        errorMessage = data?.msg || "Something went wrong";
        success = false;
      } else {
        success = true;
        setTimeout(() => {
          goto("/login");
        }, 2000);
      }
    } catch (err: any) {
      errorMessage = err?.msg || "Network error";
      success = false;
    }
  });
</script>

<svelte:head>
  <title>HexName - Free, uncomplicated DNS management</title>
  <meta property="og:title" content="HexName - Free, uncomplicated DNS management">
  <meta name="twitter:title" content="HexName - Free, uncomplicated DNS management">
  <meta name="description" content="Register our premium domains and manage DNS and DynDNS - so you can focus on what truly matters.">
  <meta property="og:description" content="Register our premium domains and manage DNS and DynDNS - so you can focus on what truly matters.">
  <meta name="twitter:description" content="Register our premium domains and manage DNS and DynDNS - so you can focus on what truly matters.">
  <meta name="robots" content="noindex, nofollow">
</svelte:head>

{#if success === undefined}
  <div class="flex flex-col items-center justify-center w-full my-80">
    <h2 class="text-4xl text-primary-content">Verifying your email</h2>
    <span class="loading loading-dots loading-lg translate-y-3 ml-1"></span>
  </div>
{:else if success}
  <div class="flex flex-col items-center justify-center w-full my-80">
    <h2 class="text-2xl text-primary-content">Email successfully verified!</h2>
    <h3 class="text-xl text-primary-content">You may log in now.</h3>
  </div>
{:else}
  <div class="flex flex-col items-center justify-center w-full my-80">
    <h2 class="text-2xl text-primary-content">Failed to verify your email:</h2>
    <h3 class="text-xl text-primary-content">{errorMessage}</h3>
  </div>
{/if}
