<script lang="ts">
  import { goto } from '$app/navigation';
  import { logout, storedUser } from '$lib/auth/session';
  import type { StoredUser } from '$lib/auth/session';
  import Hamburger from './Hamburger.svelte';
  import { slide } from 'svelte/transition';

  export let isHidden = false;
  export let currentHeight: number;

  let user: StoredUser | unknown | null = null;
  storedUser.subscribe((value) => {
    user = value;
  });

  let viewportWidth: number;

  $: largeScreen = viewportWidth > 640;
  let menuIsOpen = false;

  function closeMenu() {
    menuIsOpen = false;
  }

  function handleLogout() {
    menuIsOpen = false;
    logout();
    goto('/');
  }
</script>

<svelte:window bind:outerWidth={viewportWidth} />

<nav
  class="sticky top-0 transition-transform ease-linear z-40"
  class:navbarHidden={isHidden}
  bind:clientHeight={currentHeight}
>
  {#if !largeScreen}
    <div id="navHead" class="flex" class:smallScreen={!largeScreen}>
      <a href="/" on:click={closeMenu} class="group">
        <img
          src="/images/common/logo.svg"
          alt="Dewit Logo"
          class="w-11 h-11 p-2 transition-all bg-secondary-700 rounded-lg group-hover:p-0.5 group-hover:bg-secondary"
        />
      </a>
      <Hamburger bind:isOpen={menuIsOpen} />
    </div>
  {/if}
  {#if menuIsOpen || largeScreen}
    <div id="navContent"
      transition:slide="{{delay: largeScreen ? 0 : 100, duration: largeScreen ? 0 : 500}}"
      class:flex-col={!largeScreen}
      class="flex gap-1 items-center"
    >
      {#if largeScreen}
        <a href="/" class="group">
          <img
            src="/images/common/logo.svg"
            alt="Dewit Logo"
            class="w-11 h-11 p-2 transition-all bg-secondary-700 rounded-lg group-hover:p-0.5 group-hover:bg-secondary"
          />
        </a>
      {/if}
      {#if user}
        <a href={`/users/${user.id}`} on:click={closeMenu}>Profile</a>
        <a href={`/users/${user.id}/todos`} on:click={closeMenu}>Todos</a>
        {#if user.isAdmin}
          <a href={`/users/all`} on:click={closeMenu}>All Users</a>
        {/if}
        {#if largeScreen}<div class="grow" aria-hidden />{/if}
        <button class="outlineButton" on:click={handleLogout}>Log Out</button>
      {:else}
        {#if largeScreen}<div class="grow" aria-hidden />{/if}
        <a href="/login" on:click={closeMenu}>Log In</a>
      {/if}
    </div>
  {/if}
</nav>

<style>
  nav {
    @apply text-xl font-semibold;
    @apply p-2;
    @apply bg-primary;
  }
  a {
    @apply block max-w-fit p-2;
    @apply text-secondary text-center no-underline;
    @apply drop-shadow-md;
    @apply transition-all;
  }
  a:hover {
    @apply text-accent font-bold;
  }
  .smallScreen {
    @apply justify-between w-full;
  }
  .navbarHidden {
    @apply -translate-y-full;
  }
</style>
