import Keys from '@inject/shared/localstorage/keys'
import { makeVar, useReactiveVar } from '@inject/shared/utils/reactive'

const initialSettings: boolean =
  localStorage.getItem(Keys.HIDE_SIDEBAR) === 'true'

export const hidesidebar = makeVar<boolean>(initialSettings)
export const useHideSidebarValue = () => useReactiveVar(hidesidebar)

function change(value: boolean) {
  localStorage.setItem(Keys.HIDE_SIDEBAR, value.toString())
}

window.addEventListener('storage', ({ key, newValue, oldValue }) => {
  if (key === Keys.HIDE_SIDEBAR && newValue !== oldValue) {
    const parsedValue = JSON.parse(newValue || 'false')
    hidesidebar(parsedValue)
  }
})

hidesidebar.onNextChange(function onNext() {
  change(hidesidebar())
  hidesidebar.onNextChange(onNext)
})
