import { createStore } from '@stencil/store';
const safeRead = (storage, key) => {
  try {
    return JSON.parse(storage.getItem(key));
  }
  catch {
    return null;
  }
};
const debounce = fn => {
  let called = false;
  return () => {
    if (called) {
      return;
    }
    called = true;
    setTimeout(() => {
      fn();
      called = false;
    }, 0);
  };
};
export const createStorageStore = (storage, key, defaultValues, syncAcrossTabs = false) => {
  var _a;
  const store = createStore((_a = safeRead(storage, key)) !== null && _a !== void 0 ? _a : defaultValues, (newValue, oldValue) => {
    return JSON.stringify(newValue) !== JSON.stringify(oldValue);
  });
  // Need to sync later or we would get ourselves in an infinite loop.
  const write = debounce(() => storage.setItem(key, JSON.stringify(store.state)));
  write();
  if (syncAcrossTabs) {
    window.addEventListener('storage', () => {
      const currentState = safeRead(storage, key);
      if (currentState === null) {
        return;
      }
      for (const key in currentState) {
        store.set(key, currentState[key]);
      }
    });
  }
  store.use({ set: write, reset: write });
  return store;
};
export const createLocalStore = (key, defaultValues, syncAcrossTabs = false) => createStorageStore(localStorage, key, defaultValues, syncAcrossTabs);
export const createSessionStore = (key, defaultValues) => createStorageStore(sessionStorage, key, defaultValues);
