<script lang="ts">
  import { formatRelative, parseISO } from "date-fns";

  import { Link } from "svelte-navigator";
  import { UpListing } from "upend";
  import type { IFile, ListingResult, VaultInfo } from "upend/types";

  let infoData: VaultInfo | undefined;

  fetch("/api/info").then(async (response) => {
    infoData = await response.json();
  });

  const roots = (async () => {
    const response = await fetch("/api/hier_roots");
    const data = (await response.json()) as ListingResult;
    const listing = new UpListing(data);
    return Object.values(listing.objects).filter((obj) =>
      Boolean(obj.attr["LBL"])
    );
  })();

  const latestFiles = (async () => {
    const response = await fetch("/api/files/latest");
    return (await response.json()) as IFile[];
  })();

  function fmtDate(dateString: string) {
    const date = parseISO(dateString);
    return formatRelative(date, new Date());
  }
</script>

<div class="home">
  <h1>
    {infoData?.name || "UpEnd"}
  </h1>

  <section class="roots">
    <h2>Roots</h2>
    {#await roots}
      <sl-spinner style="font-size: 3rem; --track-width: 6px" />
    {:then data}
      <ul>
        {#each data as root}
          <li>
            <sl-card class="root">
              <Link to="/browse/{root.address}">
                <h1>{root.identify()}</h1>
              </Link>
              <div slot="footer">
                {root.attr["HAS"]?.length || 0} children
              </div>
            </sl-card>
          </li>
        {:else}
          <li>No roots :(</li>
        {/each}
      </ul>
    {/await}
  </section>

  <section class="latest">
    <h2>Most recently added files</h2>
    {#await latestFiles}
      <sl-spinner style="font-size: 3rem; --track-width: 6px" />
    {:then data}
      <table>
        {#each data as file}
          <tr>
            <td class="file-added">{fmtDate(file.added)}</td>
            <td>
              <Link to="/browse/{file.hash}">
                <div class="file-path">{file.path}</div>
              </Link>
            </td>
          </tr>
        {/each}
      </table>
    {/await}
  </section>
</div>

<style lang="scss">
  h1,
  h2 {
    text-align: center;
  }

  .latest {
    table {
      border-spacing: 1em 0.25em;
    }

    .file-added {
      opacity: 0.77;
      white-space: nowrap;
    }
  }

  sl-spinner {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
  }

  .roots {
    ul {
      list-style: none;
      padding: 0;
      margin: 0 2rem;
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 2rem;
    }

    .root {
      width: 100%;
      text-align: center;
    }
  }
</style>
