// @ts-nocheck
import { useEffect, useState } from "react"

const SESSION_STORAGE_KEY = "posts"

const sortPosts = (posts) => {
	return posts.sort((a, b) => new Date(b.date) - new Date(a.date))
}

const usePosts = () => {
	const [posts, setPosts] = useState([])

	useEffect(() => {
		const fetchPosts = async () => {
			const storedPosts =
				typeof window !== "undefined" &&
				sessionStorage.getItem(SESSION_STORAGE_KEY)
			if (storedPosts) {
				setPosts(JSON.parse(storedPosts))
			} else {
				fetch("/post-index.json")
					.then((res) => {
						if (!res.ok) {
							throw new Error(`HTTP error fetching posts. Status ${res.status}`)
						}
						return res.json()
					})
					.then((data) => {
						const sortedPosts = sortPosts(data)
						sessionStorage.setItem(
							SESSION_STORAGE_KEY,
							JSON.stringify(sortedPosts)
						)
						setPosts(sortedPosts)
					})

					.catch((err) => {
						console.error("Failed to fetch posts: ", err)
					})
			}
		}

		fetchPosts()
	}, [])

	return { posts }
}

export { usePosts }
