---
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 TableOfContents from '@/components/TableOfContents.astro'
import { badgeVariants } from '@/lib/badge-variants'
import { buttonVariants } from '@/lib/button-variants'
import Layout from '@/layouts/Layout.astro'
import { getAdjacentPosts, getAllPosts } from '@/lib/data-utils'
import { formatDate, readingTime } from '@/lib/utils'
import { Icon } from 'astro-icon/components'
import { render } from 'astro:content'

export async function getStaticPaths() {
  const posts = await getAllPosts()
  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 { next, prev } = await getAdjacentPosts(currentPostId)

const structuredData = {
  '@context': 'https://schema.org',
  '@type': 'BlogPosting',
  headline: post.data.title,
  datePublished: post.data.date,
  dateModified: post.data.date,
  author: {
    '@type': 'Person',
    name: post.data.authors ? post.data.authors[0] : 'Author',
  },
  image: new URL(`/image/${post.id}.png`, Astro.site).toString(),
  keywords: post.data.tags ? post.data.tags.join(', ') : '',
  description: post.data.description || '',
}
const canonicalUrl = new URL(`/blog/${post.id}/`, Astro.site).toString();
---

<Layout canonicalUrl={canonicalUrl} isWide={true}>
  <PostHead slot="head" post={post} />

  <script
    type="application/ld+json"
    is:inline
    set:html={JSON.stringify(structuredData)}
  />

  <div class="grid grid-cols-1 xl:grid-cols-[1fr_minmax(0,60rem)_1fr] gap-4 xl:gap-6 xl:px-8">
    <!-- Header section - spans center column only on xl, full width otherwise -->
    <header class="xl:col-start-2 px-4 sm:px-6 lg:px-8 xl:px-0">
      <Breadcrumbs
        items={[
          { href: '/blog', label: 'Blog', icon: 'lucide:archive' },
          { label: post.data.title, icon: 'lucide:file-text' },
        ]}
      />

      <div class="mt-6 flex flex-col gap-y-6 text-start">
        <div class="flex flex-col">
          <h1
            class="mb-2 text-3xl leading-tight font-medium text-pretty sm:text-5xl"
          >
            {post.data.title}
          </h1>

          <div class="flex flex-wrap justify-start gap-2">
            {
              post.data.tags && post.data.tags.length > 0 ? (
                post.data.tags.map((tag) => (
                  <a
                    href={`/tags/${tag}`}
                    class={badgeVariants({ variant: 'secondary' })}
                  >
                    <Icon name="lucide:hash" class="size-3" />
                    {tag}
                  </a>
                ))
              ) : (
                <span class="text-muted-foreground text-sm">
                  No tags available
                </span>
              )
            }
          </div>
        </div>
      </div>

      <div class="mt-6 text-muted-foreground flex flex-wrap items-center justify-center gap-2 text-sm">
        <div class="flex items-center gap-2">
          <span>{formatDate(post.data.date)}</span>
          <div class="bg-border h-4 w-px shrink-0" role="separator" aria-orientation="vertical"></div>
          <span>{readingTime(post.body!)}</span>
          <div class="bg-border h-4 w-px shrink-0" role="separator" aria-orientation="vertical"></div>
          <span>By {(post.data.authors ?? []).join(' & ')}</span>
        </div>
      </div>
    </header>

    <!-- Left sidebar (TOC) -->
    {headings.length > 0 && (
      <aside class="hidden xl:block xl:col-start-1 xl:row-start-2 justify-self-end self-stretch">
        <nav class="sticky top-24 w-48">
          <TableOfContents headings={headings} />
        </nav>
      </aside>
    )}

    <!-- Main content -->
    <main class="xl:col-start-2 xl:row-start-2 flex flex-col gap-y-6 px-4 sm:px-6 lg:px-8 xl:px-0">
      <!-- Mobile TOC -->
      {headings.length > 0 && (
        <div class="xl:hidden">
          <TableOfContents headings={headings} />
        </div>
      )}

      <article class="prose max-w-none" aria-label="Blog post">
        <Content />
      </article>

      <!-- Mobile share/support section -->
      <div class="xl:hidden rounded-xl border p-4">
        <div class="mb-2">
          <h2 class="font-custom text-2xl font-bold text-neutral-900 dark:text-white">
            Share this post
          </h2>
          <p class="text-sm text-neutral-500 dark:text-neutral-400">
            If you found this post helpful, consider sharing it with your friends
            or on social media.
          </p>
        </div>

        <div class="flex flex-wrap gap-2">
          <a
            href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
            target="_blank"
            rel="noopener noreferrer"
            title="Share on Facebook"
            aria-label="Share on Facebook"
            class={buttonVariants({ variant: 'outline', size: 'icon' })}
          >
            <Icon name="line-md:facebook" class="size-4" />
          </a>
          <a
            href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
            target="_blank"
            rel="noopener noreferrer"
            title="Share on Twitter"
            aria-label="Share on Twitter"
            class={buttonVariants({ variant: 'outline', size: 'icon' })}
          >
            <Icon name="line-md:twitter" class="size-4" />
          </a>
          <a
            href={`https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
            target="_blank"
            rel="noopener noreferrer"
            title="Share on LinkedIn"
            aria-label="Share on LinkedIn"
            class={buttonVariants({ variant: 'outline', size: 'icon' })}
          >
            <Icon name="line-md:linkedin" class="size-4" />
          </a>
          <a
            href={`https://www.reddit.com/submit?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
            target="_blank"
            rel="noopener noreferrer"
            title="Share on Reddit"
            aria-label="Share on Reddit"
            class={buttonVariants({ variant: 'outline', size: 'icon' })}
          >
            <Icon name="line-md:reddit-loop" class="size-4" />
          </a>
          <a
            href={`https://wa.me/?text=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
            target="_blank"
            rel="noopener noreferrer"
            title="Share on WhatsApp"
            aria-label="Share on WhatsApp"
            class={buttonVariants({ variant: 'outline', size: 'icon' })}
          >
            <Icon name="mdi:whatsapp" class="size-4" />
          </a>
          <a
            href={`https://t.me/share/url?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
            target="_blank"
            rel="noopener noreferrer"
            title="Share on Telegram"
            aria-label="Share on Telegram"
            class={buttonVariants({ variant: 'outline', size: 'icon' })}
          >
            <Icon name="line-md:telegram" class="size-4" />
          </a>
          <a
            href={`https://pinterest.com/pin/create/button/?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
            target="_blank"
            rel="noopener noreferrer"
            title="Share on Pinterest"
            aria-label="Share on Pinterest"
            class={buttonVariants({ variant: 'outline', size: 'icon' })}
          >
            <Icon name="mdi:pinterest" class="size-4" />
          </a>
        </div>

        <hr class="my-8" />

        <div class="mb-2">
          <h2 class="font-custom text-2xl font-bold text-neutral-900 dark:text-white">
            Enjoyed this post?
          </h2>
          <div class="text-sm text-neutral-500 dark:text-neutral-400 flex flex-col gap-3">
            <div class="flex items-center flex-wrap gap-1">
              Subscribe to my&nbsp;
              <Link href="/rss.xml" target="_blank" rel="noopener noreferrer" class="text-primary underline flex items-center gap-1">
                RSS feed
                <Icon name="lucide:rss" class="size-4" />
              </Link>
              &nbsp;to stay updated with new posts.
            </div>
            <div class="flex items-center flex-wrap gap-1">
              Check out&nbsp;
              <Link href="/blog" class="text-primary underline flex items-center gap-1">
                more posts
                <Icon name="lucide:archive" class="size-4" />
              </Link>
              &nbsp;or explore my&nbsp;
              <Link href="/projects" class="text-primary underline flex items-center gap-1">
                projects
                <Icon name="lucide:folder" class="size-4" />
              </Link>
            </div>
          </div>
        </div>
      </div>

      <PostNavigation prevPost={prev} nextPost={next} />
    </main>

    <!-- Right sidebar (Share/Support) -->
    <aside class="hidden xl:block xl:col-start-3 xl:row-start-2 justify-self-start self-stretch">
      <div class="sticky top-24 w-48">
        <div class="flex flex-col gap-4 rounded-xl border bg-card p-4 shadow-md">
          <div>
            <h2 class="font-custom text-lg font-bold text-neutral-900 dark:text-white">
              Share this post
            </h2>
            <p class="text-xs text-neutral-500 dark:text-neutral-400">
              Share with friends or on social media.
            </p>
          </div>

          <div class="flex flex-wrap gap-2">
            <a
              href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
              target="_blank"
              rel="noopener noreferrer"
              title="Share on Facebook"
              aria-label="Share on Facebook"
              class={buttonVariants({ variant: 'outline', size: 'icon' })}
            >
              <Icon name="line-md:facebook" class="size-4" />
            </a>
            <a
              href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
              target="_blank"
              rel="noopener noreferrer"
              title="Share on Twitter"
              aria-label="Share on Twitter"
              class={buttonVariants({ variant: 'outline', size: 'icon' })}
            >
              <Icon name="line-md:twitter" class="size-4" />
            </a>
            <a
              href={`https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
              target="_blank"
              rel="noopener noreferrer"
              title="Share on LinkedIn"
              aria-label="Share on LinkedIn"
              class={buttonVariants({ variant: 'outline', size: 'icon' })}
            >
              <Icon name="line-md:linkedin" class="size-4" />
            </a>
            <a
              href={`https://www.reddit.com/submit?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
              target="_blank"
              rel="noopener noreferrer"
              title="Share on Reddit"
              aria-label="Share on Reddit"
              class={buttonVariants({ variant: 'outline', size: 'icon' })}
            >
              <Icon name="line-md:reddit-loop" class="size-4" />
            </a>
            <a
              href={`https://wa.me/?text=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
              target="_blank"
              rel="noopener noreferrer"
              title="Share on WhatsApp"
              aria-label="Share on WhatsApp"
              class={buttonVariants({ variant: 'outline', size: 'icon' })}
            >
              <Icon name="mdi:whatsapp" class="size-4" />
            </a>
            <a
              href={`https://t.me/share/url?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
              target="_blank"
              rel="noopener noreferrer"
              title="Share on Telegram"
              aria-label="Share on Telegram"
              class={buttonVariants({ variant: 'outline', size: 'icon' })}
            >
              <Icon name="line-md:telegram" class="size-4" />
            </a>
            <a
              href={`https://pinterest.com/pin/create/button/?url=${encodeURIComponent(Astro.site + 'blog/' + post.id)}`}
              target="_blank"
              rel="noopener noreferrer"
              title="Share on Pinterest"
              aria-label="Share on Pinterest"
              class={buttonVariants({ variant: 'outline', size: 'icon' })}
            >
              <Icon name="mdi:pinterest" class="size-4" />
            </a>
          </div>

          <hr class="my-2 border-t" />

          <div>
            <h2 class="font-custom text-lg font-bold text-neutral-900 dark:text-white mb-2">
              Enjoyed this post?
            </h2>
            <div class="text-xs text-neutral-500 dark:text-neutral-400 flex flex-col gap-2">
              <Link href="/rss.xml" target="_blank" rel="noopener noreferrer" class="text-primary underline flex items-center gap-1 hover:text-primary/80 transition-colors">
                <Icon name="lucide:rss" class="size-3" />
                Subscribe to RSS
              </Link>
              <Link href="/blog" class="text-primary underline flex items-center gap-1 hover:text-primary/80 transition-colors">
                <Icon name="lucide:archive" class="size-3" />
                More posts
              </Link>
              <Link href="/projects" class="text-primary underline flex items-center gap-1 hover:text-primary/80 transition-colors">
                <Icon name="lucide:folder" class="size-3" />
                Explore projects
              </Link>
            </div>
          </div>
        </div>
      </div>
    </aside>
  </div>

  <button
    class={buttonVariants({ variant: 'outline', size: 'icon' }) + ' 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>
