'use client'

import { LanguageProvider, useLanguage } from '@/lib/i18n/LanguageProvider'
import { NotebooksProvider } from '@/context/notebooks-context'
import { EditorUIProvider } from '@/context/editor-ui-context'
import { NoteRefreshProvider } from '@/context/NoteRefreshContext'
import { QueryProvider } from '@/components/query-provider'
import type { ReactNode } from 'react'
import type { Translations } from '@/lib/i18n/load-translations'
import { AiConsentProvider } from '@/components/legal/ai-consent-provider'
import { SearchModalProvider } from '@/context/search-modal-context'
import { OnboardingWizard } from '@/components/onboarding/onboarding-wizard'
import { OnboardingEditorHints } from '@/components/onboarding/onboarding-editor-hints'

const RTL_LANGUAGES = ['ar', 'fa']

/** Sets `dir` on its own DOM node from React state — immune to third-party JS overwriting documentElement.dir. */
function DirWrapper({ children }: { children: ReactNode }) {
  const { language } = useLanguage()
  const dir = RTL_LANGUAGES.includes(language) ? 'rtl' : 'ltr'
  return <div dir={dir} className="contents">{children}</div>
}

interface ProvidersWrapperProps {
  children: ReactNode
  initialLanguage?: string
  initialTranslations?: Translations
  initialAiProcessingConsent?: boolean
}

export function ProvidersWrapper({
  children,
  initialLanguage = 'en',
  initialTranslations,
  initialAiProcessingConsent = false,
}: ProvidersWrapperProps) {
  return (
    <QueryProvider>
      <NoteRefreshProvider>
        <LanguageProvider initialLanguage={initialLanguage as any} initialTranslations={initialTranslations}>
          <NotebooksProvider>
            <EditorUIProvider>
              <AiConsentProvider initialPersistentConsent={initialAiProcessingConsent}>
                <DirWrapper>
                  <SearchModalProvider>
                    {children}
                    <OnboardingWizard />
                    <OnboardingEditorHints />
                  </SearchModalProvider>
                </DirWrapper>
              </AiConsentProvider>
            </EditorUIProvider>
          </NotebooksProvider>
        </LanguageProvider>
      </NoteRefreshProvider>
    </QueryProvider>
  )
}
