'use client'

import { type ReactNode, useEffect, useMemo } from 'react'

import { sidebarStore } from '@/store'

import { SidebarContext, type SidebarContextProps } from '@/contexts'
import { useIsMobile } from '@/hooks'

type SidebarProviderProps = {
	children: ReactNode
}

export function SidebarProvider({ children }: SidebarProviderProps) {
	const isMobile = useIsMobile()
	const isOpen = sidebarStore(state => state.isOpen)
	const setIsOpen = sidebarStore(state => state.setIsOpen)

	const toggleSidebar = () => {
		setIsOpen(!isOpen)
	}

	const handleKeyDown = (e: KeyboardEvent) => {
		if (e.code === 'KeyB' && (e.metaKey || e.ctrlKey)) {
			e.preventDefault()
			toggleSidebar()
		}
	}

	useEffect(() => {
		window.addEventListener('keydown', handleKeyDown)
		//
		return () => window.removeEventListener('keydown', handleKeyDown)
	}, [])

	const contextValue = useMemo<SidebarContextProps>(
		() => ({
			isOpen,
			isMobile,
			setIsOpen,
			toggleSidebar
		}),
		[isOpen, isMobile, setIsOpen, toggleSidebar]
	)

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