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

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

export const experimentalV2 = makeVar<boolean>(initialSettings)
export const useExperimentalV2 = () => useReactiveVar(experimentalV2)

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

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

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