---
import ArchivePanel from "@components/ArchivePanel.astro";
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import MainGridLayout from "@layouts/MainGridLayout.astro";
import { getSortedPosts } from "@utils/content-utils";
import { decodePathSegment, encodePathSegment } from "@utils/encoding-utils";

export async function getStaticPaths() {
	const posts = await getSortedPosts();

	const allTags = posts.reduce<Set<string>>((acc, post) => {
		if (Array.isArray(post.data.tags)) {
			// biome-ignore lint/complexity/noForEach: <explanation>
			post.data.tags.forEach((tag) => {
				if (typeof tag === "string") {
					acc.add(tag.trim());
				} else {
					acc.add(String(tag).trim());
				}
			});
		} else if (post.data.tags && typeof post.data.tags === "string") {
			// biome-ignore lint/complexity/noForEach: <explanation>
			(post.data.tags as string)
				.split(",")
				.forEach((tag) => acc.add(tag.trim()));
		}
		return acc;
	}, new Set());

	const allTagsArray = Array.from(allTags);

	// judge if the string is CJK
	const isCJK = (str: string) =>
		/[\u3000-\u9fff\uac00-\ud7af\u4e00-\u9faf]/.test(str);

	const standardPaths = allTagsArray.map((tag) => ({
		params: {
			tag: encodePathSegment(tag),
		},
		props: {
			decodedTag: tag,
		},
	}));

	const nonEncodedCJKPaths = allTagsArray.filter(isCJK).map((tag) => ({
		params: {
			tag: tag, // keep CJK characters unencoded
		},
		props: {
			decodedTag: tag,
		},
	}));

	return [...standardPaths, ...nonEncodedCJKPaths];
}

const { decodedTag } = Astro.props;
const tag = decodedTag || decodePathSegment(Astro.params.tag as string);
---

<MainGridLayout title={i18n(I18nKey.archive)} description={i18n(I18nKey.archive)}>
    <ArchivePanel tags={[tag]}></ArchivePanel>
</MainGridLayout>
