"use client";

import type { ReactNode } from "react";
import { Breadcrumb } from "@/components/breadcrumb";
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger";
import { SearchPalette } from "@/components/search/search-palette";
import { Sidebar } from "@/components/sidebar/sidebar";
import { PreferredSidebarSnapshotProvider } from "@/components/sidebar/preferred-sidebar-snapshot-context";
import type { SidebarInitialData } from "@/components/sidebar/types";
import { usePreferredSidebarSnapshot } from "@/components/sidebar/use-preferred-sidebar-snapshot";
import { useSidebarData } from "@/hooks/use-sidebar-data";
import { useSidebarTreeStream } from "@/lib/tree-stream/use-sidebar-tree-stream";

interface AppLayoutShellProps {
  initialData: SidebarInitialData;
  children: ReactNode;
}

export function AppLayoutShell({ initialData, children }: AppLayoutShellProps) {
  const sidebarQuery = useSidebarData(initialData);
  const treeStream = useSidebarTreeStream(initialData);
  const preferredSidebarSnapshot = usePreferredSidebarSnapshot({
    initialData,
    sidebarQueryData: sidebarQuery.data,
    treeStreamData: treeStream.data,
    treeStreamStatus: treeStream.status,
  });

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