import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
import { Providers } from './providers'
import prisma from '@/lib/prisma'
import PurchaseToast from '@/components/PurchaseToast'
import LiveChat from '@/components/LiveChat'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: {
    default: 'AmaneNime Store — Top Up Game & Digital Products',
    template: '%s | AmaneNime Store',
  },
  description: 'Top up game murah, cepat & terpercaya. Mobile Legends, Free Fire, PUBG, dan lebih banyak game. Juga tersedia produk digital premium: Netflix, Spotify, YouTube Premium, dan lainnya.',
  keywords: ['top up game', 'topup mobile legends', 'topup murah', 'netflix murah', 'spotify premium', 'voucher game'],
  openGraph: {
    title: 'AmaneNime Store — Top Up Game & Digital Products',
    description: 'Top up game murah, cepat & terpercaya.',
    url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',
    siteName: 'AmaneNime Store',
    locale: 'id_ID',
    type: 'website',
  },
  robots: {
    index: true,
    follow: true,
  },
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  let themeStyles = ''
  try {
    const settings = await prisma.setting.findMany({ where: { key: { startsWith: 'theme_' } } })
    const theme: Record<string, string> = {
      accent: '#f59e0b', accentDark: '#d97706', accentLight: '#fbbf24',
      bgPrimary: '#0a0a0f', bgSecondary: '#111118', bgCard: '#16161f',
      success: '#10b981', error: '#ef4444', info: '#3b82f6', purple: '#8b5cf6'
    }
    settings.forEach(s => theme[s.key.replace('theme_', '')] = s.value)
    
    themeStyles = `
      :root {
        --accent: ${theme.accent};
        --accent-dark: ${theme.accentDark};
        --accent-light: ${theme.accentLight};
        --bg-primary: ${theme.bgPrimary};
        --bg-secondary: ${theme.bgSecondary};
        --bg-card: ${theme.bgCard};
        --success: ${theme.success};
        --error: ${theme.error};
        --info: ${theme.info};
        --purple: ${theme.purple};
      }
    `
  } catch (e) {
    console.error('Failed to load theme:', e)
  }

  return (
    <html lang="id" suppressHydrationWarning>
      <head>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
        <link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@400;500;600;700&display=swap" rel="stylesheet" />
        {themeStyles && <style dangerouslySetInnerHTML={{ __html: themeStyles }} />}
      </head>
      <body className={inter.className}>
        <Providers>
          {children}
          <PurchaseToast />
          <LiveChat />
        </Providers>
      </body>
    </html>
  )
}
