<script lang="ts">
  import { getContext } from "svelte";

  import { useNavigate, useLocation } from "svelte-navigator";
  import { readable } from "svelte/store";
  import type { Address, VALUE_TYPE } from "upend/types";
  import type { BrowseContext } from "../../util/browse";
  const location = useLocation();
  const navigate = useNavigate();

  export let to: {
    entity?: Address;
    attribute?: string;
    value?: { t: VALUE_TYPE; c: string };
  };

  const context = getContext("browse") as BrowseContext | undefined;
  const index = context ? context.index : readable(0);
  const addresses = context ? context.addresses : readable([]);

  function onClick() {
    if (to.entity) {
      if ($location.pathname.startsWith("/browse")) {
        let newAddresses = $addresses.concat();

        const routerTo =
          "/browse/" +
          newAddresses
            .slice(0, $index + 1)
            .concat([to.entity])
            .join(",");

        navigate(routerTo);
        return true;
      } else {
        navigate(`/browse/${to.entity}`);
      }
    }
  }
</script>

<a
  class="uplink"
  href="/#/browse/{to.entity}"
  on:click|preventDefault={onClick}
>
  <slot />
</a>

<style lang="scss">
  :global(.uplink) {
    text-decoration: none;
  }
</style>
