import { useEffect, useState } from "react";

export const useLocalStorage = <T>(key: string, initialValue: T): [T, (value: T) => void] => {
  const [storedValue, setStoredValue] = useState<T>(initialValue);

  useEffect(() => {
    if (typeof window !== "undefined") {
      try {
        const item = window.localStorage.getItem(key);
        if (item) {
          setStoredValue(JSON.parse(item));
        }
      } catch (error) {
        console.error("Error reading localStorage", error);
      }
    }
  }, [key]);

  const setValue = (value: T) => {
    setStoredValue(value);
    if (typeof window !== "undefined") {
      try {
        window.localStorage.setItem(key, JSON.stringify(value));
      } catch (error) {
        console.error("Error writing to localStorage", error);
      }
    }
  };

  return [storedValue, setValue];
};





// "use client";

// import { useEffect, useState } from 'react'

// export const useLocalStorage = <T>(
//   key: string,
//   initialValue: T
// ): [T, (value: T) => void] => {
//   const [storedValue, setStoredValue] = useState(initialValue)

//   useEffect(() => {
//     // Retrieve from localStorage
//     const item = window.localStorage.getItem(key)
//     if (item) {
//       setStoredValue(JSON.parse(item))
//     }
//   }, [key])

//   const setValue = (value: T) => {
//     // Save state
//     setStoredValue(value)
//     // Save to localStorage
//     window.localStorage.setItem(key, JSON.stringify(value))
//   }
//   return [storedValue, setValue]
// }
