"use client"

import { useState, useCallback } from "react"

function getStorageItem<T>(key: string, initialValue: T): T {
  try {
    const item = window.localStorage.getItem(key)
    return item ? (JSON.parse(item) as T) : initialValue
  } catch {
    return initialValue
  }
}

export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((prev: T) => T)) => void] {
  const [localValue, setLocalValue] = useState<T>(() => getStorageItem(key, initialValue))

  const setValue = useCallback((newValue: T | ((prev: T) => T)) => {
    setLocalValue((prev) => {
      const nextValue = newValue instanceof Function ? newValue(prev) : newValue
      try {
        window.localStorage.setItem(key, JSON.stringify(nextValue))
      } catch (error) {
        console.error(`Error setting localStorage key "${key}":`, error)
      }
      return nextValue
    })
  }, [key])

  return [localValue, setValue]
}
