import type { FlatTemplatable } from "tempstream";
import { tempstream, TempstreamJSX } from "tempstream";
import type { Stringifiable } from "tempstream/@types/stringify.js";

const make_id = (function* () {
	let i = 0;
	while (true) {
		yield i++;
		if (i == 999999999) {
			i = 0;
		}
	}
})();

export async function horizontalScroller({
	classes = [],
	elements,
	render = async ({ scroller, markers }) => tempstream`${scroller}${markers}`,
}: {
	classes?: string[];
	elements: (Stringifiable | Promise<Stringifiable>)[];
	render?: (options: {
		scroller: FlatTemplatable;
		markers: FlatTemplatable;
	}) => Promise<FlatTemplatable>;
}) {
	const id = make_id.next().value;
	const scroller_id = `horizontal-scroller-${id}`;
	const scroller = (
		<div
			class="horizontal-scroller__element-container"
			data-horizontal-scroller-target="scroller"
		>
			{elements.map((e, index) => (
				<div
					id={scroller_id + "__element--number-" + index}
					class={"horizontal-scroller__element"}
					data-horizontal-scroller-target="element"
					data-index={index}
				>
					<span>{e}</span>
				</div>
			))}
		</div>
	);
	const markers = (
		<div class="horizontal-scroller__markers">
			{elements.map(() => (
				<div
					class="horizontal-scroller__marker"
					data-horizontal-scroller-target="marker"
				></div>
			))}
		</div>
	);
	return (
		<div
			id={scroller_id}
			class={["horizontal-scroller", ...classes]}
			data-controller="horizontal-scroller"
		>
			{render({ scroller, markers })}
		</div>
	);
}
