'use client'

import { createContext, ReactNode, useContext, useMemo } from 'react'
import { AllauthConfig, defaultConfig, createAllauthConfig } from '../config'

const Context = createContext<AllauthConfig>(defaultConfig)

interface ConfigContextProps {
    children: ReactNode
    config?: Partial<AllauthConfig>
}

export function ConfigContext({ children, config }: ConfigContextProps) {
    // Memoize the merged config to prevent creating new objects on every render
    const mergedConfig = useMemo(
        () => config ? createAllauthConfig(config) : defaultConfig,
        [config]
    )

    return (
        <Context value={mergedConfig}>
            {children}
        </Context>
    )
}

export function useAllauthConfig(): AllauthConfig {
    return useContext(Context)
}
