---
/**
 * Auto-injected /tips route (v4.3.0, closes #70).
 *
 * Gated on `routes.tips: true`. Reads `src/data/tips.json` (emitted by
 * `book-scaffold build-tips`); renders an ordered list with anchor
 * permalinks (`/tips#tip-N`).
 *
 * Graceful skip: if tips.json doesn't exist, renders an instructions
 * page (doesn't fail the build).
 */
import Base from '../layouts/Base.astro';
import { normalizeBase } from '../src/lib/nav-href';
import bookConfig from 'virtual:book-scaffold/book-config';
import { selectBookArtifact } from '../src/lib/corpus';

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

// v4.4.0 fix: use Vite's import.meta.glob with a project-root-relative
// path. The previous `../../../src/data/tips.json` resolution failed when
// the auto-injected route was processed from node_modules (or any context
// other than a workspace symlink). `/src/data/...` is consumer-project-rooted
// in Vite's resolver and works across all consumer build contexts.
type TipIndexEntry = { n: number; title: string; chapter: string; preview: string };
const tipsModules = import.meta.glob<{ default: unknown }>(
  '/src/data/tips.json',
  { eager: true },
);
const tipsEntry = tipsModules['/src/data/tips.json'];
const tips = tipsEntry
  ? selectBookArtifact<TipIndexEntry[]>(
      tipsEntry.default,
      bookConfig.corpus,
      bookId,
      'src/data/tips.json',
    )
  : [];
const loadError = tipsEntry
  ? null
  : 'src/data/tips.json not found — run `npx book-scaffold build-tips` to generate.';

// #142: chapter back-links must prefix the deploy base.
const baseUrl = normalizeBase(import.meta.env.BASE_URL);
---
<Base title="Tips" description="Numbered tips from this book, drawn from <Tip> instances in chapters." bookId={bookId}>
  <article class="prose">
    <h1>Tips</h1>
    {loadError && (
      <p class="tips-empty">{loadError}</p>
    )}
    {!loadError && tips.length === 0 && (
      <p class="tips-empty">No tips defined yet. Add <code>&lt;Tip n="1" title="..."&gt;...&lt;/Tip&gt;</code> to a chapter and rebuild.</p>
    )}
    {tips.length > 0 && (
      <ol class="tips-index">
        {tips.map((tip) => (
          <li id={`tip-${tip.n}`} class="tips-index-item">
            <h2 class="tips-index-title">
              <span class="tips-index-number">Tip {tip.n}.</span>
              {tip.title}
            </h2>
            {tip.preview && (
              <p class="tips-index-preview">{tip.preview}</p>
            )}
            <p class="tips-index-meta">
              From <a href={`${baseUrl}chapters/${bookId ? `${bookId}/` : ''}${tip.chapter}/`}>{tip.chapter}</a>
            </p>
          </li>
        ))}
      </ol>
    )}
  </article>
</Base>
