import { useState, useEffect } from 'react'

const useCollapseState = (componentName, defaultState = {}) => {
  const getInitialState = () => {
    const stored = sessionStorage.getItem(`${componentName}_collapseState`)
    if (stored) {
      return JSON.parse(stored)
    }
    return defaultState
  }

  const [collapseState, setCollapseState] = useState(getInitialState)

  useEffect(() => {
    sessionStorage.setItem(
      `${componentName}_collapseState`,
      JSON.stringify(collapseState)
    )
  }, [collapseState, componentName])

  const updateCollapseState = (key, value) => {
    setCollapseState((prev) => ({
      ...prev,
      [key]: value
    }))
  }

  return [collapseState, updateCollapseState]
}

export default useCollapseState
