import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import Script from "next/script";
import React from "react";
import "./globals.scss";
import { SignalRProvider } from '@/contexts/signalrProvider';
import { AuthProvider } from "@/contexts/authProvider";
import { MemberProvider } from "@/contexts/memberProvider";
import { ConfigProvider } from "@/contexts/configProvider";
import { getAccessToken, getSignalRCryptoUrl, getSignalRChatUrl } from "@/lib/utils/server";
import { fetchConfig } from "@/lib/api/system";

const geistSans = Geist({
    variable: "--font-geist-sans",
    subsets: ["latin"],
});

const geistMono = Geist_Mono({
    variable: "--font-geist-mono",
    subsets: ["latin"],
});

export async function generateMetadata(): Promise<Metadata> {
    const config = (await fetchConfig())?.data;

    return {
        title: config?.basic?.siteName ?? 'bitforum',
        description: config?.meta?.description ?? '',
        keywords: config?.meta?.keywords ?? '',
        authors: config?.meta?.author ? [{ name: config.meta.author }] : undefined,
        applicationName: config?.meta.applicationName,
        generator: config?.meta.generator,
        robots: config?.meta.robots
    };
}

export default async function RootLayout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {

	const accessToken = await getAccessToken();
	const signalRCryptoUrl = await getSignalRCryptoUrl();
	const signalRChatUrl = await getSignalRChatUrl();
    const config = (await fetchConfig())?.data;

    return (
        <html lang="ko">
            <head>
                <Script src="https://www.googletagmanager.com/gtag/js?id=G-DY6YFW4CTM" strategy="afterInteractive" />
                <Script id="gtag-init" strategy="afterInteractive">
                    {`
                        window.dataLayer = window.dataLayer || [];
                        function gtag(){dataLayer.push(arguments);}
                        gtag('js', new Date());
                        gtag('config', 'G-DY6YFW4CTM');
                    `}
                </Script>
            </head>
            <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
                <SignalRProvider accessToken={accessToken} signalRCryptoUrl={signalRCryptoUrl} signalRChatUrl={signalRChatUrl}>
                    <AuthProvider>
                        <MemberProvider>
                            <ConfigProvider initialConfig={config}>
                                {children}
                            </ConfigProvider>
                        </MemberProvider>
                    </AuthProvider>
                </SignalRProvider>
            </body>
        </html>
    );
}