<script lang="ts" context="module">
  async function getCurrentHash(): Promise<string> {
    const response = await fetch(
      "https://api.github.com/repos/Toby222/svelte-sharg/commits/main",
      {
        mode: "cors",
      }
    );
    if (response.status < 200 || response.status > 299) {
      throw new Error(response.statusText);
    } else {
      const result = (await response.json()).sha;
      return result;
    }
  }
  let CURRENT_HASH: string;
  getCurrentHash().then((hash) => (CURRENT_HASH = hash));
</script>

<script lang="ts">
  import Footer from "./components/Footer.svelte";
  import Header from "./components/Header.svelte";
  import Wrapper from "./components/Wrapper.svelte";
  import { SharkGame } from "./shark/SharkGame";

  import { Modals, closeModal } from "svelte-modals";
  import { onDestroy, onMount } from "svelte";
  import type { Unsubscriber } from "svelte/store";

  SharkGame.init();

  let root: HTMLElement;
  let unsubscribeSettings: Unsubscriber;
  let updateInterval: ReturnType<typeof setInterval> | undefined;

  onMount(() => {
    root = document.documentElement;

    SharkGame.Settings.subscribe((settings) => {
      root.classList.toggle("no-theme", !settings.enableThemes.current);
      settings.theme.options.forEach((theme) => {
        root.classList.toggle(theme, theme === settings.theme.current);
      });

      if (settings.updateCheck.current && updateInterval === undefined) {
        updateInterval = setInterval(async () => {
          if (
            CURRENT_HASH !== undefined &&
            CURRENT_HASH !== (await getCurrentHash())
          ) {
            console.log("Updoot");
          }
        }, 6 * 60 * 1000);
      } else if (
        !settings.updateCheck.current &&
        updateInterval !== undefined
      ) {
        clearInterval(updateInterval);
      }
    });
  });

  onDestroy(() => {
    unsubscribeSettings();
  });

  function handleKeyUp(event: KeyboardEvent) {
    if (event.key === "Escape") {
      closeModal();
    }
  }
</script>

<svelte:body on:keyup={handleKeyUp} />

<Modals>
  <div slot="backdrop" id="modal-backdrop" on:click={closeModal} />
</Modals>
<Header game={SharkGame} title={SharkGame.title} />
<Wrapper game={SharkGame} />
<Footer />
