import { useEffect, useState } from 'react'

/**
 * Hook to store a boolean flag in the session storage.
 * This is useful for storing a flag within the current tab, but not across tabs.
 *
 * Typical use-case is to only show warnings, messages or modals once per session.
 *
 * @param key The key to store the flag under.
 * @param defaultValue The default value of the flag.
 */
export function useSessionFlag(
  key: string,
  defaultValue: boolean
): [boolean, (value: boolean) => void] {
  const [value, setValue] = useState<boolean>(() => {
    const stickyValue = window.sessionStorage.getItem(key)
    return stickyValue !== null ? JSON.parse(stickyValue) : defaultValue
  })

  useEffect(() => {
    window.sessionStorage.setItem(key, JSON.stringify(value))
  }, [key, value])

  return [value, setValue]
}
