---
import SectionContainer from '../../components/SectionContainer.astro';
import tv from '../../data/watchlist.json'

let watched = [];
let currently = [];
let to_watch = [];

tv.lists.forEach(list => {
  switch (list.name) {
    case "Watched":
        watched = list.tv;
        break;
    case "Currently watching":
        currently = list.tv;
        break;
    case "Watchlist":
        to_watch = list.tv;
        break;
  }
});

const tvByYear = watched.reduce((acc, tv) => {
    const year = new Date(tv.date.string).getFullYear();
    if (!acc[year]) {
        acc[year] = [];
    }
    acc[year].push(tv);
    return acc;
}, {});

const sortedYears = Object.keys(tvByYear).sort((a: any, b: any) => b - a);
---
<SectionContainer title="watchlist" description="stuff i watch">
    <main class="flex flex-col flex-1 gap-4 mt-4">
		<h1 class="text-3xl font-extrabold">[ watchlist ]</h1>
		
        <h2 class="text-xl font-semibold">on the screen</h2>
        <ul>
            {currently.map((tv) => (
                <li class="borderbottom mb-3">👀 {tv.title}</li>
            ))}
        </ul>

        {sortedYears.map(year => (
            <details>
                <summary class="text-xl font-semibold cursor-pointer">{year} <span class="text-xs">({tvByYear[year].length} entries)</span></summary>
                <ul>
                    {
                        tvByYear[year].map(tv => (
                            <li class="flex mb-2 break-words gap-2 borderbottom">
                                <p class="text-s w-1/3">{tv.title}</p>
                                <p class="w-1/3 text-center">{tv.type}</p>
                                <p class="w-1/3 text-end">{tv.rating === 5 ? "❤️" : ""}</p>
                            </li>
                        ))
                    }
                </ul>
            </details>
        ))}

        <details>
            <summary class="text-xl font-semibold cursor-pointer">watchlist</summary>
            <ul>
                {to_watch.map((tv) => (
                    <li class="borderbottom">{tv.title}</li>
                ))}
            </ul>
        </details>
	</main>
</SectionContainer>
