export const dynamic = 'force-dynamic'

import { redirect } from 'next/navigation'
import { getServerSession } from '@/lib/auth'
import { getLibrariesForUser } from '@/lib/users'
import LibraryCard from '@/components/LibraryCard'

export default async function HomePage() {
  const session = await getServerSession()
  if (!session.userId) redirect('/login')

  const libraries = getLibrariesForUser(session.userId, session.role)

  if (libraries.length === 0) {
    if (session.role === 'admin') {
      redirect('/manage')
    }
    return (
      <div className="text-center py-16">
        <p className="text-lg font-medium mb-2" style={{ color: 'var(--text-primary)' }}>
          No libraries available
        </p>
        <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
          An administrator needs to grant you access to libraries.
        </p>
      </div>
    )
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-semibold mb-1" style={{ color: 'var(--text-primary)' }}>
            Libraries
          </h1>
          <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
            {libraries.length} {libraries.length === 1 ? 'library' : 'libraries'} available
          </p>
        </div>
      </div>
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
        {libraries.map((lib) => (
          <LibraryCard key={lib.id} library={lib} />
        ))}
      </div>
    </div>
  )
}
