"use client"

import { useEffect, useLayoutEffect, type ReactNode } from "react"
import { AiChatPanel } from "@/components/ai/ai-chat-panel"
import { AgendaOrgPolicySync } from "@/components/agenda/agenda-org-policy-sync"
import { AgendaQuickSettingsRoot } from "@/components/agenda/agenda-quick-settings-panel"
import { ComposeIdentitiesSync } from "@/components/gmail/compose-identities-sync"
import { AgendaRouteRootProvider } from "@/lib/agenda/agenda-route-context"
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,
  routeRoot,
}: {
  children: ReactNode
  routeRoot?: string
}) {
  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 (
    <AgendaRouteRootProvider routeRoot={routeRoot}>
    <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 />
        <ComposeIdentitiesSync />
        <AgendaOrgPolicySync />
        <AgendaQuickSettingsRoot />
      </div>
      </TooltipProvider>
    </SuiteThemeShell>
    </AgendaRouteRootProvider>
  )
}
