'use client'

import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from 'react'

export type UiMode = 'guided' | 'expert'

const UI_MODE_STORAGE_KEY = 'explorer_ui_mode'

const UiModeContext = createContext<{
  mode: UiMode
  setMode: (mode: UiMode) => void
  toggleMode: () => void
} | null>(null)

export function UiModeProvider({ children }: { children: ReactNode }) {
  const [mode, setModeState] = useState<UiMode>('guided')

  useEffect(() => {
    if (typeof window === 'undefined') return
    const stored = window.localStorage.getItem(UI_MODE_STORAGE_KEY)
    if (stored === 'guided' || stored === 'expert') {
      setModeState(stored)
    }
  }, [])

  const setMode = (nextMode: UiMode) => {
    setModeState(nextMode)
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(UI_MODE_STORAGE_KEY, nextMode)
    }
  }

  const value = useMemo(
    () => ({
      mode,
      setMode,
      toggleMode: () => setMode(mode === 'guided' ? 'expert' : 'guided'),
    }),
    [mode],
  )

  return <UiModeContext.Provider value={value}>{children}</UiModeContext.Provider>
}

export function useUiMode() {
  const context = useContext(UiModeContext)
  if (!context) {
    throw new Error('useUiMode must be used within a UiModeProvider')
  }
  return context
}

export function Explain({ children }: { children: ReactNode }) {
  const { mode } = useUiMode()
  if (mode === 'expert') return null
  return <>{children}</>
}
