---
import { Icon } from "astro-icon/components";
import { type CollectionEntry, getCollection } from "astro:content";

const { seriesId } = Astro.props;
const currentPath = Astro.url.pathname;

const posts = await getCollection("post");
const series = await getCollection("series");

// Находим серию по переданному `seriesId` указанному в посте
const postsSeries = series.find((s) => s.id === seriesId);
if (!postsSeries) {
  	throw new Error(`Post(s) with Series ID '${seriesId}' not found.`);
}
// console.log("Post(s) Series:", postsSeries); // Debug. Логируем найденную серию

let seriesPosts: CollectionEntry<"post">[] = [];
if (seriesId) {
	seriesPosts = posts
		.filter((p) => p.data.seriesId === seriesId)
		.sort((a, b) => (a.data.orderInSeries || 0) - (b.data.orderInSeries || 0));
}
---

<aside
	id="series-panel"
	class="hidden grid lg:block z-40 min-h-screen fixed lg:relative `shadow-[5px_0px_10px_rgba(0,0,0,0.05)]` transition-all duration-300 ease-in-out bg-bgColor"
>	
	<div class="fixed -z-10 top-0 w-screen md:w-72 md:min-w-72 md:max-w-72 h-screen bg-gradient-to-b from-orange-300 via-pink-300 to-purple-300 opacity-30 dark:opacity-0">
	</div>
	
	<div class="flex h-full flex-col px-8 pt-4 md:pt-8 w-screen md:w-72 md:min-w-72 md:max-w-72 bg-accent-base/5 border-r border-special-light">
		<div class="flex gap-x-1">
			<!--
			<Icon aria-hidden="true" class="flex-shrink-0 h-8 w-6 py-1" focusable="false" name="solar:notes-line-duotone" />
			-->
			<h4 class="flex items-center title mb-[4.5rem]">
				Docs Series panel
			</h4>
		</div>
		<button
			id="close-panel"
			class="absolute top-4 right-4 md:top-8 md:right-8 h-8 w-8 flex items-center justify-center rounded-lg bg-accent-base/5 text-accent-base hover:bg-accent-base/10"
			aria-label="Close Series Panel"
		>
			<Icon class="h-6 w-6" name="hugeicons:cancel-01" />
		</button>
		<div class="sticky top-8">
			{postsSeries.id ? (
				<a 
					href={`/series/${postsSeries.id}`} 
					aria-label={`About ${postsSeries.data.title} series`}
					class="sticky top-4 flex h-8 w-full items-center justify-center gap-x-1 rounded-lg shadow-lg bg-accent-base font-medium text-bgColor hover:brightness-110 transition-all duration-300"
				>
					<Icon class="inline-block h-6 w-6 text-bgColor" name="solar:notes-bold" />
					{postsSeries.data.title}
				</a>

				<ul class="mt-[1.0625rem] text-sm font-medium text-light">
					{seriesPosts.map((p) => {
						const isActive = currentPath === `/posts/${p.id}/`;
						return (
							<li class={`px-4 flex items-center line-clamp-2 pt-1 pb-1 ${isActive ? "rounded-lg bg-color-100" : ""}`}>
								<a
									href={`/posts/${p.id}/`}
									class={`hover:text-accent-two ${isActive ? "text-accent cursor-default pointer-events-none" : ""}`}
								>
									{p.data.title}
								</a>
							</li>
						);
					})}
				</ul>
			) : null}
		</div>
	</div>
</aside>
