import { redirect } from 'next/navigation'
import Image from 'next/image'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

export default async function AuthLayout({
  children,
}: {
  children: React.ReactNode
}) {
  let session = null
  try {
    session = await auth()
  } catch (error) {
    // Auth check failed, continue as unauthenticated
    console.error('Auth check failed in auth layout:', error)
  }

  // Redirect logged-in users to their dashboard
  // But NOT if they still need to set their password
  if (session?.user && !session.user.mustSetPassword) {
    // Verify user still exists in DB (handles deleted accounts with stale sessions)
    const dbUser = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: { id: true },
    })

    if (dbUser) {
      const role = session.user.role
      if (role === 'SUPER_ADMIN' || role === 'PROGRAM_ADMIN') {
        redirect('/admin')
      } else if (role === 'JURY_MEMBER') {
        redirect('/jury')
      } else if (role === 'OBSERVER') {
        redirect('/observer')
      } else if (role === 'MENTOR') {
        redirect('/mentor')
      }
    }
    // If user doesn't exist in DB, fall through and show auth page
  }

  return (
    <div className="min-h-screen flex flex-col">
      {/* Simple header with logo */}
      <header className="border-b bg-card">
        <div className="container-app py-4">
          <Image
            src="/images/MOPC-blue-long.png"
            alt="MOPC - Monaco Ocean Protection Challenge"
            width={160}
            height={50}
            className="h-12 w-auto"
            priority
          />
        </div>
      </header>

      {/* Main content */}
      <main className="flex-1 flex items-center justify-center p-4">
        {children}
      </main>

      {/* Simple footer */}
      <footer className="border-t bg-card py-4">
        <div className="container-app text-center text-sm text-muted-foreground">
          &copy; {new Date().getFullYear()} Monaco Ocean Protection Challenge
        </div>
      </footer>
    </div>
  )
}
