// composables/useLocalStorage.ts
import { ref, watchEffect } from "vue";

export const useLocalStorage = <T>(key: string, defaultValue: T) => {
  const state = ref<T>(defaultValue);

  // Only run on client-side
  if (process.client) {
    const readValue = () => {
      try {
        const item = window.localStorage.getItem(key);
        return item ? (JSON.parse(item) as T) : defaultValue;
      } catch (error) {
        console.warn(`Error reading localStorage key "${key}":`, error);
        return defaultValue;
      }
    };

    state.value = readValue();

    watchEffect(() => {
      try {
        window.localStorage.setItem(key, JSON.stringify(state.value));
      } catch (error) {
        console.warn(`Error setting localStorage key "${key}":`, error);
      }
    });

    // Handle storage events from other tabs
    window.addEventListener("storage", (event) => {
      if (event.key === key) {
        state.value = readValue();
      }
    });
  }

  return state;
};