import { useEffect, useState, useCallback } from 'react'

const STORAGE_KEY = 'sidebar-collapsed'

function readInitial(): boolean {
  if (typeof window === 'undefined') return false
  return window.localStorage.getItem(STORAGE_KEY) === '1'
}

/**
 * Manages desktop sidebar collapsed state with localStorage persistence.
 * Mobile sidebar (Sheet) is independent — this hook only affects desktop ≥ lg.
 */
export function useSidebar() {
  const [collapsed, setCollapsed] = useState<boolean>(readInitial)

  useEffect(() => {
    window.localStorage.setItem(STORAGE_KEY, collapsed ? '1' : '0')
  }, [collapsed])

  const toggle = useCallback(() => setCollapsed((prev) => !prev), [])

  return { collapsed, setCollapsed, toggle }
}
