<script lang="ts">
  import type { Post } from '$lib/mastodon/response';
  import AvatarComponent from '$lib/components/AvatarComponent.svelte';
  import AccountComponent from '$lib/components/AccountComponent.svelte';
  import { secondsSince, relativeTime } from '$lib/relativeTime';
  import { onMount } from 'svelte';

  export let post: Post;
  let displayRelativeTime = false;
  const absoluteDate = new Date(post.created_at).toLocaleString();
  let dateCreated = absoluteDate;
  const timePassed = secondsSince(new Date(post.created_at));
  $: if (displayRelativeTime) {
    dateCreated = relativeTime($timePassed) ?? absoluteDate;
  }

  onMount(() => {
    // Display relative time only after mount:
    // When JS is disabled the server-side rendered absolute date will be shown,
    // otherwise the relative date would be outdated very quickly
    displayRelativeTime = true;
  });
</script>

<div class="wrapper">
  <div class="avatar"><AvatarComponent account={post.account} /></div>
  <div class="post">
    <div class="meta">
      <AccountComponent account={post.account} />
      <small><a href={post.url} target="_blank" title={absoluteDate}>{dateCreated}</a></small>
    </div>
    <div class="content">{@html post.content}</div>
  </div>
</div>

<style>
  .wrapper {
    display: flex;
  }
  .post {
    display: flex;
    flex-direction: column;
    flex-grow: 2;
    word-break: break-word;
  }
  .meta {
    display: flex;
    justify-content: space-between;
  }
  .avatar {
    margin-right: 1em;
  }
  .content {
    max-width: calc(600px - 1em - 50px);
    overflow-x: auto;
  }
</style>
