<script lang="ts">
  import { createEventDispatcher, onMount } from "svelte";
  import IconButton from "../utils/IconButton.svelte";
  import Jobs from "./Jobs.svelte";
  import Notifications from "./Notifications.svelte";
  import { i18n } from "../../i18n";
  const dispatch = createEventDispatcher();

  let rootEl: HTMLElement;
  let contentEl: HTMLElement;
  let contentHeight = 0;
  let hidden = true;

  let activeJobs: number;

  onMount(() => {
    const rootObserver = new ResizeObserver((entries) => {
      // should be only one
      entries.forEach((entry) => {
        dispatch("resize", entry.contentRect.height);
      });
    });
    rootObserver.observe(rootEl);

    const contentObserver = new ResizeObserver((entries) => {
      entries.forEach((entry) => {
        contentHeight = entry.contentRect.height;
      });
    });
    contentObserver.observe(contentEl);

    rootEl.style.top = `${rootEl.getBoundingClientRect().top}px`;
  });

  function toggleHidden() {
    if (hidden) {
      rootEl.style.top = "unset";
    }
    hidden = !hidden;
  }

  function onTransitionEnd(ev: TransitionEvent) {
    if (ev.propertyName === "bottom" && hidden) {
      rootEl.style.top = `${rootEl.getBoundingClientRect().top}px`;
    }
  }
</script>

<footer
  id="footer"
  bind:this={rootEl}
  class:hidden
  style="--contentHeight: {contentHeight}px"
  on:transitionend={onTransitionEnd}
>
  <div class="status">
    <div class="info">
      {#if activeJobs > 0}
        {$i18n.t("Active jobs:")} {activeJobs}
      {:else}
        {$i18n.t("No active jobs.")}
      {/if}
    </div>
    <div class="icons">
      {#if contentHeight > 0}
        <IconButton
          name="{hidden ? 'up' : 'down'}-arrow"
          on:click={toggleHidden}
        />
      {/if}
    </div>
  </div>
  <div class="content" bind:this={contentEl}>
    <Notifications />
    <Jobs bind:active={activeJobs} />
  </div>
</footer>

<style lang="scss">
  footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    display: flex;
    flex-direction: column;
    background: var(--background);
    border-top: 1px solid var(--foreground-lighter);

    transition: 0.7s bottom ease;
  }

  footer.hidden {
    bottom: calc(var(--contentHeight) * -1);
  }

  .status {
    display: flex;
    align-items: center;
    height: 2em;
    padding: 0.2em;
    position: absolute;
    top: 0;
    width: 100%;

    .info {
      flex-grow: 1;
      opacity: 0.75;
    }
  }

  .content {
    margin-top: 2em;
  }

  :global(#footer .content > *) {
    margin: 0.5rem;
  }
</style>
