import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { books } from '../../books';

export const Route = createFileRoute('/books/$bookId')({
  parseParams: (params) => ({
    bookId: Number(params.bookId),
  }),

  loader: async ({ params }) => {
    const { bookId } = params;

    const allBooks = await Promise.resolve(books);

    const book = allBooks.find((b) => b.id === bookId);

    return { book };
  },

  component: RouteComponent,
});

function RouteComponent() {
  const { book } = Route.useLoaderData();
  const { bookId } = Route.useParams();
  const navigate = useNavigate();

  console.log('bookId (number):', bookId);

  return (
    <div>
      <h1>{book?.title}</h1>
      <p>Autor: {book?.author}</p>
      <p>ISBN: {book?.isbn}</p>
      <p>Bewertung: {book?.rating} Sterne</p>
      <button onClick={() => navigate({ to: '/books' })}>zurück</button>
    </div>
  );
}

