<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");
    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 && !path.startsWith("/rules/")) {
      if (result.moderator) {
        return this.redirect(302, "/rules/create");
      }
      return this.redirect(302, "/rules");
    }
    return result;
  }
</script>

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

  export let loggedIn!: boolean;
  let path: string;
  $: path = $page.path.slice(1);
</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 justify-end items-center px-4 z-10;
    background-color: #0a0d13;

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

      &:hover {
        @apply bg-gray-800 cursor-pointer;
      }
    }
  }
</style>

<svelte:head>
  <title>{path ? path.charAt(0).toUpperCase() + path.slice(1) : 'Index'}</title>
</svelte:head>

{#if loggedIn}
  <nav><a href="/logout">Log out</a></nav>
{/if}

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