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

  import { useNavigate, useLocation, useParams } from "svelte-navigator";
  import type { Writable } from "svelte/store";
  import type { Address, VALUE_TYPE } from "upend/types";
  const params = useParams();
  const location = useLocation();
  const navigate = useNavigate();

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

  const { index } = getContext("browse") as { index: Writable<number> };

  function onClick() {
    if ($location.pathname.startsWith("/browse") && to.entity) {
      let addresses = $params.addresses.split(",");

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

      navigate(routerTo);
      return true;
    }
  }
</script>

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

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