import { ref, watch } from 'vue'

const STORAGE_KEY = 'chat_enabled'

const chatEnabled = ref(localStorage.getItem(STORAGE_KEY) !== 'false')

watch(chatEnabled, (val) => {
  localStorage.setItem(STORAGE_KEY, val)
})

if (typeof window !== 'undefined') {
  window.addEventListener('storage', (e) => {
    if (e.key === STORAGE_KEY) {
      chatEnabled.value = e.newValue !== 'false'
    }
  })
}

export function useChatToggle() {
  function toggleChat() {
    chatEnabled.value = !chatEnabled.value
  }

  return { chatEnabled, toggleChat }
}
