<script>
  import { setContext, onMount } from "svelte";
  import { onNavigate } from '$app/navigation';
  import { page } from '$app/state';
  import '../app.css';
  import logo from '$lib/assets/logo.png';

  /* ==================== Start subscription library-esque ==================== */
  let subscriptionJson = $state(null);

  function doSubscribe() {
    navigator.serviceWorker.ready
      .then(async(registration) => {
        const response = await fetch("/api/vapid");
        // and if we fail to get it?
        const vapidPublicKey = await response.text();
        const convertedVapidKey = vapidPublicKey;
        return registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: convertedVapidKey
        });
      }).then((subscription) => {
        subscriptionJson = JSON.parse(JSON.stringify(subscription));
        return fetch("/api/register", {
          method: "post",
          headers: { "Content-type": "application/json" },
          body: JSON.stringify(subscriptionJson),
        });
      });
  }

  async function doUnsubscribe() {
    navigator.serviceWorker.ready
      .then((registration) => {
        return registration.pushManager.getSubscription();
      }).then((subscription) => {
        return subscription.unsubscribe()
          .then(function() {
            subscriptionJson = null;
            return fetch("/api/unregister", {
              method: "post",
              headers: { "Content-type": "application/json" },
              body: JSON.stringify({ subscription })
            });
          });
      });
  }

  function toggleSub() {
    if (subscriptionJson !== null) {
      doUnsubscribe();
    } else {
      doSubscribe();
    }
  }

  function notifyMe() {
    fetch("/api/echo", {
      method: "post",
      headers: { "Content-type": "application/json" },
      body: JSON.stringify({
        ...subscriptionJson,
        msg: "oople doople",
      })
    });
  }

  onMount(() => {
    navigator.serviceWorker.ready.then((registration) => {
      return registration.pushManager.getSubscription();
    }).then((subscription) => {
      if (subscription) {
        subscriptionJson = JSON.parse(JSON.stringify(subscription));
      }
    });
  });
  /* ==================== END ==================== */

  const session = $derived(page.data.session);
  let pageContext = $state({
    showMenu: false,
  });
  setContext('page', pageContext);

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

  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>
  <button onclick="{notifyMe}">
    notify
  </button>
  <button onclick="{toggleSub}">
    toggle sub
  </button>
  <div>
    hasSub: {subscriptionJson !== null}
  </div>
  <div class="trail">
    {#if session}
      <div>
        <a href="/me">@{session.currentUser.name}</a>
      </div>
    {/if}
  </div>
</div>

{@render children?.()}
