import { tempstream } from "tempstream";
import type { Readable } from "stream";
import type { Context } from "koa";
import type { HTMLOptions } from "@sealcode/sealgen";
import { htmlEscape } from "escape-goat";

export const start_timestamp = Date.now();

export function defaultHead({
	ctx,
	title,
	htmlOptions,
	metaImage,
	canonicalPath,
	css_clumps = [],
	description = "",
}: {
	ctx: Context;
	title: string | Promise<string | Readable>;
	htmlOptions: Partial<HTMLOptions>;
	metaImage?: string;
	canonicalPath?: string;
	css_clumps: string[];
	description: string;
}): JSX.Element | Readable {
	const origin = ctx.URL.origin;
	return tempstream /* HTML */ `<title>${title}</title>
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta name="description" content="${htmlEscape(description)}" />
		${ctx.$app.getFeedHTMLMetatags(ctx)}
		<script defer src="/dist/bundle.js?v=${start_timestamp}"></script>
		${metaImage ? `<meta property="og:image" content="${metaImage}" />` : ""}
		${[
			"default",
			"page",
			...(ctx.url.includes("/dowodzenie/") ? ["admin"] : []),
			...css_clumps,
		].map(
			(clump_name) =>
				/* HTML */ `<link
					href="/dist/${clump_name}.entrypoint.css?v=${start_timestamp}${htmlOptions.autoRefreshCSS
						? `?${Math.random()}${Math.random()}`
						: ""}"
					rel="stylesheet"
					type="text/css"
				/>`
		)}
		<link href="/dist/fonts/fonts.css" rel="stylesheet" type="text/css" />
		${canonicalPath
			? `<link rel="canonical" href="${origin}${canonicalPath}" />`
			: ""}
		${htmlOptions.morphing
			? `<meta name="turbo-refresh-method" content="morph" />`
			: ""}
		${htmlOptions.preserveScroll
			? `<meta name="turbo-refresh-scroll" content="preserve">`
			: ""} `;
}
