---
/**
 * 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,
	generateSiteSeoContributions,
} from "../page/seo-contributions.js";
import { renderSiteIdentity } from "../page/site-identity.js";
import { getPageRuntime } from "../page/index.js";
import { getSiteSettings } from "../settings/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 siteIdentityHtml = "";
let fragmentsHtml = "";

if (runtime) {
	// Run independent async loads in parallel: site settings (SEO meta
	// tags + favicon) and plugin page-metadata contributions. Plugin
	// contributions come BEFORE site/base in the contribution array,
	// so resolvePageMetadata's first-wins dedup lets plugins override
	// defaults.
	//
	// `getSiteSettings()` is request-cached and worker-cached, so when
	// a parent template has already called it (the standard pattern in
	// `Base.astro`), this is free. Otherwise it's a single batched
	// query that supersedes any per-key fetch this component would
	// otherwise have done.
	const [siteSettings, pluginContributions, fragments] = await Promise.all([
		getSiteSettings(),
		runtime.collectPageMetadata(page),
		runtime.collectPageFragments(page),
	]);

	const siteContributions = generateSiteSeoContributions(siteSettings.seo);
	const allContributions = [...pluginContributions, ...siteContributions, ...baseContributions];
	const resolved = resolvePageMetadata(allContributions);
	metadataHtml = renderPageMetadata(resolved);
	siteIdentityHtml = renderSiteIdentity({ favicon: siteSettings.favicon });
	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={siteIdentityHtml} />
<Fragment set:html={fragmentsHtml} />
