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

  import type { MastodonStatus } from '$lib/mastoapi/status';

  export let status: MastodonStatus;
  let node: HTMLElement;

  onMount(() => {
    for (let a of Array.from(node.getElementsByTagName('a'))) {
      const href = a.getAttribute('href');
      if (href == null) continue;

      if (a.classList.contains('hashtag')) {
        for (const tag of status.tags) {
          if (href === tag.url) {
            a.setAttribute('href', `/tags/${tag.name}`);
            a.removeAttribute('rel');
            a.removeAttribute('target');
          }
        }
      } else if (a.classList.contains('mention')) {
        for (const mention of status.mentions) {
          if (href === mention.url) {
            a.setAttribute('href', `/acc/${mention.id}`);
            a.setAttribute('title', `@${mention.acct}`);
            a.removeAttribute('rel');
            a.removeAttribute('target');
          }
        }
      } else if (new URL(href, window.location.href).origin != window.location.origin) {
        a.setAttribute('title', href);
        a.setAttribute('target', '_blank');
        a.setAttribute('rel', 'nofollow noopener external');
      }
    }
  });
</script>

<div class="foreign-content" bind:this={node}>
  {@html status.content}
</div>

<style>
  .foreign-content {
    display: contents;
  }
</style>
