import { Book } from "@/lib/types";
import { fetchBooks } from "@/lib/api";

export default async function HomePage() {
  let books: Book[] = [];

  try {
    books = await fetchBooks();
  } catch (error) {
    return (
      console.log(error),
      <div className="text-center mt-10 text-red-500">
        Error fetching books. Please try again later.
      </div>
    );
  }

  return (
    <div className="mx-auto p-6 bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 min-h-screen">
      {/* Patreon Advertisement */}
      <div className="hidden md:block bg-yellow-500 text-black py-2 px-4 rounded-lg hover:bg-yellow-600 transition duration-200 mb-6">
        <a
          href="https://patreon.com/NullTranslationGroup"
          target="_blank"
          rel="noopener noreferrer"
          className="font-semibold text-center block"
        >
          🌟 Join Us on Patreon for Unreleased Chapters!
        </a>
      </div>

      {/* Books Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 px-6">
        {books.map((book: Book) => (
          <div
            key={book.id}
            className="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-md hover:shadow-lg transition flex flex-col"
          >
            {book.Cover?.url && (
              <div className="relative w-full aspect-w-3 aspect-h-4 mb-4">
                <img
                  src={`${process.env.NEXT_PUBLIC_API_URL}${book.Cover.url}`}
                  alt={book.Cover.alternativeText || `Cover of ${book.Name}`}
                  className="rounded-lg object-cover"
                />
              </div>
            )}

            <h2 className="text-2xl font-semibold mb-2">{book.Name}</h2>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              <strong>Author:</strong> {book.Author}
            </p>
            <p className="text-sm mt-2 line-clamp-3">{book.Description}</p>

            <a
              className="mt-4 inline-block bg-blue-500 hover:bg-blue-600 text-white text-sm font-semibold px-4 py-2 rounded text-center"
              href={`/books/${book.documentId}`}
            >
              Read Book
            </a>
          </div>
        ))}
      </div>
    </div>
  );
}
