<template>
  <div :class="['address', { identified: Boolean(inferredIds) }]" ref="root">
    <hash-badge :address="address" class="hash-badge" />
    <up-link v-if="isFile" :to="{ entity: address }">
      {{ address }}
    </up-link>
    <template v-else>
      <up-link v-if="link" :to="{ entity: address }">
        {{ inferredIds.join(" | ") || address }}
      </up-link>
      <template v-else>
        {{ inferredIds.join(" | ") || address }}
      </template>
    </template>
  </div>
</template>

<script lang="ts">
import { identify, useEntity } from "@/lib/entity";
import {
  computed,
  ComputedRef,
  defineComponent,
  onMounted,
  ref,
} from "vue";
import HashBadge from "./HashBadge.vue";
import UpLink from "./UpLink.vue";

export default defineComponent({
  components: { HashBadge, UpLink },
  name: "Address",
  props: {
    address: {
      type: String,
      required: true,
    },
    link: {
      type: Boolean,
      default: false,
    },
    isFile: {
      type: Boolean,
      default: false,
    },
    resolve: {
      type: Boolean,
      default: true,
    },
  },
  setup(props) {
    // Enable IntersectionObserver for performance reasons
    const rootEl = ref<HTMLElement | undefined>();
    const visible = ref(false);
    const observer = new IntersectionObserver((entries) => {
      visible.value = entries.some((entry) => entry.isIntersecting);
    });
    onMounted(() => {
      if (rootEl.value) {
        observer.observe(rootEl.value);
      }
    });

    // Identification
    const { attributes } = useEntity(props.address, () => visible.value);
    const inferredEntries = identify(attributes);
    const inferredIds: ComputedRef<string[]> = computed(() => {
      return inferredEntries.value.map((eid) => eid.value);
    });

    return {
      root: rootEl,
      inferredIds,
    };
  },
});
</script>

<style scoped>
.address {
  font-family: var(--monospace-font);
  display: flex;
  align-items: center;
}

.address,
.address a {
  line-break: anywhere;
}

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

.hash-badge {
  margin-right: 0.5em;
}
</style>
