---
import { type CollectionEntry, render } from "astro:content";
import TOC from "@/components/blog/TOC.astro";
import BaseLayout from "./Base.astro";
import SeriesPanel from "@/components/SeriesPanel.astro";
import { Icon } from "astro-icon/components";

interface Props {
	series: CollectionEntry<"series">;
}

const { series } = Astro.props;
const { title, description } = series.data;

const { headings } = await render(series);
---

<BaseLayout meta={{ description, title }}>
	<div class="fixed left-0 top-0 z-10 flex h-16 md:h-20 w-full bg-bgColor overflow-hidden">
		<!-- Background 
			TODO: This approach is not optimal and requires improvements. 
  			- Too many absolutely positioned elements can affect performance. 
  		-->	
		<div class="absolute top-0 left-1/2 -ml-[50vw] w-screen min-h-screen pointer-events-none blur-2xl">
			<div class="absolute top-[-90%] right-[25%] w-[75%] h-full bg-gradient-to-b from-blue-300 via-pink-300 to-transparent rounded-full opacity-40 dark:opacity-5"></div>
			<div class="absolute top-[-90%] left-[25%] w-[75%] h-full bg-gradient-to-b from-blue-300 via-pink-300 to-transparent rounded-full opacity-40 dark:opacity-5"></div>
			<div class="absolute top-[-85%] right-[25%] w-[55%] h-full bg-gradient-to-b from-purple-300 via-blue-300 to-transparent rounded-full opacity-40 dark:opacity-5"></div>
			<div class="absolute top-[-85%] left-[25%] w-[55%] h-full bg-gradient-to-b from-indigo-300 via-orange-300 to-transparent rounded-full opacity-40 dark:opacity-5"></div>
			<div class="absolute top-[-75%] left-[-25%] w-[65%] h-full bg-gradient-to-b from-blue-300 via-pink-300 to-transparent rounded-full opacity-30 dark:opacity-5"></div>
			<div class="absolute top-[-75%] right-[-25%] w-[65%] h-full bg-gradient-to-b from-purple-300 via-blue-300 to-transparent rounded-full opacity-30 dark:opacity-5"></div>
			<div class="absolute top-[-85%] left-[-30%] w-[85%] h-full bg-gradient-to-b from-indigo-300 via-orange-300 to-transparent rounded-full opacity-60 dark:opacity-5"></div>
			<div class="absolute top-[-85%] right-[-30%] w-[85%] h-full bg-gradient-to-b from-orange-300 via-indigo-300 to-transparent rounded-full opacity-60 dark:opacity-5"></div>
		</div>
	</div>

	<!-- SeriesPanel вставляется в именованный слот "sidebar" -->
	{series.id && (<SeriesPanel slot="sidebar" seriesId={series.id} />)}

	<div class="md:sticky md:top-8 md:z-20 flex items-end">
		<button
			id="toggle-panel"
			class="hidden md:flex z-30 mr-2 h-8 w-8 items-center bg-accent-base/10 flex-shrink-0 justify-center rounded-lg text-accent-base hover:text-accent-base/90"
			aria-label="Toggle Series Panel"
			aria-controls="series-panel"
		>
			{/*
			<Icon aria-hidden="true" class="h-6 w-6" focusable="false" name="hugeicons:sidebar-left" />
			*/}
			<Icon aria-hidden="true" class="flex-shrink-0 h-6 w-6" focusable="false" name="solar:notes-bold" />
		</button>
		<button
			id="toggle-toc"
			class="hidden md:flex z-30 mr-2 h-8 w-8 items-center flex-shrink-0 bg-accent-base/10 justify-center rounded-lg text-accent-base hover:text-accent-base/90"
			aria-label="Table of Contents"
		>	
			<Icon aria-hidden="true" class="h-6 w-6" focusable="false" name="solar:clipboard-list-bold" />
		</button>

		<h1 class="title md:sticky md:top-4 md:z-20 line-clamp-none md:line-clamp-1 md:max-w-lg lg:max-w-xl">
			{title}
		</h1>
	</div>
	<p class="prose prose-citrus max-w-none mt-[1.125rem]">
		{description}
	</p>

	<div class="mt-6 flex sm:grid-cols-[auto_1fr] md:items-start gap-x-8">
		<article class="grid flex-grow grid-cols-1 break-words pt-4" data-pagefind-body>
			<div class="prose prose-citrus max-w-none flex-grow prose-headings:font-semibold prose-headings:text-accent-base prose-headings:before:text-accent-two sm:prose-headings:before:content-['#'] sm:prose-th:before:content-none">
				<slot />
			</div>
		</article>
		{
			!!headings.length && (
				<aside 
					id="toc-panel" 
					class="sticky md:top-20 z-10 hidden md:w-[16rem] md:min-w-[16rem] rounded-lg md:block"
				>
					<TOC headings={headings} />
				</aside>
			)
		}
	</div>

	<div class="left-0 right-12 z-50 ml-auto w-fit md:absolute">
		<button
			id="to-top-button"
			class="fixed bottom-14 flex h-12 w-12 text-light translate-y-28 items-center justify-center rounded-full border-2 border-special-lighter bg-bgColor text-3xl drop-shadow-xl transition-all duration-300 hover:text-accent-two data-[show=true]:translate-y-0 data-[show=true]:opacity-100"
			aria-label="Back to Top"
			data-show="false"
		>	
			<span class="absolute inset-0 rounded-full bg-special-light flex items-center justify-center" aria-hidden="true">
				<svg
					class="h-6 w-6"
					fill="none"
					focusable="false"
					stroke="currentColor"
					stroke-width="2"
					viewBox="0 0 24 24"
					xmlns="http://www.w3.org/2000/svg"
				>
					<path d="M4.5 15.75l7.5-7.5 7.5 7.5" stroke-linecap="round" stroke-linejoin="round"></path>
				</svg>
			</span>
		</button>
	</div>

	<!-- Кнопка серий для мобильных экранов -->
	<mobile-button
		id="toggle-panel-mobile"
		class="size-12 flex items-center justify-center block sm:hidden fixed bottom-4 shadow-[0px_10px_25px_rgba(0,0,0,0.15)] border border-special-lighter right-4 z-50 rounded-lg bg-bgColor text-accent-base hover:text-bg-accent-base/90"
		aria-label="Toggle Series Panel"
	>
		<span class="absolute inset-0 rounded-lg flex items-center justify-center bg-special-light hover:text-accent-base/90">
			<Icon class="size-8" name="solar:notes-bold"/>
		</span>
	</mobile-button>

	<!-- Кнопка таблицы контента для мобильных экранов -->
	<!--
	<mobile-button
		id="toggle-toc-mobile"
		class="size-12 flex items-center justify-center block sm:hidden fixed bottom-20 shadow-[0px_10px_25px_rgba(0,0,0,0.15)] border border-special-lighter right-4 z-50 rounded-lg bg-bgColor text-accent-base hover:text-bg-accent-base/90"
		aria-label="Toggle TOC Panel"
	>
		<span class="absolute inset-0 rounded-lg flex items-center justify-center bg-special-light hover:text-accent-base/90">
			<Icon class="size-8" name="solar:clipboard-list-bold"/>
		</span>
	</mobile-button>
	-->
</BaseLayout>

<script>
	const ANIMATION_DURATION = 300;
	// Получаем элементы кнопок и панели
	const togglePanelBtn = document.getElementById("toggle-panel");
	const closePanelBtn = document.getElementById("close-panel");
	const seriesPanel = document.getElementById("series-panel");
	const togglePanelMobileBtn = document.getElementById("toggle-panel-mobile");

	// Убедимся, что seriesPanel существует
	if (!seriesPanel) {
		console.error("Элемент series-panel не найден");
		throw new Error("series-panel is required");
	}

	// Функция для проверки, видима ли панель
	const isPanelVisible = () => {
		const isScreenLg = window.matchMedia("(min-width: 1024px)").matches; // Большие экраны
		return (
			(isScreenLg && seriesPanel.classList.contains("lg:block")) ||
			(!isScreenLg && !seriesPanel.classList.contains("hidden"))
		);
	};

	// Функция для скрытия панели
	const hidePanel = () => {
		seriesPanel.classList.add("opacity-0", "-translate-x-full");
		setTimeout(() => {
			seriesPanel.classList.remove("block", "lg:block");
			seriesPanel.classList.add("hidden");
		}, ANIMATION_DURATION);
	};

	// Функция для показа панели
	const showPanel = () => {
		seriesPanel.classList.remove("hidden");
		seriesPanel.classList.add("block", "lg:block");
		setTimeout(() => {
			seriesPanel.classList.remove("opacity-0", "-translate-x-full");
		}, 10);
	};

	// Общий обработчик для обеих кнопок
	const togglePanel = () => {
		if (isPanelVisible()) {
			hidePanel(); // Если видима, скрываем
		} else {
			showPanel(); // Если скрыта, показываем
		}
	};

	// Обработчики событий для обеих кнопок
	if (togglePanelBtn) {
		togglePanelBtn.addEventListener("click", togglePanel);
	} else {
		console.error("Элемент toggle-panel не найден");
	}

	if (togglePanelMobileBtn) {
		togglePanelMobileBtn.addEventListener("click", togglePanel);
	} else {
		console.error("Элемент toggle-panel-mobile не найден");
	}

	if (closePanelBtn) {
		closePanelBtn.addEventListener("click", hidePanel);
	} else {
		console.error("Элемент close-panel не найден");
	}
</script>

<script>
	// Получаем элементы кнопок и панели
	const toggleTocBtn = document.getElementById('toggle-toc');
	const closeTocBtn = document.getElementById('close-toc');
	const tocPanel = document.getElementById('toc-panel');
	const toggleTocMobileBtn = document.getElementById("toggle-toc-mobile");

	// Проверяем наличие панели (обязательно для работы)
	if (!tocPanel) {
		console.error('Элемент toc-panel не найден');
		throw new Error('toc-panel is required');
	}

	// Функция для проверки, видима ли таблица контента
	const isTocVisible = () => {
		const isScreenMd = window.matchMedia("(min-width: 768px)").matches;
		return (
			(isScreenMd && tocPanel.classList.contains("md:block")) ||
			(!isScreenMd && !tocPanel.classList.contains("hidden"))
		);
	};

	// Функция для скрытия панели
	const hideToc = () => {
		tocPanel.classList.add('hidden');
		tocPanel.classList.remove('md:block');
	};

	// Функция для показа панели
	const showToc = () => {
		tocPanel.classList.remove('hidden');
		tocPanel.classList.add('md:block');
	};

	// Общий обработчик для обеих кнопок
	const toggleToc = () => {
		if (isTocVisible()) {
			hideToc(); // Если видима, скрываем
		} else {
			showToc(); // Если скрыта, показываем
		}
	};
	
	// Добавляем обработчик для кнопки переключения
	if (toggleTocBtn) {
		toggleTocBtn.addEventListener("click", toggleToc);
	} else {
		console.error('Элемент toggle-toc не найден');
	}

	// Добавляем обработчик для кнопки переключения
	if (toggleTocMobileBtn) {
		toggleTocMobileBtn.addEventListener("click", toggleToc);
	} else {
		console.error('Элемент toggle-toc-mobile не найден');
	}

	// Добавляем обработчик для кнопки закрытия
	if (closeTocBtn) {
		closeTocBtn.addEventListener('click', hideToc);
	} else {
		console.error('Элемент close-toc не найден');
	}
</script>

<script>
  // Ждем загрузки контента
  document.addEventListener("DOMContentLoaded", () => {
    const buttonsPanel = document.getElementById("buttons-panel");
    
    if (buttonsPanel) {
      buttonsPanel.classList.add("fixed");
      console.log("Класс 'fixed' добавлен к элементу buttons-panel.");
    } else {
      console.error("Элемент с ID 'buttons-panel' не найден.");
    }
  });
</script>

<script>
	const scrollBtn = document.getElementById("to-top-button") as HTMLButtonElement;
	const targetHeader = document.querySelector("header") as HTMLElement;

	function callback(entries: IntersectionObserverEntry[]) {
		entries.forEach((entry) => {
			// Show the scroll to top button when the <header> is out of view
			scrollBtn.dataset.show = (!entry.isIntersecting).toString();
		});
	}

	scrollBtn.addEventListener("click", () => {
		document.documentElement.scrollTo({ behavior: "smooth", top: 0 });
	});

	const observer = new IntersectionObserver(callback);
	observer.observe(targetHeader);
</script>
