---
/**
 * ChapterNav — prev / next chapter links at the bottom of each chapter.
 *
 * v4.26.0 (#80): book-aware. `getNeighbors` scopes prev/next to the current
 * book (multi-book), and links resolve through the `chapterRoute` pattern, so a
 * multi-book consumer gets `/<book>/<slug>/` links that never bleed across books.
 * Single-book consumers are byte-identical (defaults → global order + `/chapters/<id>/`).
 */
import { getNeighbors } from '../src/lib/chapters';
import { chapterHref, normalizeBase } from '../src/lib/nav-href';
import bookConfig from 'virtual:book-scaffold/book-config';

interface Props {
  currentId: string;
}
const { currentId } = Astro.props;

const chapterRoute = (bookConfig as { chapterRoute?: string }).chapterRoute ?? '/chapters/:id/';
const bookField = (bookConfig as { bookField?: string }).bookField ?? 'book';
const baseUrl = normalizeBase(import.meta.env.BASE_URL);

const { prev, next } = await getNeighbors(currentId, { bookField, corpus: bookConfig.corpus });
// Resolve hrefs in frontmatter (casts here, never in the JSX expression container).
const prevHref = prev
  ? chapterHref({ id: prev.id, data: prev.data as Record<string, unknown> }, chapterRoute, baseUrl, bookField)
  : null;
const nextHref = next
  ? chapterHref({ id: next.id, data: next.data as Record<string, unknown> }, chapterRoute, baseUrl, bookField)
  : null;
---
{(prev || next) && (
  <nav class="chapter-nav" aria-label="Chapter navigation">
    {prev && prevHref && (
      <a href={prevHref} class="prev">
        <span class="nav-label">← Previous</span>
        <span class="nav-title">{prev.data.title}</span>
      </a>
    )}
    {next && nextHref && (
      <a href={nextHref} class="next">
        <span class="nav-label">Next →</span>
        <span class="nav-title">{next.data.title}</span>
      </a>
    )}
  </nav>
)}
