import { c as createStore } from './index6.js';
import { g as getQueryArgs, b as buildQueryString, a as addQueryArgs } from './add-query-args.js';

/**
 * Internal dependencies
 */
/**
 * Removes arguments from the query string of the url
 *
 * @param {string}    url  URL.
 * @param {...string} args Query Args.
 *
 * @example
 * ```js
 * const newUrl = removeQueryArgs( 'https://wordpress.org?foo=bar&bar=baz&baz=foobar', 'foo', 'bar' ); // https://wordpress.org?baz=foobar
 * ```
 *
 * @return {string} Updated URL.
 */

function removeQueryArgs(url) {
  const queryStringIndex = url.indexOf('?');

  if (queryStringIndex === -1) {
    return url;
  }

  const query = getQueryArgs(url);
  const baseURL = url.substr(0, queryStringIndex);

  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  args.forEach(arg => delete query[arg]);
  const queryString = buildQueryString(query);
  return queryString ? baseURL + '?' + queryString : baseURL;
}

const { state, onChange, on, set, get, dispose } = createStore({
  formId: null,
  groupId: null,
  mode: 'live',
  locks: [],
  product: null,
  checkout: null,
  currencyCode: 'usd',
  abandonedCheckoutReturnUrl: null,
  abandonedCheckoutEnabled: true,
}, (newValue, oldValue) => {
  return JSON.stringify(newValue) !== JSON.stringify(oldValue);
});

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);
  };
};
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;
};
const createLocalStore = (key, defaultValues, syncAcrossTabs = false) => createStorageStore(localStorage, key, defaultValues, syncAcrossTabs);

var _a;
const store = ((_a = window === null || window === void 0 ? void 0 : window.scData) === null || _a === void 0 ? void 0 : _a.do_not_persist_cart)
  ? createStore({
    live: {},
    test: {},
  })
  : createLocalStore('surecart-local-storage', {
    live: {},
    test: {},
  }, true);
window.scStore = store;
/** Get the checkout. */
const getOrder = (formId, mode) => { var _a; return ((_a = store.state[mode]) === null || _a === void 0 ? void 0 : _a[formId]) || {}; };
const getCheckout = getOrder;
/** Set the checkout. */
const setOrder = (data, formId) => {
  var _a;
  const mode = (data === null || data === void 0 ? void 0 : data.live_mode) ? 'live' : 'test';
  store.set(mode, { ...store.state[mode], [formId]: data });
  // update the current checkout state.
  if (state.formId === formId && state.mode === mode) {
    state.checkout = data;
  }
  // set in url only if we are not persisting the cart.
  if (((_a = window === null || window === void 0 ? void 0 : window.scData) === null || _a === void 0 ? void 0 : _a.do_not_persist_cart) && (data === null || data === void 0 ? void 0 : data.id)) {
    window.history.replaceState({}, document.title, addQueryArgs(window.location.href, { checkout_id: data === null || data === void 0 ? void 0 : data.id }));
  }
};
const setCheckout = setOrder;
/** Clear the order from the store. */
const clearOrder = (formId, mode) => {
  const { [formId]: remove, ...checkouts } = store.state[mode];
  window.history.replaceState({}, document.title, removeQueryArgs(window.location.href, 'redirect_status', 'coupon', 'line_items', 'confirm_checkout_id', 'checkout_id'));
  return store.set(mode, checkouts);
};
const clearCheckout = clearOrder;

/**
 * When the checkout changes, update the
 * checkout in localstorage.
 */
onChange('checkout', val => setCheckout(val, state.formId));
on('get', prop => {
  if (prop === 'checkout') {
    const checkout = getCheckout(state.formId, state.mode);
    if (checkout === null || checkout === void 0 ? void 0 : checkout.id) {
      state.checkout = checkout;
    }
  }
});

export { state as a, on as b, clearOrder as c, getCheckout as d, clearCheckout as e, getOrder as g, onChange as o, removeQueryArgs as r, setOrder as s };
