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

  import { useNavigate, useLocation, useParams } from "svelte-navigator";
  import { readable, 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 context = getContext("browse") as
    | { index: Writable<number> }
    | undefined;

  const index = context ? context.index : readable(0);

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

        const routerTo =
          "/browse/" +
          addresses
            .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>
