import { getAllCategories } from '@/lib/categories'
import { getAllPostsMeta } from '@/lib/posts'
import { slugify } from '@/utils/slug'
import type { Metadata } from 'next'
import Link from 'next/link'
import { metadata } from '@/app/metadata'

export async function generateMetadata(): Promise<Metadata> {
  return { title: `Categories | ${metadata.title!.toString()}`, description: 'List of categories' }
}

export default function CategoriesPage() {
  const categories = getAllCategories()
  const posts = getAllPostsMeta()

  return (
    <div className="flex w-full">
      <main className="max-w-3xl mx-auto px-4 py-8 lg:py-16 w-full">
        <h1 className="text-3xl font-bold">Categories</h1>
        <ul>
          {Object.keys(categories).map((category) => (
            <li key={category}>
              <Link href={`/categories/${slugify(category)}`}>
                {category} ({categories[category]})
              </Link>

              <ul>
                {posts
                  .filter((post) => post.category === category)
                  .map((post) => (
                    <li key={post.slug}>
                      <Link href={`/posts/${post.slug}`}>{post.title}</Link>
                    </li>
                  ))}
              </ul>
            </li>
          ))}
        </ul>
      </main>
      <div className="w-80" />
    </div>
  )
}
