<script lang="typescript" context="module">
  import type { AppSession, PageData, PreloadContext } from "src/utils/session";
  import type { AuthInfo } from "src/routes/login/check";
  import { goto } from "@sapper/app";

  // TODO: Clean up this awful mess
  export async function preload(
    this: PreloadContext,
    { path }: PageData,
    session: AppSession
  ) {
    const authResult = await this.fetch("/login/check", { credentials: "include" });
    const result = (await authResult.json()) as AuthInfo;
    if (path.startsWith("/login/")) {
      if (result.loggedIn) {
        return this.redirect(302, "/");
      } else {
        return result;
      }
    }
    if (path != "/" && !result.loggedIn) {
      return this.redirect(302, "/");
    }
    if (result.loggedIn) {
      if (!path.startsWith("/rules")) {
        return this.redirect(302, "/rules");
      }
      if (!result.moderator && path != "/rules") {
        return this.redirect(302, "/rules");
      }
    }
    return result;
  }
</script>

<script lang="typescript">
  import { stores } from "@sapper/app";
  const { page } = stores();

  export let loggedIn!: boolean;
  export let moderator!: boolean;
  let path: string;
  $: {
    path = $page.path.slice(1);
    console.log(path);
  }

  const ROUTES_NAV = [
    { route: "rules", moderator: false, name: "Rules" },
    { route: "rules/edit", moderator: true, name: "Edit rules" },
  ];
</script>

<style global>
  @import "tailwindcss/base";
  @import "tailwindcss/components";
  @import "tailwindcss/utilities";

  * {
    @apply font-sans;
  }

  nav {
    @apply fixed w-screen h-12 shadow-lg flex flex-row items-center px-4 z-10;
    background-color: #0a0d13;

    a {
      @apply text-white px-5 py-3;

      &:hover {
        @apply bg-gray-800 cursor-pointer;
      }

      &.active {
        @apply bg-gray-800;
      }
    }
  }
</style>


{#if loggedIn}
  <nav>
    {#each ROUTES_NAV as route (route.route) }
      {#if !route.moderator || (route.moderator && moderator) }
        <a href="/{route.route}" class:active={route.route == path}>{route.name}</a>
      {/if}
    {/each}
    <span class="mx-auto"></span>
    <a href="/logout">Log out</a>
  </nav>
{/if}

<div class="flex items-center justify-center bg-gray-900 h-screen w-screen">
  <slot />
</div>
