'use client'

import { LanguageProvider, useLanguage } from '@/lib/i18n/LanguageProvider'
import { LabelProvider } from '@/context/LabelContext'
import { NotebooksProvider } from '@/context/notebooks-context'
import { NotebookDragProvider } from '@/context/notebook-drag-context'
import { NoteRefreshProvider } from '@/context/NoteRefreshContext'
import { HomeViewProvider } from '@/context/home-view-context'
import type { ReactNode } from 'react'
import type { Translations } from '@/lib/i18n/load-translations'

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
}

export function ProvidersWrapper({ children, initialLanguage = 'en', initialTranslations }: ProvidersWrapperProps) {
  return (
    <NoteRefreshProvider>
      <LabelProvider>
        <NotebooksProvider>
          <NotebookDragProvider>
            <LanguageProvider initialLanguage={initialLanguage as any} initialTranslations={initialTranslations}>
              <DirWrapper>
                <HomeViewProvider>{children}</HomeViewProvider>
              </DirWrapper>
            </LanguageProvider>
          </NotebookDragProvider>
        </NotebooksProvider>
      </LabelProvider>
    </NoteRefreshProvider>
  )
}
