import { createContext, useContext, type ReactNode } from 'react'
import type { AppConfig, NavGroup, UserIdentity } from '../types'

export interface AppContextValue {
  /** App configuration */
  config: AppConfig
  /** Navigation groups for the sidebar */
  navigation: NavGroup[]
  /** Current user identity (if authenticated) */
  user?: UserIdentity
  /** Whether the app is loading initial data */
  isLoading?: boolean
}

export const AppContext = createContext<AppContextValue | null>(null)

export interface AppProviderProps {
  children: ReactNode
  config: AppConfig
  navigation?: NavGroup[]
  user?: UserIdentity
  isLoading?: boolean
}

/**
 * Provides app-level configuration and state to child components.
 *
 * @example
 * ```tsx
 * <AppProvider
 *   config={{ name: 'Admin', basePath: '/admin' }}
 *   navigation={[{ label: 'Main', items: [...] }]}
 *   user={{ id: '1', fullName: 'John Doe' }}
 * >
 *   <AppShell />
 * </AppProvider>
 * ```
 */
export function AppProvider({
  children,
  config,
  navigation = [],
  user,
  isLoading,
}: AppProviderProps) {
  return (
    <AppContext.Provider value={{ config, navigation, user, isLoading }}>
      {children}
    </AppContext.Provider>
  )
}

/**
 * Hook to access app-level configuration and state.
 * Must be used within an AppProvider.
 */
export function useApp(): AppContextValue {
  const context = useContext(AppContext)
  if (!context) {
    throw new Error('useApp must be used within an AppProvider')
  }
  return context
}
