---
/**
 * Renders base SEO metadata, plugin-contributed metadata, and trusted head fragments.
 *
 * Base SEO metadata (meta tags, OG, Twitter Card, canonical, JSON-LD) is generated
 * from the page context's seo/articleMeta/siteName fields. Plugin contributions
 * come after, so they can override base tags via first-wins dedup in resolvePageMetadata().
 *
 * Usage:
 * ```astro
 * <head>
 *   <EmDashHead page={page} />
 * </head>
 * ```
 */
import type { PublicPageContext, PageMetadataContribution } from "../plugins/types.js";
import { resolvePageMetadata, renderPageMetadata } from "../page/metadata.js";
import { renderFragments } from "../page/fragments.js";
import { generateBaseSeoContributions } from "../page/seo-contributions.js";
import { getPageRuntime } from "../page/index.js";

interface Props {
	page: PublicPageContext;
}

const { page } = Astro.props;
const runtime = getPageRuntime(Astro.locals as Record<string, unknown>);

// Base SEO contributions from page context (always generated)
const baseContributions: PageMetadataContribution[] = generateBaseSeoContributions(page);

let metadataHtml = "";
let fragmentsHtml = "";

if (runtime) {
	// Plugin contributions come BEFORE base, so resolvePageMetadata's
	// first-wins dedup lets plugins override base SEO defaults
	const pluginContributions = await runtime.collectPageMetadata(page);
	const allContributions = [...pluginContributions, ...baseContributions];
	const resolved = resolvePageMetadata(allContributions);
	metadataHtml = renderPageMetadata(resolved);

	const fragments = await runtime.collectPageFragments(page);
	fragmentsHtml = renderFragments(fragments, "head");
} else {
	// No runtime (EmDash not initialized) — still render base SEO
	const resolved = resolvePageMetadata(baseContributions);
	metadataHtml = renderPageMetadata(resolved);
}
---

<Fragment set:html={metadataHtml} />
<Fragment set:html={fragmentsHtml} />
