import { Mutate, StoreApi } from "zustand";
import { useEffect } from 'react';

export type StoreWithPersist<T> = Mutate<
  StoreApi<T>,
  [["zustand/persist", unknown]]
>;

export const usePersistentStorage = <T>(store: StoreWithPersist<T>) => {
  useEffect(() => {
    const storageEventCallback = (e: StorageEvent) => {
      if (e.key === store.persist.getOptions().name && e.newValue) {
        store.persist.rehydrate();
      }
    };

    if (typeof window !== 'undefined') {
      window.addEventListener("storage", storageEventCallback);
    }

    return () => {
      if (typeof window !== 'undefined') {
        window.removeEventListener("storage", storageEventCallback);
      }
    };
  }, [store]);
};