"use client"

import { useEffect, useLayoutEffect, type ReactNode } from "react"
import { AiChatPanel } from "@/components/ai/ai-chat-panel"
import { SuiteThemeShell } from "@/components/suite/suite-theme-shell"
import { TooltipProvider } from "@/components/ui/tooltip"
import { useIsMobile } from "@/hooks/use-mobile"
import { useAgendaUIStore } from "@/lib/agenda/agenda-store"

export function AgendaAppShell({ children }: { children: ReactNode }) {
  const isMobile = useIsMobile()
  const sidebarCollapsed = useAgendaUIStore((s) => s.sidebarCollapsed)
  const setSidebarCollapsed = useAgendaUIStore((s) => s.setSidebarCollapsed)

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

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

  return (
    <SuiteThemeShell>
      <TooltipProvider delayDuration={400}>
      <div
        className="ultimail-app relative flex h-dvh flex-col overflow-hidden bg-app-canvas"
        data-agenda-app
      >
        {isMobile && !sidebarCollapsed && (
          <button
            type="button"
            aria-label="Fermer le menu"
            className="absolute inset-0 z-40 bg-black/20"
            onClick={() => setSidebarCollapsed(true)}
          />
        )}
        {children}
        <AiChatPanel />
      </div>
      </TooltipProvider>
    </SuiteThemeShell>
  )
}
