<script lang="ts">
  import EntryList from "../components/widgets/EntryList.svelte";
  import Gallery from "../components/widgets/Gallery.svelte";
  import type { Widget } from "src/lib/types";
  import { Link } from "svelte-navigator";
  import { UpListing } from "upend";
  import AttributeView from "../components/AttributeView.svelte";
  import UpObjectCard from "../components/display/UpObjectCard.svelte";
  import Spinner from "../components/utils/Spinner.svelte";
  import api from "../lib/api";
  import { query } from "../lib/entity";
  import { vaultInfo } from "../util/info";
  import { updateTitle } from "../util/title";
  import { i18n } from "../i18n";

  const roots = (async () => {
    const data = await api.fetchRoots();
    const listing = new UpListing(data);
    return Object.values(listing.objects)
      .filter((obj) => Boolean(obj.attr["LBL"]))
      .map((obj) => [obj.address, obj.identify().join(" | ")])
      .sort(([_, i1], [__, i2]) => i1.localeCompare(i2));
  })();

  const { result: recentQuery } = query(`(matches ? "LAST_VISITED" ?)`);
  $: recent = ($recentQuery?.entries || [])
    .filter((e) => e.value.t == "Number")
    .sort((a, b) => (b.value.c as number) - (a.value.c as number))
    .slice(0, 25);

  const { result: frequentQuery } = query(`(matches ? "NUM_VISITED" ?)`);
  $: frequent = ($frequentQuery?.entries || [])
    .filter((e) => e.value.t == "Number")
    .sort((a, b) => (b.value.c as number) - (a.value.c as number))
    .slice(0, 25);

  const { result: latestQuery } = query(`(matches ? "ADDED" ?)`);
  $: latest = ($latestQuery?.entries || [])
    .filter((e) => e.value.t == "Number")
    .sort((a, b) => (b.value.c as number) - (a.value.c as number))
    .slice(0, 25);

  const shortWidgets: Widget[] = [
    {
      name: "list-table",
      icon: "list-ul",
      components: [
        {
          component: EntryList,
          props: {
            columns: "value, entity",
            columnWidths: ["6em"],
            orderByValue: true,
            header: false,
          },
        },
      ],
    },
    {
      name: "gallery-view",
      icon: "image",
      components: [
        {
          component: Gallery,
          props: (entries) => {
            return {
              entities: entries.map((e) => e.entity),
              sort: false,
            };
          },
        },
      ],
    },
  ];

  const longWidgets: Widget[] = [
    {
      name: "list-table",
      icon: "list-ul",
      components: [
        {
          component: EntryList,
          props: {
            columns: "value, entity",
            columnWidths: ["13em"],
            orderByValue: true,
            header: false,
          },
        },
      ],
    },
    {
      name: "gallery-view",
      icon: "image",
      components: [
        {
          component: Gallery,
          props: (entries) => {
            return {
              entities: entries.map((e) => e.entity),
              sort: false,
            };
          },
        },
      ],
    },
  ];

  updateTitle("Home");
</script>

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

  <section class="roots">
    <h2>{$i18n.t("Roots")}</h2>
    {#await roots}
      <Spinner centered />
    {:then data}
      <ul>
        {#each data as [address, _]}
          <li class="root">
            <UpObjectCard {address} />
          </li>
        {:else}
          <li>No roots :(</li>
        {/each}
      </ul>
    {/await}
  </section>

  <div class="frecent">
    {#if frequent.length || $frequentQuery === undefined}
      <section class="frequent">
        <h2>{$i18n.t("Frequently visited")}</h2>
        {#if $frequentQuery == undefined}
          <Spinner centered />
        {:else}
          <AttributeView
            --current-background="var(--background)"
            entries={frequent}
            widgets={shortWidgets}
          />
        {/if}
      </section>
    {/if}
    {#if recent.length || $recentQuery === undefined}
      <section class="recent">
        <h2>{$i18n.t("Recently visited")}</h2>
        {#if $recentQuery == undefined}
          <Spinner centered />
        {:else}
          <AttributeView
            --current-background="var(--background)"
            entries={recent}
            widgets={longWidgets}
          />
        {/if}
      </section>
    {/if}
  </div>

  {#if latest.length || $latestQuery === undefined}
    <section class="latest">
      <h2>{$i18n.t("Most recently added")}</h2>
      {#if $latestQuery == undefined}
        <Spinner centered />
      {:else}
        <AttributeView
          --current-background="var(--background)"
          entries={latest}
          widgets={longWidgets}
        />
      {/if}
    </section>
  {/if}

  <div class="button store-button">
    <Link to="/store">{$i18n.t("View store statistics")}</Link>
  </div>

  <footer>
    <div>
      <strong>UpEnd</strong> - {$i18n.t(
        "a database for the complex, the changing, and the indeterminate"
      )}
    </div>
    <div>
      <!-- svelte-ignore security-anchor-rel-noreferrer -->
      <a target="_blank" href="https://upend.dev">
        v{$vaultInfo?.version || "???"}
      </a>
    </div>
  </footer>
</div>

<style lang="scss">
  .home {
    display: flex;
    flex-direction: column;
  }

  h1 {
    font-size: 32pt;
    font-variant: small-caps;
  }

  h2:first-of-type {
    margin-top: 0;
  }

  h1,
  h2 {
    text-align: center;
  }

  .latest,
  .frecent {
    margin: 2rem;
  }

  .frecent {
    display: flex;
    gap: 2rem;
    & > * {
      flex-basis: 50%;
    }
  }

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

    .root {
      font-size: 24px;
    }
  }

  footer {
    border-top: 1px solid var(--foreground);
    text-align: center;
    margin: 3em 3em 1em 3em;
    & > * {
      margin: 0.5em;
    }
  }

  .store-button {
    display: inline-block;
    padding: 1em;
    margin: auto;
  }
</style>
