---
export const prerender = true

import type { GetStaticPaths, Page } from 'astro'
import type { CollectionEntry } from 'astro:content'

import Button from '@/components/Button.astro'
import PostPreview from '@/components/blog/PostPreview.astro'
import PageLayout from '@/layouts/BaseLayout.astro'
import { getallDiaries, getUniqueCategories, getUniqueTags, sortMDByDate } from '@/utils'
import { Calendar } from '@/components/blog/Calendar'

export const getStaticPaths = (async ({ paginate }) => {
	const allPosts = await getallDiaries()
	const allPostsByDate = sortMDByDate(allPosts)
	const uniqueTags = getUniqueTags(allPosts)
	const uniqueCategories = getUniqueCategories(allPosts)

	// 找到最新的有日记的月份
	const latestPost = allPostsByDate[0]
	const latestDate = latestPost ? new Date(latestPost.data.date) : new Date()

	return paginate(allPostsByDate, {
		pageSize: 50,
		props: { uniqueTags, uniqueCategories, allPosts: allPostsByDate, latestDate }
	})
}) satisfies GetStaticPaths

interface Props {
	page: Page<CollectionEntry<'post'>>
	uniqueTags: string[]
	uniqueCategories: string[]
	allPosts: CollectionEntry<'post'>[]
	latestDate: Date
}

const { page, allPosts, latestDate } = Astro.props
const currentDate = latestDate

const meta = {
	description: 'Posts',
	title: 'Diary'
}

// 序列化文章数据供客户端使用
const serializedPosts = allPosts.map((post) => ({
	slug: post.slug,
	data: {
		title: post.data.title,
		date: post.data.date
	}
}))
---

<PageLayout meta={meta}>
	<div class='w-full'>
		<Button title='Back' href='/' style='button'>
			<svg
				xmlns='http://www.w3.org/2000/svg'
				width='14'
				height='14'
				viewBox='0 0 24 24'
				slot='icon-before'
			>
				<path
					fill='currentColor'
					d='m6.921 12.5l5.792 5.792L12 19l-7-7l7-7l.713.708L6.921 11.5H19v1z'
				>
				</path>
			</svg>
		</Button>

		<h1 class='mb-6 mt-5 text-2xl font-bold'>Diary</h1>
		{page.data.length === 0 && <p>No posts yet.</p>}

		{
			page.data.length > 0 && (
				<div class='space-y-12'>
					<script
						id='posts-data'
						type='application/json'
						set:html={JSON.stringify(serializedPosts)}
					/>
					<div id='calendar-container' data-current-date={currentDate.toISOString()}>
						<Calendar posts={allPosts} currentDate={currentDate} client:load />
					</div>

					<div class='mt-8'>
						<h2 class='mb-4 text-xl font-semibold'>所有日记</h2>
						<ul class='flex flex-col gap-y-4 text-start'>
							{page.data.map((p) => (
								<PostPreview post={p} prefix='/diary/' withDesc />
							))}
						</ul>
					</div>
				</div>
			)
		}
	</div>
</PageLayout>

<script>
	function initializeCalendar() {
		const postsDataScript = document.getElementById('posts-data')
		if (!postsDataScript) return

		// 触发一个自定义事件，通知日历组件重新初始化
		window.dispatchEvent(
			new CustomEvent('calendar-init', {
				detail: {
					posts: JSON.parse(postsDataScript.textContent || '[]'),
					currentDate: document.getElementById('calendar-container')?.dataset.currentDate
				}
			})
		)
	}

	// 页面首次加载时初始化
	initializeCalendar()

	// 在视图转换后重新初始化
	document.addEventListener('astro:after-swap', () => {
		initializeCalendar()
	})
</script>
