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

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

  let infoData: VaultInfo | undefined;
  let latestFiles: IFile[] = [];

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

  fetch("/api/files/latest").then(async (response) => {
    latestFiles = await response.json();
  });

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

<div class="home">
  <h1>
    {infoData?.name || "UpEnd"}
  </h1>
  
  {#if latestFiles}
    <section class="latest">
      <h2>Most recently added files</h2>
      <table>
        {#each latestFiles 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>
    </section>
  {/if}
</div>

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

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

    .file-added {
      opacity: 0.77;
      white-space: nowrap;
    }
  }
</style>
