'use client'
import { TooltipProvider } from '@/components/ui/tooltip'
import { Toaster } from '@/components/ui/toaster'
import { Toaster as Sonner } from '@/components/ui/sonner'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { LanguageProvider } from '@/contexts/LanguageContext'
import { AuthProvider } from '@/contexts/AuthContext'
import { useEffect, useState } from 'react'

import { ThemeProvider } from 'next-themes'

export function Providers({ children }: { children: React.ReactNode }) {
    const [queryClient] = useState(() => new QueryClient())

    useEffect(() => {
        const RELOAD_KEY = 'aau_runtime_reload_once'
        const dynamicImportErrorPattern =
            /(ChunkLoadError|Loading chunk [\w-]+ failed|Failed to fetch dynamically imported module|Importing a module script failed)/i

        const reloadOnce = () => {
            try {
                if (sessionStorage.getItem(RELOAD_KEY) === '1') return
                sessionStorage.setItem(RELOAD_KEY, '1')
                window.location.reload()
            } catch {
                window.location.reload()
            }
        }

        const getMessage = (value: unknown) => {
            if (typeof value === 'string') return value
            if (value && typeof value === 'object' && 'message' in value) {
                const message = (value as { message?: unknown }).message
                return typeof message === 'string' ? message : ''
            }
            return ''
        }

        const handleError = (event: ErrorEvent) => {
            const message = `${event.message || ''} ${getMessage(event.error)}`.trim()
            if (dynamicImportErrorPattern.test(message)) {
                reloadOnce()
            }
        }

        const handleRejection = (event: PromiseRejectionEvent) => {
            const message = getMessage(event.reason)
            if (dynamicImportErrorPattern.test(message)) {
                reloadOnce()
            }
        }

        window.addEventListener('error', handleError)
        window.addEventListener('unhandledrejection', handleRejection)
        return () => {
            window.removeEventListener('error', handleError)
            window.removeEventListener('unhandledrejection', handleRejection)
        }
    }, [])

    return (
        <QueryClientProvider client={queryClient}>
            <LanguageProvider>
                <ThemeProvider attribute="class" defaultTheme="light" enableSystem={false}>
                    <TooltipProvider>
                        <AuthProvider>
                            <Toaster />
                            <Sonner />
                            {children}
                        </AuthProvider>
                    </TooltipProvider>
                </ThemeProvider>
            </LanguageProvider>
        </QueryClientProvider>
    )
}

