---
import arrow from '../../images/icon-arrow-link.svg'
import { getPostLink } from '../../lib/blog-helpers.ts'
import type { Post } from '../../lib/interfaces.ts'
import { getPostByPageId } from '../../lib/notion/client'
import '../../styles/notion-color.css'

export interface Props {
  pageId: string
}

const { pageId } = Astro.props

let post: Post | null = null
if (pageId) {
  post = await getPostByPageId(pageId)
}
---

{
  post ? (
    <a href={getPostLink(post.Slug)} class="link">
      <>
        <span class="icon">
          {post.Icon && post.Icon.Type === 'emoji' ? (
            post.Icon.Emoji
          ) : post.Icon && post.Icon.Type === 'external' ? (
            <img
              src={post.Icon.Url}
              class="notion-icon"
              alt="Post title icon in a page link"
            />
          ) : (
            '📄'
          )}
          <img
            src={arrow.src}
            class="icon-link"
            alt="Arrow icon of a page link"
          />
        </span>
        <span class="text">{post.Title}</span>
      </>
    </a>
  ) : (
    <a class="link">
      <span class="icon">
        🚫
        <img
          src={arrow.src}
          class="icon-link"
          alt="Arrow icon of a page link"
        />
      </span>
      <span class="text not-found">Post not found</span>
    </a>
  )
}

<style>
  a.link {
    display: inline-flex;
    font-weight: 600;
    gap: 4px;
  }
  span.icon {
    height: fit-content;
    flex-shrink: 0;
    position: relative;
  }
  span.icon img.notion-icon {
    width: 1.3em;
    height: 1.3rem;
    vertical-align: sub;
    flex-shrink: 0;
    position: relative;
  }
  span.icon img.icon-link {
    display: block;
    position: absolute;
    top: 1em;
    right: 0;
    width: 8px;
    height: 8px;
  }
  span.text {
    color: var(--fg);
    font-weight: 500;
    text-decoration: underline;
  }
  span.text.not-found {
    font-weight: normal;
    text-decoration: none;
  }
</style>
