'use client'

import { useCallback, useSyncExternalStore } from 'react'

const CHANGE_EVENT = 'hha-browser-storage-change'

function read(key: string): string | null {
  try { return window.localStorage.getItem(key) } catch { return null }
}

/** A hydration-safe subscription to one localStorage value. */
export function useBrowserStorageItem(key: string): [string | null, (value: string) => void] {
  const subscribe = useCallback((notify: () => void) => {
    const storage = (event: StorageEvent) => { if (event.key === key) notify() }
    const changed = (event: Event) => {
      if ((event as CustomEvent<string>).detail === key) notify()
    }
    window.addEventListener('storage', storage)
    window.addEventListener(CHANGE_EVENT, changed)
    return () => {
      window.removeEventListener('storage', storage)
      window.removeEventListener(CHANGE_EVENT, changed)
    }
  }, [key])
  const snapshot = useCallback(() => read(key), [key])
  const value = useSyncExternalStore(subscribe, snapshot, () => null)
  const write = useCallback((next: string) => {
    try { window.localStorage.setItem(key, next) } catch { return }
    window.dispatchEvent(new CustomEvent(CHANGE_EVENT, { detail: key }))
  }, [key])
  return [value, write]
}

export function writeBrowserStorageItem(key: string, value: string): void {
  try { window.localStorage.setItem(key, value) } catch { return }
  window.dispatchEvent(new CustomEvent(CHANGE_EVENT, { detail: key }))
}
