---
import { type CollectionEntry, getCollection, render } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';
import Button from '../../components/Button.astro';
import FormattedDate from '../../components/FormattedDate.astro';
import PostPreview from '../../components/PostPreview.astro';
import Subscribe from '../../components/Subscribe.astro';
import { sortItemsByDateDesc } from '../../utils/data-utils';
import { slugify } from '../../utils/common-utils';

export async function getStaticPaths() {
    const posts = (await getCollection('blog')).sort(sortItemsByDateDesc);
    const postCount = posts.length;
    return posts.map((post, index) => ({
        params: { id: post.id },
        props: {
            post,
            prevPost: index + 1 !== postCount ? posts[index + 1] : null,
            nextPost: index !== 0 ? posts[index - 1] : null
        }
    }));
}

type Props = { post: CollectionEntry<'blog'>; prevPost: CollectionEntry<'blog'>; nextPost: CollectionEntry<'blog'> };

const { href } = Astro.url;
const { post, prevPost, nextPost } = Astro.props;
const { title, publishDate, updatedDate, excerpt, tags = [], seo } = post.data;
const { Content } = await render(post);
---

<BaseLayout title={seo?.title ?? title} description={seo?.description ?? excerpt} image={seo?.image} pageType="article" showHeader={false}>
    <article class="mb-16 sm:mb-24">
        <header class="mb-8">
            <h1 class="text-3xl leading-tight font-serif font-medium sm:text-5xl sm:leading-tight">{title}</h1>
            <div class="mt-4 text-sm">
                <FormattedDate date={publishDate} />
                {
                    updatedDate && (
                        <>
                            {' '}
                            <span>
                                (Updated on <FormattedDate date={updatedDate} />)
                            </span>
                        </>
                    )
                }
            </div>
        </header>
        <div class="max-w-none prose sm:prose-lg">
            <Content />
        </div>
        <div class="mt-8 flex flex-wrap items-center gap-6 text-sm justify-between sm:mt-12 sm:text-base">
            {
                tags.length > 0 && (
                    <div class="flex flex-wrap gap-x-5 gap-y-1 text-sm">
                        {tags.map((tag) => (
                            <a class="text-main hover:underline" href={`/tags/${slugify(tag)}`}>
                                #{tag}
                            </a>
                        ))}
                    </div>
                )
            }
            <Button class="copy-url-button" aria-label="Copy link" data-url={href} data-tooltip-default="Copy link" data-tooltip-success="Copied">Share</Button>
        </div>
    </article>
    {
        (prevPost || nextPost) && (
            <div class="my-16 sm:my-24">
                <h2 class="mb-12 text-xl font-serif italic sm:mb-16 sm:text-2xl">Read Next</h2>
                {nextPost && <PostPreview post={nextPost} class="mb-10 sm:mb-12" headingLevel="h3" />}
                {prevPost && <PostPreview post={prevPost} class="mb-10 sm:mb-12" headingLevel="h3" />}
            </div>
        )
    }
    <Subscribe class="my-16 sm:my-24" />
</BaseLayout>

<script>
    document.addEventListener('astro:page-load', () => {
        const copyUrlButton = document.querySelector('.copy-url-button') as HTMLButtonElement;
        copyUrlButton?.addEventListener('click', async () => {
            await copyUrl(copyUrlButton);
        });

        async function copyUrl(button: HTMLButtonElement) {
            let url = button.getAttribute('data-url') || '';
            let label = button.innerText;

            await navigator.clipboard.writeText(url);

            button.innerText = 'Copied';

            setTimeout(() => {
                button.innerText = label;
            }, 2500);
        }
    });
</script>
