'use client'

import { createContext, useContext, useState, useCallback, useMemo } from 'react'

interface NoteRefreshContextType {
  refreshKey: number
  triggerRefresh: () => void
}

const NoteRefreshContext = createContext<NoteRefreshContextType | undefined>(undefined)

export function NoteRefreshProvider({ children }: { children: React.ReactNode }) {
  const [refreshKey, setRefreshKey] = useState(0)

  const triggerRefresh = useCallback(() => {
    setRefreshKey(prev => prev + 1)
  }, [])

  const value = useMemo(() => ({ refreshKey, triggerRefresh }), [refreshKey, triggerRefresh])

  return (
    <NoteRefreshContext.Provider value={value}>
      {children}
    </NoteRefreshContext.Provider>
  )
}

export function useNoteRefresh() {
  const context = useContext(NoteRefreshContext)
  if (!context) {
    throw new Error('useNoteRefresh must be used within NoteRefreshProvider')
  }
  return context
}

/**
 * Same as useNoteRefresh but tolerates being called outside the provider
 * (e.g. shared header rendered in admin pages). Returns a no-op when absent.
 */
export function useNoteRefreshOptional(): NoteRefreshContextType {
  const context = useContext(NoteRefreshContext)
  return context ?? { refreshKey: 0, triggerRefresh: () => {} }
}
