---
import Breadcrumbs from '@/components/Breadcrumbs.astro'
import Link from '@/components/Link.astro'
import PostHead from '@/components/PostHead.astro'
import PostNavigation from '@/components/PostNavigation.astro'
import SubpostsHeader from '@/components/SubpostsHeader.astro'
import SubpostsSidebar from '@/components/SubpostsSidebar.astro'
import TOCHeader from '@/components/TOCHeader.astro'
import TOCSidebar from '@/components/TOCSidebar.astro'
import { badgeVariants } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Ratings } from '@/components/ui/rating'
import { Separator } from '@/components/ui/separator'
import Layout from '@/layouts/Layout.astro'
import {
  getAdjacentPosts,
  getAllPostsAndSubposts,
  getParentId,
  getParentPost,
  getPostReadingTime,
  getSubpostCount,
  hasSubposts,
  isSubpost,
  parseAuthors,
} from '@/lib/data-utils'
import { getReleaseData } from '@/lib/discogs'
import { formatDate } from '@/lib/utils'
import { Icon } from 'astro-icon/components'
import { Image } from 'astro:assets'
import { render } from 'astro:content'

export const prerender = true

export async function getStaticPaths() {
  const posts = await getAllPostsAndSubposts()
  return posts.map((post) => ({
    params: { id: post.id },
    props: post,
  }))
}

const post = Astro.props
const currentPostId = Astro.params.id
const { Content, headings } = await render(post)
const authors = await parseAuthors(post.data.authors ?? [])

const isCurrentSubpost = isSubpost(currentPostId)
const navigation = await getAdjacentPosts(currentPostId)
const parentPost = isCurrentSubpost ? await getParentPost(currentPostId) : null

const hasChildPosts = await hasSubposts(currentPostId)
const subpostCount = !isCurrentSubpost
  ? await getSubpostCount(currentPostId)
  : 0
const postReadingTime = await getPostReadingTime(currentPostId)
const rating = post.data.tags?.find((tag) => tag.startsWith('rating-'))
const discogs = post.data.discogs
  ? await getReleaseData(post.data.discogs)
  : null
---

<Layout>
  <PostHead slot="head" post={post} />
  {
    (hasChildPosts || isCurrentSubpost) && (
      <SubpostsHeader
        slot="subposts-navigation"
        parentId={isCurrentSubpost ? getParentId(currentPostId) : currentPostId}
      />
    )
  }
  {
    headings?.length > 0 && (
      <TOCHeader slot="table-of-contents" headings={headings} />
    )
  }

  <section
    class="relative left-[calc(50%-50vw)] grid w-screen grid-cols-[minmax(0px,1fr)_min(calc(var(--breakpoint-md)-2rem),100%)_minmax(0px,1fr)] gap-y-6 px-4"
  >
    <div class="col-start-2">
      <Breadcrumbs
        items={[
          { href: '/blog', label: 'Blog', icon: 'lucide:library-big' },
          ...(isCurrentSubpost && parentPost
            ? [
                {
                  href: `/blog/${parentPost.id}`,
                  label: parentPost.data.title,
                  icon: 'lucide:book-open',
                },
                {
                  href: `/blog/${currentPostId}`,
                  label: post.data.title,
                  icon: 'lucide:file-text',
                },
              ]
            : [
                {
                  href: `/blog/${currentPostId}`,
                  label: post.data.title,
                  icon: 'lucide:book-open-text',
                },
              ]),
        ]}
      />
    </div>

    {
      post.data.image ||
        (discogs && discogs.images[0]?.resource_url && (
          <Image
            src={post.data.image || discogs.images[0].resource_url}
            alt={post.data.title}
            width={1200}
            height={630}
            class="col-span-full mx-auto max-h-96 w-full max-w-4xl rounded-lg object-contain"
          />
        ))
    }

    <section class="col-start-2 flex flex-col gap-y-6 text-center">
      <div class="flex flex-col">
        <h1
          class="mb-2 scroll-mt-31 text-4xl leading-tight font-medium text-pretty"
          id="post-title"
        >
          {post.data.title}
        </h1>

        <div
          class="text-muted-foreground mb-4 flex flex-wrap items-center justify-center gap-2 text-sm"
        >
          {
            authors.length > 0 && (
              <>
                <div class="flex items-center gap-x-2">
                  {authors.map((author) => (
                    <div class="flex items-center gap-x-1.5">
                      <Image
                        src={author.avatar}
                        alt={author.name}
                        width={24}
                        height={24}
                        class="rounded-full"
                      />
                      {author.isRegistered ? (
                        <Link
                          href={`/authors/${author.id}`}
                          underline
                          class="text-foreground"
                        >
                          <span>{author.name}</span>
                        </Link>
                      ) : (
                        <span>{author.name}</span>
                      )}
                    </div>
                  ))}
                </div>
                <Separator orientation="vertical" className="h-4!" />
              </>
            )
          }
          <div class="flex items-center gap-2">
            <span>{formatDate(post.data.date)}</span>
            <Separator orientation="vertical" className="h-4!" />
            <span>{postReadingTime}</span>
            {
              subpostCount > 0 && (
                <>
                  {' '}
                  <Separator orientation="vertical" className="h-4!" />{' '}
                  <span class="flex items-center gap-1">
                    {' '}
                    <Icon name="lucide:file-text" class="size-3" />{' '}
                    {subpostCount} subpost{subpostCount === 1 ? '' : 's'}{' '}
                  </span>{' '}
                </>
              )
            }
          </div>
        </div>

        <div class="flex flex-wrap justify-center gap-2">
          {rating && (
            <Ratings rating={parseFloat(rating.replace('rating-', ''))} size={15} />
          )}
          {
            post.data.tags && post.data.tags.length > 0 ? (
              post.data.tags.map((tag) => {
                if (tag.startsWith('rating-')) return null;
                return (
                  <div>
                    <a
                      href={`/tags/${tag}`}
                      class={badgeVariants({ variant: 'secondary' })}
                    >
                      <Icon name="lucide:hash" class="size-3" />
                      {tag}
                    </a>
                  </div>
                )
              })
            ) : (
              <span class="text-muted-foreground text-sm">
                No tags available
              </span>
            )
          }
        </div>
      </div>

      <PostNavigation
        newerPost={navigation.newer}
        olderPost={navigation.older}
        parentPost={isCurrentSubpost ? navigation.parent : undefined}
      />
    </section>

    {headings.length > 0 && <TOCSidebar headings={headings} />}

    <article class="prose col-start-2 max-w-none">
      <Content />
    </article>

    {
      (hasChildPosts || isCurrentSubpost) && (
        <SubpostsSidebar
          parentId={
            isCurrentSubpost ? getParentId(currentPostId) : currentPostId
          }
          className="w-64"
        />
      )
    }

    <PostNavigation
      newerPost={navigation.newer}
      olderPost={navigation.older}
      parentPost={isCurrentSubpost ? navigation.parent : undefined}
    />
  </section>

  <Button
    variant="outline"
    size="icon"
    className="group fixed right-8 bottom-8 z-50 hidden"
    id="scroll-to-top"
    title="Scroll to top"
    aria-label="Scroll to top"
  >
    <Icon
      name="lucide:arrow-up"
      class="mx-auto size-4 transition-all group-hover:-translate-y-0.5"
    />
  </Button>

  <script>
    document.addEventListener('astro:page-load', () => {
      const scrollToTopButton = document.getElementById('scroll-to-top')
      const footer = document.querySelector('footer')

      if (scrollToTopButton && footer) {
        scrollToTopButton.addEventListener('click', () => {
          window.scrollTo({ top: 0, behavior: 'smooth' })
        })

        window.addEventListener('scroll', () => {
          const footerRect = footer.getBoundingClientRect()
          const isFooterVisible = footerRect.top <= window.innerHeight

          scrollToTopButton.classList.toggle(
            'hidden',
            window.scrollY <= 300 || isFooterVisible
          )
        })
      }
    })
  </script>
</Layout>
