---
import { Image } from "astro:assets";
import { getCollection, render } from "astro:content";
import BlogPostSeries from "@/components/BlogPostSeries.astro";
import JsonLd from "@/components/JsonLd.astro";
import TableOfContents from "@/components/TableOfContents.astro";
import WebMentions from "@/components/WebMentions.astro";
import BaseLayout from "@/layouts/BaseLayout.astro";
export async function getStaticPaths() {
  const posts = (await getCollection("blog", ({ data }) => !data.draft)).sort(
    (a, b) => a.data.publishDate.valueOf() - b.data.publishDate.valueOf(),
  );
  return posts.map((post, i) => {
    const prev = posts[i - 1];
    const next = posts[i + 1];
    return {
      params: { slug: post.id },
      props: {
        post,
        prevPost: prev ? { id: prev.id, title: prev.data.title } : null,
        nextPost: next ? { id: next.id, title: next.data.title } : null,
      },
    };
  });
}

const { post, prevPost, nextPost } = Astro.props;
const { Content, headings } = await render(post);
const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
function capitalize(s: string) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

const allPosts = await getCollection("blog");
const seriesChildren = allPosts
  .filter((a) => a.data.seriesParent === post.id && !a.data.draft)
  .sort((a, b) => (a.data.seriesOrder ?? 99) - (b.data.seriesOrder ?? 99));

// For child posts: find parent + siblings
const seriesParentPost = post.data.seriesParent
  ? allPosts.find((a) => a.id === post.data.seriesParent)
  : undefined;
const seriesSiblings = seriesParentPost
  ? allPosts
      .filter(
        (a) => a.data.seriesParent === seriesParentPost.id && !a.data.draft,
      )
      .sort((a, b) => (a.data.seriesOrder ?? 99) - (b.data.seriesOrder ?? 99))
  : [];

// Series data for sidebar + bottom block
const hasSeries = seriesChildren.length > 0 || seriesSiblings.length > 0;

function formatDate(date: Date) {
  return date.toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}

const ogImageUrl = new URL(`/og/blog/${post.id}.png`, Astro.site).toString();
const postUrl = new URL(`/blog/${post.id}/`, Astro.site).toString();
const postSchema = {
  "@context": "https://schema.org",
  "@type": "Article",
  headline: post.data.title,
  description: post.data.description,
  datePublished: post.data.publishDate.toISOString(),
  image: ogImageUrl,
  url: postUrl,
  author: {
    "@type": "Person",
    name: "Adrian Altner",
    url: "https://adrian-altner.com",
  },
};
---

<BaseLayout
  title={post.data.title}
  description={post.data.description}
  image={{ src: ogImageUrl, alt: post.data.title }}
>
  <JsonLd schema={postSchema} slot="head" />
  <div class="page">
    <div class="main">
      <a href="/blog" class="back">← Back to Blog</a>
      <div class="content">
        <article class="h-entry">
          <a
            href={postUrl}
            class="u-url"
            aria-hidden="true"
            tabindex="-1"
            style="display:none">Permalink</a
          >
          <span class="p-author h-card" style="display:none"
            ><img
              class="u-photo"
              src="https://adrian-altner.com/avatar.jpg"
              alt="Adrian Altner"
            /><span class="p-name">Adrian Altner</span><a
              class="u-url"
              href="https://adrian-altner.com">adrian-altner.com</a
            ></span
          >
          <header class="post-header">
            <h1 class="post-title p-name">{post.data.title}</h1>
            <div class="post-meta">
              <time
                class="dt-published"
                datetime={post.data.publishDate.toISOString()}
              >
                {formatDate(post.data.publishDate)}
              </time>
              {
                post.data.tags.length > 0 && (
                  <div class="post-tags">
                    {post.data.tags.map((tag) => (
                      <a href={`/tags/${tag}`} class="tag">
                        {capitalize(tag)}
                      </a>
                    ))}
                  </div>
                )
              }
            </div>
          </header>
          {post.data.cover && (
            <Image class="post-cover" src={post.data.cover} alt={post.data.coverAlt ?? ""} />
          )}
          <div class="prose e-content">
            <Content />
          </div>
          {
            seriesChildren.length > 0 && (
              <BlogPostSeries
                children={seriesChildren}
                currentId={post.id}
                parent={post}
              />
            )
          }
          {
            seriesParentPost && seriesSiblings.length > 0 && (
              <BlogPostSeries
                children={seriesSiblings}
                currentId={post.id}
                parent={seriesParentPost}
              />
            )
          }
          <WebMentions url={postUrl} />
        </article>
        {
          (tocHeadings.length > 1 || hasSeries) && (
            <aside class="toc-sidebar">
              {tocHeadings.length > 1 && (
                <TableOfContents headings={tocHeadings} />
              )}
              {seriesChildren.length > 0 && (
                <BlogPostSeries
                  children={seriesChildren}
                  currentId={post.id}
                  parent={post}
                  sidebar={true}
                />
              )}
              {seriesParentPost && seriesSiblings.length > 0 && (
                <BlogPostSeries
                  children={seriesSiblings}
                  currentId={post.id}
                  parent={seriesParentPost}
                  sidebar={true}
                />
              )}
            </aside>
          )
        }
      </div>
      {
        (prevPost || nextPost) && (
          <nav class="post-pagination" aria-label="Post navigation">
            <div class="pagination-prev">
              {nextPost && (
                <a href={`/blog/${nextPost.id}`} class="pagination-link">
                  <span class="pagination-label">← Newer</span>
                  <span class="pagination-title">{nextPost.title}</span>
                </a>
              )}
            </div>
            <div class="pagination-next">
              {prevPost && (
                <a
                  href={`/blog/${prevPost.id}`}
                  class="pagination-link pagination-link--next"
                >
                  <span class="pagination-label">Older →</span>
                  <span class="pagination-title">{prevPost.title}</span>
                </a>
              )}
            </div>
          </nav>
        )
      }
      <a href="/blog" class="back">← Back to Blog</a>
    </div>
  </div>
</BaseLayout>

<style>
  .page {
    display: grid;
    grid-template-rows: auto 1fr auto;
    min-height: 100dvh;
    background: #f5f5f3;
    color: #111;
  }

  .main {
    max-width: var(--width-content);
    margin: 0 auto;
    padding: 2rem 2rem 4rem;
    width: 100%;
  }

  .content {
    display: grid;
    grid-template-columns: 1fr var(--width-sidebar-toc);
    gap: 3rem;
    align-items: start;
  }

  .toc-sidebar {
    min-width: 0;
    position: sticky;
    top: 2rem;
    max-height: calc(100vh - 4rem);
    overflow-y: auto;
  }

  @media (max-width: 900px) {
    .content {
      grid-template-columns: 1fr;
    }

    .toc-sidebar {
      display: none;
    }
  }

  article {
    min-width: 0;
    max-width: var(--width-prose);
  }

  .post-header {
    margin-bottom: 2.5rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid #e0e0de;
  }

  .post-title {
    font-weight: 400;
    letter-spacing: -0.02em;
    margin-bottom: 0.75rem;
  }

  .post-meta {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex-wrap: wrap;
  }

  .post-meta time {
    font-size: 0.875rem;
    color: #888;
  }

  .post-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
  }

  .tag {
    font-size: 0.75rem;
    color: var(--accent);
    text-decoration: none;
    border: 1px solid var(--accent);
    border-radius: 3px;
    padding: 0.15rem 0.5rem;
    opacity: 0.8;
  }

  .tag:hover {
    opacity: 1;
  }

  .post-cover {
    width: 100%;
    height: auto;
    border-radius: 6px;
    display: block;
    margin-bottom: 2rem;
  }

  .prose {
    font-size: 1rem;
    line-height: 1.7;
    color: #333;
  }

  .prose :global(h2) {
    font-size: var(--text-md);
    font-weight: 500;
    margin: 2rem 0 0.75rem;
    color: #111;
  }

  .prose :global(h3) {
    font-size: var(--text-sm);
    font-weight: 500;
    margin: 1.5rem 0 0.5rem;
    color: #111;
  }

  .prose :global(p) {
    margin-bottom: 1.25rem;
  }

  .prose :global(a) {
    color: var(--accent);
    text-underline-offset: 3px;
  }

  .prose :global(blockquote) {
    border-left: 3px solid var(--accent);
    margin: 1.5rem 0;
    padding: 0.25rem 0 0.25rem 1.25rem;
    color: #555;
    font-style: italic;
  }

  .prose :global(code) {
    font-family: ui-monospace, monospace;
    font-size: 0.875em;
    background: #e8e8e6;
    padding: 0.1em 0.35em;
    border-radius: 3px;
  }

  .prose :global(pre) {
    background: #2b2b2b;
    color: #e0e0e0;
    padding: 1.25rem;
    border-radius: 6px;
    overflow-x: auto;
    margin: 1.5rem 0;
  }

  .prose :global(pre code) {
    background: none;
    padding: 0;
    font-size: 0.875rem;
  }

  .prose :global(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 1.75rem 0;
    font-size: 0.95rem;
    line-height: 1.6;
  }

  .prose :global(thead) {
    border-bottom: 2px solid #d7d7d2;
  }

  .prose :global(tbody tr) {
    border-bottom: 1px solid #e0e0de;
  }

  .prose :global(tbody tr:last-child) {
    border-bottom: none;
  }

  .prose :global(th),
  .prose :global(td) {
    padding: 0.8rem 1rem 0.8rem 0;
    text-align: left;
    vertical-align: top;
    overflow-wrap: anywhere;
  }

  .prose :global(th:last-child),
  .prose :global(td:last-child) {
    padding-right: 0;
  }

  .prose :global(th) {
    font-weight: 600;
    color: #111;
  }

  .prose :global(ul),
  .prose :global(ol) {
    padding-left: 1.5rem;
    margin-bottom: 1.25rem;
  }

  .prose :global(li) {
    margin-bottom: 0.4rem;
  }

  .back {
    display: inline-block;
    font-size: 0.9rem;
    color: #555;
    text-decoration: none;
    border-bottom: 1px solid #ccc;
    padding-bottom: 1px;
    margin-bottom: 1.5rem;
  }


  .back:hover {
    color: var(--accent);
    border-color: var(--accent);
  }

  .post-pagination {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    max-width: var(--width-prose);
    margin: 1rem 0 2rem;
    padding-top: 2rem;
    border-top: 1px solid #e0e0de;
  }

  .pagination-next {
    text-align: right;
  }

  .pagination-link {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
    text-decoration: none;
    color: inherit;
  }

  .pagination-link--next {
    align-items: flex-end;
  }

  .pagination-label {
    font-size: 0.75rem;
    font-weight: 600;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: var(--accent);
  }

  .pagination-title {
    font-size: 0.9rem;
    color: #333;
    line-height: 1.4;
  }

  .pagination-link:hover .pagination-title {
    color: var(--accent);
  }
</style>
