<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import { identify, useEntity } from "../lib/entity";
  import HashBadge from "./HashBadge.svelte";
  import Marquee from "./Marquee.svelte";
  import UpLink from "./UpLink.svelte";
  const dispatch = createEventDispatcher();

  export let address: string;
  export let link = false;
  export let isFile = false;
  export let resolve = true;

  let resolving = resolve;

  // Identification
  let inferredIds: string[] = [];
  const { attributes, backlinks } = useEntity(address, () => resolve);
  $: {
    if (resolve) {
      resolving = true;
      identify($attributes, $backlinks).then((inferredEntries) => {
        inferredIds = inferredEntries.map((eid) => eid.value);
        resolving = false;
      });
    }
  }

  $: dispatch("resolved", inferredIds);
</script>

<div class="address" class:identified={Boolean(inferredIds)}>
  <HashBadge {address} />
  <div class="separator" />
  <Marquee>
    <div class="label" class:resolving>
      {#if isFile}
        <UpLink to={{ entity: address }}>
          {address}
        </UpLink>
      {:else if link}
        <UpLink to={{ entity: address }}>
          {inferredIds.join(" | ") || address}
        </UpLink>
      {:else}
        {inferredIds.join(" | ") || address}
      {/if}
    </div>
  </Marquee>
</div>

<style scoped lang="scss">
  .address {
    display: flex;
    align-items: center;

    padding: 0.1em;

    border: 0.1em solid var(--foreground);
    border-radius: 0.2em;

    font-family: var(--monospace-font);
    line-break: anywhere;

    &.identified {
      font-family: var(--default-font);
      font-size: 0.95em;
      line-break: auto;
    }
  }

  .separator {
    width: 0.5em;
  }

  .resolving {
    opacity: 0.7;
  }
</style>
