<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";
  import api from "../../lib/api";
  const location = useLocation();
  const navigate = useNavigate();

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

  const NOOP = "#";
  let targetHref = NOOP;
  $: {
    if (to.entity) {
      targetHref = to.entity;
    } else if (to.attribute) {
      api.getAddress({ attribute: to.attribute }).then((address) => {
        targetHref = address;
      });
    }
  }

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

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

      const routerTo =
        "/browse/" +
        (ev.shiftKey ? newAddresses : newAddresses.slice(0, $index + 1))
          .concat([targetHref])
          .join(",");

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

<a
  class="uplink"
  class:passthrough
  class:unresolved={targetHref === NOOP}
  href="/#/browse/{targetHref}"
  on:click|preventDefault={onClick}
>
  <slot />
</a>

<style lang="scss">
  :global(.uplink) {
    text-decoration: none;
  }
  :global(.uplink.passthrough) {
    display: contents;
  }
  :global(.uplink.unresolved) {
    pointer-events: none;
  }
</style>
