import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { Sidebar } from "@/components/sidebar/sidebar";
import { GlobalAiAgentHost } from "@/components/ai-agent/GlobalAiAgentHost";
import { Breadcrumb } from "@/components/breadcrumb";
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger";
import { SearchPalette } from "@/components/search/search-palette";
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 {
      documents,
      sidebarInitialData,
    } = await loadSidebarDataFromConvex({
      client,
      userId: auth.userId,
      fallbackName: auth.name ?? auth.email ?? "我的空间",
    });

    return (
      <div className="flex h-screen w-full overflow-hidden bg-wolai-bg text-wolai-text-primary">
        {sidebarInitialData && <Sidebar initialData={sidebarInitialData} />}
        <div className="flex min-w-0 flex-1 flex-col h-full bg-white relative overflow-hidden">
          <header className="h-[44px] w-full flex items-center px-4 text-wolai-text-secondary text-sm bg-white/80 backdrop-blur-sm sticky top-0 z-50">
            <MobileSidebarTrigger />
            <Breadcrumb documents={documents} />
          </header>
          <main className="flex-1 overflow-hidden bg-white">{children}</main>
          <SearchPalette workspaceId={sidebarInitialData?.activeWorkspaceId ?? null} />
          <GlobalAiAgentHost />
        </div>
      </div>
    );
  }

  redirect("/login");
}
