<script lang="ts">
  import { initClient } from "@urql/svelte";
  import { removeCookie } from "typescript-cookie";

  import { session } from "$app/stores";
  import { goto } from "$app/navigation";
  import * as cookieNames from "$lib/cookieNames";

  initClient({
    url: "/graphql",
    fetchOptions() {
      if ($session.user.token) {
        return {
          headers: {
            Authorization: `Bearer ${$session.user.token}`,
          },
        };
      }

      return {};
    },
  });

  function logout(): void {
    $session.user.token = undefined;
    removeCookie(cookieNames.TOKEN);
    goto("/login");
  }
</script>

<nav>
  <ul>
    <li>
      {#if $session.user.token}
        <button on:click={logout}>Logout</button>
      {:else}
        <button><a href="/login">Login</a></button>
      {/if}
    </li>
  </ul>
</nav>

<hr />

<main>
  <slot />
</main>
