<script lang="ts">
  import type { ProjectResult } from "../models/project";
  import selectionStore from "../stores/selection";
  import ProjectEntry from "./ProjectEntry.svelte";
  import QlList from "./QLList.svelte";

  export let projects: ProjectResult[];

  let expiringProjects: ProjectResult[];
  let activeProjects: ProjectResult[];
  let completedProjects: ProjectResult[];
  let project: ProjectResult = null;

  $: project = $selectionStore.hash.startsWith("P") ? projects.find(p => p.id === $selectionStore.hash) : null;
  $: expiringProjects = projects.filter(p => p.active && p.endTime).sort((a,b) => Date.parse(a.endTime) - Date.parse(b.endTime));
  $: activeProjects = projects.filter(p => p.active && !p.endTime).sort((a,b) => a.name.localeCompare(b.name));
  $: completedProjects = projects.filter(p => !p.active).sort((a,b) => a.name.localeCompare(b.name));

  $: {
    if (project === null && projects.length > 0) {
      project = expiringProjects[0] || activeProjects[0] || completedProjects[0] || null;
      if (project !== null) {
        selectionStore.change("hash", project.id);
      }
    }
  }
</script>

<div class="quest-log">
  <div class="list">
    <QlList label="Deadlines" projects={expiringProjects} />
    <QlList label="Active" projects={activeProjects} />
    <QlList label="Completed" projects={completedProjects} />
  </div>
  <div class="body">
    {#if project != null}
      <ProjectEntry hideIcon project={project} showAllOptions />
    {/if}
  </div>
</div>

<style>
  div.quest-log {
    display: flex;
    flex-direction: row;
  }

  div.list {
    flex-shrink: 0;
    width: 32ch;
  }

  div.body {
    flex-grow: 1;
    margin: 1em 1ch;
  }
</style>