import { useState, useEffect } from 'react'

const SIDEBAR_STORAGE_KEY = 'sidebar_collapsed'

export default function useSidebarToggle() {
  const [isCollapsed, setIsCollapsed] = useState(() => {
    if (typeof window === 'undefined') return true
    
    const saved = localStorage.getItem(SIDEBAR_STORAGE_KEY)
    return saved ? JSON.parse(saved) : true
  })

  const toggle = () => {
    setIsCollapsed(prev => {
      const newState = !prev
      localStorage.setItem(SIDEBAR_STORAGE_KEY, JSON.stringify(newState))
      return newState
    })
  }

  useEffect(() => {
    localStorage.setItem(SIDEBAR_STORAGE_KEY, JSON.stringify(isCollapsed))
  }, [isCollapsed])

  return {
    isCollapsed,
    toggle
  }
}