"use client"

import { useEffect, useLayoutEffect, type ReactNode } from "react"
import { DriveSidebar } from "@/components/drive/drive-sidebar"
import { AiChatPanel } from "@/components/ai/ai-chat-panel"
import { FilePreviewDialog } from "@/components/drive/file-preview-dialog"
import { ShareDialog } from "@/components/drive/share-dialog"
import { SuiteThemeShell } from "@/components/suite/suite-theme-shell"
import { useIsMobile } from "@/hooks/use-mobile"
import { getDemoDriveLayoutPreview } from "@/lib/demo/demo-drive-layout-preview"
import { DriveRouteRootProvider } from "@/lib/drive/drive-route-context"
import { useDriveUIStore } from "@/lib/stores/drive-ui-store"

export function DriveAppShell({
  children,
  routeRoot,
}: {
  children: ReactNode
  routeRoot?: string
}) {
  const isMobile = useIsMobile()
  const layoutPreview = getDemoDriveLayoutPreview()
  const sidebarCollapsed = useDriveUIStore((s) => s.sidebarCollapsed)
  const setSidebarCollapsed = useDriveUIStore((s) => s.setSidebarCollapsed)
  const sidebarOpen = !sidebarCollapsed

  useLayoutEffect(() => {
    if (layoutPreview) return
    if (!isMobile) setSidebarCollapsed(false)
  }, [isMobile, layoutPreview, setSidebarCollapsed])

  useEffect(() => {
    if (layoutPreview) return
    if (isMobile) setSidebarCollapsed(true)
  }, [isMobile, layoutPreview, setSidebarCollapsed])

  return (
    <DriveRouteRootProvider routeRoot={routeRoot}>
    <SuiteThemeShell>
      <div className="ultimail-app relative flex h-dvh overflow-hidden bg-app-canvas" data-drive-app>
        {isMobile && sidebarOpen && (
          <button
            type="button"
            aria-label="Fermer le menu"
            className="absolute inset-0 z-40 bg-black/20"
            onClick={() => setSidebarCollapsed(true)}
          />
        )}
        <DriveSidebar overlay={isMobile} open={sidebarOpen} />
        <div className="flex min-w-0 flex-1 flex-col bg-app-canvas" data-drive-main-column>{children}</div>
        <ShareDialog />
        <FilePreviewDialog />
        <AiChatPanel />
      </div>
    </SuiteThemeShell>
    </DriveRouteRootProvider>
  )
}
