import { db } from '@/lib/db'
import { notFound } from 'next/navigation'
import ClassicLandingPage from './landing-pages/classic/page'
import ModernLandingPage from './landing-pages/modern/page'
import MinimalLandingPage from '@/components/landing-pages/MinimalLandingPage'
import CorporateLandingPage from '@/components/landing-pages/CorporateLandingPage'
import WonosoboLandingPage from '@/components/landing-pages/WonosoboLandingPage'

// Landing page components mapping
const landingPageComponents = {
  CLASSIC: ClassicLandingPage,
  MODERN: ModernLandingPage,
  MINIMAL: MinimalLandingPage,
  CORPORATE: CorporateLandingPage,
  WONOSOBO: WonosoboLandingPage,
}

export default async function Home() {
  try {
    // Fetch active landing page directly from database
    let landingPage = await db.landingPage.findFirst({
      where: { 
        isDefault: true,
        isActive: true 
      }
    })

    // If no default found, get the first active landing page
    if (!landingPage) {
      landingPage = await db.landingPage.findFirst({
        where: { isActive: true },
        orderBy: { createdAt: 'asc' }
      })
    }

    if (landingPage) {
      // Get the appropriate component for the landing page type
      const LandingPageComponent = landingPageComponents[landingPage.type]
      
      if (LandingPageComponent) {
        // Render the landing page component directly at root URL
        return <LandingPageComponent />
      } else {
        console.error(`Unknown landing page type: ${landingPage.type}`)
        // Fallback to classic if type is unknown
        return <ClassicLandingPage />
      }
    }
    
    // Fallback: if no active landing page, show default content
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">
            Sistem Pelayanan Digital
          </h1>
          <p className="text-xl text-gray-600 mb-8">
            Polres Wonosobo
          </p>
          <p className="text-gray-500">
            No active landing page configured. Please contact administrator.
          </p>
        </div>
      </div>
    )
  } catch (error) {
    console.error('Error fetching active landing page:', error)
    
    // Fallback page
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">
            Sistem Pelayanan Digital
          </h1>
          <p className="text-xl text-gray-600 mb-8">
            Polres Wonosobo
          </p>
          <p className="text-gray-500">
            System temporarily unavailable. Please try again later.
          </p>
        </div>
      </div>
    )
  }
}