import React, { createContext, useMemo, useSyncExternalStore } from 'react'
import {
	getTerminalFocused,
	getTerminalFocusState,
	subscribeTerminalFocus,
	type TerminalFocusState,
} from '../terminal-focus-state.js'

export type { TerminalFocusState }
export type TerminalFocusContextProps = {
	readonly isTerminalFocused: boolean
	readonly terminalFocusState: TerminalFocusState
}
const TerminalFocusContext = createContext<TerminalFocusContextProps>({
	isTerminalFocused: true,
	terminalFocusState: 'unknown',
})

// eslint-disable-next-line custom-rules/no-top-level-side-effects
TerminalFocusContext.displayName = 'TerminalFocusContext'

export function TerminalFocusProvider({ children }: { children: React.ReactNode }) {
	const isTerminalFocused = useSyncExternalStore(subscribeTerminalFocus, getTerminalFocused)
	const terminalFocusState = useSyncExternalStore(subscribeTerminalFocus, getTerminalFocusState)
	const value = useMemo<TerminalFocusContextProps>(
		() => ({ isTerminalFocused, terminalFocusState }),
		[isTerminalFocused, terminalFocusState],
	)
	return useMemo(
		() => <TerminalFocusContext.Provider value={value}>{children}</TerminalFocusContext.Provider>,
		[children, value],
	)
}
export default TerminalFocusContext
