/**
 * Globals Context — shared state for the Globals feature
 *
 * Provides settings state + drill-down navigation to both
 * the sidebar (GlobalsSidebar) and the main content (GlobalsSettings).
 *
 * Wraps the entire AppContent so both trees can consume it.
 * The underlying hook only fetches data when the globals page is active.
 */

import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { useNavigation } from '@/contexts/navigation-context'
import { useGlobalStyles } from '../hooks/use-global-styles'
import { GlobalStyles } from '../config'

/* ── Types ────────────────────────────────────────────────── */

export type GlobalsView = 'home' | 'colors' | 'typography'

interface GlobalsContextType {
  /* settings state */
  settings: GlobalStyles
  loading: boolean
  saving: boolean
  error: string | null
  hasChanges: boolean
  setSettings: (settings: GlobalStyles) => void
  saveSettings: (newSettings?: Partial<GlobalStyles>) => Promise<boolean>
  resetToDefaults: () => void
  fetchSettings: () => Promise<void>
  /* drill-down navigation */
  globalsView: GlobalsView
  setGlobalsView: (view: GlobalsView) => void
}

/* ── Context ──────────────────────────────────────────────── */

const GlobalsContext = createContext<GlobalsContextType | null>(null)

export function GlobalsProvider({ children }: { children: ReactNode }) {
  const { currentPage } = useNavigation()
  const isActive = currentPage === 'globals'

  const state = useGlobalStyles(isActive)
  const [globalsView, setGlobalsView] = useState<GlobalsView>('home')

  // Reset drill-down when navigating away from globals
  useEffect(() => {
    if (!isActive) setGlobalsView('home')
  }, [isActive])

  return (
    <GlobalsContext.Provider value={{ ...state, globalsView, setGlobalsView }}>
      {children}
    </GlobalsContext.Provider>
  )
}

export function useGlobalsContext() {
  const context = useContext(GlobalsContext)
  if (!context) {
    throw new Error('useGlobalsContext must be used within a GlobalsProvider')
  }
  return context
}
