import type { Context } from "koa";
import { TempstreamJSX } from "tempstream";
import { get_breadcrumbs_from_path } from "../url-tree.js";

const arrow_width = 8;
const arrow_height = 28;

function arrow_tail() {
	return (
		<svg
			xmlns="http://www.w3.org/2000/svg"
			width={`${arrow_width}px`}
			height={`${arrow_height}px`}
			viewBox="0 0 ${arrow_width} ${arrow_height}"
			style="margin-right: -1px"
		>
			{
				/* HTML */ `<path
					d="M 0 0 ${arrow_width} 0l0 ${arrow_height} -${arrow_width} 0L${arrow_width} ${arrow_height /
					2}Z"
					style="fill:var(--bg);"
				/>`
			}
		</svg>
	);
}

function arrow_head() {
	return (
		<svg
			xmlns="http://www.w3.org/2000/svg"
			width={`${arrow_width}px`}
			height={`${arrow_height}px`}
			viewBox="0 0 ${arrow_width} ${arrow_height}"
		>
			{
				/* HTML */ `<path
					d="m 0 0 ${arrow_width} ${arrow_height / 2}L0 ${arrow_height}Z"
					style="fill:var(--bg);"
				/>`
			}
		</svg>
	);
}

export async function breadcrumbs(ctx: Context) {
	const breadcrumbs = await Promise.all(
		get_breadcrumbs_from_path(ctx.path).map(async (e, i, all) => {
			if (!e.actionName) {
				return "";
			}

			const breadcrumbLabel = e.breadcrumbLabel?.({ ...ctx });
			const breadcrumbLabelResult = await breadcrumbLabel;

			if (i == all.length - 1) {
				return <span>{breadcrumbLabelResult || e.actionName}</span>;
			}
			return (
				<>
					<a href={e.url}>
						{i !== 0 ? arrow_tail() : ""}
						<span>{breadcrumbLabelResult || e.actionName}</span>
						{arrow_head()}
					</a>
				</>
			);
		})
	);
	return <div class="breadcrumbs">{breadcrumbs.filter((e) => e !== "").join("")}</div>;
}
