---
/**
 * PageTitle override — emits the docs-page mockup's article header:
 *   .breadcrumbs · <h1> with <em> gradient accent · .doc-lede · .doc-meta
 *
 * Replaces Starlight's bare-<h1> default at
 *   node_modules/@astrojs/starlight/components/PageTitle.astro
 *
 * Data comes from Astro.locals.starlightRoute. Styles live in
 *   src/styles/starlight-docs-bridge.css §08 (.breadcrumbs / .doc-lede / .doc-meta)
 */
// Starlight's internal PAGE_TITLE_ID constant (not exported publicly).
// Inlined here so the H1 anchor matches what Starlight's TOC scroll-spy expects.
const PAGE_TITLE_ID = '_top';

const route = Astro.locals.starlightRoute;
const { entry, sidebar, lastUpdated, editUrl, locale } = route;

const title = entry.data.title;
const description = entry.data.description;

// Wrap last word of title in <em> for the amber→magenta gradient accent.
// Pages can opt out by setting frontmatter `accent: false`.
const accent = (entry.data as Record<string, unknown>).accent;
let titleHead = title;
let titleTail = '';
if (accent !== false) {
	const idx = title.lastIndexOf(' ');
	if (idx > 0) {
		titleHead = title.slice(0, idx);
		titleTail = title.slice(idx + 1);
	}
}

// Breadcrumbs — walk sidebar to find the current entry's ancestry.
type SidebarItem = { label: string; href?: string; isCurrent?: boolean; entries?: SidebarItem[]; type?: string };
function findCrumbs(items: SidebarItem[], trail: SidebarItem[] = []): SidebarItem[] | null {
	for (const item of items) {
		const next = [...trail, item];
		if (item.isCurrent) return next;
		if (item.entries) {
			const found = findCrumbs(item.entries, next);
			if (found) return found;
		}
	}
	return null;
}
const crumbs = findCrumbs(sidebar as SidebarItem[]) ?? [];
// "Docs" root crumb (localized via Starlight i18n)
const docsRoot = locale ? `/${locale}/` : '/';

// Reading time — rough estimate from rendered body word count (250 wpm).
const bodyText = (entry.body ?? '').replace(/[`*_#>\-]+/g, ' ').replace(/\s+/g, ' ').trim();
const wordCount = bodyText ? bodyText.split(' ').length : 0;
const minutes = Math.max(1, Math.round(wordCount / 250));

// Last-updated — relative format ("2 days ago")
let updatedRel: string | null = null;
if (lastUpdated) {
	const now = Date.now();
	const diffMs = now - lastUpdated.getTime();
	const day = 86400000;
	const rtf = new Intl.RelativeTimeFormat(locale ?? 'en', { numeric: 'auto' });
	if (diffMs < day) updatedRel = rtf.format(-Math.round(diffMs / 3600000), 'hour');
	else if (diffMs < 30 * day) updatedRel = rtf.format(-Math.round(diffMs / day), 'day');
	else if (diffMs < 365 * day) updatedRel = rtf.format(-Math.round(diffMs / (30 * day)), 'month');
	else updatedRel = rtf.format(-Math.round(diffMs / (365 * day)), 'year');
}

// Stability badge — read frontmatter `status` (stable | beta | experimental); default 'Stable'
const status = ((entry.data as Record<string, unknown>).status as string | undefined) ?? 'stable';
const statusLabel = status.charAt(0).toUpperCase() + status.slice(1);
---

{crumbs.length > 0 && (
	<nav class="breadcrumbs" aria-label="Breadcrumb">
		<a href={docsRoot}>Docs</a>
		<span class="sep">/</span>
		{crumbs.map((c, i) => (
			i === crumbs.length - 1
				? <span>{c.label}</span>
				: <>
					{c.href ? <a href={c.href}>{c.label}</a> : <span>{c.label}</span>}
					<span class="sep">/</span>
				</>
		))}
	</nav>
)}

<h1 id={PAGE_TITLE_ID}>
	{titleHead}{titleTail && <> <em>{titleTail}</em></>}
</h1>

{description && <p class="doc-lede">{description}</p>}

<div class="doc-meta">
	<span><span class="pulse"></span> <strong>{statusLabel}</strong></span>
	{updatedRel && <span>Updated <strong>{updatedRel}</strong></span>}
	{minutes > 0 && <span>Reading time <strong>~ {minutes} min</strong></span>}
	{editUrl && <span>Edit on <a href={editUrl.toString()}><strong>GitHub</strong></a></span>}
</div>
