"use client"

import type React from "react"
import { createContext, useState, useContext, useEffect, type ReactNode } from "react"

interface SidebarContextProps {
  sidebarVisible: boolean
  setSidebarVisible: (visible: boolean) => void
  toggleSidebar: () => void
}

const SidebarContext = createContext<SidebarContextProps | undefined>(undefined)

interface SidebarProviderProps {
  children: ReactNode
}

export const SidebarProvider: React.FC<SidebarProviderProps> = ({ children }) => {
  const [sidebarVisible, setSidebarVisible] = useState(false)
  const [isMobile, setIsMobile] = useState(false)

  // Check for mobile screen size
  useEffect(() => {
    const checkMobile = () => {
      const mobile = window.innerWidth < 768
      setIsMobile(mobile)

      // Set initial sidebar state based on screen size
      if (mobile) {
        setSidebarVisible(false) // Hidden by default on mobile
      } else {
        setSidebarVisible(true) // Visible by default on desktop
      }
    }

    checkMobile()
    window.addEventListener("resize", checkMobile)

    return () => window.removeEventListener("resize", checkMobile)
  }, [])

  // Hide sidebar on route changes for mobile
  useEffect(() => {
    const handleRouteChange = () => {
      if (isMobile) {
        setSidebarVisible(false)
      }
    }

    // Listen for navigation events
    window.addEventListener("popstate", handleRouteChange)

    // Use a more stable approach for programmatic navigation
    const handleNavigation = () => {
      // Use setTimeout to avoid scheduling updates during render
      setTimeout(() => {
        if (isMobile) {
          setSidebarVisible(false)
        }
      }, 0)
    }

    // Listen for custom navigation events instead of intercepting history
    window.addEventListener("navigation", handleNavigation)

    return () => {
      window.removeEventListener("popstate", handleRouteChange)
      window.removeEventListener("navigation", handleNavigation)
    }
  }, [isMobile])

  const toggleSidebar = () => {
    setSidebarVisible((prev) => !prev)
  }

  const value: SidebarContextProps = {
    sidebarVisible,
    setSidebarVisible,
    toggleSidebar,
  }

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

export const useSidebar = (): SidebarContextProps => {
  const context = useContext(SidebarContext)
  if (!context) {
    throw new Error("useSidebar must be used within a SidebarProvider")
  }
  return context
}
