---
import SectionContainer from '../../components/SectionContainer.astro';
import biblioteca from '../../data/bookshelf.json'

let booksRead = [];
let booksShelf = [];
let booksReading = [];
let booksWant = [];

biblioteca.lists.forEach(list => {
  switch (list.name) {
    case "Read":
      booksRead = list.books;
      break;
    case "On the shelf":
      booksShelf = list.books;
      break;
    case "Currently reading":
      booksReading = list.books;
      break;
    case "Want to read":
      booksWant = list.books;
      break;
  }
});

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

const sortedYears = Object.keys(booksByYear).sort((a: any, b: any) => b - a);
---

<SectionContainer title="bookshelf" description="stuff i read">
    <main class="flex flex-col flex-1 gap-4 mt-4">
        <h1 class="text-3xl font-extrabold">[ bookshelf ]</h1>
        <h2 class="text-xl font-semibold">on the shelf</h2>
        <ul class="flex flex-col text-s gap-2 text-l">
            {booksShelf.length !== 0 ? (
            booksShelf.map((book) => (
                <li class="borderbottom">📚 {book.title}</li>
            ))
          ) : (
            <p>currently empty...</p>
          )}
        </ul>

        <h2 class="text-xl font-semibold">on the nightstand</h2>
        <ul  class="flex flex-col text-s gap-2 text-l">
          {booksReading.length !== 0 ? (
            booksReading.map((book) => (
              <li class="borderbottom">📖 {book.title}</li>
            ))
          ) : (
            <p>currently empty...</p>
          )}
        </ul>

        {sortedYears.map(year => (
          <details>
            <summary class="text-xl font-semibold cursor-pointer">{year} <span class="text-xs">({booksByYear[year].length} entries)</span></summary>
              <ul class="mt-2">
                {booksByYear[year].map((book) => (
                  <div class="flex justify-between mb-2 break-words gap-2 borderbottom">
                    <p class="text-s">{book.title}</p>
                    <p>{book.rating === 5 ? "❤️" : ""}</p>
                  </div>
                ))}
              </ul>
          </details>
        ))}

        <details>
          <summary class="text-xl font-semibold cursor-pointer">want to read</summary>
          <ul>
              {booksWant.map((book) => (
                  <li class="borderbottom">{book.title}</li>
              ))}
          </ul>
        </details>
    </main>
</SectionContainer>
