import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { AppLayoutShell } from "@/components/app-layout-shell";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { loadSidebarDataFromConvex } from "@/lib/server/sidebar-data";

export default async function AppLayout({ children }: { children: ReactNode }) {
  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    const {
      sidebarInitialData,
    } = await loadSidebarDataFromConvex({
      client,
      auth,
      fallbackName: auth.name ?? auth.email ?? "我的空间",
    });

    if (!sidebarInitialData) {
      return (
        <div className="flex h-screen w-full overflow-hidden bg-wolai-bg text-wolai-text-primary">
          <div className="relative flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-white">
            <main className="flex-1 overflow-hidden bg-white">{children}</main>
          </div>
        </div>
      );
    }

    return (
      <AppLayoutShell initialData={sidebarInitialData}>
        {children}
      </AppLayoutShell>
    );
  }

  redirect("/login");
}
