import type { Metadata } from "next";
import "./globals.css";
import { QueryProvider } from "@/components/providers/query-provider";
import { ConvexClientProvider } from "@/components/providers/convex-provider";
import { AppPreferencesHydrator } from "@/components/providers/app-preferences-hydrator";
import { getMnotePublicRuntimeConfig } from "@/lib/runtime-config";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { ConvexAuthNextjsServerProvider } from "@convex-dev/auth/nextjs/server";

export const metadata: Metadata = {
  title: "Wolai Clone",
  description: "Convex 自部署模式",
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const isDesktop = process.env.MNOTE_DESKTOP === "1";
  const useConvex = isConvexEnabled();

  const runtimeConfig = { ...getMnotePublicRuntimeConfig(), isDesktop, useConvex };
  const runtimeConfigJson = JSON.stringify(runtimeConfig).replace(/</g, "\\u003cc");

  return (
    <html lang="zh-CN">
      <head>
        <script
          // 说明：桌面端需要“运行期可覆盖”的配置（避免 build 时把 NEXT_PUBLIC_* 写死）。
          // 这里将服务端读取到的配置注入到 window，客户端再优先读取它。
          dangerouslySetInnerHTML={{
            __html: `window.__MNOTE_RUNTIME_CONFIG__=${runtimeConfigJson};`,
          }}
        />
      </head>
      <body className="antialiased">
        <ConvexAuthNextjsServerProvider>
          <ConvexClientProvider>
            <AppPreferencesHydrator />
            <QueryProvider>{children}</QueryProvider>
          </ConvexClientProvider>
        </ConvexAuthNextjsServerProvider>
      </body>
    </html>
  );
}
