1 import React, { createContext, useContext } from "react"
2 import { useFeatureFlags, FeatureFlags } from "../../hooks/api/feature-flags"
3
4 interface FeatureFlagContextValue {
5 flags: FeatureFlags
6 isLoading: boolean
7 isFeatureEnabled: (flag: keyof FeatureFlags) => boolean
8 }
9
10 const FeatureFlagContext = createContext<FeatureFlagContextValue | null>(null)
11
12 export const useFeatureFlag = (flag: keyof FeatureFlags): boolean => {
13 const context = useContext(FeatureFlagContext)
14 if (!context) {
15 // If no context, assume feature is disabled
16 return false
17 }
18 return context.isFeatureEnabled(flag)
19 }
20
21 export const useFeatureFlagContext = () => {
22 const context = useContext(FeatureFlagContext)
23 if (!context) {
24 throw new Error(
25 "useFeatureFlagContext must be used within FeatureFlagProvider"
26 )
27 }
28 return context
29 }
30
31 interface FeatureFlagProviderProps {
32 children: React.ReactNode
33 }
34
35 export const FeatureFlagProvider: React.FC<FeatureFlagProviderProps> = ({
36 children,
37 }) => {
38 const { data: flags = {}, isLoading } = useFeatureFlags()
39
40 const isFeatureEnabled = (flag: keyof FeatureFlags): boolean => {
41 const enabled = flags[flag] === true
42 return enabled
43 }
44
45 return (
46 <FeatureFlagContext.Provider value={{ flags, isLoading, isFeatureEnabled }}>
47 {children}
48 </FeatureFlagContext.Provider>
49 )
50 }