'use client'

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

interface MobileContextValue {
  // Sidebar visibility
  isLeftSidebarOpen: boolean
  isRightSidebarOpen: boolean
  // Toggle functions
  toggleLeftSidebar: () => void
  toggleRightSidebar: () => void
  openLeftSidebar: () => void
  closeLeftSidebar: () => void
  openRightSidebar: () => void
  closeRightSidebar: () => void
  // Close all sidebars (useful when navigating)
  closeAllSidebars: () => void
  // Mobile detection
  isMobile: boolean
}

const MobileContext = createContext<MobileContextValue | null>(null)

export function MobileProvider({ children }: { children: ReactNode }) {
  const [isLeftSidebarOpen, setIsLeftSidebarOpen] = useState(false)
  const [isRightSidebarOpen, setIsRightSidebarOpen] = useState(false)
  const [isMobile, setIsMobile] = useState(false)

  // Detect mobile on mount and window resize
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 1024) // lg breakpoint
    }
    
    // Initial check
    checkMobile()
    
    // Listen for resize
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  // Close sidebars when switching to desktop
  useEffect(() => {
    if (!isMobile) {
      setIsLeftSidebarOpen(false)
      setIsRightSidebarOpen(false)
    }
  }, [isMobile])

  const toggleLeftSidebar = useCallback(() => {
    setIsLeftSidebarOpen(prev => !prev)
    // Close right sidebar when opening left
    setIsRightSidebarOpen(false)
  }, [])

  const toggleRightSidebar = useCallback(() => {
    setIsRightSidebarOpen(prev => !prev)
    // Close left sidebar when opening right
    setIsLeftSidebarOpen(false)
  }, [])

  const openLeftSidebar = useCallback(() => {
    setIsLeftSidebarOpen(true)
    setIsRightSidebarOpen(false)
  }, [])

  const closeLeftSidebar = useCallback(() => {
    setIsLeftSidebarOpen(false)
  }, [])

  const openRightSidebar = useCallback(() => {
    setIsRightSidebarOpen(true)
    setIsLeftSidebarOpen(false)
  }, [])

  const closeRightSidebar = useCallback(() => {
    setIsRightSidebarOpen(false)
  }, [])

  const closeAllSidebars = useCallback(() => {
    setIsLeftSidebarOpen(false)
    setIsRightSidebarOpen(false)
  }, [])

  return (
    <MobileContext.Provider
      value={{
        isLeftSidebarOpen,
        isRightSidebarOpen,
        toggleLeftSidebar,
        toggleRightSidebar,
        openLeftSidebar,
        closeLeftSidebar,
        openRightSidebar,
        closeRightSidebar,
        closeAllSidebars,
        isMobile,
      }}
    >
      {children}
    </MobileContext.Provider>
  )
}

export function useMobile() {
  const context = useContext(MobileContext)
  if (!context) {
    throw new Error('useMobile must be used within a MobileProvider')
  }
  return context
}
