<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";
import UpObjectCard from "../components/display/UpObjectCard.svelte";
import Spinner from "../components/utils/Spinner.svelte";

  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}
      <Spinner />
    {:then data}
      <ul>
        {#each data as root}
          <li class="root">
            <UpObjectCard address={root.address} />
          </li>
        {:else}
          <li>No roots :(</li>
        {/each}
      </ul>
    {/await}
  </section>

  <section class="latest">
    <h2>Most recently added files</h2>
    {#await latestFiles}
      <Spinner />
    {: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;
      text-align: center;
    }
  }

  .roots {
    ul {
      list-style: none;
      padding: 0;
      margin: 0 2rem;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 2rem;
    }

    .root {
      font-size: 24px;
    }
  }
</style>
