<script>
  import { setContext } from 'svelte';
  import { browser } from '$app/environment';
  import { goto, onNavigate, afterNavigate } from '$app/navigation';
  import { page } from '$app/stores';
  import '../app.css';
  import logo from '$lib/assets/logo.png';
  import { STORE_KEY_LAST_ACTIVE } from '$lib/constants';
  import { currentUser } from '$lib/store';

  let activeChannel = $derived($page.params.channel);

  let pageContext = $state({
    showMenu: false
  });
  setContext('page', pageContext);

  function toggleMenu(event) {
    event.preventDefault();
    pageContext.showMenu = !pageContext.showMenu;
  }

  function getLastActiveChannel() {
    return (
      browser && JSON.parse(localStorage.getItem(STORE_KEY_LAST_ACTIVE))
    );
  }

  function setLastActiveChannel(channelId) {
    browser && localStorage.setItem(
      STORE_KEY_LAST_ACTIVE,
      JSON.stringify(channelId)
    );
  }

  afterNavigate(() => {
    const lastActiveChannel = getLastActiveChannel();
    if (!activeChannel && lastActiveChannel) {
      goto(`/ch/${lastActiveChannel}`);
    } else {
      setLastActiveChannel(activeChannel || null);
    }
  });

  onNavigate(() => {
    pageContext.showMenu = false;
  });

  let { children } = $props();
</script>

<div class="app-bar">
  <div class="lead">
    <button onclick={toggleMenu}>
      <img alt="logo" src={logo} />
    </button>
  </div>
  <a href="/">pilcrow</a>
  <div class="trail">
    {#if $currentUser}
      <div>
        <a href="/me">@{$currentUser.username}</a>
      </div>
    {/if}
  </div>
</div>

{@render children?.()}
