<script lang="ts">
  import { tick } from "svelte";

  import { navigate } from "svelte-routing";

  import QuestLog from "../components/QuestLog.svelte";
  import RefreshSelection from "../components/RefreshSelection.svelte";
  import projectGroupStore from "../stores/projectGroup";
  import { sortProjects } from "../utils/sorters";

  export let groupId = "";
  export let projectId = "";

  $: {
    if ($projectGroupStore.stale && !$projectGroupStore.loading) {
      projectGroupStore.load();
    }
  }

  $: {
    if ($projectGroupStore.groups.length > 0 && groupId === "") {
      const group = $projectGroupStore.groups[0];

      if (group.projects.length > 0) {
        const projects = [...group.projects].sort(sortProjects);

        navigate(`/questlog/${group.id}/${projects[0].id}`, {replace: true});

        // There's some weirdness with navigate. This hack will just do a 
        // groups = [...groups] in the sttore to get the page to update.
        tick().then(() => {
          projectGroupStore.fakeRefresh();
        })
      } else {
        navigate(`/questlog/${group.id}`);
      }
    }
  }
</script>

<div class="page">
  <QuestLog groups={$projectGroupStore.groups} groupId={groupId} projectId={projectId} />
</div>
<RefreshSelection />


<style>
  div.page {
    display: block;
    margin: auto;
    max-width: 100%;
    width: 1020px;
    margin-top: 0;
    box-sizing: border-box;
  }
</style>