import { useState, useLayoutEffect } from 'preact/hooks'

const PREFIX = 'amidala_'

export default function usePersistentState (key, initialState) {
  const [state, setState] = useState(getGlobal(key) ?? initialState)
  setGlobal(key, state) // Save initial state.

  useLayoutEffect(() => {
    // Update local state when the global state changes.
    const listener = () => {
      // Prevent empty state.
      const globalState = getGlobal(key) ?? initialState
      setState(globalState)
    }

    globalThis.addEventListener('storage', listener)
    return () => globalThis.removeEventListener('storage', listener)
  }, [key])

  const setPersistentState = callback => {
    const newState = callback(getGlobal(key))

    // Update both global and local states.
    if (JSON.stringify(newState) !== JSON.stringify(state)) {
      setGlobal(key, newState)
      // Force change in the same window.
      globalThis.dispatchEvent(new Event('storage'))
    }
  }

  return [state, setPersistentState]
}

function getGlobal (key) {
  const value = localStorage.getItem(`${PREFIX}${key}`)
  return value ? JSON.parse(value) : null
}

function setGlobal (key, value) {
  localStorage.setItem(`${PREFIX}${key}`, JSON.stringify(value))
}
