import type { Metadata } from 'next'
import { Montserrat, Open_Sans } from 'next/font/google'
import { Navigation } from '@/components/Navigation'
import { Footer } from '@/components/Footer'
import { getNavigation, getSiteSettings, getSocialLinks } from '@/lib/api'
import './globals.css'

export async function generateMetadata(): Promise<Metadata> {
  const settings = await getSiteSettings() as Record<string, unknown> | null
  const favicon = settings?.favicon as Record<string, unknown> | undefined
  const faviconUrl = favicon?.url as string | undefined

  return {
    title: 'Martin Porwoll',
    description: 'Whistleblower. Unternehmer. Mensch.',
    icons: faviconUrl ? { icon: faviconUrl } : undefined,
  }
}

const montserrat = Montserrat({
  subsets: ['latin'],
  weight: ['400', '700'],
  variable: '--font-montserrat',
  display: 'swap',
})

const openSans = Open_Sans({
  subsets: ['latin'],
  weight: ['300', '400', '600', '700', '800'],
  variable: '--font-open-sans',
  display: 'swap',
})

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const [navigation, siteSettings, socialLinks] = await Promise.all([
    getNavigation('header'),
    getSiteSettings(),
    getSocialLinks(),
  ])

  // Transform CMS navigation items into NavItem format
  const nav = navigation as unknown as Record<string, unknown> | null
  const navItems = nav?.items
    ? (nav.items as Array<Record<string, unknown>>).map(
        (item) => ({
          label: (item.label as string) || '',
          href: (item.link as string) || (item.url as string) || '#',
        })
      )
    : [
        { label: 'Home', href: '/' },
        { label: 'Der Mensch', href: '/mensch' },
        { label: 'Whistleblowing', href: '/whistleblowing' },
        { label: 'Kontakt', href: '/kontakt' },
      ]

  const settings = siteSettings as unknown as Record<string, unknown> | null
  const logoMedia = settings?.logo as Record<string, unknown> | undefined
  const logoUrl = logoMedia?.url as string | undefined

  const contactInfo = settings?.contactInfo as Record<string, string> | undefined

  return (
    <html lang="de" className={`${montserrat.variable} ${openSans.variable}`}>
      <body className="font-body">
        <Navigation
          items={navItems}
          logo={logoUrl}
          transparent={true}
        />

        <main id="top">
          {children}
        </main>

        <Footer
          socialLinks={socialLinks}
          contact={{
            email: contactInfo?.email,
            phone: contactInfo?.phone,
            address: contactInfo?.address,
          }}
        />
      </body>
    </html>
  )
}
