var __defProp = Object.defineProperty;
var __getProtoOf = Object.getPrototypeOf;
var __reflectGet = Reflect.get;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var __accessCheck = (obj, member, msg) => {
  if (!member.has(obj))
    throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
  __accessCheck(obj, member, "read from private field");
  return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
  if (member.has(obj))
    throw TypeError("Cannot add the same private member more than once");
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
  __accessCheck(obj, member, "write to private field");
  setter ? setter.call(obj, value) : member.set(obj, value);
  return value;
};
var __privateWrapper = (obj, member, setter, getter) => ({
  set _(value) {
    __privateSet(obj, member, value, setter);
  },
  get _() {
    return __privateGet(obj, member, getter);
  }
});
var __privateMethod = (obj, member, method) => {
  __accessCheck(obj, member, "access private method");
  return method;
};
var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
var _debounceClear, _timeout, _setDebounce, setDebounce_fn, _getFocusableSelectors, getFocusableSelectors_fn, _logging, _current, _cssRule, _docKey, _selector, _styleElement, _version, _hostData, _DerivedReducerCtor, _parentIndex, _derived, _destroyed, _filtersData, _indexUpdate, _mapUnsubscribe, _sortData, _indexUpdate2, _unsubscribe, _indexData, _map, _derived2, _derivedPublicAPI, _filters, _filtersData2, _index, _indexPublicAPI, _reversed, _sort, _sortData2, _subscriptions, _destroyed2, _updateSubscribers, updateSubscribers_fn, _map2, _derived3, _derivedPublicAPI2, _filters2, _filtersData3, _index2, _indexPublicAPI2, _reversed2, _sort2, _sortData3, _subscriptions2, _destroyed3, _updateSubscribers2, updateSubscribers_fn2, _stores, _createStore, createStore_fn, _getStore, getStore_fn, _renderContextRegex, _name, _document, _collectionToDocName, _embeddedNames, _document2, _embeddedStoreManager, _embeddedAPI, _uuidv4, _options, _subscriptions3, _updateOptions, _deleted, deleted_fn, _updateSubscribers3, updateSubscribers_fn3, _setDocument, setDocument_fn, _ease, _easeOptions, _subscriptions4, _updateSubscribers4, updateSubscribers_fn4, _stores2, _animationData, _finishedPromise, _willFinish, _voidControl, _data, _position, _instanceCount, _cleanup, _addAnimation, addAnimation_fn, _cleanupInstance, cleanupInstance_fn, _animationControls, _finishedPromise2, _voidControl2, _isPosition, isPosition_fn, _element, _height, _lock, _width, _data2, _dataSaved, _position2, _transforms, _boundingRect, _corners, _mat4, _originTranslations, _enabled, _validatorData, _mapUnsubscribe2, _constrain, _element2, _enabled2, _height2, _lock2, _width2, _constrain2, _element3, _enabled3, _height3, _lock3, _width3, _orderList, _data3, _animate, _enabled4, _positionChangeSet, _options2, _parent, _stores3, _styleCache, _subscriptions5, _transforms2, _updateElementData, _updateElementPromise, _validators, _validatorData2, _state, _updatePosition, updatePosition_fn, _application, _dataSaved2, _applicationShellHolder, _svelteData, _application2, _initialized, _sessionStorage, _storeAppOptions, _storeAppOptionsUpdate, _dataUIState, _storeUIState, _storeUIStateUpdate, _storeUnsubscribe, _storesInitialize, storesInitialize_fn, _storesSubscribe, storesSubscribe_fn, _storesUnsubscribe, storesUnsubscribe_fn, _applicationShellHolder2, _applicationState, _elementTarget, _elementContent, _initialZIndex, _onMount, _position3, _reactive, _svelteData2, _getSvelteData, _stores4, _updateApplicationShell, updateApplicationShell_fn, _application3, _data4, _managedPromise, _invokeFn, invokeFn_fn, _a, _sheet, _sheetMap, _initialized2, _initialize, initialize_fn, _clamp, clamp_fn, _onQuit, _s_UUID_REGEX, _transformUUID, transformUUID_fn, _b, _contextMenu, _processItems, processItems_fn, _active, _activationTimeout, _deactivationTimeout, _pending, _onActivate, onActivate_fn, _onDeactivate, onDeactivate_fn, _startDeactivation, startDeactivation_fn, _clearDeactivation, clearDeactivation_fn;
const styles = "";
const module_name = "item-piles";
const module_path = `modules/${module_name}/`;
const baseFlag = `flags.${module_name}`;
const CONSTANTS = {
  MODULE_NAME: module_name,
  PATH: module_path,
  ACTOR_DELTA_PROPERTY: "actorData",
  FLAGS: {
    VERSION: `${baseFlag}.version`,
    PILE: `${baseFlag}.data`,
    ITEM: `${baseFlag}.item`,
    NO_VERSION: `${baseFlag}.-=version`,
    NO_PILE: `${baseFlag}.-=data`,
    NO_ITEM: `${baseFlag}.-=item`,
    LOG: `${baseFlag}.log`,
    SHARING: `${baseFlag}.sharing`,
    PUBLIC_TRADE_ID: `${baseFlag}.publicTradeId`,
    TRADE_USERS: `${baseFlag}.tradeUsers`,
    TEMPORARY_ITEM: `${baseFlag}.temporary_item`,
    CUSTOM_CATEGORY: `${baseFlag}.item.customCategory`
  },
  SIMPLE_FLAGS: {
    VERSION: `${module_name}.version`,
    PILE: `${module_name}.data`,
    ITEM: `${module_name}.item`,
    NO_VERSION: `${module_name}.-=version`,
    NO_PILE: `${module_name}.-=data`,
    NO_ITEM: `${module_name}.-=item`,
    LOG: `${module_name}.log`,
    SHARING: `${module_name}.sharing`,
    PUBLIC_TRADE_ID: `${module_name}.publicTradeId`,
    TRADE_USERS: `${module_name}.tradeUsers`,
    TEMPORARY_ITEM: `${module_name}.temporary_item`,
    CUSTOM_CATEGORY: `${module_name}.item.customCategory`
  },
  ITEM_DEFAULTS: {
    // Merchants
    hidden: false,
    notForSale: false,
    infiniteQuantity: "default",
    displayQuantity: "default",
    free: false,
    keepZeroQuantity: false,
    disableNormalCost: false,
    cantBeSoldToMerchants: false,
    isService: false,
    keepOnMerchant: false,
    macro: "",
    customCategory: "",
    prices: [],
    // Vaults
    vaultExpander: false,
    vaultSlot: null,
    addsCols: 0,
    addsRows: 0,
    x: null,
    y: null,
    width: 1,
    height: 1,
    flipped: false,
    vaultImage: "",
    vaultImageFlipped: "",
    canStack: "default"
  },
  PILE_TYPES: {
    PILE: "pile",
    CONTAINER: "container",
    MERCHANT: "merchant",
    VAULT: "vault"
  },
  VAULT_LOGGING_TYPES: {
    USER_ACTOR: "user_actor",
    USER: "user",
    ACTOR: "actor"
  },
  CUSTOM_PILE_TYPES: {},
  PILE_DEFAULTS: {
    // Core settings
    enabled: false,
    type: "pile",
    distance: 1,
    macro: "",
    deleteWhenEmpty: "default",
    canStackItems: "yes",
    canInspectItems: true,
    displayItemTypes: false,
    description: "",
    // Overrides
    overrideItemFilters: false,
    overrideCurrencies: false,
    overrideSecondaryCurrencies: false,
    // Token settings
    displayOne: false,
    showItemName: false,
    overrideSingleItemScale: false,
    singleItemScale: 1,
    // Sharing settings
    shareItemsEnabled: false,
    shareCurrenciesEnabled: true,
    takeAllEnabled: false,
    splitAllEnabled: true,
    activePlayers: false,
    // Container settings
    closed: false,
    locked: false,
    closedImage: "",
    closedImages: [],
    emptyImage: "",
    emptyImages: [],
    openedImage: "",
    openedImages: [],
    lockedImage: "",
    lockedImages: [],
    closeSound: "",
    closeSounds: [],
    openSound: "",
    openSounds: [],
    lockedSound: "",
    lockedSounds: [],
    unlockedSound: "",
    unlockedSounds: [],
    // Merchant settings
    merchantImage: "",
    infiniteQuantity: false,
    infiniteCurrencies: true,
    purchaseOnly: false,
    hideNewItems: false,
    hideItemsWithZeroCost: false,
    keepZeroQuantity: false,
    onlyAcceptBasePrice: true,
    displayQuantity: "yes",
    buyPriceModifier: 1,
    sellPriceModifier: 0.5,
    itemTypePriceModifiers: [],
    actorPriceModifiers: [],
    tablesForPopulate: [],
    merchantColumns: [],
    hideTokenWhenClosed: false,
    openTimes: {
      enabled: false,
      status: "open",
      /*
      auto = rely on simple calendar
      open = always open
      closed = always closed
       */
      open: {
        hour: 9,
        minute: 0
      },
      close: {
        hour: 18,
        minute: 0
      }
    },
    closedDays: [],
    closedHolidays: [],
    refreshItemsOnOpen: false,
    refreshItemsDays: [],
    refreshItemsHolidays: [],
    logMerchantActivity: false,
    // Vault settings
    cols: 10,
    rows: 5,
    restrictVaultAccess: false,
    vaultExpansion: false,
    baseExpansionCols: 0,
    baseExpansionRows: 0,
    vaultAccess: [],
    logVaultActions: false,
    vaultLogType: "user_actor"
  }
};
CONSTANTS.ITEM_FORCED_UNIQUE_KEYS = ["vaultExpander"].map((val) => CONSTANTS.FLAGS.ITEM + "." + val);
const prefix = /* @__PURE__ */ __name((string) => (strings, ...expressions) => `${string}-${strings.reduce((a, c, i) => a + expressions[i - 1] + c)}`, "prefix");
const module = prefix(CONSTANTS.MODULE_NAME);
CONSTANTS.HOOKS = {
  READY: module`ready`,
  RESET_SETTINGS: module`resetSettings`,
  DRAG_DOCUMENT: module`onDragDocument`,
  DROP_DOCUMENT: module`onDropDocument`,
  PRE_TRANSFER_EVERYTHING: module`preTransferEverything`,
  TRANSFER_EVERYTHING: module`transferEverything`,
  PRE_RENDER_SHEET: module`preRenderActorSheet`,
  PRE_RENDER_INTERFACE: module`preRenderInterface`,
  PRE_OPEN_INTERFACE: module`preOpenInterface`,
  OPEN_INTERFACE: module`openInterface`,
  PRE_CLOSE_INTERFACE: module`preCloseInterface`,
  CLOSE_INTERFACE: module`closeInterface`,
  RENDER_VAULT_GRID_ITEM: module`renderVaultGridItem`,
  PILE: {
    PRE_CREATE: module`preCreateItemPile`,
    CREATE: module`createItemPile`,
    PRE_UPDATE: module`preUpdateItemPile`,
    UPDATE: module`updateItemPile`,
    PRE_DELETE: module`preDeleteItemPile`,
    DELETE: module`deleteItemPile`,
    PRE_CLOSE: module`preCloseItemPile`,
    CLOSE: module`closeItemPile`,
    PRE_OPEN: module`preOpenItemPile`,
    OPEN: module`openItemPile`,
    PRE_LOCK: module`preLockItemPile`,
    LOCK: module`lockItemPile`,
    PRE_UNLOCK: module`preUnlockItemPile`,
    UNLOCK: module`unlockItemPile`,
    PRE_RATTLE: module`preRattleItemPile`,
    RATTLE: module`rattleItemPile`,
    PRE_TURN_INTO: module`preTurnIntoItemPiles`,
    TURN_INTO: module`turnIntoItemPiles`,
    PRE_REVERT_FROM: module`preRevertFromItemPiles`,
    REVERT_FROM: module`revertFromItemPiles`,
    PRE_SPLIT_INVENTORY: module`preSplitItemPileContent`,
    SPLIT_INVENTORY: module`splitItemPileContent`,
    PRE_CLICK: module`preClickItemPile`,
    PRE_DIRECTORY_CLICK: module`preClickDirectoryItemPile`,
    PRE_RIGHT_CLICK_ITEM: module`preRightClickItem`,
    PRE_REFRESH_INVENTORY: module`preRefreshInventory`
  },
  ITEM: {
    PRE_DROP_DETERMINED: module`preDropItemDetermined`,
    PRE_DROP: module`preDropItem`,
    DROP: module`dropItem`,
    PRE_TRANSFER: module`preTransferItems`,
    TRANSFER: module`transferItems`,
    PRE_ADD: module`preAddItems`,
    ADD: module`addItems`,
    PRE_REMOVE: module`preRemoveItems`,
    REMOVE: module`removeItems`,
    PRE_TRANSFER_ALL: module`preTransferAllItems`,
    TRANSFER_ALL: module`transferAllItems`,
    PRE_CALC_TRADE: module`preCalculateTradeItems`,
    PRE_TRADE: module`preTradeItems`,
    TRADE: module`tradeItems`,
    PRE_GIVE: module`preGiveItem`,
    GIVE: module`giveItem`
  },
  CURRENCY: {
    PRE_TRANSFER: module`preTransferCurrencies`,
    TRANSFER: module`transferCurrencies`,
    PRE_ADD: module`preAddCurrencies`,
    ADD: module`addCurrencies`,
    PRE_REMOVE: module`preRemoveCurrencies`,
    REMOVE: module`removeCurrencies`,
    PRE_TRANSFER_ALL: module`preTransferAllCurrencies`,
    TRANSFER_ALL: module`transferAllCurrencies`
  },
  ATTRIBUTE: {
    PRE_TRANSFER: module`preTransferAttributes`,
    TRANSFER: module`transferAttributes`,
    PRE_SET: module`preSetAttributes`,
    SET: module`setAttributes`,
    PRE_ADD: module`preAddAttributes`,
    ADD: module`addAttributes`,
    PRE_REMOVE: module`preRemoveAttributes`,
    REMOVE: module`removeAttributes`,
    PRE_TRANSFER_ALL: module`preTransferAllAttributes`,
    TRANSFER_ALL: module`transferAllAttributes`
  },
  TRADE: {
    STARTED: module`tradeStarted`,
    COMPLETE: module`tradeComplete`
  }
};
const dnd4e = {
  "VERSION": "1.0.4",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "Player Character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "classFeats,feat,raceFeats,pathFeats,destinyFeats,ritual,power"
    }
  ],
  // This function is an optional system handler that specifically transforms an item when it is added to actors
  "ITEM_TRANSFORMER": async (itemData) => {
    ["equipped", "proficient", "prepared"].forEach((key) => {
      if (itemData?.system?.[key] !== void 0) {
        delete itemData.system[key];
      }
    });
    setProperty(itemData, "system.attunement", false);
    return itemData;
  },
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "DND4EBETA.CurrencyAD",
      img: "icons/commodities/gems/gem-faceted-round-white.webp",
      abbreviation: "{#}AD",
      data: {
        path: "system.currency.ad"
      },
      primary: false,
      exchangeRate: 1e4
    },
    {
      type: "attribute",
      name: "DND4EBETA.CurrencyPP",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}PP",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 100
    },
    {
      type: "attribute",
      name: "DND4EBETA.CurrencyGP",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}GP",
      data: {
        path: "system.currency.gp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND4EBETA.CurrencySP",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#}SP",
      data: {
        path: "system.currency.sp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "DND4EBETA.CurrencyCP",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}CP",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    },
    {
      type: "attribute",
      name: "DND4EBETA.RitualCompAR",
      img: "icons/commodities/materials/bowl-powder-teal.webp",
      abbreviation: "{#}AR",
      data: {
        path: "system.ritualcomp.ar"
      },
      primary: false,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND4EBETA.RitualCompMS",
      img: "icons/commodities/materials/bowl-liquid-white.webp",
      abbreviation: "{#}MS",
      data: {
        path: "system.ritualcomp.ms"
      },
      primary: false,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND4EBETA.RitualCompRH",
      img: "icons/commodities/materials/plant-sprout-seed-brown-green.webp",
      abbreviation: "{#}RH",
      data: {
        path: "system.ritualcomp.rh"
      },
      primary: false,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND4EBETA.RitualCompSI",
      img: "icons/commodities/materials/bowl-liquid-red.webp",
      abbreviation: "{#}SI",
      data: {
        path: "system.ritualcomp.si"
      },
      primary: false,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND4EBETA.RitualCompRS",
      img: "icons/commodities/gems/gem-faceted-cushion-teal.webp",
      abbreviation: "{#}RS",
      data: {
        path: "system.ritualcomp.rs"
      },
      primary: false,
      exchangeRate: 1
    }
  ]
};
function noop() {
}
__name(noop, "noop");
const identity = /* @__PURE__ */ __name((x) => x, "identity");
function assign(tar, src) {
  for (const k in src)
    tar[k] = src[k];
  return tar;
}
__name(assign, "assign");
function run(fn) {
  return fn();
}
__name(run, "run");
function blank_object() {
  return /* @__PURE__ */ Object.create(null);
}
__name(blank_object, "blank_object");
function run_all(fns) {
  fns.forEach(run);
}
__name(run_all, "run_all");
function is_function(thing) {
  return typeof thing === "function";
}
__name(is_function, "is_function");
function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function");
}
__name(safe_not_equal, "safe_not_equal");
let src_url_equal_anchor;
function src_url_equal(element_src, url) {
  if (!src_url_equal_anchor) {
    src_url_equal_anchor = document.createElement("a");
  }
  src_url_equal_anchor.href = url;
  return element_src === src_url_equal_anchor.href;
}
__name(src_url_equal, "src_url_equal");
function is_empty(obj) {
  return Object.keys(obj).length === 0;
}
__name(is_empty, "is_empty");
function subscribe(store, ...callbacks) {
  if (store == null) {
    return noop;
  }
  const unsub = store.subscribe(...callbacks);
  return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
__name(subscribe, "subscribe");
function get_store_value(store) {
  let value;
  subscribe(store, (_) => value = _)();
  return value;
}
__name(get_store_value, "get_store_value");
function component_subscribe(component, store, callback) {
  component.$$.on_destroy.push(subscribe(store, callback));
}
__name(component_subscribe, "component_subscribe");
function create_slot(definition, ctx, $$scope, fn) {
  if (definition) {
    const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
    return definition[0](slot_ctx);
  }
}
__name(create_slot, "create_slot");
function get_slot_context(definition, ctx, $$scope, fn) {
  return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx;
}
__name(get_slot_context, "get_slot_context");
function get_slot_changes(definition, $$scope, dirty, fn) {
  if (definition[2] && fn) {
    const lets = definition[2](fn(dirty));
    if ($$scope.dirty === void 0) {
      return lets;
    }
    if (typeof lets === "object") {
      const merged = [];
      const len = Math.max($$scope.dirty.length, lets.length);
      for (let i = 0; i < len; i += 1) {
        merged[i] = $$scope.dirty[i] | lets[i];
      }
      return merged;
    }
    return $$scope.dirty | lets;
  }
  return $$scope.dirty;
}
__name(get_slot_changes, "get_slot_changes");
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
  if (slot_changes) {
    const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
    slot.p(slot_context, slot_changes);
  }
}
__name(update_slot_base, "update_slot_base");
function get_all_dirty_from_scope($$scope) {
  if ($$scope.ctx.length > 32) {
    const dirty = [];
    const length = $$scope.ctx.length / 32;
    for (let i = 0; i < length; i++) {
      dirty[i] = -1;
    }
    return dirty;
  }
  return -1;
}
__name(get_all_dirty_from_scope, "get_all_dirty_from_scope");
function exclude_internal_props(props) {
  const result = {};
  for (const k in props)
    if (k[0] !== "$")
      result[k] = props[k];
  return result;
}
__name(exclude_internal_props, "exclude_internal_props");
function compute_slots(slots) {
  const result = {};
  for (const key in slots) {
    result[key] = true;
  }
  return result;
}
__name(compute_slots, "compute_slots");
function null_to_empty(value) {
  return value == null ? "" : value;
}
__name(null_to_empty, "null_to_empty");
function set_store_value(store, ret, value) {
  store.set(value);
  return ret;
}
__name(set_store_value, "set_store_value");
function action_destroyer(action_result) {
  return action_result && is_function(action_result.destroy) ? action_result.destroy : noop;
}
__name(action_destroyer, "action_destroyer");
const is_client = typeof window !== "undefined";
let now = is_client ? () => window.performance.now() : () => Date.now();
let raf = is_client ? (cb) => requestAnimationFrame(cb) : noop;
const tasks = /* @__PURE__ */ new Set();
function run_tasks(now2) {
  tasks.forEach((task) => {
    if (!task.c(now2)) {
      tasks.delete(task);
      task.f();
    }
  });
  if (tasks.size !== 0)
    raf(run_tasks);
}
__name(run_tasks, "run_tasks");
function loop$1(callback) {
  let task;
  if (tasks.size === 0)
    raf(run_tasks);
  return {
    promise: new Promise((fulfill) => {
      tasks.add(task = { c: callback, f: fulfill });
    }),
    abort() {
      tasks.delete(task);
    }
  };
}
__name(loop$1, "loop$1");
const globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global;
function append(target, node) {
  target.appendChild(node);
}
__name(append, "append");
function get_root_for_style(node) {
  if (!node)
    return document;
  const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
  if (root && root.host) {
    return root;
  }
  return node.ownerDocument;
}
__name(get_root_for_style, "get_root_for_style");
function append_empty_stylesheet(node) {
  const style_element = element("style");
  append_stylesheet(get_root_for_style(node), style_element);
  return style_element.sheet;
}
__name(append_empty_stylesheet, "append_empty_stylesheet");
function append_stylesheet(node, style) {
  append(node.head || node, style);
  return style.sheet;
}
__name(append_stylesheet, "append_stylesheet");
function insert(target, node, anchor) {
  target.insertBefore(node, anchor || null);
}
__name(insert, "insert");
function detach(node) {
  if (node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
__name(detach, "detach");
function destroy_each(iterations, detaching) {
  for (let i = 0; i < iterations.length; i += 1) {
    if (iterations[i])
      iterations[i].d(detaching);
  }
}
__name(destroy_each, "destroy_each");
function element(name) {
  return document.createElement(name);
}
__name(element, "element");
function svg_element(name) {
  return document.createElementNS("http://www.w3.org/2000/svg", name);
}
__name(svg_element, "svg_element");
function text(data2) {
  return document.createTextNode(data2);
}
__name(text, "text");
function space() {
  return text(" ");
}
__name(space, "space");
function empty() {
  return text("");
}
__name(empty, "empty");
function listen(node, event, handler, options) {
  node.addEventListener(event, handler, options);
  return () => node.removeEventListener(event, handler, options);
}
__name(listen, "listen");
function prevent_default(fn) {
  return function(event) {
    event.preventDefault();
    return fn.call(this, event);
  };
}
__name(prevent_default, "prevent_default");
function stop_propagation(fn) {
  return function(event) {
    event.stopPropagation();
    return fn.call(this, event);
  };
}
__name(stop_propagation, "stop_propagation");
function attr(node, attribute, value) {
  if (value == null)
    node.removeAttribute(attribute);
  else if (node.getAttribute(attribute) !== value)
    node.setAttribute(attribute, value);
}
__name(attr, "attr");
const always_set_through_set_attribute = ["width", "height"];
function set_attributes(node, attributes) {
  const descriptors = Object.getOwnPropertyDescriptors(node.__proto__);
  for (const key in attributes) {
    if (attributes[key] == null) {
      node.removeAttribute(key);
    } else if (key === "style") {
      node.style.cssText = attributes[key];
    } else if (key === "__value") {
      node.value = node[key] = attributes[key];
    } else if (descriptors[key] && descriptors[key].set && always_set_through_set_attribute.indexOf(key) === -1) {
      node[key] = attributes[key];
    } else {
      attr(node, key, attributes[key]);
    }
  }
}
__name(set_attributes, "set_attributes");
function to_number(value) {
  return value === "" ? null : +value;
}
__name(to_number, "to_number");
function children(element2) {
  return Array.from(element2.childNodes);
}
__name(children, "children");
function set_data(text2, data2) {
  data2 = "" + data2;
  if (text2.data === data2)
    return;
  text2.data = data2;
}
__name(set_data, "set_data");
function set_input_value(input, value) {
  input.value = value == null ? "" : value;
}
__name(set_input_value, "set_input_value");
function set_style(node, key, value, important) {
  if (value == null) {
    node.style.removeProperty(key);
  } else {
    node.style.setProperty(key, value, important ? "important" : "");
  }
}
__name(set_style, "set_style");
function select_option(select, value, mounting) {
  for (let i = 0; i < select.options.length; i += 1) {
    const option = select.options[i];
    if (option.__value === value) {
      option.selected = true;
      return;
    }
  }
  if (!mounting || value !== void 0) {
    select.selectedIndex = -1;
  }
}
__name(select_option, "select_option");
function select_value(select) {
  const selected_option = select.querySelector(":checked");
  return selected_option && selected_option.__value;
}
__name(select_value, "select_value");
function toggle_class(element2, name, toggle) {
  element2.classList[toggle ? "add" : "remove"](name);
}
__name(toggle_class, "toggle_class");
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  const e = document.createEvent("CustomEvent");
  e.initCustomEvent(type, bubbles, cancelable, detail);
  return e;
}
__name(custom_event, "custom_event");
const _HtmlTag = class _HtmlTag {
  constructor(is_svg = false) {
    this.is_svg = false;
    this.is_svg = is_svg;
    this.e = this.n = null;
  }
  c(html) {
    this.h(html);
  }
  m(html, target, anchor = null) {
    if (!this.e) {
      if (this.is_svg)
        this.e = svg_element(target.nodeName);
      else
        this.e = element(target.nodeType === 11 ? "TEMPLATE" : target.nodeName);
      this.t = target.tagName !== "TEMPLATE" ? target : target.content;
      this.c(html);
    }
    this.i(anchor);
  }
  h(html) {
    this.e.innerHTML = html;
    this.n = Array.from(this.e.nodeName === "TEMPLATE" ? this.e.content.childNodes : this.e.childNodes);
  }
  i(anchor) {
    for (let i = 0; i < this.n.length; i += 1) {
      insert(this.t, this.n[i], anchor);
    }
  }
  p(html) {
    this.d();
    this.h(html);
    this.i(this.a);
  }
  d() {
    this.n.forEach(detach);
  }
};
__name(_HtmlTag, "HtmlTag");
let HtmlTag = _HtmlTag;
function construct_svelte_component(component, props) {
  return new component(props);
}
__name(construct_svelte_component, "construct_svelte_component");
const managed_styles = /* @__PURE__ */ new Map();
let active = 0;
function hash(str) {
  let hash2 = 5381;
  let i = str.length;
  while (i--)
    hash2 = (hash2 << 5) - hash2 ^ str.charCodeAt(i);
  return hash2 >>> 0;
}
__name(hash, "hash");
function create_style_information(doc, node) {
  const info = { stylesheet: append_empty_stylesheet(node), rules: {} };
  managed_styles.set(doc, info);
  return info;
}
__name(create_style_information, "create_style_information");
function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
  const step = 16.666 / duration;
  let keyframes = "{\n";
  for (let p = 0; p <= 1; p += step) {
    const t = a + (b - a) * ease(p);
    keyframes += p * 100 + `%{${fn(t, 1 - t)}}
`;
  }
  const rule = keyframes + `100% {${fn(b, 1 - b)}}
}`;
  const name = `__svelte_${hash(rule)}_${uid}`;
  const doc = get_root_for_style(node);
  const { stylesheet, rules } = managed_styles.get(doc) || create_style_information(doc, node);
  if (!rules[name]) {
    rules[name] = true;
    stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
  }
  const animation = node.style.animation || "";
  node.style.animation = `${animation ? `${animation}, ` : ""}${name} ${duration}ms linear ${delay}ms 1 both`;
  active += 1;
  return name;
}
__name(create_rule, "create_rule");
function delete_rule(node, name) {
  const previous = (node.style.animation || "").split(", ");
  const next2 = previous.filter(
    name ? (anim) => anim.indexOf(name) < 0 : (anim) => anim.indexOf("__svelte") === -1
    // remove all Svelte animations
  );
  const deleted = previous.length - next2.length;
  if (deleted) {
    node.style.animation = next2.join(", ");
    active -= deleted;
    if (!active)
      clear_rules();
  }
}
__name(delete_rule, "delete_rule");
function clear_rules() {
  raf(() => {
    if (active)
      return;
    managed_styles.forEach((info) => {
      const { ownerNode } = info.stylesheet;
      if (ownerNode)
        detach(ownerNode);
    });
    managed_styles.clear();
  });
}
__name(clear_rules, "clear_rules");
function create_animation(node, from, fn, params) {
  if (!from)
    return noop;
  const to = node.getBoundingClientRect();
  if (from.left === to.left && from.right === to.right && from.top === to.top && from.bottom === to.bottom)
    return noop;
  const {
    delay = 0,
    duration = 300,
    easing = identity,
    // @ts-ignore todo: should this be separated from destructuring? Or start/end added to public api and documentation?
    start: start_time = now() + delay,
    // @ts-ignore todo:
    end = start_time + duration,
    tick: tick2 = noop,
    css
  } = fn(node, { from, to }, params);
  let running = true;
  let started = false;
  let name;
  function start() {
    if (css) {
      name = create_rule(node, 0, 1, duration, delay, easing, css);
    }
    if (!delay) {
      started = true;
    }
  }
  __name(start, "start");
  function stop() {
    if (css)
      delete_rule(node, name);
    running = false;
  }
  __name(stop, "stop");
  loop$1((now2) => {
    if (!started && now2 >= start_time) {
      started = true;
    }
    if (started && now2 >= end) {
      tick2(1, 0);
      stop();
    }
    if (!running) {
      return false;
    }
    if (started) {
      const p = now2 - start_time;
      const t = 0 + 1 * easing(p / duration);
      tick2(t, 1 - t);
    }
    return true;
  });
  start();
  tick2(0, 1);
  return stop;
}
__name(create_animation, "create_animation");
function fix_position(node) {
  const style = getComputedStyle(node);
  if (style.position !== "absolute" && style.position !== "fixed") {
    const { width, height } = style;
    const a = node.getBoundingClientRect();
    node.style.position = "absolute";
    node.style.width = width;
    node.style.height = height;
    add_transform(node, a);
  }
}
__name(fix_position, "fix_position");
function add_transform(node, a) {
  const b = node.getBoundingClientRect();
  if (a.left !== b.left || a.top !== b.top) {
    const style = getComputedStyle(node);
    const transform = style.transform === "none" ? "" : style.transform;
    node.style.transform = `${transform} translate(${a.left - b.left}px, ${a.top - b.top}px)`;
  }
}
__name(add_transform, "add_transform");
let current_component;
function set_current_component(component) {
  current_component = component;
}
__name(set_current_component, "set_current_component");
function get_current_component() {
  if (!current_component)
    throw new Error("Function called outside component initialization");
  return current_component;
}
__name(get_current_component, "get_current_component");
function beforeUpdate(fn) {
  get_current_component().$$.before_update.push(fn);
}
__name(beforeUpdate, "beforeUpdate");
function onMount(fn) {
  get_current_component().$$.on_mount.push(fn);
}
__name(onMount, "onMount");
function onDestroy(fn) {
  get_current_component().$$.on_destroy.push(fn);
}
__name(onDestroy, "onDestroy");
function createEventDispatcher() {
  const component = get_current_component();
  return (type, detail, { cancelable = false } = {}) => {
    const callbacks = component.$$.callbacks[type];
    if (callbacks) {
      const event = custom_event(type, detail, { cancelable });
      callbacks.slice().forEach((fn) => {
        fn.call(component, event);
      });
      return !event.defaultPrevented;
    }
    return true;
  };
}
__name(createEventDispatcher, "createEventDispatcher");
function setContext(key, context) {
  get_current_component().$$.context.set(key, context);
  return context;
}
__name(setContext, "setContext");
function getContext(key) {
  return get_current_component().$$.context.get(key);
}
__name(getContext, "getContext");
function bubble(component, event) {
  const callbacks = component.$$.callbacks[event.type];
  if (callbacks) {
    callbacks.slice().forEach((fn) => fn.call(this, event));
  }
}
__name(bubble, "bubble");
const dirty_components = [];
const binding_callbacks = [];
let render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = /* @__PURE__ */ Promise.resolve();
let update_scheduled = false;
function schedule_update() {
  if (!update_scheduled) {
    update_scheduled = true;
    resolved_promise.then(flush);
  }
}
__name(schedule_update, "schedule_update");
function tick() {
  schedule_update();
  return resolved_promise;
}
__name(tick, "tick");
function add_render_callback(fn) {
  render_callbacks.push(fn);
}
__name(add_render_callback, "add_render_callback");
function add_flush_callback(fn) {
  flush_callbacks.push(fn);
}
__name(add_flush_callback, "add_flush_callback");
const seen_callbacks = /* @__PURE__ */ new Set();
let flushidx = 0;
function flush() {
  if (flushidx !== 0) {
    return;
  }
  const saved_component = current_component;
  do {
    try {
      while (flushidx < dirty_components.length) {
        const component = dirty_components[flushidx];
        flushidx++;
        set_current_component(component);
        update(component.$$);
      }
    } catch (e) {
      dirty_components.length = 0;
      flushidx = 0;
      throw e;
    }
    set_current_component(null);
    dirty_components.length = 0;
    flushidx = 0;
    while (binding_callbacks.length)
      binding_callbacks.pop()();
    for (let i = 0; i < render_callbacks.length; i += 1) {
      const callback = render_callbacks[i];
      if (!seen_callbacks.has(callback)) {
        seen_callbacks.add(callback);
        callback();
      }
    }
    render_callbacks.length = 0;
  } while (dirty_components.length);
  while (flush_callbacks.length) {
    flush_callbacks.pop()();
  }
  update_scheduled = false;
  seen_callbacks.clear();
  set_current_component(saved_component);
}
__name(flush, "flush");
function update($$) {
  if ($$.fragment !== null) {
    $$.update();
    run_all($$.before_update);
    const dirty = $$.dirty;
    $$.dirty = [-1];
    $$.fragment && $$.fragment.p($$.ctx, dirty);
    $$.after_update.forEach(add_render_callback);
  }
}
__name(update, "update");
function flush_render_callbacks(fns) {
  const filtered = [];
  const targets = [];
  render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
  targets.forEach((c) => c());
  render_callbacks = filtered;
}
__name(flush_render_callbacks, "flush_render_callbacks");
let promise;
function wait$1() {
  if (!promise) {
    promise = Promise.resolve();
    promise.then(() => {
      promise = null;
    });
  }
  return promise;
}
__name(wait$1, "wait$1");
function dispatch(node, direction, kind) {
  node.dispatchEvent(custom_event(`${direction ? "intro" : "outro"}${kind}`));
}
__name(dispatch, "dispatch");
const outroing = /* @__PURE__ */ new Set();
let outros;
function group_outros() {
  outros = {
    r: 0,
    c: [],
    p: outros
    // parent group
  };
}
__name(group_outros, "group_outros");
function check_outros() {
  if (!outros.r) {
    run_all(outros.c);
  }
  outros = outros.p;
}
__name(check_outros, "check_outros");
function transition_in(block, local) {
  if (block && block.i) {
    outroing.delete(block);
    block.i(local);
  }
}
__name(transition_in, "transition_in");
function transition_out(block, local, detach2, callback) {
  if (block && block.o) {
    if (outroing.has(block))
      return;
    outroing.add(block);
    outros.c.push(() => {
      outroing.delete(block);
      if (callback) {
        if (detach2)
          block.d(1);
        callback();
      }
    });
    block.o(local);
  } else if (callback) {
    callback();
  }
}
__name(transition_out, "transition_out");
const null_transition = { duration: 0 };
function create_in_transition(node, fn, params) {
  const options = { direction: "in" };
  let config = fn(node, params, options);
  let running = false;
  let animation_name;
  let task;
  let uid = 0;
  function cleanup() {
    if (animation_name)
      delete_rule(node, animation_name);
  }
  __name(cleanup, "cleanup");
  function go() {
    const { delay = 0, duration = 300, easing = identity, tick: tick2 = noop, css } = config || null_transition;
    if (css)
      animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);
    tick2(0, 1);
    const start_time = now() + delay;
    const end_time = start_time + duration;
    if (task)
      task.abort();
    running = true;
    add_render_callback(() => dispatch(node, true, "start"));
    task = loop$1((now2) => {
      if (running) {
        if (now2 >= end_time) {
          tick2(1, 0);
          dispatch(node, true, "end");
          cleanup();
          return running = false;
        }
        if (now2 >= start_time) {
          const t = easing((now2 - start_time) / duration);
          tick2(t, 1 - t);
        }
      }
      return running;
    });
  }
  __name(go, "go");
  let started = false;
  return {
    start() {
      if (started)
        return;
      started = true;
      delete_rule(node);
      if (is_function(config)) {
        config = config(options);
        wait$1().then(go);
      } else {
        go();
      }
    },
    invalidate() {
      started = false;
    },
    end() {
      if (running) {
        cleanup();
        running = false;
      }
    }
  };
}
__name(create_in_transition, "create_in_transition");
function create_out_transition(node, fn, params) {
  const options = { direction: "out" };
  let config = fn(node, params, options);
  let running = true;
  let animation_name;
  const group = outros;
  group.r += 1;
  function go() {
    const { delay = 0, duration = 300, easing = identity, tick: tick2 = noop, css } = config || null_transition;
    if (css)
      animation_name = create_rule(node, 1, 0, duration, delay, easing, css);
    const start_time = now() + delay;
    const end_time = start_time + duration;
    add_render_callback(() => dispatch(node, false, "start"));
    loop$1((now2) => {
      if (running) {
        if (now2 >= end_time) {
          tick2(0, 1);
          dispatch(node, false, "end");
          if (!--group.r) {
            run_all(group.c);
          }
          return false;
        }
        if (now2 >= start_time) {
          const t = easing((now2 - start_time) / duration);
          tick2(1 - t, t);
        }
      }
      return running;
    });
  }
  __name(go, "go");
  if (is_function(config)) {
    wait$1().then(() => {
      config = config(options);
      go();
    });
  } else {
    go();
  }
  return {
    end(reset) {
      if (reset && config.tick) {
        config.tick(1, 0);
      }
      if (running) {
        if (animation_name)
          delete_rule(node, animation_name);
        running = false;
      }
    }
  };
}
__name(create_out_transition, "create_out_transition");
function create_bidirectional_transition(node, fn, params, intro) {
  const options = { direction: "both" };
  let config = fn(node, params, options);
  let t = intro ? 0 : 1;
  let running_program = null;
  let pending_program = null;
  let animation_name = null;
  function clear_animation() {
    if (animation_name)
      delete_rule(node, animation_name);
  }
  __name(clear_animation, "clear_animation");
  function init2(program, duration) {
    const d = program.b - t;
    duration *= Math.abs(d);
    return {
      a: t,
      b: program.b,
      d,
      duration,
      start: program.start,
      end: program.start + duration,
      group: program.group
    };
  }
  __name(init2, "init");
  function go(b) {
    const { delay = 0, duration = 300, easing = identity, tick: tick2 = noop, css } = config || null_transition;
    const program = {
      start: now() + delay,
      b
    };
    if (!b) {
      program.group = outros;
      outros.r += 1;
    }
    if (running_program || pending_program) {
      pending_program = program;
    } else {
      if (css) {
        clear_animation();
        animation_name = create_rule(node, t, b, duration, delay, easing, css);
      }
      if (b)
        tick2(0, 1);
      running_program = init2(program, duration);
      add_render_callback(() => dispatch(node, b, "start"));
      loop$1((now2) => {
        if (pending_program && now2 > pending_program.start) {
          running_program = init2(pending_program, duration);
          pending_program = null;
          dispatch(node, running_program.b, "start");
          if (css) {
            clear_animation();
            animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
          }
        }
        if (running_program) {
          if (now2 >= running_program.end) {
            tick2(t = running_program.b, 1 - t);
            dispatch(node, running_program.b, "end");
            if (!pending_program) {
              if (running_program.b) {
                clear_animation();
              } else {
                if (!--running_program.group.r)
                  run_all(running_program.group.c);
              }
            }
            running_program = null;
          } else if (now2 >= running_program.start) {
            const p = now2 - running_program.start;
            t = running_program.a + running_program.d * easing(p / running_program.duration);
            tick2(t, 1 - t);
          }
        }
        return !!(running_program || pending_program);
      });
    }
  }
  __name(go, "go");
  return {
    run(b) {
      if (is_function(config)) {
        wait$1().then(() => {
          config = config(options);
          go(b);
        });
      } else {
        go(b);
      }
    },
    end() {
      clear_animation();
      running_program = pending_program = null;
    }
  };
}
__name(create_bidirectional_transition, "create_bidirectional_transition");
function destroy_block(block, lookup) {
  block.d(1);
  lookup.delete(block.key);
}
__name(destroy_block, "destroy_block");
function outro_and_destroy_block(block, lookup) {
  transition_out(block, 1, 1, () => {
    lookup.delete(block.key);
  });
}
__name(outro_and_destroy_block, "outro_and_destroy_block");
function fix_and_outro_and_destroy_block(block, lookup) {
  block.f();
  outro_and_destroy_block(block, lookup);
}
__name(fix_and_outro_and_destroy_block, "fix_and_outro_and_destroy_block");
function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block2, next2, get_context) {
  let o = old_blocks.length;
  let n = list.length;
  let i = o;
  const old_indexes = {};
  while (i--)
    old_indexes[old_blocks[i].key] = i;
  const new_blocks = [];
  const new_lookup = /* @__PURE__ */ new Map();
  const deltas = /* @__PURE__ */ new Map();
  const updates = [];
  i = n;
  while (i--) {
    const child_ctx = get_context(ctx, list, i);
    const key = get_key(child_ctx);
    let block = lookup.get(key);
    if (!block) {
      block = create_each_block2(key, child_ctx);
      block.c();
    } else if (dynamic) {
      updates.push(() => block.p(child_ctx, dirty));
    }
    new_lookup.set(key, new_blocks[i] = block);
    if (key in old_indexes)
      deltas.set(key, Math.abs(i - old_indexes[key]));
  }
  const will_move = /* @__PURE__ */ new Set();
  const did_move = /* @__PURE__ */ new Set();
  function insert2(block) {
    transition_in(block, 1);
    block.m(node, next2);
    lookup.set(block.key, block);
    next2 = block.first;
    n--;
  }
  __name(insert2, "insert");
  while (o && n) {
    const new_block = new_blocks[n - 1];
    const old_block = old_blocks[o - 1];
    const new_key = new_block.key;
    const old_key = old_block.key;
    if (new_block === old_block) {
      next2 = new_block.first;
      o--;
      n--;
    } else if (!new_lookup.has(old_key)) {
      destroy(old_block, lookup);
      o--;
    } else if (!lookup.has(new_key) || will_move.has(new_key)) {
      insert2(new_block);
    } else if (did_move.has(old_key)) {
      o--;
    } else if (deltas.get(new_key) > deltas.get(old_key)) {
      did_move.add(new_key);
      insert2(new_block);
    } else {
      will_move.add(old_key);
      o--;
    }
  }
  while (o--) {
    const old_block = old_blocks[o];
    if (!new_lookup.has(old_block.key))
      destroy(old_block, lookup);
  }
  while (n)
    insert2(new_blocks[n - 1]);
  run_all(updates);
  return new_blocks;
}
__name(update_keyed_each, "update_keyed_each");
function get_spread_update(levels, updates) {
  const update2 = {};
  const to_null_out = {};
  const accounted_for = { $$scope: 1 };
  let i = levels.length;
  while (i--) {
    const o = levels[i];
    const n = updates[i];
    if (n) {
      for (const key in o) {
        if (!(key in n))
          to_null_out[key] = 1;
      }
      for (const key in n) {
        if (!accounted_for[key]) {
          update2[key] = n[key];
          accounted_for[key] = 1;
        }
      }
      levels[i] = n;
    } else {
      for (const key in o) {
        accounted_for[key] = 1;
      }
    }
  }
  for (const key in to_null_out) {
    if (!(key in update2))
      update2[key] = void 0;
  }
  return update2;
}
__name(get_spread_update, "get_spread_update");
function get_spread_object(spread_props) {
  return typeof spread_props === "object" && spread_props !== null ? spread_props : {};
}
__name(get_spread_object, "get_spread_object");
function bind(component, name, callback) {
  const index2 = component.$$.props[name];
  if (index2 !== void 0) {
    component.$$.bound[index2] = callback;
    callback(component.$$.ctx[index2]);
  }
}
__name(bind, "bind");
function create_component(block) {
  block && block.c();
}
__name(create_component, "create_component");
function mount_component(component, target, anchor, customElement) {
  const { fragment, after_update } = component.$$;
  fragment && fragment.m(target, anchor);
  if (!customElement) {
    add_render_callback(() => {
      const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
      if (component.$$.on_destroy) {
        component.$$.on_destroy.push(...new_on_destroy);
      } else {
        run_all(new_on_destroy);
      }
      component.$$.on_mount = [];
    });
  }
  after_update.forEach(add_render_callback);
}
__name(mount_component, "mount_component");
function destroy_component(component, detaching) {
  const $$ = component.$$;
  if ($$.fragment !== null) {
    flush_render_callbacks($$.after_update);
    run_all($$.on_destroy);
    $$.fragment && $$.fragment.d(detaching);
    $$.on_destroy = $$.fragment = null;
    $$.ctx = [];
  }
}
__name(destroy_component, "destroy_component");
function make_dirty(component, i) {
  if (component.$$.dirty[0] === -1) {
    dirty_components.push(component);
    schedule_update();
    component.$$.dirty.fill(0);
  }
  component.$$.dirty[i / 31 | 0] |= 1 << i % 31;
}
__name(make_dirty, "make_dirty");
function init(component, options, instance2, create_fragment2, not_equal, props, append_styles, dirty = [-1]) {
  const parent_component = current_component;
  set_current_component(component);
  const $$ = component.$$ = {
    fragment: null,
    ctx: [],
    // state
    props,
    update: noop,
    not_equal,
    bound: blank_object(),
    // lifecycle
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
    // everything else
    callbacks: blank_object(),
    dirty,
    skip_bound: false,
    root: options.target || parent_component.$$.root
  };
  append_styles && append_styles($$.root);
  let ready = false;
  $$.ctx = instance2 ? instance2(component, options.props || {}, (i, ret, ...rest) => {
    const value = rest.length ? rest[0] : ret;
    if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
      if (!$$.skip_bound && $$.bound[i])
        $$.bound[i](value);
      if (ready)
        make_dirty(component, i);
    }
    return ret;
  }) : [];
  $$.update();
  ready = true;
  run_all($$.before_update);
  $$.fragment = create_fragment2 ? create_fragment2($$.ctx) : false;
  if (options.target) {
    if (options.hydrate) {
      const nodes = children(options.target);
      $$.fragment && $$.fragment.l(nodes);
      nodes.forEach(detach);
    } else {
      $$.fragment && $$.fragment.c();
    }
    if (options.intro)
      transition_in(component.$$.fragment);
    mount_component(component, options.target, options.anchor, options.customElement);
    flush();
  }
  set_current_component(parent_component);
}
__name(init, "init");
const _SvelteComponent = class _SvelteComponent {
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  $on(type, callback) {
    if (!is_function(callback)) {
      return noop;
    }
    const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
    callbacks.push(callback);
    return () => {
      const index2 = callbacks.indexOf(callback);
      if (index2 !== -1)
        callbacks.splice(index2, 1);
    };
  }
  $set($$props) {
    if (this.$$set && !is_empty($$props)) {
      this.$$.skip_bound = true;
      this.$$set($$props);
      this.$$.skip_bound = false;
    }
  }
};
__name(_SvelteComponent, "SvelteComponent");
let SvelteComponent = _SvelteComponent;
function setupCaches() {
  Hooks.on(CONSTANTS.HOOKS.PILE.DELETE, (doc) => {
    const uuid = getUuid(doc);
    let actor = getActor(doc);
    if (actor instanceof Actor) {
      actor = actor.toObject();
    }
    deletedActorCache.set(uuid, actor);
  });
}
__name(setupCaches, "setupCaches");
const _DebouncedCache = class _DebouncedCache extends Map {
  constructor(timeout = 50) {
    super();
    __privateAdd(this, _setDebounce);
    __privateAdd(this, _debounceClear, {});
    __privateAdd(this, _timeout, {});
    __privateSet(this, _timeout, timeout);
  }
  set(key, value) {
    __privateMethod(this, _setDebounce, setDebounce_fn).call(this, key);
    return super.set(key, value);
  }
};
_debounceClear = new WeakMap();
_timeout = new WeakMap();
_setDebounce = new WeakSet();
setDebounce_fn = /* @__PURE__ */ __name(function(key) {
  if (!__privateGet(this, _debounceClear)[key]) {
    const self = this;
    __privateGet(this, _debounceClear)[key] = foundry.utils.debounce(() => {
      delete __privateGet(self, _debounceClear)[key];
      self.delete(key);
    }, __privateGet(this, _timeout));
  }
  __privateGet(this, _debounceClear)[key]();
}, "#setDebounce");
__name(_DebouncedCache, "DebouncedCache");
let DebouncedCache = _DebouncedCache;
const deletedActorCache = new DebouncedCache(5e3);
const cachedActorCurrencies = new DebouncedCache();
const cachedFilterList = new DebouncedCache();
const cachedCurrencyList = new DebouncedCache();
function getActivePlayers(onlyActive = false) {
  return Array.from(game.users).filter((u) => (u.active || !onlyActive) && u.character);
}
__name(getActivePlayers, "getActivePlayers");
function getPlayersForItemPile(target) {
  const targetActor = getActor(target);
  if (!isValidItemPile(targetActor))
    return [];
  const pileData = getActorFlagData(targetActor);
  return getActivePlayers(pileData.activePlayers);
}
__name(getPlayersForItemPile, "getPlayersForItemPile");
function canItemPileBeSplit(target) {
  const pileData = getActorFlagData(target);
  const shareData = getItemPileSharingData(target);
  const playerActors = getPlayersForItemPile(target).map((player) => getUserCharacter(player));
  const items = pileData.shareItemsEnabled ? getActorItems(target) : [];
  const currencies = pileData.shareCurrenciesEnabled || pileData.splitAllEnabled ? getActorCurrencies(target) : [];
  for (const item of items) {
    if (playerActors.every((character) => getItemSharesLeftForActor(target, item, character, {
      shareData,
      floor: true,
      players: playerActors.length
    }))) {
      return true;
    }
  }
  for (const currency of currencies) {
    if (currency.type === "item") {
      if (playerActors.every((character) => getItemSharesLeftForActor(target, currency.item, character, {
        shareData,
        floor: true,
        players: playerActors.length
      }))) {
        return true;
      }
    } else {
      if (playerActors.every((character) => getAttributeSharesLeftForActor(target, currency.path, character, {
        shareData,
        floor: true,
        players: playerActors.length
      }))) {
        return true;
      }
    }
  }
  return false;
}
__name(canItemPileBeSplit, "canItemPileBeSplit");
function getItemPileSharingData(target) {
  const targetActor = getActor(target);
  return foundry.utils.duplicate(getProperty(targetActor, CONSTANTS.FLAGS.SHARING) ?? {});
}
__name(getItemPileSharingData, "getItemPileSharingData");
function updateItemPileSharingData(target, incomingSharingData) {
  const targetActor = getActor(target);
  const currentSharingData = getItemPileSharingData(targetActor);
  const newSharingData = foundry.utils.mergeObject(currentSharingData, incomingSharingData);
  return targetActor.update({
    [CONSTANTS.FLAGS.SHARING]: newSharingData
  });
}
__name(updateItemPileSharingData, "updateItemPileSharingData");
function clearItemPileSharingData(target) {
  const targetActor = getActor(target);
  return targetActor.update({
    [CONSTANTS.FLAGS.SHARING]: null
  });
}
__name(clearItemPileSharingData, "clearItemPileSharingData");
async function setItemPileSharingData(sourceUuid, targetUuid, { items = [], attributes = [] } = {}) {
  const sourceActor = getActor(sourceUuid);
  const targetActor = getActor(targetUuid);
  const sourceIsItemPile = isValidItemPile(sourceActor);
  const targetIsItemPile = isValidItemPile(targetActor);
  if (sourceIsItemPile && targetIsItemPile)
    return;
  if (items.length) {
    items = items.map((itemData) => {
      setItemQuantity(itemData.item, Math.abs(itemData.quantity));
      return itemData.item;
    });
  }
  if (!Array.isArray(attributes) && typeof attributes === "object") {
    attributes = Object.entries(attributes).map((entry) => {
      return {
        path: entry[0],
        quantity: Math.abs(entry[1])
      };
    });
  }
  if (sourceIsItemPile) {
    if (isItemPileEmpty(sourceIsItemPile)) {
      return clearItemPileSharingData(sourceIsItemPile);
    }
    const sharingData2 = addToItemPileSharingData(sourceActor, targetActor.uuid, { items, attributes });
    return updateItemPileSharingData(sourceActor, sharingData2);
  }
  const sharingData = removeFromItemPileSharingData(targetActor, sourceActor.uuid, { items, attributes });
  return updateItemPileSharingData(targetActor, sharingData);
}
__name(setItemPileSharingData, "setItemPileSharingData");
function addToItemPileSharingData(itemPile, actorUuid, {
  sharingData = false,
  items = [],
  attributes = []
} = {}) {
  const pileData = getActorFlagData(itemPile);
  const pileCurrencies = getActorCurrencies(itemPile, { getAll: true });
  const filteredItems = items.filter((item) => !pileCurrencies.some((currency) => item.id !== currency.id));
  const currencies = items.filter((item) => !pileCurrencies.some((currency) => item.id === currency.id));
  let pileSharingData = {};
  if (!sharingData && (pileData.shareItemsEnabled && filteredItems.length || pileData.shareCurrenciesEnabled && (attributes.length || currencies.length))) {
    pileSharingData = getItemPileSharingData(itemPile);
  }
  if (pileData.shareItemsEnabled && filteredItems.length || pileData.shareCurrenciesEnabled && currencies.length) {
    if (!pileSharingData.items) {
      pileSharingData.items = [];
    }
    for (const item of filteredItems.concat(currencies)) {
      let existingItem = findSimilarItem(pileSharingData.items, item);
      if (!existingItem) {
        let itemIndex = pileSharingData.items.push(setSimilarityProperties({
          actors: [{ uuid: actorUuid, quantity: 0 }]
        }, item));
        existingItem = pileSharingData.items[itemIndex - 1];
      } else if (!existingItem.actors) {
        existingItem.actors = [];
        existingItem._id = item.id;
      }
      let actorData = existingItem.actors.find((data2) => data2.uuid === actorUuid);
      const itemQuantity = getItemQuantity(item);
      if (!actorData) {
        if (itemQuantity > 0) {
          existingItem.actors.push({ uuid: actorUuid, quantity: itemQuantity });
        }
      } else {
        actorData.quantity += itemQuantity;
        if (actorData.quantity <= 0) {
          existingItem.actors.splice(existingItem.actors.indexOf(actorData), 1);
        }
        if (existingItem.actors.length === 0) {
          pileSharingData.items.splice(pileSharingData.items.indexOf(existingItem), 1);
        }
      }
    }
  }
  if (pileData.shareCurrenciesEnabled && attributes.length) {
    if (!pileSharingData.attributes) {
      pileSharingData.attributes = [];
    }
    for (const attribute of attributes) {
      let existingCurrency = pileSharingData.attributes.find((sharingCurrency) => sharingCurrency.path === attribute.path);
      if (!existingCurrency) {
        let itemIndex = pileSharingData.attributes.push({
          path: attribute.path,
          actors: [{ uuid: actorUuid, quantity: 0 }]
        });
        existingCurrency = pileSharingData.attributes[itemIndex - 1];
      } else {
        if (!existingCurrency.actors) {
          existingCurrency.actors = [];
        }
      }
      let actorData = existingCurrency.actors.find((data2) => data2.uuid === actorUuid);
      if (!actorData) {
        if (attribute.quantity > 0) {
          existingCurrency.actors.push({ uuid: actorUuid, quantity: attribute.quantity });
        }
      } else {
        actorData.quantity += attribute.quantity;
        if (actorData.quantity <= 0) {
          existingCurrency.actors.splice(existingCurrency.actors.indexOf(actorData), 1);
        }
        if (existingCurrency.actors.length === 0) {
          pileSharingData.attributes.splice(pileSharingData.attributes.indexOf(existingCurrency), 1);
        }
      }
    }
  }
  return pileSharingData;
}
__name(addToItemPileSharingData, "addToItemPileSharingData");
function removeFromItemPileSharingData(itemPile, actorUuid, { items = [], attributes = [] } = {}) {
  items = items.map((item) => {
    setItemQuantity(item, getItemQuantity(item) * -1);
    return item;
  });
  attributes = attributes.map((attribute) => {
    attribute.quantity = attribute.quantity * -1;
    return attribute;
  });
  return addToItemPileSharingData(itemPile, actorUuid, { items, attributes });
}
__name(removeFromItemPileSharingData, "removeFromItemPileSharingData");
function getItemSharesLeftForActor(pile, item, recipient, {
  currentQuantity = null,
  floor: floor2 = null,
  players = null,
  shareData = null
} = {}) {
  if (item instanceof String) {
    item = pile.items.get(item);
  }
  let previouslyTaken = 0;
  let recipientUuid = getUuid(recipient);
  currentQuantity = currentQuantity ?? Math.abs(getItemQuantity(item));
  let totalShares = currentQuantity;
  shareData = shareData ?? getItemPileSharingData(pile);
  if (shareData?.items?.length) {
    const foundItem = findSimilarItem(shareData.items, item);
    if (foundItem) {
      totalShares = foundItem.actors.reduce((acc, actor) => acc + actor.quantity, currentQuantity);
      const quantityTakenBefore = foundItem.actors.find((actor) => actor.uuid === recipientUuid);
      previouslyTaken = quantityTakenBefore ? quantityTakenBefore.quantity : 0;
    }
  }
  players = players ?? getPlayersForItemPile(pile).length;
  let totalActorShare = totalShares / players;
  if (!Number.isInteger(totalActorShare) && !floor2) {
    totalActorShare += 1;
  }
  return Math.max(0, Math.min(currentQuantity, Math.floor(totalActorShare - previouslyTaken)));
}
__name(getItemSharesLeftForActor, "getItemSharesLeftForActor");
function getAttributeSharesLeftForActor(pile, path, recipient, {
  currentQuantity = null,
  floor: floor2 = null,
  players = null,
  shareData = null
} = {}) {
  let previouslyTaken = 0;
  let recipientUuid = getUuid(recipient);
  currentQuantity = currentQuantity ?? Number(getProperty(pile, path) ?? 0);
  let totalShares = currentQuantity;
  shareData = shareData ?? getItemPileSharingData(pile);
  if (shareData?.attributes?.length) {
    const existingCurrency = shareData.attributes.find((storedCurrency) => storedCurrency.path === path);
    if (existingCurrency) {
      totalShares = existingCurrency.actors.reduce((acc, actor) => acc + actor.quantity, currentQuantity);
      const quantityTakenBefore = existingCurrency?.actors?.find((actor) => actor.uuid === recipientUuid);
      previouslyTaken = quantityTakenBefore ? quantityTakenBefore.quantity : 0;
    }
  }
  players = players ?? getPlayersForItemPile(pile).length;
  let totalActorShare = totalShares / players;
  if (!Number.isInteger(totalActorShare) && !floor2) {
    totalActorShare += 1;
  }
  return Math.max(0, Math.min(currentQuantity, Math.floor(totalActorShare - previouslyTaken)));
}
__name(getAttributeSharesLeftForActor, "getAttributeSharesLeftForActor");
const s_TAG_OBJECT = "[object Object]";
function deepMerge(target = {}, ...sourceObj) {
  if (Object.prototype.toString.call(target) !== s_TAG_OBJECT) {
    throw new TypeError(`deepMerge error: 'target' is not an 'object'.`);
  }
  for (let cntr = 0; cntr < sourceObj.length; cntr++) {
    if (Object.prototype.toString.call(sourceObj[cntr]) !== s_TAG_OBJECT) {
      throw new TypeError(`deepMerge error: 'sourceObj[${cntr}]' is not an 'object'.`);
    }
  }
  return _deepMerge(target, ...sourceObj);
}
__name(deepMerge, "deepMerge");
function isIterable(value) {
  if (value === null || value === void 0 || typeof value !== "object") {
    return false;
  }
  return typeof value[Symbol.iterator] === "function";
}
__name(isIterable, "isIterable");
function isObject(value) {
  return value !== null && typeof value === "object";
}
__name(isObject, "isObject");
function isPlainObject(value) {
  if (Object.prototype.toString.call(value) !== s_TAG_OBJECT) {
    return false;
  }
  const prototype = Object.getPrototypeOf(value);
  return prototype === null || prototype === Object.prototype;
}
__name(isPlainObject, "isPlainObject");
function safeAccess(data2, accessor, defaultValue = void 0) {
  if (typeof data2 !== "object") {
    return defaultValue;
  }
  if (typeof accessor !== "string") {
    return defaultValue;
  }
  const access = accessor.split(".");
  for (let cntr = 0; cntr < access.length; cntr++) {
    if (typeof data2[access[cntr]] === "undefined" || data2[access[cntr]] === null) {
      return defaultValue;
    }
    data2 = data2[access[cntr]];
  }
  return data2;
}
__name(safeAccess, "safeAccess");
function safeSet(data2, accessor, value, operation = "set", createMissing = true) {
  if (typeof data2 !== "object") {
    throw new TypeError(`safeSet Error: 'data' is not an 'object'.`);
  }
  if (typeof accessor !== "string") {
    throw new TypeError(`safeSet Error: 'accessor' is not a 'string'.`);
  }
  const access = accessor.split(".");
  for (let cntr = 0; cntr < access.length; cntr++) {
    if (Array.isArray(data2)) {
      const number = +access[cntr];
      if (!Number.isInteger(number) || number < 0) {
        return false;
      }
    }
    if (cntr === access.length - 1) {
      switch (operation) {
        case "add":
          data2[access[cntr]] += value;
          break;
        case "div":
          data2[access[cntr]] /= value;
          break;
        case "mult":
          data2[access[cntr]] *= value;
          break;
        case "set":
          data2[access[cntr]] = value;
          break;
        case "set-undefined":
          if (typeof data2[access[cntr]] === "undefined") {
            data2[access[cntr]] = value;
          }
          break;
        case "sub":
          data2[access[cntr]] -= value;
          break;
      }
    } else {
      if (createMissing && typeof data2[access[cntr]] === "undefined") {
        data2[access[cntr]] = {};
      }
      if (data2[access[cntr]] === null || typeof data2[access[cntr]] !== "object") {
        return false;
      }
      data2 = data2[access[cntr]];
    }
  }
  return true;
}
__name(safeSet, "safeSet");
function _deepMerge(target = {}, ...sourceObj) {
  for (let cntr = 0; cntr < sourceObj.length; cntr++) {
    const obj = sourceObj[cntr];
    for (const prop in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, prop)) {
        if (prop.startsWith("-=")) {
          delete target[prop.slice(2)];
          continue;
        }
        target[prop] = Object.prototype.hasOwnProperty.call(target, prop) && target[prop]?.constructor === Object && obj[prop]?.constructor === Object ? _deepMerge({}, target[prop], obj[prop]) : obj[prop];
      }
    }
  }
  return target;
}
__name(_deepMerge, "_deepMerge");
const _A11yHelper = class _A11yHelper {
  /**
   * Apply focus to the HTMLElement targets in a given A11yFocusSource data object. An iterable list `options.focusEl`
   * can contain HTMLElements or selector strings. If multiple focus targets are provided in a list then the first
   * valid target found will be focused. If focus target is a string then a lookup via `document.querySelector` is
   * performed. In this case you should provide a unique selector for the desired focus target.
   *
   * Note: The body of this method is postponed to the next clock tick to allow any changes in the DOM to occur that
   * might alter focus targets before applying.
   *
   * @param {A11yFocusSource|{ focusSource: A11yFocusSource }}   options - The focus options instance to apply.
   */
  static applyFocusSource(options) {
    if (!isObject(options)) {
      return;
    }
    const focusOpts = isObject(options?.focusSource) ? options.focusSource : options;
    setTimeout(() => {
      const debug2 = typeof focusOpts.debug === "boolean" ? focusOpts.debug : false;
      if (isIterable(focusOpts.focusEl)) {
        if (debug2) {
          console.debug(`A11yHelper.applyFocusSource debug - Attempting to apply focus target: `, focusOpts.focusEl);
        }
        for (const target of focusOpts.focusEl) {
          if (target instanceof HTMLElement && target.isConnected) {
            target.focus();
            if (debug2) {
              console.debug(`A11yHelper.applyFocusSource debug - Applied focus to target: `, target);
            }
            break;
          } else if (typeof target === "string") {
            const element2 = document.querySelector(target);
            if (element2 instanceof HTMLElement && element2.isConnected) {
              element2.focus();
              if (debug2) {
                console.debug(`A11yHelper.applyFocusSource debug - Applied focus to target: `, element2);
              }
              break;
            } else if (debug2) {
              console.debug(`A11yHelper.applyFocusSource debug - Could not query selector: `, target);
            }
          }
        }
      } else if (debug2) {
        console.debug(`A11yHelper.applyFocusSource debug - No focus targets defined.`);
      }
    }, 0);
  }
  /**
   * Returns first focusable element within a specified element.
   *
   * @param {HTMLElement|Document} [element=document] - Optional element to start query.
   *
   * @param {object} [options] - Optional parameters.
   *
   * @param {Iterable<string>} [options.ignoreClasses] - Iterable list of classes to ignore elements.
   *
   * @param {Set<HTMLElement>} [options.ignoreElements] - Set of elements to ignore.
   *
   * @returns {HTMLElement} First focusable child element
   */
  static getFirstFocusableElement(element2 = document, options) {
    const focusableElements = this.getFocusableElements(element2, options);
    return focusableElements.length > 0 ? focusableElements[0] : void 0;
  }
  /**
   * Returns all focusable elements within a specified element.
   *
   * @param {HTMLElement|Document} [element=document] Optional element to start query.
   *
   * @param {object}            [options] - Optional parameters.
   *
   * @param {boolean}           [options.anchorHref=true] - When true anchors must have an HREF.
   *
   * @param {Iterable<string>}  [options.ignoreClasses] - Iterable list of classes to ignore elements.
   *
   * @param {Set<HTMLElement>}  [options.ignoreElements] - Set of elements to ignore.
   *
   * @param {string}            [options.selectors] - Custom list of focusable selectors for `querySelectorAll`.
   *
   * @returns {Array<HTMLElement>} Child keyboard focusable
   */
  static getFocusableElements(element2 = document, { anchorHref = true, ignoreClasses, ignoreElements, selectors } = {}) {
    if (!(element2 instanceof HTMLElement) && !(element2 instanceof Document)) {
      throw new TypeError(`'element' is not a HTMLElement or Document instance.`);
    }
    if (typeof anchorHref !== "boolean") {
      throw new TypeError(`'anchorHref' is not a boolean.`);
    }
    if (ignoreClasses !== void 0 && !isIterable(ignoreClasses)) {
      throw new TypeError(`'ignoreClasses' is not an iterable list.`);
    }
    if (ignoreElements !== void 0 && !(ignoreElements instanceof Set)) {
      throw new TypeError(`'ignoreElements' is not a Set.`);
    }
    if (selectors !== void 0 && typeof selectors !== "string") {
      throw new TypeError(`'selectors' is not a string.`);
    }
    const selectorQuery = selectors ?? __privateMethod(this, _getFocusableSelectors, getFocusableSelectors_fn).call(this, anchorHref);
    const allElements = [...element2.querySelectorAll(selectorQuery)];
    if (ignoreElements && ignoreClasses) {
      return allElements.filter((el) => {
        let hasIgnoreClass = false;
        for (const ignoreClass of ignoreClasses) {
          if (el.classList.contains(ignoreClass)) {
            hasIgnoreClass = true;
            break;
          }
        }
        return !hasIgnoreClass && !ignoreElements.has(el) && el.style.display !== "none" && el.style.visibility !== "hidden" && !el.hasAttribute("disabled") && !el.hasAttribute("inert") && el.getAttribute("aria-hidden") !== "true";
      });
    } else if (ignoreClasses) {
      return allElements.filter((el) => {
        let hasIgnoreClass = false;
        for (const ignoreClass of ignoreClasses) {
          if (el.classList.contains(ignoreClass)) {
            hasIgnoreClass = true;
            break;
          }
        }
        return !hasIgnoreClass && el.style.display !== "none" && el.style.visibility !== "hidden" && !el.hasAttribute("disabled") && !el.hasAttribute("inert") && el.getAttribute("aria-hidden") !== "true";
      });
    } else if (ignoreElements) {
      return allElements.filter((el) => {
        return !ignoreElements.has(el) && el.style.display !== "none" && el.style.visibility !== "hidden" && !el.hasAttribute("disabled") && !el.hasAttribute("inert") && el.getAttribute("aria-hidden") !== "true";
      });
    } else {
      return allElements.filter((el) => {
        return el.style.display !== "none" && el.style.visibility !== "hidden" && !el.hasAttribute("disabled") && !el.hasAttribute("inert") && el.getAttribute("aria-hidden") !== "true";
      });
    }
  }
  /**
   * Gets a A11yFocusSource object from the given DOM event allowing for optional X / Y screen space overrides.
   * Browsers (Firefox / Chrome) forwards a mouse event for the context menu keyboard button. Provides detection of
   * when the context menu event is from the keyboard. Firefox as of (1/23) does not provide the correct screen space
   * coordinates, so for keyboard context menu presses coordinates are generated from the centroid point of the
   * element.
   *
   * A default fallback element or selector string may be provided to provide the focus target. If the event comes from
   * the keyboard however the source focused element is inserted as the target with the fallback value appended to the
   * list of focus targets. When A11yFocusSource is applied by {@link A11yHelper.applyFocusSource} the target focus
   * list is iterated through until a connected target is found and focus applied.
   *
   * @param {object} options - Options
   *
   * @param {KeyboardEvent|MouseEvent}   [options.event] - The source DOM event.
   *
   * @param {boolean} [options.debug] - When true {@link A11yHelper.applyFocusSource} logs focus target data.
   *
   * @param {HTMLElement|string} [options.focusEl] - A specific HTMLElement or selector string as the focus target.
   *
   * @param {number}   [options.x] - Used when an event isn't provided; integer of event source in screen space.
   *
   * @param {number}   [options.y] - Used when an event isn't provided; integer of event source in screen space.
   *
   * @returns {A11yFocusSource} A A11yFocusSource object.
   *
   * @see https://bugzilla.mozilla.org/show_bug.cgi?id=1426671
   * @see https://bugzilla.mozilla.org/show_bug.cgi?id=314314
   *
   * TODO: Evaluate / test against touch input devices.
   */
  static getFocusSource({ event, x, y, focusEl, debug: debug2 = false }) {
    if (focusEl !== void 0 && !(focusEl instanceof HTMLElement) && typeof focusEl !== "string") {
      throw new TypeError(
        `A11yHelper.getFocusSource error: 'focusEl' is not a HTMLElement or string.`
      );
    }
    if (debug2 !== void 0 && typeof debug2 !== "boolean") {
      throw new TypeError(`A11yHelper.getFocusSource error: 'debug' is not a boolean.`);
    }
    if (event === void 0) {
      if (typeof x !== "number") {
        throw new TypeError(`A11yHelper.getFocusSource error: 'event' not defined and 'x' is not a number.`);
      }
      if (typeof y !== "number") {
        throw new TypeError(`A11yHelper.getFocusSource error: 'event' not defined and 'y' is not a number.`);
      }
      return {
        debug: debug2,
        focusEl: focusEl !== void 0 ? [focusEl] : void 0,
        x,
        y
      };
    }
    if (!(event instanceof KeyboardEvent) && !(event instanceof MouseEvent)) {
      throw new TypeError(`A11yHelper.getFocusSource error: 'event' is not a KeyboardEvent or MouseEvent.`);
    }
    if (x !== void 0 && !Number.isInteger(x)) {
      throw new TypeError(`A11yHelper.getFocusSource error: 'x' is not a number.`);
    }
    if (y !== void 0 && !Number.isInteger(y)) {
      throw new TypeError(`A11yHelper.getFocusSource error: 'y' is not a number.`);
    }
    const targetEl = event.target;
    if (!(targetEl instanceof HTMLElement)) {
      throw new TypeError(`A11yHelper.getFocusSource error: 'event.target' is not an HTMLElement.`);
    }
    const result = { debug: debug2 };
    if (event instanceof MouseEvent) {
      if (event?.button !== 2 && event.type === "contextmenu") {
        const rect = targetEl.getBoundingClientRect();
        result.x = x ?? rect.left + rect.width / 2;
        result.y = y ?? rect.top + rect.height / 2;
        result.focusEl = focusEl !== void 0 ? [targetEl, focusEl] : [targetEl];
        result.source = "keyboard";
      } else {
        result.x = x ?? event.pageX;
        result.y = y ?? event.pageY;
        result.focusEl = focusEl !== void 0 ? [focusEl] : void 0;
      }
    } else {
      const rect = targetEl.getBoundingClientRect();
      result.x = x ?? rect.left + rect.width / 2;
      result.y = y ?? rect.top + rect.height / 2;
      result.focusEl = focusEl !== void 0 ? [targetEl, focusEl] : [targetEl];
      result.source = "keyboard";
    }
    return result;
  }
  /**
   * Returns first focusable element within a specified element.
   *
   * @param {HTMLElement|Document} [element=document] - Optional element to start query.
   *
   * @param {object} [options] - Optional parameters.
   *
   * @param {Iterable<string>} [options.ignoreClasses] - Iterable list of classes to ignore elements.
   *
   * @param {Set<HTMLElement>} [options.ignoreElements] - Set of elements to ignore.
   *
   * @returns {HTMLElement} First focusable child element
   */
  static getLastFocusableElement(element2 = document, options) {
    const focusableElements = this.getFocusableElements(element2, options);
    return focusableElements.length > 0 ? focusableElements[focusableElements.length - 1] : void 0;
  }
  /**
   * Tests if the given element is focusable.
   *
   * @param {HTMLElement} [el] - Element to test.
   *
   * @param {object} [options] - Optional parameters.
   *
   * @param {boolean} [options.anchorHref=true] - When true anchors must have an HREF.
   *
   * @param {Iterable<string>} [options.ignoreClasses] - Iterable list of classes to ignore elements.
   *
   * @returns {boolean} Element is focusable.
   */
  static isFocusable(el, { anchorHref = true, ignoreClasses } = {}) {
    if (el === void 0 || el === null || !(el instanceof HTMLElement) || el?.hidden || !el?.isConnected) {
      return false;
    }
    if (typeof anchorHref !== "boolean") {
      throw new TypeError(`'anchorHref' is not a boolean.`);
    }
    if (ignoreClasses !== void 0 && !isIterable(ignoreClasses)) {
      throw new TypeError(`'ignoreClasses' is not an iterable list.`);
    }
    const contenteditableAttr = el.getAttribute("contenteditable");
    const contenteditableFocusable = typeof contenteditableAttr === "string" && (contenteditableAttr === "" || contenteditableAttr === "true");
    const tabindexAttr = el.getAttribute("tabindex");
    const tabindexFocusable = typeof tabindexAttr === "string" && tabindexAttr !== "-1";
    const isAnchor = el instanceof HTMLAnchorElement;
    if (contenteditableFocusable || tabindexFocusable || isAnchor || el instanceof HTMLButtonElement || el instanceof HTMLDetailsElement || el instanceof HTMLEmbedElement || el instanceof HTMLIFrameElement || el instanceof HTMLInputElement || el instanceof HTMLObjectElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement) {
      if (isAnchor && anchorHref && typeof el.getAttribute("href") !== "string") {
        return false;
      }
      return el.style.display !== "none" && el.style.visibility !== "hidden" && !el.hasAttribute("disabled") && !el.hasAttribute("inert") && el.getAttribute("aria-hidden") !== "true";
    }
    return false;
  }
  /**
   * Convenience method to check if the given data is a valid focus source.
   *
   * @param {HTMLElement|string}   data - Either an HTMLElement or selector string.
   *
   * @returns {boolean} Is valid focus source.
   */
  static isFocusSource(data2) {
    return data2 instanceof HTMLElement || typeof data2 === "string";
  }
};
_getFocusableSelectors = new WeakSet();
getFocusableSelectors_fn = /* @__PURE__ */ __name(function(anchorHref = true) {
  return `button, [contenteditable=""], [contenteditable="true"], details summary:not([tabindex="-1"]), embed, a${anchorHref ? "[href]" : ""}, iframe, object, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])`;
}, "#getFocusableSelectors");
/**
 * Returns the default focusable selectors query.
 *
 * @param {boolean}  [anchorHref=true] - When true anchors must have an HREF.
 *
 * @returns {string} Focusable selectors for `querySelectorAll`.
 */
__privateAdd(_A11yHelper, _getFocusableSelectors);
__name(_A11yHelper, "A11yHelper");
let A11yHelper = _A11yHelper;
const _ManagedPromise = class _ManagedPromise {
  constructor() {
    /** @type {{ isProcessing?: boolean, promise?: Promise, reject: Function, resolve: Function }} */
    __privateAdd(this, _current, void 0);
  }
  /**
   * @returns {boolean} Whether global logging is enabled.
   */
  static get logging() {
    return __privateGet(this, _logging);
  }
  /**
   * @returns {boolean} Whether there is an active managed Promise.
   */
  get isActive() {
    return __privateGet(this, _current) !== void 0;
  }
  /**
   * @returns {boolean} Whether there is an active managed Promise and resolution is currently being processed.
   */
  get isProcessing() {
    return __privateGet(this, _current) !== void 0 ? __privateGet(this, _current).isProcessing : false;
  }
  /**
   * Sets global logging enabled state.
   *
   * @param {boolean}  logging - New logging enabled state.
   */
  static set logging(logging) {
    if (typeof logging !== "boolean") {
      throw new TypeError(`[TRL] ManagedPromise.logging error: 'logging' is not a boolean.`);
    }
    __privateSet(this, _logging, logging);
  }
  // ----------------------------------------------------------------------------------------------------------------
  /**
   * Resolves any current Promise with undefined and creates a new current Promise.
   *
   * @template T
   *
   * @param {object} opts - Options.
   *
   * @param {boolean}  [opts.reuse=false] - When true if there is an existing live Promise it is returned immediately.
   *
   * @returns {Promise<T>} The new current managed Promise.
   */
  create({ reuse = false } = {}) {
    if (typeof reuse !== "boolean") {
      throw new TypeError(`[TRL] ManagedPromise.create error: 'reuse' is not a boolean.`);
    }
    if (reuse && __privateGet(this, _current) !== void 0 && __privateGet(this, _current).promise instanceof Promise) {
      if (__privateGet(_ManagedPromise, _logging)) {
        console.warn(`[TRL] ManagedPromise.create info: Reusing / returning existing managed Promise.`);
      }
      return __privateGet(this, _current).promise;
    }
    if (__privateGet(this, _current) !== void 0) {
      if (__privateGet(_ManagedPromise, _logging)) {
        console.warn(
          `[TRL] ManagedPromise.create info: Creating a new Promise and resolving existing immediately.`
        );
      }
      __privateGet(this, _current).resolve(void 0);
      __privateSet(this, _current, void 0);
    }
    const promise2 = new Promise((resolve, reject) => {
      __privateSet(this, _current, {
        isProcessing: false,
        reject,
        resolve
      });
    });
    __privateGet(this, _current).promise = promise2;
    return promise2;
  }
  /**
   * Gets the current Promise if any.
   *
   * @returns {Promise<any>} Current Promise.
   */
  get() {
    return __privateGet(this, _current) ? __privateGet(this, _current).promise : void 0;
  }
  /**
   * Rejects the current Promise if applicable.
   *
   * @param {*}  [result] - Result to reject.
   *
   * @returns {boolean} Was the promise rejected.
   */
  reject(result = void 0) {
    if (__privateGet(this, _current) !== void 0 && __privateGet(this, _current).isProcessing) {
      if (__privateGet(_ManagedPromise, _logging)) {
        console.warn(`[TRL] ManagedPromise.reject info: Currently processing promise.`);
      }
      return true;
    }
    if (__privateGet(this, _current) !== void 0) {
      __privateGet(this, _current).isProcessing = true;
      if (result instanceof Promise) {
        result.then((value) => {
          __privateGet(this, _current).reject(value);
          __privateSet(this, _current, void 0);
        }).catch((err) => {
          __privateGet(this, _current).reject(err);
          __privateSet(this, _current, void 0);
        });
      } else {
        __privateGet(this, _current).reject(result);
        __privateSet(this, _current, void 0);
      }
      return true;
    } else {
      if (__privateGet(_ManagedPromise, _logging)) {
        console.warn(`[TRL] ManagedPromise.reject warning: No current managed Promise to reject.`);
      }
      return false;
    }
  }
  /**
   * Resolves the current Promise if applicable.
   *
   * @param {*}  [result] - Result to resolve.
   *
   * @returns {boolean} Was the promise resolved.
   */
  resolve(result = void 0) {
    if (__privateGet(this, _current) !== void 0 && __privateGet(this, _current).isProcessing) {
      if (__privateGet(_ManagedPromise, _logging)) {
        console.warn(`[TRL] ManagedPromise.resolve info: Currently processing promise.`);
      }
      return true;
    }
    if (__privateGet(this, _current) !== void 0) {
      if (result instanceof Promise) {
        __privateGet(this, _current).isProcessing = true;
        result.then((value) => {
          __privateGet(this, _current).resolve(value);
          __privateSet(this, _current, void 0);
        }).catch((err) => {
          __privateGet(this, _current).reject(err);
          __privateSet(this, _current, void 0);
        });
      } else {
        __privateGet(this, _current).resolve(result);
        __privateSet(this, _current, void 0);
      }
      return true;
    } else {
      if (__privateGet(_ManagedPromise, _logging)) {
        console.warn(`[TRL] ManagedPromise.resolve warning: No current managed Promise to resolve.`);
      }
      return false;
    }
  }
};
_logging = new WeakMap();
_current = new WeakMap();
__name(_ManagedPromise, "ManagedPromise");
/** @type {boolean} */
__privateAdd(_ManagedPromise, _logging, false);
let ManagedPromise = _ManagedPromise;
const s_UUIDV4_REGEX = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
function uuidv4() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ (globalThis.crypto || globalThis.msCrypto).getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
}
__name(uuidv4, "uuidv4");
uuidv4.isValid = (uuid) => s_UUIDV4_REGEX.test(uuid);
function getStackingContext(node) {
  if (!node || node.nodeName === "HTML") {
    return { node: document.documentElement, reason: "root" };
  }
  if (node.nodeName === "#document-fragment") {
    return getStackingContext(node.host);
  }
  const computedStyle = globalThis.getComputedStyle(node);
  if (computedStyle.position === "fixed" || computedStyle.position === "sticky") {
    return { node, reason: `position: ${computedStyle.position}` };
  }
  if (computedStyle.zIndex !== "auto" && computedStyle.position !== "static") {
    return { node, reason: `position: ${computedStyle.position}; z-index: ${computedStyle.zIndex}` };
  }
  if (computedStyle.opacity !== "1") {
    return { node, reason: `opacity: ${computedStyle.opacity}` };
  }
  if (computedStyle.transform !== "none") {
    return { node, reason: `transform: ${computedStyle.transform}` };
  }
  if (computedStyle.mixBlendMode !== "normal") {
    return { node, reason: `mixBlendMode: ${computedStyle.mixBlendMode}` };
  }
  if (computedStyle.filter !== "none") {
    return { node, reason: `filter: ${computedStyle.filter}` };
  }
  if (computedStyle.perspective !== "none") {
    return { node, reason: `perspective: ${computedStyle.perspective}` };
  }
  if (computedStyle.clipPath !== "none") {
    return { node, reason: `clip-path: ${computedStyle.clipPath} ` };
  }
  const mask = computedStyle.mask || computedStyle.webkitMask;
  if (mask !== "none" && mask !== void 0) {
    return { node, reason: `mask:  ${mask}` };
  }
  const maskImage = computedStyle.maskImage || computedStyle.webkitMaskImage;
  if (maskImage !== "none" && maskImage !== void 0) {
    return { node, reason: `mask-image: ${maskImage}` };
  }
  const maskBorder = computedStyle.maskBorder || computedStyle.webkitMaskBorder;
  if (maskBorder !== "none" && maskBorder !== void 0) {
    return { node, reason: `mask-border: ${maskBorder}` };
  }
  if (computedStyle.isolation === "isolate") {
    return { node, reason: `isolation: ${computedStyle.isolation}` };
  }
  if (computedStyle.willChange === "transform" || computedStyle.willChange === "opacity") {
    return { node, reason: `willChange: ${computedStyle.willChange}` };
  }
  if (computedStyle.webkitOverflowScrolling === "touch") {
    return { node, reason: "-webkit-overflow-scrolling: touch" };
  }
  if (computedStyle.zIndex !== "auto") {
    const parentStyle = globalThis.getComputedStyle(node.parentNode);
    if (parentStyle.display === "flex" || parentStyle.display === "inline-flex") {
      return { node, reason: `flex-item; z-index: ${computedStyle.zIndex}` };
    } else if (parentStyle.grid !== "none / none / none / row / auto / auto") {
      return { node, reason: `child of grid container; z-index: ${computedStyle.zIndex}` };
    }
  }
  const contain = computedStyle.contain;
  if (["layout", "paint", "strict", "content"].indexOf(contain) > -1 || contain.indexOf("paint") > -1 || contain.indexOf("layout") > -1) {
    return { node, reason: `contain: ${contain}` };
  }
  return getStackingContext(node.parentNode);
}
__name(getStackingContext, "getStackingContext");
const _StyleManager = class _StyleManager {
  /**
   *
   * @param {object}   opts - Options.
   *
   * @param {string}   opts.docKey - Required key providing a link to a specific style sheet element.
   *
   * @param {string}   [opts.selector=:root] - Selector element.
   *
   * @param {Document} [opts.document] - Target document to load styles into.
   *
   * @param {number}   [opts.version] - An integer representing the version / level of styles being managed.
   *
   */
  constructor({ docKey, selector = ":root", document: document2 = globalThis.document, version } = {}) {
    /** @type {CSSStyleRule} */
    __privateAdd(this, _cssRule, void 0);
    /** @type {string} */
    __privateAdd(this, _docKey, void 0);
    /** @type {string} */
    __privateAdd(this, _selector, void 0);
    /** @type {HTMLStyleElement} */
    __privateAdd(this, _styleElement, void 0);
    /** @type {number} */
    __privateAdd(this, _version, void 0);
    if (typeof docKey !== "string") {
      throw new TypeError(`StyleManager error: 'docKey' is not a string.`);
    }
    if (typeof selector !== "string") {
      throw new TypeError(`StyleManager error: 'selector' is not a string.`);
    }
    if (version !== void 0 && !Number.isSafeInteger(version) && version < 1) {
      throw new TypeError(`StyleManager error: 'version' is defined and is not a positive integer >= 1.`);
    }
    __privateSet(this, _selector, selector);
    __privateSet(this, _docKey, docKey);
    __privateSet(this, _version, version);
    if (document2[__privateGet(this, _docKey)] === void 0) {
      __privateSet(this, _styleElement, document2.createElement("style"));
      document2.head.append(__privateGet(this, _styleElement));
      __privateGet(this, _styleElement)._STYLE_MANAGER_VERSION = version;
      __privateGet(this, _styleElement).sheet.insertRule(`${selector} {}`, 0);
      __privateSet(this, _cssRule, __privateGet(this, _styleElement).sheet.cssRules[0]);
      document2[docKey] = __privateGet(this, _styleElement);
    } else {
      __privateSet(this, _styleElement, document2[docKey]);
      __privateSet(this, _cssRule, __privateGet(this, _styleElement).sheet.cssRules[0]);
      if (version) {
        const existingVersion = __privateGet(this, _styleElement)._STYLE_MANAGER_VERSION ?? 0;
        if (version > existingVersion) {
          __privateGet(this, _cssRule).style.cssText = "";
        }
      }
    }
  }
  /**
   * @returns {string} Provides an accessor to get the `cssText` for the style sheet.
   */
  get cssText() {
    return __privateGet(this, _cssRule).style.cssText;
  }
  /**
   * @returns {number} Returns the version of this instance.
   */
  get version() {
    return __privateGet(this, _version);
  }
  /**
   * Provides a copy constructor to duplicate an existing StyleManager instance into a new document.
   *
   * Note: This is used to support the `PopOut` module.
   *
   * @param {Document} [document] Target browser document to clone into.
   *
   * @returns {StyleManager} New style manager instance.
   */
  clone(document2 = globalThis.document) {
    const newStyleManager = new _StyleManager({
      selector: __privateGet(this, _selector),
      docKey: __privateGet(this, _docKey),
      document: document2,
      version: __privateGet(this, _version)
    });
    __privateGet(newStyleManager, _cssRule).style.cssText = __privateGet(this, _cssRule).style.cssText;
    return newStyleManager;
  }
  get() {
    const cssText = __privateGet(this, _cssRule).style.cssText;
    const result = {};
    if (cssText !== "") {
      for (const entry of cssText.split(";")) {
        if (entry !== "") {
          const values = entry.split(":");
          result[values[0].trim()] = values[1];
        }
      }
    }
    return result;
  }
  /**
   * Gets a particular CSS variable.
   *
   * @param {string}   key - CSS variable property key.
   *
   * @returns {string} Returns CSS variable value.
   */
  getProperty(key) {
    if (typeof key !== "string") {
      throw new TypeError(`StyleManager error: 'key' is not a string.`);
    }
    return __privateGet(this, _cssRule).style.getPropertyValue(key);
  }
  /**
   * Set rules by property / value; useful for CSS variables.
   *
   * @param {Object<string, string>}  rules - An object with property / value string pairs to load.
   *
   * @param {boolean}                 [overwrite=true] - When true overwrites any existing values.
   */
  setProperties(rules, overwrite = true) {
    if (!isObject(rules)) {
      throw new TypeError(`StyleManager error: 'rules' is not an object.`);
    }
    if (typeof overwrite !== "boolean") {
      throw new TypeError(`StyleManager error: 'overwrite' is not a boolean.`);
    }
    if (overwrite) {
      for (const [key, value] of Object.entries(rules)) {
        __privateGet(this, _cssRule).style.setProperty(key, value);
      }
    } else {
      for (const [key, value] of Object.entries(rules)) {
        if (__privateGet(this, _cssRule).style.getPropertyValue(key) === "") {
          __privateGet(this, _cssRule).style.setProperty(key, value);
        }
      }
    }
  }
  /**
   * Sets a particular property.
   *
   * @param {string}   key - CSS variable property key.
   *
   * @param {string}   value - CSS variable value.
   *
   * @param {boolean}  [overwrite=true] - Overwrite any existing value.
   */
  setProperty(key, value, overwrite = true) {
    if (typeof key !== "string") {
      throw new TypeError(`StyleManager error: 'key' is not a string.`);
    }
    if (typeof value !== "string") {
      throw new TypeError(`StyleManager error: 'value' is not a string.`);
    }
    if (typeof overwrite !== "boolean") {
      throw new TypeError(`StyleManager error: 'overwrite' is not a boolean.`);
    }
    if (overwrite) {
      __privateGet(this, _cssRule).style.setProperty(key, value);
    } else {
      if (__privateGet(this, _cssRule).style.getPropertyValue(key) === "") {
        __privateGet(this, _cssRule).style.setProperty(key, value);
      }
    }
  }
  /**
   * Removes the property keys specified. If `keys` is an iterable list then all property keys in the list are removed.
   *
   * @param {Iterable<string>} keys - The property keys to remove.
   */
  removeProperties(keys) {
    if (!isIterable(keys)) {
      throw new TypeError(`StyleManager error: 'keys' is not an iterable list.`);
    }
    for (const key of keys) {
      if (typeof key === "string") {
        __privateGet(this, _cssRule).style.removeProperty(key);
      }
    }
  }
  /**
   * Removes a particular CSS variable.
   *
   * @param {string}   key - CSS variable property key.
   *
   * @returns {string} CSS variable value when removed.
   */
  removeProperty(key) {
    if (typeof key !== "string") {
      throw new TypeError(`StyleManager error: 'key' is not a string.`);
    }
    return __privateGet(this, _cssRule).style.removeProperty(key);
  }
};
_cssRule = new WeakMap();
_docKey = new WeakMap();
_selector = new WeakMap();
_styleElement = new WeakMap();
_version = new WeakMap();
__name(_StyleManager, "StyleManager");
let StyleManager = _StyleManager;
const s_REGEX = /(\d+)\s*px/;
function styleParsePixels(value) {
  if (typeof value !== "string") {
    return void 0;
  }
  const isPixels = s_REGEX.test(value);
  const number = parseInt(value);
  return isPixels && Number.isFinite(number) ? number : void 0;
}
__name(styleParsePixels, "styleParsePixels");
const applicationShellContract = ["elementRoot"];
Object.freeze(applicationShellContract);
function isApplicationShell(component) {
  if (component === null || component === void 0) {
    return false;
  }
  let compHasContract = true;
  let protoHasContract = true;
  for (const accessor of applicationShellContract) {
    const descriptor = Object.getOwnPropertyDescriptor(component, accessor);
    if (descriptor === void 0 || descriptor.get === void 0 || descriptor.set === void 0) {
      compHasContract = false;
    }
  }
  const prototype = Object.getPrototypeOf(component);
  for (const accessor of applicationShellContract) {
    const descriptor = Object.getOwnPropertyDescriptor(prototype, accessor);
    if (descriptor === void 0 || descriptor.get === void 0 || descriptor.set === void 0) {
      protoHasContract = false;
    }
  }
  return compHasContract || protoHasContract;
}
__name(isApplicationShell, "isApplicationShell");
function isHMRProxy(comp) {
  const instanceName = comp?.constructor?.name;
  if (typeof instanceName === "string" && (instanceName.startsWith("Proxy<") || instanceName === "ProxyComponent")) {
    return true;
  }
  const prototypeName = comp?.prototype?.constructor?.name;
  return typeof prototypeName === "string" && (prototypeName.startsWith("Proxy<") || prototypeName === "ProxyComponent");
}
__name(isHMRProxy, "isHMRProxy");
function isSvelteComponent(comp) {
  if (comp === null || comp === void 0 || typeof comp !== "function") {
    return false;
  }
  const prototypeName = comp?.prototype?.constructor?.name;
  if (typeof prototypeName === "string" && (prototypeName.startsWith("Proxy<") || prototypeName === "ProxyComponent")) {
    return true;
  }
  return typeof window !== void 0 ? typeof comp.prototype.$destroy === "function" && typeof comp.prototype.$on === "function" : (
    // client-side
    typeof comp.render === "function"
  );
}
__name(isSvelteComponent, "isSvelteComponent");
async function outroAndDestroy(instance2) {
  return new Promise((resolve) => {
    if (instance2.$$.fragment && instance2.$$.fragment.o) {
      group_outros();
      transition_out(instance2.$$.fragment, 0, 0, () => {
        instance2.$destroy();
        resolve();
      });
      check_outros();
    } else {
      instance2.$destroy();
      resolve();
    }
  });
}
__name(outroAndDestroy, "outroAndDestroy");
function parseSvelteConfig(config, thisArg = void 0) {
  if (typeof config !== "object") {
    throw new TypeError(`parseSvelteConfig - 'config' is not an object:
${JSON.stringify(config)}.`);
  }
  if (!isSvelteComponent(config.class)) {
    throw new TypeError(
      `parseSvelteConfig - 'class' is not a Svelte component constructor for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.hydrate !== void 0 && typeof config.hydrate !== "boolean") {
    throw new TypeError(
      `parseSvelteConfig - 'hydrate' is not a boolean for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.intro !== void 0 && typeof config.intro !== "boolean") {
    throw new TypeError(
      `parseSvelteConfig - 'intro' is not a boolean for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.target !== void 0 && typeof config.target !== "string" && !(config.target instanceof HTMLElement) && !(config.target instanceof ShadowRoot) && !(config.target instanceof DocumentFragment)) {
    throw new TypeError(
      `parseSvelteConfig - 'target' is not a string, HTMLElement, ShadowRoot, or DocumentFragment for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.anchor !== void 0 && typeof config.anchor !== "string" && !(config.anchor instanceof HTMLElement) && !(config.anchor instanceof ShadowRoot) && !(config.anchor instanceof DocumentFragment)) {
    throw new TypeError(
      `parseSvelteConfig - 'anchor' is not a string, HTMLElement, ShadowRoot, or DocumentFragment for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.context !== void 0 && typeof config.context !== "function" && !(config.context instanceof Map) && typeof config.context !== "object") {
    throw new TypeError(
      `parseSvelteConfig - 'context' is not a Map, function or object for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.selectorTarget !== void 0 && typeof config.selectorTarget !== "string") {
    throw new TypeError(
      `parseSvelteConfig - 'selectorTarget' is not a string for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.options !== void 0 && typeof config.options !== "object") {
    throw new TypeError(
      `parseSvelteConfig - 'options' is not an object for config:
${JSON.stringify(config)}.`
    );
  }
  if (config.options !== void 0) {
    if (config.options.injectApp !== void 0 && typeof config.options.injectApp !== "boolean") {
      throw new TypeError(
        `parseSvelteConfig - 'options.injectApp' is not a boolean for config:
${JSON.stringify(config)}.`
      );
    }
    if (config.options.injectEventbus !== void 0 && typeof config.options.injectEventbus !== "boolean") {
      throw new TypeError(
        `parseSvelteConfig - 'options.injectEventbus' is not a boolean for config:
${JSON.stringify(config)}.`
      );
    }
    if (config.options.selectorElement !== void 0 && typeof config.options.selectorElement !== "string") {
      throw new TypeError(
        `parseSvelteConfig - 'selectorElement' is not a string for config:
${JSON.stringify(config)}.`
      );
    }
  }
  const svelteConfig = { ...config };
  delete svelteConfig.options;
  let externalContext = {};
  if (typeof svelteConfig.context === "function") {
    const contextFunc = svelteConfig.context;
    delete svelteConfig.context;
    const result = contextFunc.call(thisArg);
    if (isObject(result)) {
      externalContext = { ...result };
    } else {
      throw new Error(`parseSvelteConfig - 'context' is a function that did not return an object for config:
${JSON.stringify(config)}`);
    }
  } else if (svelteConfig.context instanceof Map) {
    externalContext = Object.fromEntries(svelteConfig.context);
    delete svelteConfig.context;
  } else if (isObject(svelteConfig.context)) {
    externalContext = svelteConfig.context;
    delete svelteConfig.context;
  }
  svelteConfig.props = s_PROCESS_PROPS(svelteConfig.props, thisArg, config);
  if (Array.isArray(svelteConfig.children)) {
    const children2 = [];
    for (let cntr = 0; cntr < svelteConfig.children.length; cntr++) {
      const child = svelteConfig.children[cntr];
      if (!isSvelteComponent(child.class)) {
        throw new Error(`parseSvelteConfig - 'class' is not a Svelte component for child[${cntr}] for config:
${JSON.stringify(config)}`);
      }
      child.props = s_PROCESS_PROPS(child.props, thisArg, config);
      children2.push(child);
    }
    if (children2.length > 0) {
      externalContext.children = children2;
    }
    delete svelteConfig.children;
  } else if (isObject(svelteConfig.children)) {
    if (!isSvelteComponent(svelteConfig.children.class)) {
      throw new Error(`parseSvelteConfig - 'class' is not a Svelte component for children object for config:
${JSON.stringify(config)}`);
    }
    svelteConfig.children.props = s_PROCESS_PROPS(svelteConfig.children.props, thisArg, config);
    externalContext.children = [svelteConfig.children];
    delete svelteConfig.children;
  }
  if (!(svelteConfig.context instanceof Map)) {
    svelteConfig.context = /* @__PURE__ */ new Map();
  }
  svelteConfig.context.set("#external", externalContext);
  return svelteConfig;
}
__name(parseSvelteConfig, "parseSvelteConfig");
function s_PROCESS_PROPS(props, thisArg, config) {
  if (typeof props === "function") {
    const result = props.call(thisArg);
    if (isObject(result)) {
      return result;
    } else {
      throw new Error(`parseSvelteConfig - 'props' is a function that did not return an object for config:
${JSON.stringify(config)}`);
    }
  } else if (isObject(props)) {
    return props;
  } else if (props !== void 0) {
    throw new Error(
      `parseSvelteConfig - 'props' is not a function or an object for config:
${JSON.stringify(config)}`
    );
  }
  return {};
}
__name(s_PROCESS_PROPS, "s_PROCESS_PROPS");
function hasGetter(object, accessor) {
  if (object === null || object === void 0) {
    return false;
  }
  const iDescriptor = Object.getOwnPropertyDescriptor(object, accessor);
  if (iDescriptor !== void 0 && iDescriptor.get !== void 0) {
    return true;
  }
  for (let o = Object.getPrototypeOf(object); o; o = Object.getPrototypeOf(o)) {
    const descriptor = Object.getOwnPropertyDescriptor(o, accessor);
    if (descriptor !== void 0 && descriptor.get !== void 0) {
      return true;
    }
  }
  return false;
}
__name(hasGetter, "hasGetter");
function hasPrototype(target, Prototype) {
  if (typeof target !== "function") {
    return false;
  }
  if (target === Prototype) {
    return true;
  }
  for (let proto = Object.getPrototypeOf(target); proto; proto = Object.getPrototypeOf(proto)) {
    if (proto === Prototype) {
      return true;
    }
  }
  return false;
}
__name(hasPrototype, "hasPrototype");
function getUUIDFromDataTransfer(data2, { actor = true, compendium = true, world = true, types = void 0 } = {}) {
  if (typeof data2 !== "object") {
    return void 0;
  }
  if (Array.isArray(types) && !types.includes(data2.type)) {
    return void 0;
  }
  let uuid = void 0;
  if (typeof data2.uuid === "string") {
    const isCompendium = data2.uuid.startsWith("Compendium");
    if (isCompendium && compendium) {
      uuid = data2.uuid;
    } else if (world) {
      uuid = data2.uuid;
    }
  } else {
    if (actor && world && data2.actorId && data2.type) {
      uuid = `Actor.${data2.actorId}.${data2.type}.${data2.data._id}`;
    } else if (typeof data2.id === "string") {
      if (compendium && typeof data2.pack === "string") {
        uuid = `Compendium.${data2.pack}.${data2.id}`;
      } else if (world) {
        uuid = `${data2.type}.${data2.id}`;
      }
    }
  }
  return uuid;
}
__name(getUUIDFromDataTransfer, "getUUIDFromDataTransfer");
const s_STYLE_KEY$1 = "#__trl-root-styles";
const cssVariables$1 = new StyleManager({ docKey: s_STYLE_KEY$1, version: 1 });
const TJSContainer_svelte_svelte_type_style_lang = "";
const subscriber_queue = [];
function readable(value, start) {
  return {
    subscribe: writable$1(value, start).subscribe
  };
}
__name(readable, "readable");
function writable$1(value, start = noop) {
  let stop;
  const subscribers = /* @__PURE__ */ new Set();
  function set(new_value) {
    if (safe_not_equal(value, new_value)) {
      value = new_value;
      if (stop) {
        const run_queue = !subscriber_queue.length;
        for (const subscriber of subscribers) {
          subscriber[1]();
          subscriber_queue.push(subscriber, value);
        }
        if (run_queue) {
          for (let i = 0; i < subscriber_queue.length; i += 2) {
            subscriber_queue[i][0](subscriber_queue[i + 1]);
          }
          subscriber_queue.length = 0;
        }
      }
    }
  }
  __name(set, "set");
  function update2(fn) {
    set(fn(value));
  }
  __name(update2, "update");
  function subscribe2(run2, invalidate = noop) {
    const subscriber = [run2, invalidate];
    subscribers.add(subscriber);
    if (subscribers.size === 1) {
      stop = start(set) || noop;
    }
    run2(value);
    return () => {
      subscribers.delete(subscriber);
      if (subscribers.size === 0 && stop) {
        stop();
        stop = null;
      }
    };
  }
  __name(subscribe2, "subscribe");
  return { set, update: update2, subscribe: subscribe2 };
}
__name(writable$1, "writable$1");
function derived(stores, fn, initial_value) {
  const single = !Array.isArray(stores);
  const stores_array = single ? [stores] : stores;
  const auto = fn.length < 2;
  return readable(initial_value, (set) => {
    let started = false;
    const values = [];
    let pending = 0;
    let cleanup = noop;
    const sync = /* @__PURE__ */ __name(() => {
      if (pending) {
        return;
      }
      cleanup();
      const result = fn(single ? values[0] : values, set);
      if (auto) {
        set(result);
      } else {
        cleanup = is_function(result) ? result : noop;
      }
    }, "sync");
    const unsubscribers = stores_array.map((store, i) => subscribe(store, (value) => {
      values[i] = value;
      pending &= ~(1 << i);
      if (started) {
        sync();
      }
    }, () => {
      pending |= 1 << i;
    }));
    started = true;
    sync();
    return /* @__PURE__ */ __name(function stop() {
      run_all(unsubscribers);
      cleanup();
      started = false;
    }, "stop");
  });
}
__name(derived, "derived");
const _DynReducerUtils = class _DynReducerUtils {
  /**
   * Checks for array equality between two arrays of numbers.
   *
   * @param a - Array A
   *
   * @param b - Array B
   *
   * @returns Arrays are equal.
   */
  static arrayEquals(a, b) {
    if (a === b) {
      return true;
    }
    if (a === null || b === null) {
      return false;
    }
    if (a.length !== b.length) {
      return false;
    }
    for (let cntr = a.length; --cntr >= 0; ) {
      if (a[cntr] !== b[cntr]) {
        return false;
      }
    }
    return true;
  }
  /**
   * Provides a solid string hashing algorithm.
   *
   * Sourced from: https://stackoverflow.com/a/52171480
   *
   * @param str - String to hash.
   *
   * @param seed - A seed value altering the hash.
   *
   * @returns Hash code.
   */
  static hashString(str, seed = 0) {
    let h1 = 3735928559 ^ seed, h2 = 1103547991 ^ seed;
    for (let ch, i = 0; i < str.length; i++) {
      ch = str.charCodeAt(i);
      h1 = Math.imul(h1 ^ ch, 2654435761);
      h2 = Math.imul(h2 ^ ch, 1597334677);
    }
    h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
    h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
    return 4294967296 * (2097151 & h2) + (h1 >>> 0);
  }
  /**
   * Converts an unknown value for hashing purposes in {@link AdapterIndexer.calcHashUpdate}.
   *
   * Currently objects / Map w/ object keys is not supported. Potentially can include `object-hash` to handle this
   * case, but it is not common to use objects as keys in Maps.
   *
   * @param value - An unknown value to convert to a number.
   */
  static hashUnknown(value) {
    if (value === null || value === void 0) {
      return 0;
    }
    let result = 0;
    switch (typeof value) {
      case "boolean":
        result = value ? 1 : 0;
        break;
      case "bigint":
        result = Number(BigInt.asIntN(64, value));
        break;
      case "function":
        result = this.hashString(value.name);
        break;
      case "number":
        result = Number.isFinite(value) ? value : 0;
        break;
      case "object":
        break;
      case "string":
        result = this.hashString(value);
        break;
      case "symbol":
        result = this.hashString(Symbol.keyFor(value));
        break;
    }
    return result;
  }
  /**
   * @param target -
   *
   * @param Prototype -
   *
   * @returns target constructor function has Prototype.
   */
  static hasPrototype(target, Prototype) {
    if (typeof target !== "function") {
      return false;
    }
    if (target === Prototype) {
      return true;
    }
    for (let proto = Object.getPrototypeOf(target); proto; proto = Object.getPrototypeOf(proto)) {
      if (proto === Prototype) {
        return true;
      }
    }
    return false;
  }
  /**
   * Provides a utility method to determine if the given data is iterable / implements iterator protocol.
   *
   * @param data - Data to verify as iterable.
   *
   * @returns Is data iterable.
   */
  static isIterable(data2) {
    return data2 !== null && data2 !== void 0 && typeof data2 === "object" && typeof data2[Symbol.iterator] === "function";
  }
};
__name(_DynReducerUtils, "DynReducerUtils");
let DynReducerUtils = _DynReducerUtils;
const _AdapterDerived = class _AdapterDerived {
  /**
   * @param hostData - Hosted data structure.
   *
   * @param parentIndex - Any associated parent index API.
   *
   * @param DerivedReducerCtor - The default derived reducer constructor function.
   */
  constructor(hostData, parentIndex, DerivedReducerCtor) {
    __privateAdd(this, _hostData, void 0);
    __privateAdd(this, _DerivedReducerCtor, void 0);
    __privateAdd(this, _parentIndex, void 0);
    __privateAdd(this, _derived, /* @__PURE__ */ new Map());
    __privateAdd(this, _destroyed, false);
    __privateSet(this, _hostData, hostData);
    __privateSet(this, _parentIndex, parentIndex);
    __privateSet(this, _DerivedReducerCtor, DerivedReducerCtor);
    Object.freeze(this);
  }
  /**
   * Creates a new derived reducer.
   *
   * @param options - Options defining the new derived reducer.
   *
   * @returns Newly created derived reducer.
   */
  create(options) {
    if (__privateGet(this, _destroyed)) {
      throw Error(`AdapterDerived.create error: this instance has been destroyed.`);
    }
    let name;
    let rest = {};
    let ctor;
    const DerivedReducerCtor = __privateGet(this, _DerivedReducerCtor);
    if (typeof options === "string") {
      name = options;
      ctor = DerivedReducerCtor;
    } else if (typeof options === "function" && DynReducerUtils.hasPrototype(options, DerivedReducerCtor)) {
      ctor = options;
    } else if (typeof options === "object" && options !== null) {
      ({ name, ctor = DerivedReducerCtor, ...rest } = options);
    } else {
      throw new TypeError(`AdapterDerived.create error: 'options' does not conform to allowed parameters.`);
    }
    if (!DynReducerUtils.hasPrototype(ctor, DerivedReducerCtor)) {
      throw new TypeError(`AdapterDerived.create error: 'ctor' is not a '${DerivedReducerCtor?.name}'.`);
    }
    name = name ?? ctor?.name;
    if (typeof name !== "string") {
      throw new TypeError(`AdapterDerived.create error: 'name' is not a string.`);
    }
    const derivedReducer = new ctor(__privateGet(this, _hostData), __privateGet(this, _parentIndex), rest);
    __privateGet(this, _derived).set(name, derivedReducer);
    return derivedReducer;
  }
  /**
   * Removes all derived reducers and associated subscriptions.
   */
  clear() {
    if (__privateGet(this, _destroyed)) {
      return;
    }
    for (const reducer of __privateGet(this, _derived).values()) {
      reducer.destroy();
    }
    __privateGet(this, _derived).clear();
  }
  /**
   * Deletes and destroys a derived reducer by name.
   *
   * @param name - Name of the derived reducer.
   */
  delete(name) {
    if (__privateGet(this, _destroyed)) {
      throw Error(`AdapterDerived.delete error: this instance has been destroyed.`);
    }
    const reducer = __privateGet(this, _derived).get(name);
    if (reducer) {
      reducer.destroy();
    }
    return __privateGet(this, _derived).delete(name);
  }
  /**
   * Removes all derived reducers, subscriptions, and cleans up all resources.
   */
  destroy() {
    if (__privateGet(this, _destroyed)) {
      return;
    }
    this.clear();
    __privateSet(this, _hostData, [null]);
    __privateSet(this, _parentIndex, null);
    __privateSet(this, _destroyed, true);
  }
  /**
   * Returns an existing derived reducer.
   *
   * @param name - Name of derived reducer.
   */
  get(name) {
    if (__privateGet(this, _destroyed)) {
      throw Error(`AdapterDerived.get error: this instance has been destroyed.`);
    }
    return __privateGet(this, _derived).get(name);
  }
  /**
   * Updates all managed derived reducer indexes.
   *
   * @param [force] - Force an update to subscribers.
   */
  update(force = false) {
    if (__privateGet(this, _destroyed)) {
      return;
    }
    for (const reducer of __privateGet(this, _derived).values()) {
      reducer.index.update(force);
    }
  }
};
_hostData = new WeakMap();
_DerivedReducerCtor = new WeakMap();
_parentIndex = new WeakMap();
_derived = new WeakMap();
_destroyed = new WeakMap();
__name(_AdapterDerived, "AdapterDerived");
let AdapterDerived = _AdapterDerived;
const _AdapterFilters = class _AdapterFilters {
  /**
   * @param indexUpdate - update function for the indexer.
   *
   * @param filtersAdapter - Stores the filter function data.
   */
  constructor(indexUpdate, filtersAdapter) {
    __privateAdd(this, _filtersData, void 0);
    __privateAdd(this, _indexUpdate, void 0);
    __privateAdd(this, _mapUnsubscribe, /* @__PURE__ */ new Map());
    __privateSet(this, _indexUpdate, indexUpdate);
    __privateSet(this, _filtersData, filtersAdapter);
    Object.freeze(this);
  }
  /**
   * @returns Returns the length of the filter data.
   */
  get length() {
    return __privateGet(this, _filtersData).filters.length;
  }
  /**
   * Provides an iterator for filters.
   *
   * @returns Generator / iterator of filters.
   * @yields {DataFilter<T>}
   */
  *[Symbol.iterator]() {
    if (__privateGet(this, _filtersData).filters.length === 0) {
      return;
    }
    for (const entry of __privateGet(this, _filtersData).filters) {
      yield { ...entry };
    }
  }
  /**
   * @param filters -
   */
  add(...filters) {
    let subscribeCount = 0;
    for (const filter2 of filters) {
      const filterType = typeof filter2;
      if (filterType !== "function" && (filterType !== "object" || filter2 === null)) {
        throw new TypeError(`AdapterFilters error: 'filter' is not a function or object.`);
      }
      let data2 = void 0;
      let subscribeFn = void 0;
      if (filterType === "function") {
        data2 = {
          id: void 0,
          filter: filter2,
          weight: 1
        };
        subscribeFn = filter2.subscribe;
      } else if (filterType === "object") {
        if ("filter" in filter2) {
          if (typeof filter2.filter !== "function") {
            throw new TypeError(`AdapterFilters error: 'filter' attribute is not a function.`);
          }
          if (filter2.weight !== void 0 && typeof filter2.weight !== "number" || (filter2.weight < 0 || filter2.weight > 1)) {
            throw new TypeError(`AdapterFilters error: 'weight' attribute is not a number between '0 - 1' inclusive.`);
          }
          data2 = {
            id: filter2.id !== void 0 ? filter2.id : void 0,
            filter: filter2.filter,
            weight: filter2.weight || 1
          };
          subscribeFn = filter2.filter.subscribe ?? filter2.subscribe;
        } else {
          throw new TypeError(`AdapterFilters error: 'filter' attribute is not a function.`);
        }
      }
      const index2 = __privateGet(this, _filtersData).filters.findIndex((value) => {
        return data2.weight < value.weight;
      });
      if (index2 >= 0) {
        __privateGet(this, _filtersData).filters.splice(index2, 0, data2);
      } else {
        __privateGet(this, _filtersData).filters.push(data2);
      }
      if (typeof subscribeFn === "function") {
        const unsubscribe = subscribeFn(__privateGet(this, _indexUpdate));
        if (typeof unsubscribe !== "function") {
          throw new TypeError("AdapterFilters error: Filter has subscribe function, but no unsubscribe function is returned.");
        }
        if (__privateGet(this, _mapUnsubscribe).has(data2.filter)) {
          throw new Error("AdapterFilters error: Filter added already has an unsubscribe function registered.");
        }
        __privateGet(this, _mapUnsubscribe).set(data2.filter, unsubscribe);
        subscribeCount++;
      }
    }
    if (subscribeCount < filters.length) {
      __privateGet(this, _indexUpdate).call(this);
    }
  }
  /**
   * Clears and removes all filters.
   */
  clear() {
    __privateGet(this, _filtersData).filters.length = 0;
    for (const unsubscribe of __privateGet(this, _mapUnsubscribe).values()) {
      unsubscribe();
    }
    __privateGet(this, _mapUnsubscribe).clear();
    __privateGet(this, _indexUpdate).call(this);
  }
  /**
   * @param filters -
   */
  remove(...filters) {
    const length = __privateGet(this, _filtersData).filters.length;
    if (length === 0) {
      return;
    }
    for (const data2 of filters) {
      const actualFilter = typeof data2 === "function" ? data2 : data2 !== null && typeof data2 === "object" ? data2.filter : void 0;
      if (!actualFilter) {
        continue;
      }
      for (let cntr = __privateGet(this, _filtersData).filters.length; --cntr >= 0; ) {
        if (__privateGet(this, _filtersData).filters[cntr].filter === actualFilter) {
          __privateGet(this, _filtersData).filters.splice(cntr, 1);
          let unsubscribe = void 0;
          if (typeof (unsubscribe = __privateGet(this, _mapUnsubscribe).get(actualFilter)) === "function") {
            unsubscribe();
            __privateGet(this, _mapUnsubscribe).delete(actualFilter);
          }
        }
      }
    }
    if (length !== __privateGet(this, _filtersData).filters.length) {
      __privateGet(this, _indexUpdate).call(this);
    }
  }
  /**
   * Remove filters by the provided callback. The callback takes 3 parameters: `id`, `filter`, and `weight`.
   * Any truthy value returned will remove that filter.
   *
   * @param callback - Callback function to evaluate each filter entry.
   */
  removeBy(callback) {
    const length = __privateGet(this, _filtersData).filters.length;
    if (length === 0) {
      return;
    }
    if (typeof callback !== "function") {
      throw new TypeError(`AdapterFilters error: 'callback' is not a function.`);
    }
    __privateGet(this, _filtersData).filters = __privateGet(this, _filtersData).filters.filter((data2) => {
      const remove = callback.call(callback, { ...data2 });
      if (remove) {
        let unsubscribe;
        if (typeof (unsubscribe = __privateGet(this, _mapUnsubscribe).get(data2.filter)) === "function") {
          unsubscribe();
          __privateGet(this, _mapUnsubscribe).delete(data2.filter);
        }
      }
      return !remove;
    });
    if (length !== __privateGet(this, _filtersData).filters.length) {
      __privateGet(this, _indexUpdate).call(this);
    }
  }
  /**
   * @param ids - Removes filters by ID.
   */
  removeById(...ids) {
    const length = __privateGet(this, _filtersData).filters.length;
    if (length === 0) {
      return;
    }
    __privateGet(this, _filtersData).filters = __privateGet(this, _filtersData).filters.filter((data2) => {
      let remove = 0;
      for (const id of ids) {
        remove |= data2.id === id ? 1 : 0;
      }
      if (!!remove) {
        let unsubscribe;
        if (typeof (unsubscribe = __privateGet(this, _mapUnsubscribe).get(data2.filter)) === "function") {
          unsubscribe();
          __privateGet(this, _mapUnsubscribe).delete(data2.filter);
        }
      }
      return !remove;
    });
    if (length !== __privateGet(this, _filtersData).filters.length) {
      __privateGet(this, _indexUpdate).call(this);
    }
  }
};
_filtersData = new WeakMap();
_indexUpdate = new WeakMap();
_mapUnsubscribe = new WeakMap();
__name(_AdapterFilters, "AdapterFilters");
let AdapterFilters = _AdapterFilters;
const _AdapterIndexer = class _AdapterIndexer {
  derivedAdapter;
  filtersData;
  hostData;
  hostUpdate;
  indexData;
  sortData;
  sortFn;
  destroyed = false;
  /**
   * @param hostData - Hosted data structure.
   *
   * @param hostUpdate - Host update function invoked on index updates.
   *
   * @param [parentIndexer] - Any associated parent index API.
   *
   * @returns Indexer adapter instance.
   */
  constructor(hostData, hostUpdate, parentIndexer) {
    this.hostData = hostData;
    this.hostUpdate = hostUpdate;
    this.indexData = { index: null, hash: null, reversed: false, parent: parentIndexer };
  }
  /**
   * @returns Returns whether the index is active.
   */
  get active() {
    return this.filtersData.filters.length > 0 || this.sortData.compareFn !== null || this.indexData.parent?.active === true;
  }
  /**
   * @returns Returns length of reduced index.
   */
  get length() {
    return this.indexData.index ? this.indexData.index.length : 0;
  }
  /* c8 ignore start */
  /**
   * @returns Returns reversed state.
   */
  get reversed() {
    return this.indexData.reversed;
  }
  /* c8 ignore end */
  /**
   * @param reversed - New reversed state.
   */
  set reversed(reversed) {
    this.indexData.reversed = reversed;
  }
  // -------------------------------------------------------------------------------------------------------------------
  /**
   * Calculates a new hash value for the new index array if any. If the new index array is null then the hash value
   * is set to null. Set calculated new hash value to the index adapter hash value.
   *
   * After hash generation compare old and new hash values and perform an update if they are different. If they are
   * equal check for array equality between the old and new index array and perform an update if they are not equal.
   *
   * @param oldIndex - Old index array.
   *
   * @param oldHash - Old index hash value.
   *
   * @param [force=false] - When true forces an update to subscribers.
   */
  calcHashUpdate(oldIndex, oldHash, force = false) {
    const actualForce = typeof force === "boolean" ? force : (
      /* c8 ignore next */
      false
    );
    let newHash = null;
    const newIndex = this.indexData.index;
    if (newIndex) {
      for (let cntr = newIndex.length; --cntr >= 0; ) {
        newHash ^= DynReducerUtils.hashUnknown(newIndex[cntr]) + 2654435769 + (newHash << 6) + (newHash >> 2);
      }
    }
    this.indexData.hash = newHash;
    if (actualForce || (oldHash === newHash ? !DynReducerUtils.arrayEquals(oldIndex, newIndex) : true)) {
      this.hostUpdate();
    }
  }
  /**
   * Destroys all resources.
   */
  destroy() {
    if (this.destroyed) {
      return;
    }
    this.indexData.index = null;
    this.indexData.hash = null;
    this.indexData.reversed = null;
    this.indexData.parent = null;
    this.destroyed = true;
  }
  /**
   * Store associated filter and sort data that are constructed after the indexer.
   *
   * @param filtersData - Associated AdapterFilters instance.
   *
   * @param sortData - Associated AdapterSort instance.
   *
   * @param derivedAdapter - Associated AdapterDerived instance.
   */
  initAdapters(filtersData, sortData, derivedAdapter) {
    this.filtersData = filtersData;
    this.sortData = sortData;
    this.derivedAdapter = derivedAdapter;
    this.sortFn = this.createSortFn();
  }
};
__name(_AdapterIndexer, "AdapterIndexer");
let AdapterIndexer = _AdapterIndexer;
const _AdapterSort = class _AdapterSort {
  /**
   * @param indexUpdate - Function to update indexer.
   *
   * @param sortData - Storage for compare function.
   */
  constructor(indexUpdate, sortData) {
    __privateAdd(this, _sortData, void 0);
    __privateAdd(this, _indexUpdate2, void 0);
    __privateAdd(this, _unsubscribe, void 0);
    __privateSet(this, _indexUpdate2, indexUpdate);
    __privateSet(this, _sortData, sortData);
    Object.freeze(this);
  }
  /**
   * Clears & removes any assigned sort function and triggers an index update.
   */
  clear() {
    const oldCompareFn = __privateGet(this, _sortData).compareFn;
    __privateGet(this, _sortData).compareFn = null;
    if (typeof __privateGet(this, _unsubscribe) === "function") {
      __privateGet(this, _unsubscribe).call(this);
      __privateSet(this, _unsubscribe, void 0);
    }
    if (typeof oldCompareFn === "function") {
      __privateGet(this, _indexUpdate2).call(this);
    }
  }
  /**
   * @param data - A callback function that compares two values. Return > 0 to sort b before a;
   * < 0 to sort a before b; or 0 to keep original order of a & b.
   *
   * Note: You can set a compare function that also has a subscribe function attached as the `subscribe` attribute.
   *
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#parameters
   */
  set(data2) {
    if (typeof __privateGet(this, _unsubscribe) === "function") {
      __privateGet(this, _unsubscribe).call(this);
      __privateSet(this, _unsubscribe, void 0);
    }
    let compareFn = void 0;
    let subscribeFn = void 0;
    switch (typeof data2) {
      case "function":
        compareFn = data2;
        subscribeFn = data2.subscribe;
        break;
      case "object":
        if (data2 === null) {
          break;
        }
        if (typeof data2.compare !== "function") {
          throw new TypeError(`AdapterSort error: 'compare' attribute is not a function.`);
        }
        compareFn = data2.compare;
        subscribeFn = data2.compare.subscribe ?? data2.subscribe;
        break;
    }
    if (typeof compareFn === "function") {
      __privateGet(this, _sortData).compareFn = compareFn;
    } else {
      const oldCompareFn = __privateGet(this, _sortData).compareFn;
      __privateGet(this, _sortData).compareFn = null;
      if (typeof oldCompareFn === "function") {
        __privateGet(this, _indexUpdate2).call(this);
      }
      return;
    }
    if (typeof subscribeFn === "function") {
      __privateSet(this, _unsubscribe, subscribeFn(__privateGet(this, _indexUpdate2)));
      if (typeof __privateGet(this, _unsubscribe) !== "function") {
        throw new Error(`AdapterSort error: sort has 'subscribe' function, but no 'unsubscribe' function is returned.`);
      }
    } else {
      __privateGet(this, _indexUpdate2).call(this);
    }
  }
};
_sortData = new WeakMap();
_indexUpdate2 = new WeakMap();
_unsubscribe = new WeakMap();
__name(_AdapterSort, "AdapterSort");
let AdapterSort = _AdapterSort;
const _IndexerAPI = class _IndexerAPI {
  constructor(adapterIndexer) {
    __privateAdd(this, _indexData, void 0);
    /**
     * Provides a getter to determine if the index is active.
     */
    __publicField(this, "active");
    /**
     * Provides length of reduced / indexed elements.
     */
    __publicField(this, "length");
    /**
     * Manually invoke an update of the index.
     *
     * @param force - Force update to any subscribers.
     */
    __publicField(this, "update");
    __privateSet(this, _indexData, adapterIndexer.indexData);
    this.update = adapterIndexer.update.bind(adapterIndexer);
    Object.defineProperties(this, {
      active: { get: () => adapterIndexer.active },
      length: { get: () => adapterIndexer.length }
    });
    Object.freeze(this);
  }
  /**
   * - Current hash value of the index.
   */
  get hash() {
    return __privateGet(this, _indexData).hash;
  }
  /**
   * Provides an iterator over the index array.
   *
   * @returns Iterator / generator
   * @yields {K}
   */
  *[Symbol.iterator]() {
    const indexData = __privateGet(this, _indexData);
    if (!indexData.index) {
      return;
    }
    const reversed = indexData.reversed;
    const length = indexData.index.length;
    if (reversed) {
      for (let cntr = length; --cntr >= 0; ) {
        yield indexData.index[cntr];
      }
    } else {
      for (let cntr = 0; cntr < length; cntr++) {
        yield indexData.index[cntr];
      }
    }
  }
};
_indexData = new WeakMap();
__name(_IndexerAPI, "IndexerAPI");
let IndexerAPI = _IndexerAPI;
const _DerivedAPI = class _DerivedAPI {
  /**
   * Removes all derived reducers and associated subscriptions.
   */
  clear;
  /**
   * @param options - Options for creating a reducer.
   *
   * @returns Newly created derived reducer.
   */
  create;
  /**
   * Deletes and destroys a derived reducer.
   *
   * @param name - Name of the derived reducer
   */
  delete;
  /**
   * Removes all derived reducers, associated subscriptions, and cleans up all resources.
   */
  destroy;
  /**
   * Returns an existing derived reducer.
   *
   * @param name - Name of derived reducer.
   */
  get;
  constructor(adapterDerived) {
    this.clear = adapterDerived.clear.bind(adapterDerived);
    this.create = adapterDerived.create.bind(adapterDerived);
    this.delete = adapterDerived.delete.bind(adapterDerived);
    this.destroy = adapterDerived.destroy.bind(adapterDerived);
    this.get = adapterDerived.get.bind(adapterDerived);
    Object.freeze(this);
  }
};
__name(_DerivedAPI, "DerivedAPI");
let DerivedAPI = _DerivedAPI;
const _Indexer = class _Indexer extends AdapterIndexer {
  /**
   * @inheritDoc
   */
  createSortFn() {
    return (a, b) => this.sortData.compareFn(this.hostData[0].get(a), this.hostData[0].get(b));
  }
  /**
   * Provides the custom filter / reduce step that is ~25-40% faster than implementing with `Array.reduce`.
   *
   * Note: Other loop unrolling techniques like Duff's Device gave a slight faster lower bound on large data sets,
   * but the maintenance factor is not worth the extra complication.
   *
   * @returns New filtered index array.
   */
  reduceImpl() {
    const data2 = [];
    const map = this.hostData[0];
    if (!map) {
      return data2;
    }
    const filters = this.filtersData.filters;
    let include = true;
    const parentIndex = this.indexData.parent;
    if (DynReducerUtils.isIterable(parentIndex) && parentIndex.active) {
      for (const key of parentIndex) {
        const value = map.get(key);
        include = true;
        for (let filCntr = 0, filLength = filters.length; filCntr < filLength; filCntr++) {
          if (!filters[filCntr].filter(value)) {
            include = false;
            break;
          }
        }
        if (include) {
          data2.push(key);
        }
      }
    } else {
      for (const key of map.keys()) {
        include = true;
        const value = map.get(key);
        for (let filCntr = 0, filLength = filters.length; filCntr < filLength; filCntr++) {
          if (!filters[filCntr].filter(value)) {
            include = false;
            break;
          }
        }
        if (include) {
          data2.push(key);
        }
      }
    }
    return data2;
  }
  /**
   * Update the reducer indexes. If there are changes subscribers are notified. If data order is changed externally
   * pass in true to force an update to subscribers.
   *
   * @param [force=false] - When true forces an update to subscribers.
   */
  update(force = false) {
    if (this.destroyed) {
      return;
    }
    const oldIndex = this.indexData.index;
    const oldHash = this.indexData.hash;
    const map = this.hostData[0];
    const parentIndex = this.indexData.parent;
    if (this.filtersData.filters.length === 0 && !this.sortData.compareFn || this.indexData.index && map?.size !== this.indexData.index.length) {
      this.indexData.index = null;
    }
    if (this.filtersData.filters.length > 0) {
      this.indexData.index = this.reduceImpl();
    }
    if (!this.indexData.index && parentIndex?.active) {
      this.indexData.index = [...parentIndex];
    }
    if (this.sortData.compareFn && map instanceof Map) {
      if (!this.indexData.index) {
        this.indexData.index = this.indexData.index = [...map.keys()];
      }
      this.indexData.index.sort(this.sortFn);
    }
    this.calcHashUpdate(oldIndex, oldHash, force);
    this.derivedAdapter?.update(force);
  }
};
__name(_Indexer, "Indexer");
let Indexer = _Indexer;
const _DerivedMapReducer = class _DerivedMapReducer {
  /**
   * @param map - Data host Map.
   *
   * @param parentIndex - Parent indexer.
   *
   * @param options - Any filters and sort functions to apply.
   */
  constructor(map, parentIndex, options) {
    /**
     * Updates subscribers on changes.
     */
    __privateAdd(this, _updateSubscribers);
    __privateAdd(this, _map, void 0);
    __privateAdd(this, _derived2, void 0);
    __privateAdd(this, _derivedPublicAPI, void 0);
    __privateAdd(this, _filters, void 0);
    __privateAdd(this, _filtersData2, { filters: [] });
    __privateAdd(this, _index, void 0);
    __privateAdd(this, _indexPublicAPI, void 0);
    __privateAdd(this, _reversed, false);
    __privateAdd(this, _sort, void 0);
    __privateAdd(this, _sortData2, { compareFn: null });
    __privateAdd(this, _subscriptions, []);
    __privateAdd(this, _destroyed2, false);
    __privateSet(this, _map, map);
    __privateSet(this, _index, new Indexer(__privateGet(this, _map), __privateMethod(this, _updateSubscribers, updateSubscribers_fn).bind(this), parentIndex));
    __privateSet(this, _indexPublicAPI, new IndexerAPI(__privateGet(this, _index)));
    __privateSet(this, _filters, new AdapterFilters(__privateGet(this, _indexPublicAPI).update, __privateGet(this, _filtersData2)));
    __privateSet(this, _sort, new AdapterSort(__privateGet(this, _indexPublicAPI).update, __privateGet(this, _sortData2)));
    __privateSet(this, _derived2, new AdapterDerived(__privateGet(this, _map), __privateGet(this, _indexPublicAPI), _DerivedMapReducer));
    __privateSet(this, _derivedPublicAPI, new DerivedAPI(__privateGet(this, _derived2)));
    __privateGet(this, _index).initAdapters(__privateGet(this, _filtersData2), __privateGet(this, _sortData2), __privateGet(this, _derived2));
    let filters = void 0;
    let sort = void 0;
    if (options !== void 0 && ("filters" in options || "sort" in options)) {
      if (options.filters !== void 0) {
        if (DynReducerUtils.isIterable(options.filters)) {
          filters = options.filters;
        } else {
          throw new TypeError(`DerivedMapReducer error (DataDerivedOptions): 'filters' attribute is not iterable.`);
        }
      }
      if (options.sort !== void 0) {
        if (typeof options.sort === "function") {
          sort = options.sort;
        } else if (typeof options.sort === "object" && options.sort !== null) {
          sort = options.sort;
        } else {
          throw new TypeError(`DerivedMapReducer error (DataDerivedOptions): 'sort' attribute is not a function or object.`);
        }
      }
    }
    if (filters) {
      this.filters.add(...filters);
    }
    if (sort) {
      this.sort.set(sort);
    }
    this.initialize();
  }
  /**
   * Returns the internal data of this instance. Be careful!
   *
   * Note: The returned map is the same map set by the main reducer. If any changes are performed to the data
   * externally do invoke {@link IndexerAPI.update} with `true` to recalculate the index and notify all subscribers.
   *
   * @returns The internal data.
   */
  get data() {
    return __privateGet(this, _map)[0];
  }
  /**
   * @returns Derived public API.
   */
  get derived() {
    return __privateGet(this, _derivedPublicAPI);
  }
  /**
   * @returns The filters adapter.
   */
  get filters() {
    return __privateGet(this, _filters);
  }
  /**
   * Returns the Indexer public API.
   *
   * @returns Indexer API - is also iterable.
   */
  get index() {
    return __privateGet(this, _indexPublicAPI);
  }
  /**
   * Returns whether this derived reducer is destroyed.
   */
  get destroyed() {
    return __privateGet(this, _destroyed2);
  }
  /**
   * @returns Main data / items length or indexed length.
   */
  get length() {
    const map = __privateGet(this, _map)[0];
    return __privateGet(this, _index).active ? this.index.length : map ? map.size : 0;
  }
  /**
   * @returns Gets current reversed state.
   */
  get reversed() {
    return __privateGet(this, _reversed);
  }
  /**
   * @returns The sort adapter.
   */
  get sort() {
    return __privateGet(this, _sort);
  }
  /**
   * Sets reversed state and notifies subscribers.
   *
   * @param reversed - New reversed state.
   */
  set reversed(reversed) {
    if (typeof reversed !== "boolean") {
      throw new TypeError(`DerivedMapReducer.reversed error: 'reversed' is not a boolean.`);
    }
    __privateSet(this, _reversed, reversed);
    __privateGet(this, _index).reversed = reversed;
    this.index.update(true);
  }
  /**
   * Removes all derived reducers, subscriptions, and cleans up all resources.
   */
  destroy() {
    __privateSet(this, _destroyed2, true);
    __privateSet(this, _map, [null]);
    __privateGet(this, _index).update(true);
    __privateGet(this, _subscriptions).length = 0;
    __privateGet(this, _derived2).destroy();
    __privateGet(this, _index).destroy();
    __privateGet(this, _filters).clear();
    __privateGet(this, _sort).clear();
  }
  /**
   * Provides a callback for custom derived reducers to initialize any data / custom configuration. This allows
   * child classes to avoid implementing the constructor.
   *
   * @protected
   */
  initialize() {
  }
  /**
   * Provides an iterator for data stored in DerivedMapReducer.
   *
   * @returns Generator / iterator of all data.
   */
  *[Symbol.iterator]() {
    const map = __privateGet(this, _map)[0];
    if (__privateGet(this, _destroyed2) || map === null || map?.size === 0) {
      return;
    }
    if (__privateGet(this, _index).active) {
      for (const key of this.index) {
        yield map.get(key);
      }
    } else {
      if (this.reversed) {
        const values = [...map.values()];
        for (let cntr = values.length; --cntr >= 0; ) {
          yield values[cntr];
        }
      } else {
        for (const value of map.values()) {
          yield value;
        }
      }
    }
  }
  // -------------------------------------------------------------------------------------------------------------------
  /**
   * Subscribe to this DerivedMapReducer.
   *
   * @param handler - Callback function that is invoked on update / changes. Receives `this` reference.
   *
   * @returns Unsubscribe function.
   */
  subscribe(handler) {
    __privateGet(this, _subscriptions).push(handler);
    handler(this);
    return () => {
      const index2 = __privateGet(this, _subscriptions).findIndex((sub) => sub === handler);
      if (index2 >= 0) {
        __privateGet(this, _subscriptions).splice(index2, 1);
      }
    };
  }
};
_map = new WeakMap();
_derived2 = new WeakMap();
_derivedPublicAPI = new WeakMap();
_filters = new WeakMap();
_filtersData2 = new WeakMap();
_index = new WeakMap();
_indexPublicAPI = new WeakMap();
_reversed = new WeakMap();
_sort = new WeakMap();
_sortData2 = new WeakMap();
_subscriptions = new WeakMap();
_destroyed2 = new WeakMap();
_updateSubscribers = new WeakSet();
updateSubscribers_fn = /* @__PURE__ */ __name(function() {
  for (let cntr = 0; cntr < __privateGet(this, _subscriptions).length; cntr++) {
    __privateGet(this, _subscriptions)[cntr](this);
  }
}, "#updateSubscribers");
__name(_DerivedMapReducer, "DerivedMapReducer");
let DerivedMapReducer = _DerivedMapReducer;
const _DynMapReducer = class _DynMapReducer {
  /**
   * Initializes DynMapReducer. Any iterable is supported for initial data. Take note that if `data` is an array it
   * will be used as the host array and not copied. All non-array iterables otherwise create a new array / copy.
   *
   * @param [data] - Data iterable to store if array or copy otherwise.
   */
  constructor(data2) {
    /**
     * Updates subscribers on changes.
     */
    __privateAdd(this, _updateSubscribers2);
    __privateAdd(this, _map2, [null]);
    __privateAdd(this, _derived3, void 0);
    __privateAdd(this, _derivedPublicAPI2, void 0);
    __privateAdd(this, _filters2, void 0);
    __privateAdd(this, _filtersData3, { filters: [] });
    __privateAdd(this, _index2, void 0);
    __privateAdd(this, _indexPublicAPI2, void 0);
    __privateAdd(this, _reversed2, false);
    __privateAdd(this, _sort2, void 0);
    __privateAdd(this, _sortData3, { compareFn: null });
    __privateAdd(this, _subscriptions2, []);
    __privateAdd(this, _destroyed3, false);
    let dataMap = void 0;
    let filters = void 0;
    let sort = void 0;
    if (data2 === null) {
      throw new TypeError(`DynMapReducer error: 'data' is not an object or Map.`);
    }
    if (data2 !== void 0 && typeof data2 !== "object" && !(data2 instanceof Map)) {
      throw new TypeError(`DynMapReducer error: 'data' is not an object or Map.`);
    }
    if (data2 !== void 0 && data2 instanceof Map) {
      dataMap = data2;
    } else if (data2 !== void 0 && ("data" in data2 || "filters" in data2 || "sort" in data2)) {
      if (data2.data !== void 0 && !(data2.data instanceof Map)) {
        throw new TypeError(`DynMapReducer error (DataDynMap): 'data' attribute is not a Map.`);
      }
      dataMap = data2.data;
      if (data2.filters !== void 0) {
        if (DynReducerUtils.isIterable(data2.filters)) {
          filters = data2.filters;
        } else {
          throw new TypeError(`DynMapReducer error (DataDynMap): 'filters' attribute is not iterable.`);
        }
      }
      if (data2.sort !== void 0) {
        if (typeof data2.sort === "function") {
          sort = data2.sort;
        } else if (typeof data2.sort === "object" && data2.sort !== null) {
          sort = data2.sort;
        } else {
          throw new TypeError(`DynMapReducer error (DataDynMap): 'sort' attribute is not a function or object.`);
        }
      }
    }
    if (dataMap) {
      __privateGet(this, _map2)[0] = dataMap;
    }
    __privateSet(this, _index2, new Indexer(__privateGet(this, _map2), __privateMethod(this, _updateSubscribers2, updateSubscribers_fn2).bind(this)));
    __privateSet(this, _indexPublicAPI2, new IndexerAPI(__privateGet(this, _index2)));
    __privateSet(this, _filters2, new AdapterFilters(__privateGet(this, _indexPublicAPI2).update, __privateGet(this, _filtersData3)));
    __privateSet(this, _sort2, new AdapterSort(__privateGet(this, _indexPublicAPI2).update, __privateGet(this, _sortData3)));
    __privateSet(this, _derived3, new AdapterDerived(__privateGet(this, _map2), __privateGet(this, _indexPublicAPI2), DerivedMapReducer));
    __privateSet(this, _derivedPublicAPI2, new DerivedAPI(__privateGet(this, _derived3)));
    __privateGet(this, _index2).initAdapters(__privateGet(this, _filtersData3), __privateGet(this, _sortData3), __privateGet(this, _derived3));
    if (filters) {
      this.filters.add(...filters);
    }
    if (sort) {
      this.sort.set(sort);
    }
    this.initialize();
  }
  /**
   * Returns the internal data of this instance. Be careful!
   *
   * Note: When a map is set as data then that map is used as the internal data. If any changes are
   * performed to the data externally do invoke {@link AdapterIndexer.index.update} with `true` to recalculate the
   * index and notify all subscribers.
   *
   * @returns The internal data.
   */
  get data() {
    return __privateGet(this, _map2)[0];
  }
  /**
   * @returns Derived public API.
   */
  get derived() {
    return __privateGet(this, _derivedPublicAPI2);
  }
  /**
   * @returns The filters adapter.
   */
  get filters() {
    return __privateGet(this, _filters2);
  }
  /**
   * @returns Returns the Indexer public API.
   */
  get index() {
    return __privateGet(this, _indexPublicAPI2);
  }
  /**
   * Returns whether this instance is destroyed.
   */
  get destroyed() {
    return __privateGet(this, _destroyed3);
  }
  /**
   * Gets the main data / items length.
   *
   * @returns {number} Main data / items length.
   */
  get length() {
    const map = __privateGet(this, _map2)[0];
    return __privateGet(this, _index2).active ? __privateGet(this, _indexPublicAPI2).length : map ? map.size : 0;
  }
  /**
   * Gets current reversed state.
   *
   * @returns {boolean} Reversed state.
   */
  get reversed() {
    return __privateGet(this, _reversed2);
  }
  /**
   * @returns The sort adapter.
   */
  get sort() {
    return __privateGet(this, _sort2);
  }
  /**
   * Sets reversed state and notifies subscribers.
   *
   * @param reversed - New reversed state.
   */
  set reversed(reversed) {
    if (typeof reversed !== "boolean") {
      throw new TypeError(`DynMapReducer.reversed error: 'reversed' is not a boolean.`);
    }
    __privateSet(this, _reversed2, reversed);
    __privateGet(this, _index2).reversed = reversed;
    this.index.update(true);
  }
  /**
   * Removes all derived reducers, subscriptions, and cleans up all resources.
   */
  destroy() {
    if (__privateGet(this, _destroyed3)) {
      return;
    }
    __privateSet(this, _destroyed3, true);
    __privateGet(this, _derived3).destroy();
    __privateSet(this, _map2, [null]);
    this.index.update(true);
    __privateGet(this, _subscriptions2).length = 0;
    __privateGet(this, _index2).destroy();
    __privateGet(this, _filters2).clear();
    __privateGet(this, _sort2).clear();
  }
  /**
   * Provides a callback for custom reducers to initialize any data / custom configuration. This allows
   * child classes to avoid implementing the constructor.
   *
   * @protected
   */
  initialize() {
  }
  /**
   * Removes internal data and pushes new data. This does not destroy any initial array set to internal data unless
   * `replace` is set to true.
   *
   * @param data - New data to set to internal data.
   *
   * @param replace=false - New data to set to internal data.
   */
  setData(data2, replace = false) {
    if (data2 !== null && !(data2 instanceof Map)) {
      throw new TypeError(`DynMapReducer.setData error: 'data' is not iterable.`);
    }
    if (typeof replace !== "boolean") {
      throw new TypeError(`DynMapReducer.setData error: 'replace' is not a boolean.`);
    }
    const map = __privateGet(this, _map2)[0];
    if (!(map instanceof Map) || replace) {
      __privateGet(this, _map2)[0] = data2 instanceof Map ? data2 : null;
    } else if (data2 instanceof Map && map instanceof Map) {
      const removeKeySet = new Set(map.keys());
      for (const key of data2.keys()) {
        map.set(key, data2.get(key));
        if (removeKeySet.has(key)) {
          removeKeySet.delete(key);
        }
      }
      for (const key of removeKeySet) {
        map.delete(key);
      }
    } else if (data2 === null) {
      __privateGet(this, _map2)[0] = null;
    }
    this.index.update(true);
  }
  /**
   * Add a subscriber to this DynMapReducer instance.
   *
   * @param handler - Callback function that is invoked on update / changes. Receives `this` reference.
   *
   * @returns Unsubscribe function.
   */
  subscribe(handler) {
    __privateGet(this, _subscriptions2).push(handler);
    handler(this);
    return () => {
      const index2 = __privateGet(this, _subscriptions2).findIndex((sub) => sub === handler);
      if (index2 >= 0) {
        __privateGet(this, _subscriptions2).splice(index2, 1);
      }
    };
  }
  /**
   * Provides an iterator for data stored in DynMapReducer.
   *
   * @returns Generator / iterator of all data.
   * @yields {T}
   */
  *[Symbol.iterator]() {
    const map = __privateGet(this, _map2)[0];
    if (__privateGet(this, _destroyed3) || map === null || map?.size === 0) {
      return;
    }
    if (__privateGet(this, _index2).active) {
      for (const key of this.index) {
        yield map.get(key);
      }
    } else {
      if (this.reversed) {
        const values = [...map.values()];
        for (let cntr = values.length; --cntr >= 0; ) {
          yield values[cntr];
        }
      } else {
        for (const value of map.values()) {
          yield value;
        }
      }
    }
  }
};
_map2 = new WeakMap();
_derived3 = new WeakMap();
_derivedPublicAPI2 = new WeakMap();
_filters2 = new WeakMap();
_filtersData3 = new WeakMap();
_index2 = new WeakMap();
_indexPublicAPI2 = new WeakMap();
_reversed2 = new WeakMap();
_sort2 = new WeakMap();
_sortData3 = new WeakMap();
_subscriptions2 = new WeakMap();
_destroyed3 = new WeakMap();
_updateSubscribers2 = new WeakSet();
updateSubscribers_fn2 = /* @__PURE__ */ __name(function() {
  for (let cntr = 0; cntr < __privateGet(this, _subscriptions2).length; cntr++) {
    __privateGet(this, _subscriptions2)[cntr](this);
  }
}, "#updateSubscribers");
__name(_DynMapReducer, "DynMapReducer");
let DynMapReducer = _DynMapReducer;
function isSimpleDeriver(deriver) {
  return deriver.length < 2;
}
__name(isSimpleDeriver, "isSimpleDeriver");
function generator(storage2) {
  function readable2(key, value, start) {
    return {
      subscribe: writable2(key, value, start).subscribe
    };
  }
  __name(readable2, "readable");
  function writable2(key, value, start = noop) {
    function wrap_start(ogSet) {
      return start(/* @__PURE__ */ __name(function wrap_set(new_value) {
        if (storage2) {
          storage2.setItem(key, JSON.stringify(new_value));
        }
        return ogSet(new_value);
      }, "wrap_set"));
    }
    __name(wrap_start, "wrap_start");
    if (storage2) {
      const storageValue = storage2.getItem(key);
      try {
        if (storageValue) {
          value = JSON.parse(storageValue);
        }
      } catch (err) {
      }
      storage2.setItem(key, JSON.stringify(value));
    }
    const ogStore = writable$1(value, start ? wrap_start : void 0);
    function set(new_value) {
      if (storage2) {
        storage2.setItem(key, JSON.stringify(new_value));
      }
      ogStore.set(new_value);
    }
    __name(set, "set");
    function update2(fn) {
      set(fn(get_store_value(ogStore)));
    }
    __name(update2, "update");
    function subscribe2(run2, invalidate = noop) {
      return ogStore.subscribe(run2, invalidate);
    }
    __name(subscribe2, "subscribe");
    return { set, update: update2, subscribe: subscribe2 };
  }
  __name(writable2, "writable");
  function derived2(key, stores, fn, initial_value) {
    const single = !Array.isArray(stores);
    const stores_array = single ? [stores] : stores;
    if (storage2 && storage2.getItem(key)) {
      try {
        initial_value = JSON.parse(storage2.getItem(key));
      } catch (err) {
      }
    }
    return readable2(key, initial_value, (set) => {
      let inited = false;
      const values = [];
      let pending = 0;
      let cleanup = noop;
      const sync = /* @__PURE__ */ __name(() => {
        if (pending) {
          return;
        }
        cleanup();
        const input = single ? values[0] : values;
        if (isSimpleDeriver(fn)) {
          set(fn(input));
        } else {
          const result = fn(input, set);
          cleanup = is_function(result) ? result : noop;
        }
      }, "sync");
      const unsubscribers = stores_array.map((store, i) => store.subscribe((value) => {
        values[i] = value;
        pending &= ~(1 << i);
        if (inited) {
          sync();
        }
      }, () => {
        pending |= 1 << i;
      }));
      inited = true;
      sync();
      return /* @__PURE__ */ __name(function stop() {
        run_all(unsubscribers);
        cleanup();
      }, "stop");
    });
  }
  __name(derived2, "derived");
  return {
    readable: readable2,
    writable: writable2,
    derived: derived2,
    get: get_store_value
  };
}
__name(generator, "generator");
var storage = typeof window !== "undefined" ? window.sessionStorage : void 0;
var g = generator(storage);
var writable = g.writable;
const _TJSSessionStorage = class _TJSSessionStorage {
  constructor() {
    /**
     * Gets a store from the `stores` Map or creates a new store for the key and a given default value.
     *
     * @param {string}               key - Key to lookup in stores map.
     *
     * @param {boolean}              [defaultValue] - A default value to set for the store.
     *
     * @returns {import('svelte/store').Writable} The store for the given key.
     */
    __privateAdd(this, _getStore);
    /**
     * @type {Map<string, import('svelte/store').Writable>}
     */
    __privateAdd(this, _stores, /* @__PURE__ */ new Map());
  }
  /**
   * Get value from the sessionStorage.
   *
   * @param {string}   key - Key to lookup in sessionStorage.
   *
   * @param {*}        [defaultValue] - A default value to return if key not present in session storage.
   *
   * @returns {*} Value from session storage or if not defined any default value provided.
   */
  getItem(key, defaultValue) {
    let value = defaultValue;
    const storageValue = sessionStorage.getItem(key);
    if (storageValue !== null) {
      try {
        value = storageValue === "undefined" ? void 0 : JSON.parse(storageValue);
      } catch (err) {
        value = defaultValue;
      }
    } else if (defaultValue !== void 0) {
      try {
        const newValue = JSON.stringify(defaultValue);
        sessionStorage.setItem(key, newValue === "undefined" ? void 0 : newValue);
      } catch (err) {
      }
    }
    return value;
  }
  /**
   * Returns the backing Svelte store for the given key; potentially sets a default value if the key
   * is not already set.
   *
   * @param {string}   key - Key to lookup in sessionStorage.
   *
   * @param {*}        [defaultValue] - A default value to return if key not present in session storage.
   *
   * @returns {import('svelte/store').Writable} The Svelte store for this key.
   */
  getStore(key, defaultValue) {
    return __privateMethod(this, _getStore, getStore_fn).call(this, key, defaultValue);
  }
  /**
   * Sets the value for the given key in sessionStorage.
   *
   * @param {string}   key - Key to lookup in sessionStorage.
   *
   * @param {*}        value - A value to set for this key.
   */
  setItem(key, value) {
    const store = __privateMethod(this, _getStore, getStore_fn).call(this, key);
    store.set(value);
  }
  /**
   * Convenience method to swap a boolean value stored in session storage.
   *
   * @param {string}   key - Key to lookup in sessionStorage.
   *
   * @param {boolean}  [defaultValue] - A default value to return if key not present in session storage.
   *
   * @returns {boolean} The boolean swap for the given key.
   */
  swapItemBoolean(key, defaultValue) {
    const store = __privateMethod(this, _getStore, getStore_fn).call(this, key, defaultValue);
    let currentValue = false;
    try {
      currentValue = !!JSON.parse(sessionStorage.getItem(key));
    } catch (err) {
    }
    const newValue = typeof currentValue === "boolean" ? !currentValue : false;
    store.set(newValue);
    return newValue;
  }
};
_stores = new WeakMap();
_createStore = new WeakSet();
createStore_fn = /* @__PURE__ */ __name(function(key, defaultValue = void 0) {
  try {
    const value = sessionStorage.getItem(key);
    if (value !== null) {
      defaultValue = value === "undefined" ? void 0 : JSON.parse(value);
    }
  } catch (err) {
  }
  return writable(key, defaultValue);
}, "#createStore");
_getStore = new WeakSet();
getStore_fn = /* @__PURE__ */ __name(function(key, defaultValue = void 0) {
  var _a2;
  let store = __privateGet(this, _stores).get(key);
  if (store === void 0) {
    store = __privateMethod(_a2 = _TJSSessionStorage, _createStore, createStore_fn).call(_a2, key, defaultValue);
    __privateGet(this, _stores).set(key, store);
  }
  return store;
}, "#getStore");
/**
 * Creates a new store for the given key.
 *
 * @param {string}   key - Key to lookup in stores map.
 *
 * @param {boolean}  [defaultValue] - A default value to set for the store.
 *
 * @returns {import('svelte/store').Writable} The new store.
 */
__privateAdd(_TJSSessionStorage, _createStore);
__name(_TJSSessionStorage, "TJSSessionStorage");
let TJSSessionStorage = _TJSSessionStorage;
function isUpdatableStore(store) {
  if (store === null || store === void 0) {
    return false;
  }
  switch (typeof store) {
    case "function":
    case "object":
      return typeof store.subscribe === "function" && typeof store.update === "function";
  }
  return false;
}
__name(isUpdatableStore, "isUpdatableStore");
function isWritableStore(store) {
  if (store === null || store === void 0) {
    return false;
  }
  switch (typeof store) {
    case "function":
    case "object":
      return typeof store.subscribe === "function" && typeof store.set === "function";
  }
  return false;
}
__name(isWritableStore, "isWritableStore");
function subscribeIgnoreFirst(store, update2) {
  let firedFirst = false;
  return store.subscribe((value) => {
    if (!firedFirst) {
      firedFirst = true;
    } else {
      update2(value);
    }
  });
}
__name(subscribeIgnoreFirst, "subscribeIgnoreFirst");
function writableDerived(origins, derive, reflect, initial) {
  var childDerivedSetter, originValues, blockNextDerive = false;
  var reflectOldValues = reflect.length >= 2;
  var wrappedDerive = /* @__PURE__ */ __name((got, set) => {
    childDerivedSetter = set;
    if (reflectOldValues) {
      originValues = got;
    }
    if (!blockNextDerive) {
      let returned = derive(got, set);
      if (derive.length < 2) {
        set(returned);
      } else {
        return returned;
      }
    }
    blockNextDerive = false;
  }, "wrappedDerive");
  var childDerived = derived(origins, wrappedDerive, initial);
  var singleOrigin = !Array.isArray(origins);
  function doReflect(reflecting) {
    var setWith = reflect(reflecting, originValues);
    if (singleOrigin) {
      blockNextDerive = true;
      origins.set(setWith);
    } else {
      setWith.forEach((value, i) => {
        blockNextDerive = true;
        origins[i].set(value);
      });
    }
    blockNextDerive = false;
  }
  __name(doReflect, "doReflect");
  var tryingSet = false;
  function update2(fn) {
    var isUpdated, mutatedBySubscriptions, oldValue, newValue;
    if (tryingSet) {
      newValue = fn(get_store_value(childDerived));
      childDerivedSetter(newValue);
      return;
    }
    var unsubscribe = childDerived.subscribe((value) => {
      if (!tryingSet) {
        oldValue = value;
      } else if (!isUpdated) {
        isUpdated = true;
      } else {
        mutatedBySubscriptions = true;
      }
    });
    newValue = fn(oldValue);
    tryingSet = true;
    childDerivedSetter(newValue);
    unsubscribe();
    tryingSet = false;
    if (mutatedBySubscriptions) {
      newValue = get_store_value(childDerived);
    }
    if (isUpdated) {
      doReflect(newValue);
    }
  }
  __name(update2, "update");
  return {
    subscribe: childDerived.subscribe,
    set(value) {
      update2(() => value);
    },
    update: update2
  };
}
__name(writableDerived, "writableDerived");
function propertyStore(origin, propName) {
  if (!Array.isArray(propName)) {
    return writableDerived(
      origin,
      (object) => object[propName],
      (reflecting, object) => {
        object[propName] = reflecting;
        return object;
      }
    );
  } else {
    let props = propName.concat();
    return writableDerived(
      origin,
      (value) => {
        for (let i = 0; i < props.length; ++i) {
          value = value[props[i]];
        }
        return value;
      },
      (reflecting, object) => {
        let target = object;
        for (let i = 0; i < props.length - 1; ++i) {
          target = target[props[i]];
        }
        target[props[props.length - 1]] = reflecting;
        return object;
      }
    );
  }
}
__name(propertyStore, "propertyStore");
const _EmbeddedStoreManager = class _EmbeddedStoreManager {
  /**
   * @param {foundry.abstract.Document[]} document - The associated document holder.
   */
  constructor(document2) {
    /**
     * @type {Map<string, EmbeddedCollectionData>}
     */
    __privateAdd(this, _name, /* @__PURE__ */ new Map());
    /**
     * @type {foundry.abstract.Document[]}
     */
    __privateAdd(this, _document, void 0);
    /**
     * @type {Map<string, string>}
     */
    __privateAdd(this, _collectionToDocName, /* @__PURE__ */ new Map());
    /**
     * @type {Set<string>}
     */
    __privateAdd(this, _embeddedNames, /* @__PURE__ */ new Set());
    __privateSet(this, _document, document2);
    this.handleDocChange();
    Object.seal(this);
  }
  /**
   * @template T
   *
   * @param {string} embeddedName -
   *
   * @param {import('@typhonjs-fvtt/svelte/store').OptionsDynMapCreate<string, T>} options -
   *
   * @returns {import('@typhonjs-fvtt/svelte/store').DynMapReducer<string, T>} DynMapReducer instance
   */
  create(embeddedName, options) {
    const doc = __privateGet(this, _document)[0];
    let collection = null;
    if (doc) {
      try {
        collection = doc.getEmbeddedCollection(embeddedName);
      } catch (err) {
        console.warn(`EmbeddedStoreManager.create error: No valid embedded collection for: ${embeddedName}`);
      }
    }
    let embeddedData;
    if (!__privateGet(this, _name).has(embeddedName)) {
      embeddedData = {
        collection,
        stores: /* @__PURE__ */ new Map()
      };
      __privateGet(this, _name).set(embeddedName, embeddedData);
    } else {
      embeddedData = __privateGet(this, _name).get(embeddedName);
    }
    let name;
    let rest = {};
    let ctor;
    if (typeof options === "string") {
      name = options;
      ctor = DynMapReducer;
    } else if (typeof options === "function" && hasPrototype(options, DynMapReducer)) {
      ctor = options;
    } else if (isObject(options)) {
      ({ name, ctor = DynMapReducer, ...rest } = options);
    } else {
      throw new TypeError(`EmbeddedStoreManager.create error: 'options' does not conform to allowed parameters.`);
    }
    if (!hasPrototype(ctor, DynMapReducer)) {
      throw new TypeError(`EmbeddedStoreManager.create error: 'ctor' is not a 'DynMapReducer'.`);
    }
    name = name ?? ctor?.name;
    if (typeof name !== "string") {
      throw new TypeError(`EmbeddedStoreManager.create error: 'name' is not a string.`);
    }
    if (embeddedData.stores.has(name)) {
      return embeddedData.stores.get(name);
    } else {
      const storeOptions = collection ? { data: collection, ...rest } : { ...rest };
      const store = new ctor(storeOptions);
      embeddedData.stores.set(name, store);
      return store;
    }
  }
  /**
   * Destroys and removes embedded collection stores. Invoking this method with no parameters destroys all stores.
   * Invoking with an embedded name destroys all stores for that particular collection. If you provide an embedded and
   * store name just that particular store is destroyed and removed.
   *
   * @param {string}   [embeddedName] - Specific embedded collection name.
   *
   * @param {string}   [storeName] - Specific store name.
   *
   * @returns {boolean} One or more stores destroyed?
   */
  destroy(embeddedName, storeName) {
    let count = 0;
    if (embeddedName === void 0) {
      for (const embeddedData of __privateGet(this, _name).values()) {
        embeddedData.collection = null;
        for (const store of embeddedData.stores.values()) {
          store.destroy();
          count++;
        }
      }
      __privateGet(this, _name).clear();
    } else if (typeof embeddedName === "string" && storeName === void 0) {
      const embeddedData = __privateGet(this, _name).get(embeddedName);
      if (embeddedData) {
        embeddedData.collection = null;
        for (const store of embeddedData.stores.values()) {
          store.destroy();
          count++;
        }
      }
      __privateGet(this, _name).delete(embeddedName);
    } else if (typeof embeddedName === "string" && storeName === "string") {
      const embeddedData = __privateGet(this, _name).get(embeddedName);
      if (embeddedData) {
        const store = embeddedData.stores.get(storeName);
        if (store) {
          store.destroy();
          count++;
        }
      }
    }
    return count > 0;
  }
  /**
   * @template T
   *
   * @param {string} embeddedName -
   *
   * @param {string} storeName -
   *
   * @returns {import('@typhonjs-fvtt/svelte/store').DynMapReducer<string, T>} DynMapReducer instance.
   */
  get(embeddedName, storeName) {
    if (!__privateGet(this, _name).has(embeddedName)) {
      return void 0;
    }
    return __privateGet(this, _name).get(embeddedName).stores.get(storeName);
  }
  /**
   * Updates all existing embedded collection stores with the associated embedded collection
   */
  handleDocChange() {
    const doc = __privateGet(this, _document)[0];
    if (doc instanceof globalThis.foundry.abstract.Document) {
      const existingEmbeddedNames = new Set(__privateGet(this, _name).keys());
      const embeddedNames = Object.entries(doc.constructor?.metadata?.embedded ?? []);
      __privateGet(this, _collectionToDocName).clear();
      __privateGet(this, _embeddedNames).clear();
      for (const [docName, collectionName] of embeddedNames) {
        existingEmbeddedNames.delete(docName);
        __privateGet(this, _embeddedNames).add(`create${docName}`);
        __privateGet(this, _embeddedNames).add(`delete${docName}`);
        __privateGet(this, _embeddedNames).add(`update${docName}`);
        __privateGet(this, _embeddedNames).add(`create.${collectionName}`);
        __privateGet(this, _embeddedNames).add(`delete.${collectionName}`);
        __privateGet(this, _embeddedNames).add(`update.${collectionName}`);
        __privateGet(this, _collectionToDocName).set(docName, docName);
        __privateGet(this, _collectionToDocName).set(collectionName, docName);
        let collection = null;
        try {
          collection = doc.getEmbeddedCollection(docName);
        } catch (err) {
          console.warn(`EmbeddedStoreManager.handleDocUpdate error: No valid embedded collection for: ${docName}`);
        }
        const embeddedData = __privateGet(this, _name).get(docName);
        if (embeddedData) {
          embeddedData.collection = collection;
          for (const store of embeddedData.stores.values()) {
            store.setData(collection, true);
          }
        }
      }
      for (const embeddedName of existingEmbeddedNames) {
        const embeddedData = __privateGet(this, _name).get(embeddedName);
        if (embeddedData) {
          embeddedData.collection = null;
          for (const store of embeddedData.stores.values()) {
            store.setData(null, true);
          }
        }
      }
    } else {
      __privateGet(this, _collectionToDocName).clear();
      __privateGet(this, _embeddedNames).clear();
      for (const embeddedData of __privateGet(this, _name).values()) {
        embeddedData.collection = null;
        for (const store of embeddedData.stores.values()) {
          store.setData(null, true);
        }
      }
    }
  }
  /**
   * Handles updates to embedded stores parsing the render context for valid embedded store types.
   *
   * On create, delete, update parse the type being modified then force index updates for the embedded type.
   *
   * @param {string}   renderContext - render context update from document.
   */
  handleUpdate(renderContext) {
    if (!__privateGet(this, _embeddedNames).has(renderContext)) {
      return;
    }
    const match = __privateGet(_EmbeddedStoreManager, _renderContextRegex).exec(renderContext);
    if (match) {
      const docOrCollectionName = match.groups.name;
      const embeddedName = __privateGet(this, _collectionToDocName).get(docOrCollectionName);
      if (!__privateGet(this, _name).has(embeddedName)) {
        return;
      }
      for (const store of __privateGet(this, _name).get(embeddedName).stores.values()) {
        store.index.update(true);
      }
    }
  }
};
_renderContextRegex = new WeakMap();
_name = new WeakMap();
_document = new WeakMap();
_collectionToDocName = new WeakMap();
_embeddedNames = new WeakMap();
__name(_EmbeddedStoreManager, "EmbeddedStoreManager");
/**
 * RegExp for detecting CRUD updates for renderContext.
 *
 * @type {RegExp}
 */
__privateAdd(_EmbeddedStoreManager, _renderContextRegex, /(?<action>create|delete|update)(?<sep>\.?)(?<name>\w+)/);
let EmbeddedStoreManager = _EmbeddedStoreManager;
const _TJSDocument = class _TJSDocument {
  /**
   * @param {foundry.abstract.Document | TJSDocumentOptions}  [document] - Document to wrap or TJSDocumentOptions.
   *
   * @param {TJSDocumentOptions}      [options] - TJSDocument options.
   */
  constructor(document2, options = {}) {
    /**
     * Handles cleanup when the document is deleted. Invoking any optional delete function set in the constructor.
     *
     * @returns {Promise<void>}
     */
    __privateAdd(this, _deleted);
    /**
     * @param {boolean}  [force] - unused - signature from Foundry render function.
     *
     * @param {object}   [options] - Options from render call; will have document update context.
     */
    __privateAdd(this, _updateSubscribers3);
    /**
     *
     * @param {foundry.abstract.Document | undefined} doc -
     */
    __privateAdd(this, _setDocument);
    /**
     * @type {foundry.abstract.Document[]}
     */
    __privateAdd(this, _document2, [void 0]);
    /**
     * @type {EmbeddedStoreManager}
     */
    __privateAdd(this, _embeddedStoreManager, void 0);
    __privateAdd(this, _embeddedAPI, void 0);
    /**
     * @type {string}
     */
    __privateAdd(this, _uuidv4, void 0);
    /**
     * @type {TJSDocumentOptions}
     */
    __privateAdd(this, _options, { delete: void 0, preDelete: void 0 });
    __privateAdd(this, _subscriptions3, []);
    __privateAdd(this, _updateOptions, void 0);
    __privateSet(this, _uuidv4, `tjs-document-${uuidv4()}`);
    if (isPlainObject(document2)) {
      this.setOptions(document2);
    } else {
      this.setOptions(options);
      this.set(document2);
    }
  }
  /**
   * @returns {EmbeddedAPI} Embedded store manager.
   */
  get embedded() {
    if (!__privateGet(this, _embeddedAPI)) {
      __privateSet(this, _embeddedStoreManager, new EmbeddedStoreManager(__privateGet(this, _document2)));
      __privateSet(this, _embeddedAPI, {
        create: (embeddedName, options) => __privateGet(this, _embeddedStoreManager).create(embeddedName, options),
        destroy: (embeddedName, storeName) => __privateGet(this, _embeddedStoreManager).destroy(embeddedName, storeName),
        get: (embeddedName, storeName) => __privateGet(this, _embeddedStoreManager).get(embeddedName, storeName)
      });
    }
    return __privateGet(this, _embeddedAPI);
  }
  /**
   * Returns the options passed on last update.
   *
   * @returns {object} Last update options.
   */
  get updateOptions() {
    return __privateGet(this, _updateOptions) ?? {};
  }
  /**
   * Returns the UUID assigned to this store.
   *
   * @returns {string} UUID
   */
  get uuidv4() {
    return __privateGet(this, _uuidv4);
  }
  /**
   * Completely removes all internal subscribers, any optional delete callback, and unregisters from the
   * ClientDocumentMixin `apps` tracking object.
   */
  destroy() {
    const doc = __privateGet(this, _document2)[0];
    if (__privateGet(this, _embeddedStoreManager)) {
      __privateGet(this, _embeddedStoreManager).destroy();
      __privateSet(this, _embeddedStoreManager, void 0);
      __privateSet(this, _embeddedAPI, void 0);
    }
    if (doc instanceof globalThis.foundry.abstract.Document) {
      delete doc?.apps[__privateGet(this, _uuidv4)];
      __privateMethod(this, _setDocument, setDocument_fn).call(this, void 0);
    }
    __privateGet(this, _options).delete = void 0;
    __privateGet(this, _subscriptions3).length = 0;
  }
  /**
   * @returns {foundry.abstract.Document | undefined} Current document
   */
  get() {
    return __privateGet(this, _document2)[0];
  }
  /**
   * @param {foundry.abstract.Document | undefined}  document - New document to set.
   *
   * @param {object}         [options] - New document update options to set.
   */
  set(document2, options = {}) {
    if (__privateGet(this, _document2)[0]) {
      delete __privateGet(this, _document2)[0].apps[__privateGet(this, _uuidv4)];
    }
    if (document2 !== void 0 && !(document2 instanceof globalThis.foundry.abstract.Document)) {
      throw new TypeError(`TJSDocument set error: 'document' is not a valid Document or undefined.`);
    }
    if (options === null || typeof options !== "object") {
      throw new TypeError(`TJSDocument set error: 'options' is not an object.`);
    }
    if (document2 instanceof globalThis.foundry.abstract.Document) {
      document2.apps[__privateGet(this, _uuidv4)] = {
        close: __privateMethod(this, _deleted, deleted_fn).bind(this),
        render: __privateMethod(this, _updateSubscribers3, updateSubscribers_fn3).bind(this)
      };
    }
    __privateMethod(this, _setDocument, setDocument_fn).call(this, document2);
    __privateSet(this, _updateOptions, options);
    __privateMethod(this, _updateSubscribers3, updateSubscribers_fn3).call(this);
  }
  /**
   * Potentially sets new document from data transfer object.
   *
   * @param {object}   data - Document transfer data.
   *
   * @param {ParseDataTransferOptions & TJSDocumentOptions}   [options] - Optional parameters.
   *
   * @returns {Promise<boolean>} Returns true if new document set from data transfer blob.
   */
  async setFromDataTransfer(data2, options) {
    return this.setFromUUID(getUUIDFromDataTransfer(data2, options), options);
  }
  /**
   * Sets the document by Foundry UUID performing a lookup and setting the document if found.
   *
   * @param {string}   uuid - A Foundry UUID to lookup.
   *
   * @param {TJSDocumentOptions}   [options] - New document update options to set.
   *
   * @returns {Promise<boolean>} True if successfully set document from UUID.
   */
  async setFromUUID(uuid, options = {}) {
    if (typeof uuid !== "string" || uuid.length === 0) {
      return false;
    }
    try {
      const doc = await globalThis.fromUuid(uuid);
      if (doc) {
        this.set(doc, options);
        return true;
      }
    } catch (err) {
    }
    return false;
  }
  /**
   * Sets options for this document wrapper / store.
   *
   * @param {TJSDocumentOptions}   options - Options for TJSDocument.
   */
  setOptions(options) {
    if (!isObject(options)) {
      throw new TypeError(`TJSDocument error: 'options' is not a plain object.`);
    }
    if (options.delete !== void 0 && typeof options.delete !== "function") {
      throw new TypeError(`TJSDocument error: 'delete' attribute in options is not a function.`);
    }
    if (options.preDelete !== void 0 && typeof options.preDelete !== "function") {
      throw new TypeError(`TJSDocument error: 'preDelete' attribute in options is not a function.`);
    }
    if (options.delete === void 0 || typeof options.delete === "function") {
      __privateGet(this, _options).delete = options.delete;
    }
    if (options.preDelete === void 0 || typeof options.preDelete === "function") {
      __privateGet(this, _options).preDelete = options.preDelete;
    }
  }
  /**
   * @param {function(foundry.abstract.Document, object): void} handler - Callback function that is invoked on update / changes.
   *
   * @returns {(function(): void)} Unsubscribe function.
   */
  subscribe(handler) {
    __privateGet(this, _subscriptions3).push(handler);
    const updateOptions = { action: "subscribe", data: void 0 };
    handler(__privateGet(this, _document2)[0], updateOptions);
    return () => {
      const index2 = __privateGet(this, _subscriptions3).findIndex((sub) => sub === handler);
      if (index2 >= 0) {
        __privateGet(this, _subscriptions3).splice(index2, 1);
      }
    };
  }
};
_document2 = new WeakMap();
_embeddedStoreManager = new WeakMap();
_embeddedAPI = new WeakMap();
_uuidv4 = new WeakMap();
_options = new WeakMap();
_subscriptions3 = new WeakMap();
_updateOptions = new WeakMap();
_deleted = new WeakSet();
deleted_fn = /* @__PURE__ */ __name(async function() {
  const doc = __privateGet(this, _document2)[0];
  if (doc instanceof globalThis.foundry.abstract.Document && !doc?.collection?.has(doc.id)) {
    delete doc?.apps[__privateGet(this, _uuidv4)];
    __privateMethod(this, _setDocument, setDocument_fn).call(this, void 0);
    if (typeof __privateGet(this, _options).preDelete === "function") {
      await __privateGet(this, _options).preDelete(doc);
    }
    __privateMethod(this, _updateSubscribers3, updateSubscribers_fn3).call(this, false, { action: "delete", data: void 0 });
    if (typeof __privateGet(this, _options).delete === "function") {
      await __privateGet(this, _options).delete(doc);
    }
    __privateSet(this, _updateOptions, void 0);
  }
}, "#deleted");
_updateSubscribers3 = new WeakSet();
updateSubscribers_fn3 = /* @__PURE__ */ __name(function(force = false, options = {}) {
  __privateSet(this, _updateOptions, options);
  const doc = __privateGet(this, _document2)[0];
  for (let cntr = 0; cntr < __privateGet(this, _subscriptions3).length; cntr++) {
    __privateGet(this, _subscriptions3)[cntr](doc, options);
  }
  if (__privateGet(this, _embeddedStoreManager)) {
    __privateGet(this, _embeddedStoreManager).handleUpdate(options.renderContext);
  }
}, "#updateSubscribers");
_setDocument = new WeakSet();
setDocument_fn = /* @__PURE__ */ __name(function(doc) {
  __privateGet(this, _document2)[0] = doc;
  if (__privateGet(this, _embeddedStoreManager)) {
    __privateGet(this, _embeddedStoreManager).handleDocChange();
  }
}, "#setDocument");
__name(_TJSDocument, "TJSDocument");
let TJSDocument = _TJSDocument;
const storeState = writable$1(void 0);
({
  subscribe: storeState.subscribe,
  get: () => game
});
Hooks.once("ready", () => storeState.set(game));
function cubicOut(t) {
  const f = t - 1;
  return f * f * f + 1;
}
__name(cubicOut, "cubicOut");
function quintOut(t) {
  return --t * t * t * t * t + 1;
}
__name(quintOut, "quintOut");
function resizeObserver(node, target) {
  ResizeObserverManager.add(node, target);
  return {
    update: (newTarget) => {
      ResizeObserverManager.remove(node, target);
      target = newTarget;
      ResizeObserverManager.add(node, target);
    },
    destroy: () => {
      ResizeObserverManager.remove(node, target);
    }
  };
}
__name(resizeObserver, "resizeObserver");
resizeObserver.updateCache = function(el) {
  if (!(el instanceof HTMLElement)) {
    throw new TypeError(`resizeObserverUpdate error: 'el' is not an HTMLElement.`);
  }
  const subscribers = s_MAP.get(el);
  if (Array.isArray(subscribers)) {
    const computed = globalThis.getComputedStyle(el);
    const borderBottom = styleParsePixels(el.style.borderBottom) ?? styleParsePixels(computed.borderBottom) ?? 0;
    const borderLeft = styleParsePixels(el.style.borderLeft) ?? styleParsePixels(computed.borderLeft) ?? 0;
    const borderRight = styleParsePixels(el.style.borderRight) ?? styleParsePixels(computed.borderRight) ?? 0;
    const borderTop = styleParsePixels(el.style.borderTop) ?? styleParsePixels(computed.borderTop) ?? 0;
    const paddingBottom = styleParsePixels(el.style.paddingBottom) ?? styleParsePixels(computed.paddingBottom) ?? 0;
    const paddingLeft = styleParsePixels(el.style.paddingLeft) ?? styleParsePixels(computed.paddingLeft) ?? 0;
    const paddingRight = styleParsePixels(el.style.paddingRight) ?? styleParsePixels(computed.paddingRight) ?? 0;
    const paddingTop = styleParsePixels(el.style.paddingTop) ?? styleParsePixels(computed.paddingTop) ?? 0;
    const additionalWidth = borderLeft + borderRight + paddingLeft + paddingRight;
    const additionalHeight = borderTop + borderBottom + paddingTop + paddingBottom;
    for (const subscriber of subscribers) {
      subscriber.styles.additionalWidth = additionalWidth;
      subscriber.styles.additionalHeight = additionalHeight;
      s_UPDATE_SUBSCRIBER(subscriber, subscriber.contentWidth, subscriber.contentHeight);
    }
  }
};
const s_MAP = /* @__PURE__ */ new Map();
const _ResizeObserverManager = class _ResizeObserverManager {
  /**
   * Add an HTMLElement and ResizeObserverTarget instance for monitoring. Create cached style attributes for the
   * given element include border & padding dimensions for offset width / height calculations.
   *
   * @param {HTMLElement}    el - The element to observe.
   *
   * @param {ResizeObserverTarget} target - A target that contains one of several mechanisms for updating resize data.
   */
  static add(el, target) {
    const updateType = s_GET_UPDATE_TYPE(target);
    if (updateType === 0) {
      throw new Error(`'target' does not match supported ResizeObserverManager update mechanisms.`);
    }
    const computed = globalThis.getComputedStyle(el);
    const borderBottom = styleParsePixels(el.style.borderBottom) ?? styleParsePixels(computed.borderBottom) ?? 0;
    const borderLeft = styleParsePixels(el.style.borderLeft) ?? styleParsePixels(computed.borderLeft) ?? 0;
    const borderRight = styleParsePixels(el.style.borderRight) ?? styleParsePixels(computed.borderRight) ?? 0;
    const borderTop = styleParsePixels(el.style.borderTop) ?? styleParsePixels(computed.borderTop) ?? 0;
    const paddingBottom = styleParsePixels(el.style.paddingBottom) ?? styleParsePixels(computed.paddingBottom) ?? 0;
    const paddingLeft = styleParsePixels(el.style.paddingLeft) ?? styleParsePixels(computed.paddingLeft) ?? 0;
    const paddingRight = styleParsePixels(el.style.paddingRight) ?? styleParsePixels(computed.paddingRight) ?? 0;
    const paddingTop = styleParsePixels(el.style.paddingTop) ?? styleParsePixels(computed.paddingTop) ?? 0;
    const data2 = {
      updateType,
      target,
      // Stores most recent contentRect.width and contentRect.height values from ResizeObserver.
      contentWidth: 0,
      contentHeight: 0,
      // Convenience data for total border & padding for offset width & height calculations.
      styles: {
        additionalWidth: borderLeft + borderRight + paddingLeft + paddingRight,
        additionalHeight: borderTop + borderBottom + paddingTop + paddingBottom
      }
    };
    if (s_MAP.has(el)) {
      const subscribers = s_MAP.get(el);
      subscribers.push(data2);
    } else {
      s_MAP.set(el, [data2]);
    }
    s_RESIZE_OBSERVER.observe(el);
  }
  /**
   * Removes all targets from monitoring when just an element is provided otherwise removes a specific target
   * from the monitoring map. If no more targets remain then the element is removed from monitoring.
   *
   * @param {HTMLElement}          el - Element to remove from monitoring.
   *
   * @param {ResizeObserverTarget} [target] - A specific target to remove from monitoring.
   */
  static remove(el, target = void 0) {
    const subscribers = s_MAP.get(el);
    if (Array.isArray(subscribers)) {
      const index2 = subscribers.findIndex((entry) => entry.target === target);
      if (index2 >= 0) {
        s_UPDATE_SUBSCRIBER(subscribers[index2], void 0, void 0);
        subscribers.splice(index2, 1);
      }
      if (subscribers.length === 0) {
        s_MAP.delete(el);
        s_RESIZE_OBSERVER.unobserve(el);
      }
    }
  }
};
__name(_ResizeObserverManager, "ResizeObserverManager");
let ResizeObserverManager = _ResizeObserverManager;
const s_UPDATE_TYPES = {
  none: 0,
  attribute: 1,
  function: 2,
  resizeObserved: 3,
  setContentBounds: 4,
  setDimension: 5,
  storeObject: 6,
  storesObject: 7
};
const s_RESIZE_OBSERVER = new ResizeObserver((entries) => {
  for (const entry of entries) {
    const subscribers = s_MAP.get(entry?.target);
    if (Array.isArray(subscribers)) {
      const contentWidth = entry.contentRect.width;
      const contentHeight = entry.contentRect.height;
      for (const subscriber of subscribers) {
        s_UPDATE_SUBSCRIBER(subscriber, contentWidth, contentHeight);
      }
    }
  }
});
function s_GET_UPDATE_TYPE(target) {
  if (target?.resizeObserved instanceof Function) {
    return s_UPDATE_TYPES.resizeObserved;
  }
  if (target?.setDimension instanceof Function) {
    return s_UPDATE_TYPES.setDimension;
  }
  if (target?.setContentBounds instanceof Function) {
    return s_UPDATE_TYPES.setContentBounds;
  }
  const targetType = typeof target;
  if (targetType !== null && (targetType === "object" || targetType === "function")) {
    if (isUpdatableStore(target.resizeObserved)) {
      return s_UPDATE_TYPES.storeObject;
    }
    const stores = target?.stores;
    if (isObject(stores) || typeof stores === "function") {
      if (isUpdatableStore(stores.resizeObserved)) {
        return s_UPDATE_TYPES.storesObject;
      }
    }
  }
  if (targetType !== null && targetType === "object") {
    return s_UPDATE_TYPES.attribute;
  }
  if (targetType === "function") {
    return s_UPDATE_TYPES.function;
  }
  return s_UPDATE_TYPES.none;
}
__name(s_GET_UPDATE_TYPE, "s_GET_UPDATE_TYPE");
function s_UPDATE_SUBSCRIBER(subscriber, contentWidth, contentHeight) {
  const styles2 = subscriber.styles;
  subscriber.contentWidth = contentWidth;
  subscriber.contentHeight = contentHeight;
  const offsetWidth = Number.isFinite(contentWidth) ? contentWidth + styles2.additionalWidth : void 0;
  const offsetHeight = Number.isFinite(contentHeight) ? contentHeight + styles2.additionalHeight : void 0;
  const target = subscriber.target;
  switch (subscriber.updateType) {
    case s_UPDATE_TYPES.attribute:
      target.contentWidth = contentWidth;
      target.contentHeight = contentHeight;
      target.offsetWidth = offsetWidth;
      target.offsetHeight = offsetHeight;
      break;
    case s_UPDATE_TYPES.function:
      target?.(offsetWidth, offsetHeight, contentWidth, contentHeight);
      break;
    case s_UPDATE_TYPES.resizeObserved:
      target.resizeObserved?.(offsetWidth, offsetHeight, contentWidth, contentHeight);
      break;
    case s_UPDATE_TYPES.setContentBounds:
      target.setContentBounds?.(contentWidth, contentHeight);
      break;
    case s_UPDATE_TYPES.setDimension:
      target.setDimension?.(offsetWidth, offsetHeight);
      break;
    case s_UPDATE_TYPES.storeObject:
      target.resizeObserved.update((object) => {
        object.contentHeight = contentHeight;
        object.contentWidth = contentWidth;
        object.offsetHeight = offsetHeight;
        object.offsetWidth = offsetWidth;
        return object;
      });
      break;
    case s_UPDATE_TYPES.storesObject:
      target.stores.resizeObserved.update((object) => {
        object.contentHeight = contentHeight;
        object.contentWidth = contentWidth;
        object.offsetHeight = offsetHeight;
        object.offsetWidth = offsetWidth;
        return object;
      });
      break;
  }
}
__name(s_UPDATE_SUBSCRIBER, "s_UPDATE_SUBSCRIBER");
function applyStyles(node, properties) {
  function setProperties() {
    if (typeof properties !== "object") {
      return;
    }
    for (const prop of Object.keys(properties)) {
      node.style.setProperty(`${prop}`, properties[prop]);
    }
  }
  __name(setProperties, "setProperties");
  setProperties();
  return {
    update(newProperties) {
      properties = newProperties;
      setProperties();
    }
  };
}
__name(applyStyles, "applyStyles");
function draggable(node, {
  position,
  active: active2 = true,
  button = 0,
  storeDragging = void 0,
  ease = false,
  easeOptions = { duration: 0.1, ease: cubicOut },
  hasTargetClassList,
  ignoreTargetClassList
}) {
  if (hasTargetClassList !== void 0 && !isIterable(hasTargetClassList)) {
    throw new TypeError(`'hasTargetClassList' is not iterable.`);
  }
  if (ignoreTargetClassList !== void 0 && !isIterable(ignoreTargetClassList)) {
    throw new TypeError(`'ignoreTargetClassList' is not iterable.`);
  }
  let initialPosition = null;
  let initialDragPoint = {};
  let dragging = false;
  let quickTo = position.animate.quickTo(["top", "left"], easeOptions);
  const handlers = {
    dragDown: ["pointerdown", (e) => onDragPointerDown(e), false],
    dragMove: ["pointermove", (e) => onDragPointerChange(e), false],
    dragUp: ["pointerup", (e) => onDragPointerUp(e), false]
  };
  function activateListeners() {
    node.addEventListener(...handlers.dragDown);
    node.classList.add("draggable");
  }
  __name(activateListeners, "activateListeners");
  function removeListeners() {
    if (typeof storeDragging?.set === "function") {
      storeDragging.set(false);
    }
    node.removeEventListener(...handlers.dragDown);
    node.removeEventListener(...handlers.dragMove);
    node.removeEventListener(...handlers.dragUp);
    node.classList.remove("draggable");
  }
  __name(removeListeners, "removeListeners");
  if (active2) {
    activateListeners();
  }
  function onDragPointerDown(event) {
    if (event.button !== button || !event.isPrimary) {
      return;
    }
    if (!position.enabled) {
      return;
    }
    if (ignoreTargetClassList !== void 0 && event.target instanceof HTMLElement) {
      for (const targetClass of ignoreTargetClassList) {
        if (event.target.classList.contains(targetClass)) {
          return;
        }
      }
    }
    if (hasTargetClassList !== void 0 && event.target instanceof HTMLElement) {
      let foundTarget = false;
      for (const targetClass of hasTargetClassList) {
        if (event.target.classList.contains(targetClass)) {
          foundTarget = true;
          break;
        }
      }
      if (!foundTarget) {
        return;
      }
    }
    event.preventDefault();
    dragging = false;
    initialPosition = position.get();
    initialDragPoint = { x: event.clientX, y: event.clientY };
    node.addEventListener(...handlers.dragMove);
    node.addEventListener(...handlers.dragUp);
    node.setPointerCapture(event.pointerId);
  }
  __name(onDragPointerDown, "onDragPointerDown");
  function onDragPointerChange(event) {
    if ((event.buttons & 1) === 0) {
      onDragPointerUp(event);
      return;
    }
    if (event.button !== -1 || !event.isPrimary) {
      return;
    }
    event.preventDefault();
    if (!dragging && typeof storeDragging?.set === "function") {
      dragging = true;
      storeDragging.set(true);
    }
    const newLeft = initialPosition.left + (event.clientX - initialDragPoint.x);
    const newTop = initialPosition.top + (event.clientY - initialDragPoint.y);
    if (ease) {
      quickTo(newTop, newLeft);
    } else {
      s_POSITION_DATA.left = newLeft;
      s_POSITION_DATA.top = newTop;
      position.set(s_POSITION_DATA);
    }
  }
  __name(onDragPointerChange, "onDragPointerChange");
  function onDragPointerUp(event) {
    event.preventDefault();
    dragging = false;
    if (typeof storeDragging?.set === "function") {
      storeDragging.set(false);
    }
    node.removeEventListener(...handlers.dragMove);
    node.removeEventListener(...handlers.dragUp);
  }
  __name(onDragPointerUp, "onDragPointerUp");
  return {
    // The default of active being true won't automatically add listeners twice.
    update: (options) => {
      if (typeof options.active === "boolean") {
        active2 = options.active;
        if (active2) {
          activateListeners();
        } else {
          removeListeners();
        }
      }
      if (typeof options.button === "number") {
        button = options.button;
      }
      if (options.position !== void 0 && options.position !== position) {
        position = options.position;
        quickTo = position.animate.quickTo(["top", "left"], easeOptions);
      }
      if (typeof options.ease === "boolean") {
        ease = options.ease;
      }
      if (isObject(options.easeOptions)) {
        easeOptions = options.easeOptions;
        quickTo.options(easeOptions);
      }
      if (options.hasTargetClassList !== void 0) {
        if (!isIterable(options.hasTargetClassList)) {
          throw new TypeError(`'hasTargetClassList' is not iterable.`);
        } else {
          hasTargetClassList = options.hasTargetClassList;
        }
      }
      if (options.ignoreTargetClassList !== void 0) {
        if (!isIterable(options.ignoreTargetClassList)) {
          throw new TypeError(`'ignoreTargetClassList' is not iterable.`);
        } else {
          ignoreTargetClassList = options.ignoreTargetClassList;
        }
      }
    },
    destroy: () => removeListeners()
  };
}
__name(draggable, "draggable");
const _DraggableOptions = class _DraggableOptions {
  constructor({ ease, easeOptions } = {}) {
    __privateAdd(this, _updateSubscribers4);
    __privateAdd(this, _ease, false);
    __privateAdd(this, _easeOptions, { duration: 0.1, ease: cubicOut });
    /**
     * Stores the subscribers.
     *
     * @type {(function(DraggableOptions): void)[]}
     */
    __privateAdd(this, _subscriptions4, []);
    Object.defineProperty(this, "ease", {
      get: () => {
        return __privateGet(this, _ease);
      },
      set: (newEase) => {
        if (typeof newEase !== "boolean") {
          throw new TypeError(`'ease' is not a boolean.`);
        }
        __privateSet(this, _ease, newEase);
        __privateMethod(this, _updateSubscribers4, updateSubscribers_fn4).call(this);
      },
      enumerable: true
    });
    Object.defineProperty(this, "easeOptions", {
      get: () => {
        return __privateGet(this, _easeOptions);
      },
      set: (newEaseOptions) => {
        if (newEaseOptions === null || typeof newEaseOptions !== "object") {
          throw new TypeError(`'easeOptions' is not an object.`);
        }
        if (newEaseOptions.duration !== void 0) {
          if (!Number.isFinite(newEaseOptions.duration)) {
            throw new TypeError(`'easeOptions.duration' is not a finite number.`);
          }
          if (newEaseOptions.duration < 0) {
            throw new Error(`'easeOptions.duration' is less than 0.`);
          }
          __privateGet(this, _easeOptions).duration = newEaseOptions.duration;
        }
        if (newEaseOptions.ease !== void 0) {
          if (typeof newEaseOptions.ease !== "function" && typeof newEaseOptions.ease !== "string") {
            throw new TypeError(`'easeOptions.ease' is not a function or string.`);
          }
          __privateGet(this, _easeOptions).ease = newEaseOptions.ease;
        }
        __privateMethod(this, _updateSubscribers4, updateSubscribers_fn4).call(this);
      },
      enumerable: true
    });
    if (ease !== void 0) {
      this.ease = ease;
    }
    if (easeOptions !== void 0) {
      this.easeOptions = easeOptions;
    }
  }
  /**
   * @returns {number} Get ease duration
   */
  get easeDuration() {
    return __privateGet(this, _easeOptions).duration;
  }
  /**
   * @returns {string|Function} Get easing function value.
   */
  get easeValue() {
    return __privateGet(this, _easeOptions).ease;
  }
  /**
   * @param {number}   duration - Set ease duration.
   */
  set easeDuration(duration) {
    if (!Number.isFinite(duration)) {
      throw new TypeError(`'duration' is not a finite number.`);
    }
    if (duration < 0) {
      throw new Error(`'duration' is less than 0.`);
    }
    __privateGet(this, _easeOptions).duration = duration;
    __privateMethod(this, _updateSubscribers4, updateSubscribers_fn4).call(this);
  }
  /**
   * @param {string|Function} value - Get easing function value.
   */
  set easeValue(value) {
    if (typeof value !== "function" && typeof value !== "string") {
      throw new TypeError(`'value' is not a function or string.`);
    }
    __privateGet(this, _easeOptions).ease = value;
    __privateMethod(this, _updateSubscribers4, updateSubscribers_fn4).call(this);
  }
  /**
   * Resets all options data to default values.
   */
  reset() {
    __privateSet(this, _ease, false);
    __privateSet(this, _easeOptions, { duration: 0.1, ease: cubicOut });
    __privateMethod(this, _updateSubscribers4, updateSubscribers_fn4).call(this);
  }
  /**
   * Resets easing options to default values.
   */
  resetEase() {
    __privateSet(this, _easeOptions, { duration: 0.1, ease: cubicOut });
    __privateMethod(this, _updateSubscribers4, updateSubscribers_fn4).call(this);
  }
  /**
   *
   * @param {function(DraggableOptions): void} handler - Callback function that is invoked on update / changes.
   *                                                 Receives the DraggableOptions object / instance.
   *
   * @returns {(function(): void)} Unsubscribe function.
   */
  subscribe(handler) {
    __privateGet(this, _subscriptions4).push(handler);
    handler(this);
    return () => {
      const index2 = __privateGet(this, _subscriptions4).findIndex((sub) => sub === handler);
      if (index2 >= 0) {
        __privateGet(this, _subscriptions4).splice(index2, 1);
      }
    };
  }
};
_ease = new WeakMap();
_easeOptions = new WeakMap();
_subscriptions4 = new WeakMap();
_updateSubscribers4 = new WeakSet();
updateSubscribers_fn4 = /* @__PURE__ */ __name(function() {
  const subscriptions = __privateGet(this, _subscriptions4);
  if (subscriptions.length > 0) {
    for (let cntr = 0; cntr < subscriptions.length; cntr++) {
      subscriptions[cntr](this);
    }
  }
}, "#updateSubscribers");
__name(_DraggableOptions, "DraggableOptions");
let DraggableOptions = _DraggableOptions;
draggable.options = (options) => new DraggableOptions(options);
const s_POSITION_DATA = { left: 0, top: 0 };
function lerp$5(start, end, amount) {
  return (1 - amount) * start + amount * end;
}
__name(lerp$5, "lerp$5");
function degToRad(deg) {
  return deg * (Math.PI / 180);
}
__name(degToRad, "degToRad");
var EPSILON = 1e-6;
var ARRAY_TYPE = typeof Float32Array !== "undefined" ? Float32Array : Array;
var RANDOM = Math.random;
if (!Math.hypot)
  Math.hypot = function() {
    var y = 0, i = arguments.length;
    while (i--) {
      y += arguments[i] * arguments[i];
    }
    return Math.sqrt(y);
  };
function create$6() {
  var out = new ARRAY_TYPE(9);
  if (ARRAY_TYPE != Float32Array) {
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[5] = 0;
    out[6] = 0;
    out[7] = 0;
  }
  out[0] = 1;
  out[4] = 1;
  out[8] = 1;
  return out;
}
__name(create$6, "create$6");
function create$5() {
  var out = new ARRAY_TYPE(16);
  if (ARRAY_TYPE != Float32Array) {
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[11] = 0;
    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
  }
  out[0] = 1;
  out[5] = 1;
  out[10] = 1;
  out[15] = 1;
  return out;
}
__name(create$5, "create$5");
function clone$5(a) {
  var out = new ARRAY_TYPE(16);
  out[0] = a[0];
  out[1] = a[1];
  out[2] = a[2];
  out[3] = a[3];
  out[4] = a[4];
  out[5] = a[5];
  out[6] = a[6];
  out[7] = a[7];
  out[8] = a[8];
  out[9] = a[9];
  out[10] = a[10];
  out[11] = a[11];
  out[12] = a[12];
  out[13] = a[13];
  out[14] = a[14];
  out[15] = a[15];
  return out;
}
__name(clone$5, "clone$5");
function copy$5(out, a) {
  out[0] = a[0];
  out[1] = a[1];
  out[2] = a[2];
  out[3] = a[3];
  out[4] = a[4];
  out[5] = a[5];
  out[6] = a[6];
  out[7] = a[7];
  out[8] = a[8];
  out[9] = a[9];
  out[10] = a[10];
  out[11] = a[11];
  out[12] = a[12];
  out[13] = a[13];
  out[14] = a[14];
  out[15] = a[15];
  return out;
}
__name(copy$5, "copy$5");
function fromValues$5(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  var out = new ARRAY_TYPE(16);
  out[0] = m00;
  out[1] = m01;
  out[2] = m02;
  out[3] = m03;
  out[4] = m10;
  out[5] = m11;
  out[6] = m12;
  out[7] = m13;
  out[8] = m20;
  out[9] = m21;
  out[10] = m22;
  out[11] = m23;
  out[12] = m30;
  out[13] = m31;
  out[14] = m32;
  out[15] = m33;
  return out;
}
__name(fromValues$5, "fromValues$5");
function set$5(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  out[0] = m00;
  out[1] = m01;
  out[2] = m02;
  out[3] = m03;
  out[4] = m10;
  out[5] = m11;
  out[6] = m12;
  out[7] = m13;
  out[8] = m20;
  out[9] = m21;
  out[10] = m22;
  out[11] = m23;
  out[12] = m30;
  out[13] = m31;
  out[14] = m32;
  out[15] = m33;
  return out;
}
__name(set$5, "set$5");
function identity$2(out) {
  out[0] = 1;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = 1;
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[10] = 1;
  out[11] = 0;
  out[12] = 0;
  out[13] = 0;
  out[14] = 0;
  out[15] = 1;
  return out;
}
__name(identity$2, "identity$2");
function transpose(out, a) {
  if (out === a) {
    var a01 = a[1], a02 = a[2], a03 = a[3];
    var a12 = a[6], a13 = a[7];
    var a23 = a[11];
    out[1] = a[4];
    out[2] = a[8];
    out[3] = a[12];
    out[4] = a01;
    out[6] = a[9];
    out[7] = a[13];
    out[8] = a02;
    out[9] = a12;
    out[11] = a[14];
    out[12] = a03;
    out[13] = a13;
    out[14] = a23;
  } else {
    out[0] = a[0];
    out[1] = a[4];
    out[2] = a[8];
    out[3] = a[12];
    out[4] = a[1];
    out[5] = a[5];
    out[6] = a[9];
    out[7] = a[13];
    out[8] = a[2];
    out[9] = a[6];
    out[10] = a[10];
    out[11] = a[14];
    out[12] = a[3];
    out[13] = a[7];
    out[14] = a[11];
    out[15] = a[15];
  }
  return out;
}
__name(transpose, "transpose");
function invert$2(out, a) {
  var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
  var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
  var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
  var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
  var b00 = a00 * a11 - a01 * a10;
  var b01 = a00 * a12 - a02 * a10;
  var b02 = a00 * a13 - a03 * a10;
  var b03 = a01 * a12 - a02 * a11;
  var b04 = a01 * a13 - a03 * a11;
  var b05 = a02 * a13 - a03 * a12;
  var b06 = a20 * a31 - a21 * a30;
  var b07 = a20 * a32 - a22 * a30;
  var b08 = a20 * a33 - a23 * a30;
  var b09 = a21 * a32 - a22 * a31;
  var b10 = a21 * a33 - a23 * a31;
  var b11 = a22 * a33 - a23 * a32;
  var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  if (!det) {
    return null;
  }
  det = 1 / det;
  out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  return out;
}
__name(invert$2, "invert$2");
function adjoint(out, a) {
  var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
  var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
  var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
  var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
  out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);
  out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
  out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);
  out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
  out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
  out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);
  out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
  out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);
  out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);
  out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
  out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);
  out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
  out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
  out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);
  out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
  out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);
  return out;
}
__name(adjoint, "adjoint");
function determinant(a) {
  var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
  var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
  var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
  var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
  var b00 = a00 * a11 - a01 * a10;
  var b01 = a00 * a12 - a02 * a10;
  var b02 = a00 * a13 - a03 * a10;
  var b03 = a01 * a12 - a02 * a11;
  var b04 = a01 * a13 - a03 * a11;
  var b05 = a02 * a13 - a03 * a12;
  var b06 = a20 * a31 - a21 * a30;
  var b07 = a20 * a32 - a22 * a30;
  var b08 = a20 * a33 - a23 * a30;
  var b09 = a21 * a32 - a22 * a31;
  var b10 = a21 * a33 - a23 * a31;
  var b11 = a22 * a33 - a23 * a32;
  return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
}
__name(determinant, "determinant");
function multiply$5(out, a, b) {
  var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
  var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
  var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
  var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
  var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
  out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  b0 = b[4];
  b1 = b[5];
  b2 = b[6];
  b3 = b[7];
  out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  b0 = b[8];
  b1 = b[9];
  b2 = b[10];
  b3 = b[11];
  out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  b0 = b[12];
  b1 = b[13];
  b2 = b[14];
  b3 = b[15];
  out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  return out;
}
__name(multiply$5, "multiply$5");
function translate$1(out, a, v) {
  var x = v[0], y = v[1], z = v[2];
  var a00, a01, a02, a03;
  var a10, a11, a12, a13;
  var a20, a21, a22, a23;
  if (a === out) {
    out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
    out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
    out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
    out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  } else {
    a00 = a[0];
    a01 = a[1];
    a02 = a[2];
    a03 = a[3];
    a10 = a[4];
    a11 = a[5];
    a12 = a[6];
    a13 = a[7];
    a20 = a[8];
    a21 = a[9];
    a22 = a[10];
    a23 = a[11];
    out[0] = a00;
    out[1] = a01;
    out[2] = a02;
    out[3] = a03;
    out[4] = a10;
    out[5] = a11;
    out[6] = a12;
    out[7] = a13;
    out[8] = a20;
    out[9] = a21;
    out[10] = a22;
    out[11] = a23;
    out[12] = a00 * x + a10 * y + a20 * z + a[12];
    out[13] = a01 * x + a11 * y + a21 * z + a[13];
    out[14] = a02 * x + a12 * y + a22 * z + a[14];
    out[15] = a03 * x + a13 * y + a23 * z + a[15];
  }
  return out;
}
__name(translate$1, "translate$1");
function scale$5(out, a, v) {
  var x = v[0], y = v[1], z = v[2];
  out[0] = a[0] * x;
  out[1] = a[1] * x;
  out[2] = a[2] * x;
  out[3] = a[3] * x;
  out[4] = a[4] * y;
  out[5] = a[5] * y;
  out[6] = a[6] * y;
  out[7] = a[7] * y;
  out[8] = a[8] * z;
  out[9] = a[9] * z;
  out[10] = a[10] * z;
  out[11] = a[11] * z;
  out[12] = a[12];
  out[13] = a[13];
  out[14] = a[14];
  out[15] = a[15];
  return out;
}
__name(scale$5, "scale$5");
function rotate$1(out, a, rad, axis) {
  var x = axis[0], y = axis[1], z = axis[2];
  var len = Math.hypot(x, y, z);
  var s, c, t;
  var a00, a01, a02, a03;
  var a10, a11, a12, a13;
  var a20, a21, a22, a23;
  var b00, b01, b02;
  var b10, b11, b12;
  var b20, b21, b22;
  if (len < EPSILON) {
    return null;
  }
  len = 1 / len;
  x *= len;
  y *= len;
  z *= len;
  s = Math.sin(rad);
  c = Math.cos(rad);
  t = 1 - c;
  a00 = a[0];
  a01 = a[1];
  a02 = a[2];
  a03 = a[3];
  a10 = a[4];
  a11 = a[5];
  a12 = a[6];
  a13 = a[7];
  a20 = a[8];
  a21 = a[9];
  a22 = a[10];
  a23 = a[11];
  b00 = x * x * t + c;
  b01 = y * x * t + z * s;
  b02 = z * x * t - y * s;
  b10 = x * y * t - z * s;
  b11 = y * y * t + c;
  b12 = z * y * t + x * s;
  b20 = x * z * t + y * s;
  b21 = y * z * t - x * s;
  b22 = z * z * t + c;
  out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  if (a !== out) {
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
  }
  return out;
}
__name(rotate$1, "rotate$1");
function rotateX$3(out, a, rad) {
  var s = Math.sin(rad);
  var c = Math.cos(rad);
  var a10 = a[4];
  var a11 = a[5];
  var a12 = a[6];
  var a13 = a[7];
  var a20 = a[8];
  var a21 = a[9];
  var a22 = a[10];
  var a23 = a[11];
  if (a !== out) {
    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
  }
  out[4] = a10 * c + a20 * s;
  out[5] = a11 * c + a21 * s;
  out[6] = a12 * c + a22 * s;
  out[7] = a13 * c + a23 * s;
  out[8] = a20 * c - a10 * s;
  out[9] = a21 * c - a11 * s;
  out[10] = a22 * c - a12 * s;
  out[11] = a23 * c - a13 * s;
  return out;
}
__name(rotateX$3, "rotateX$3");
function rotateY$3(out, a, rad) {
  var s = Math.sin(rad);
  var c = Math.cos(rad);
  var a00 = a[0];
  var a01 = a[1];
  var a02 = a[2];
  var a03 = a[3];
  var a20 = a[8];
  var a21 = a[9];
  var a22 = a[10];
  var a23 = a[11];
  if (a !== out) {
    out[4] = a[4];
    out[5] = a[5];
    out[6] = a[6];
    out[7] = a[7];
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
  }
  out[0] = a00 * c - a20 * s;
  out[1] = a01 * c - a21 * s;
  out[2] = a02 * c - a22 * s;
  out[3] = a03 * c - a23 * s;
  out[8] = a00 * s + a20 * c;
  out[9] = a01 * s + a21 * c;
  out[10] = a02 * s + a22 * c;
  out[11] = a03 * s + a23 * c;
  return out;
}
__name(rotateY$3, "rotateY$3");
function rotateZ$3(out, a, rad) {
  var s = Math.sin(rad);
  var c = Math.cos(rad);
  var a00 = a[0];
  var a01 = a[1];
  var a02 = a[2];
  var a03 = a[3];
  var a10 = a[4];
  var a11 = a[5];
  var a12 = a[6];
  var a13 = a[7];
  if (a !== out) {
    out[8] = a[8];
    out[9] = a[9];
    out[10] = a[10];
    out[11] = a[11];
    out[12] = a[12];
    out[13] = a[13];
    out[14] = a[14];
    out[15] = a[15];
  }
  out[0] = a00 * c + a10 * s;
  out[1] = a01 * c + a11 * s;
  out[2] = a02 * c + a12 * s;
  out[3] = a03 * c + a13 * s;
  out[4] = a10 * c - a00 * s;
  out[5] = a11 * c - a01 * s;
  out[6] = a12 * c - a02 * s;
  out[7] = a13 * c - a03 * s;
  return out;
}
__name(rotateZ$3, "rotateZ$3");
function fromTranslation$1(out, v) {
  out[0] = 1;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = 1;
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[10] = 1;
  out[11] = 0;
  out[12] = v[0];
  out[13] = v[1];
  out[14] = v[2];
  out[15] = 1;
  return out;
}
__name(fromTranslation$1, "fromTranslation$1");
function fromScaling(out, v) {
  out[0] = v[0];
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = v[1];
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[10] = v[2];
  out[11] = 0;
  out[12] = 0;
  out[13] = 0;
  out[14] = 0;
  out[15] = 1;
  return out;
}
__name(fromScaling, "fromScaling");
function fromRotation$1(out, rad, axis) {
  var x = axis[0], y = axis[1], z = axis[2];
  var len = Math.hypot(x, y, z);
  var s, c, t;
  if (len < EPSILON) {
    return null;
  }
  len = 1 / len;
  x *= len;
  y *= len;
  z *= len;
  s = Math.sin(rad);
  c = Math.cos(rad);
  t = 1 - c;
  out[0] = x * x * t + c;
  out[1] = y * x * t + z * s;
  out[2] = z * x * t - y * s;
  out[3] = 0;
  out[4] = x * y * t - z * s;
  out[5] = y * y * t + c;
  out[6] = z * y * t + x * s;
  out[7] = 0;
  out[8] = x * z * t + y * s;
  out[9] = y * z * t - x * s;
  out[10] = z * z * t + c;
  out[11] = 0;
  out[12] = 0;
  out[13] = 0;
  out[14] = 0;
  out[15] = 1;
  return out;
}
__name(fromRotation$1, "fromRotation$1");
function fromXRotation(out, rad) {
  var s = Math.sin(rad);
  var c = Math.cos(rad);
  out[0] = 1;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = c;
  out[6] = s;
  out[7] = 0;
  out[8] = 0;
  out[9] = -s;
  out[10] = c;
  out[11] = 0;
  out[12] = 0;
  out[13] = 0;
  out[14] = 0;
  out[15] = 1;
  return out;
}
__name(fromXRotation, "fromXRotation");
function fromYRotation(out, rad) {
  var s = Math.sin(rad);
  var c = Math.cos(rad);
  out[0] = c;
  out[1] = 0;
  out[2] = -s;
  out[3] = 0;
  out[4] = 0;
  out[5] = 1;
  out[6] = 0;
  out[7] = 0;
  out[8] = s;
  out[9] = 0;
  out[10] = c;
  out[11] = 0;
  out[12] = 0;
  out[13] = 0;
  out[14] = 0;
  out[15] = 1;
  return out;
}
__name(fromYRotation, "fromYRotation");
function fromZRotation(out, rad) {
  var s = Math.sin(rad);
  var c = Math.cos(rad);
  out[0] = c;
  out[1] = s;
  out[2] = 0;
  out[3] = 0;
  out[4] = -s;
  out[5] = c;
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[10] = 1;
  out[11] = 0;
  out[12] = 0;
  out[13] = 0;
  out[14] = 0;
  out[15] = 1;
  return out;
}
__name(fromZRotation, "fromZRotation");
function fromRotationTranslation$1(out, q, v) {
  var x = q[0], y = q[1], z = q[2], w = q[3];
  var x2 = x + x;
  var y2 = y + y;
  var z2 = z + z;
  var xx = x * x2;
  var xy = x * y2;
  var xz = x * z2;
  var yy = y * y2;
  var yz = y * z2;
  var zz = z * z2;
  var wx = w * x2;
  var wy = w * y2;
  var wz = w * z2;
  out[0] = 1 - (yy + zz);
  out[1] = xy + wz;
  out[2] = xz - wy;
  out[3] = 0;
  out[4] = xy - wz;
  out[5] = 1 - (xx + zz);
  out[6] = yz + wx;
  out[7] = 0;
  out[8] = xz + wy;
  out[9] = yz - wx;
  out[10] = 1 - (xx + yy);
  out[11] = 0;
  out[12] = v[0];
  out[13] = v[1];
  out[14] = v[2];
  out[15] = 1;
  return out;
}
__name(fromRotationTranslation$1, "fromRotationTranslation$1");
function fromQuat2(out, a) {
  var translation = new ARRAY_TYPE(3);
  var bx = -a[0], by = -a[1], bz = -a[2], bw = a[3], ax = a[4], ay = a[5], az = a[6], aw = a[7];
  var magnitude = bx * bx + by * by + bz * bz + bw * bw;
  if (magnitude > 0) {
    translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;
    translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;
    translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;
  } else {
    translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
    translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
    translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
  }
  fromRotationTranslation$1(out, a, translation);
  return out;
}
__name(fromQuat2, "fromQuat2");
function getTranslation$1(out, mat) {
  out[0] = mat[12];
  out[1] = mat[13];
  out[2] = mat[14];
  return out;
}
__name(getTranslation$1, "getTranslation$1");
function getScaling(out, mat) {
  var m11 = mat[0];
  var m12 = mat[1];
  var m13 = mat[2];
  var m21 = mat[4];
  var m22 = mat[5];
  var m23 = mat[6];
  var m31 = mat[8];
  var m32 = mat[9];
  var m33 = mat[10];
  out[0] = Math.hypot(m11, m12, m13);
  out[1] = Math.hypot(m21, m22, m23);
  out[2] = Math.hypot(m31, m32, m33);
  return out;
}
__name(getScaling, "getScaling");
function getRotation(out, mat) {
  var scaling = new ARRAY_TYPE(3);
  getScaling(scaling, mat);
  var is1 = 1 / scaling[0];
  var is2 = 1 / scaling[1];
  var is3 = 1 / scaling[2];
  var sm11 = mat[0] * is1;
  var sm12 = mat[1] * is2;
  var sm13 = mat[2] * is3;
  var sm21 = mat[4] * is1;
  var sm22 = mat[5] * is2;
  var sm23 = mat[6] * is3;
  var sm31 = mat[8] * is1;
  var sm32 = mat[9] * is2;
  var sm33 = mat[10] * is3;
  var trace = sm11 + sm22 + sm33;
  var S = 0;
  if (trace > 0) {
    S = Math.sqrt(trace + 1) * 2;
    out[3] = 0.25 * S;
    out[0] = (sm23 - sm32) / S;
    out[1] = (sm31 - sm13) / S;
    out[2] = (sm12 - sm21) / S;
  } else if (sm11 > sm22 && sm11 > sm33) {
    S = Math.sqrt(1 + sm11 - sm22 - sm33) * 2;
    out[3] = (sm23 - sm32) / S;
    out[0] = 0.25 * S;
    out[1] = (sm12 + sm21) / S;
    out[2] = (sm31 + sm13) / S;
  } else if (sm22 > sm33) {
    S = Math.sqrt(1 + sm22 - sm11 - sm33) * 2;
    out[3] = (sm31 - sm13) / S;
    out[0] = (sm12 + sm21) / S;
    out[1] = 0.25 * S;
    out[2] = (sm23 + sm32) / S;
  } else {
    S = Math.sqrt(1 + sm33 - sm11 - sm22) * 2;
    out[3] = (sm12 - sm21) / S;
    out[0] = (sm31 + sm13) / S;
    out[1] = (sm23 + sm32) / S;
    out[2] = 0.25 * S;
  }
  return out;
}
__name(getRotation, "getRotation");
function fromRotationTranslationScale(out, q, v, s) {
  var x = q[0], y = q[1], z = q[2], w = q[3];
  var x2 = x + x;
  var y2 = y + y;
  var z2 = z + z;
  var xx = x * x2;
  var xy = x * y2;
  var xz = x * z2;
  var yy = y * y2;
  var yz = y * z2;
  var zz = z * z2;
  var wx = w * x2;
  var wy = w * y2;
  var wz = w * z2;
  var sx = s[0];
  var sy = s[1];
  var sz = s[2];
  out[0] = (1 - (yy + zz)) * sx;
  out[1] = (xy + wz) * sx;
  out[2] = (xz - wy) * sx;
  out[3] = 0;
  out[4] = (xy - wz) * sy;
  out[5] = (1 - (xx + zz)) * sy;
  out[6] = (yz + wx) * sy;
  out[7] = 0;
  out[8] = (xz + wy) * sz;
  out[9] = (yz - wx) * sz;
  out[10] = (1 - (xx + yy)) * sz;
  out[11] = 0;
  out[12] = v[0];
  out[13] = v[1];
  out[14] = v[2];
  out[15] = 1;
  return out;
}
__name(fromRotationTranslationScale, "fromRotationTranslationScale");
function fromRotationTranslationScaleOrigin(out, q, v, s, o) {
  var x = q[0], y = q[1], z = q[2], w = q[3];
  var x2 = x + x;
  var y2 = y + y;
  var z2 = z + z;
  var xx = x * x2;
  var xy = x * y2;
  var xz = x * z2;
  var yy = y * y2;
  var yz = y * z2;
  var zz = z * z2;
  var wx = w * x2;
  var wy = w * y2;
  var wz = w * z2;
  var sx = s[0];
  var sy = s[1];
  var sz = s[2];
  var ox = o[0];
  var oy = o[1];
  var oz = o[2];
  var out0 = (1 - (yy + zz)) * sx;
  var out1 = (xy + wz) * sx;
  var out2 = (xz - wy) * sx;
  var out4 = (xy - wz) * sy;
  var out5 = (1 - (xx + zz)) * sy;
  var out6 = (yz + wx) * sy;
  var out8 = (xz + wy) * sz;
  var out9 = (yz - wx) * sz;
  var out10 = (1 - (xx + yy)) * sz;
  out[0] = out0;
  out[1] = out1;
  out[2] = out2;
  out[3] = 0;
  out[4] = out4;
  out[5] = out5;
  out[6] = out6;
  out[7] = 0;
  out[8] = out8;
  out[9] = out9;
  out[10] = out10;
  out[11] = 0;
  out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);
  out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);
  out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);
  out[15] = 1;
  return out;
}
__name(fromRotationTranslationScaleOrigin, "fromRotationTranslationScaleOrigin");
function fromQuat(out, q) {
  var x = q[0], y = q[1], z = q[2], w = q[3];
  var x2 = x + x;
  var y2 = y + y;
  var z2 = z + z;
  var xx = x * x2;
  var yx = y * x2;
  var yy = y * y2;
  var zx = z * x2;
  var zy = z * y2;
  var zz = z * z2;
  var wx = w * x2;
  var wy = w * y2;
  var wz = w * z2;
  out[0] = 1 - yy - zz;
  out[1] = yx + wz;
  out[2] = zx - wy;
  out[3] = 0;
  out[4] = yx - wz;
  out[5] = 1 - xx - zz;
  out[6] = zy + wx;
  out[7] = 0;
  out[8] = zx + wy;
  out[9] = zy - wx;
  out[10] = 1 - xx - yy;
  out[11] = 0;
  out[12] = 0;
  out[13] = 0;
  out[14] = 0;
  out[15] = 1;
  return out;
}
__name(fromQuat, "fromQuat");
function frustum(out, left, right, bottom, top, near, far) {
  var rl = 1 / (right - left);
  var tb = 1 / (top - bottom);
  var nf = 1 / (near - far);
  out[0] = near * 2 * rl;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = near * 2 * tb;
  out[6] = 0;
  out[7] = 0;
  out[8] = (right + left) * rl;
  out[9] = (top + bottom) * tb;
  out[10] = (far + near) * nf;
  out[11] = -1;
  out[12] = 0;
  out[13] = 0;
  out[14] = far * near * 2 * nf;
  out[15] = 0;
  return out;
}
__name(frustum, "frustum");
function perspectiveNO(out, fovy, aspect, near, far) {
  var f = 1 / Math.tan(fovy / 2), nf;
  out[0] = f / aspect;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = f;
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[11] = -1;
  out[12] = 0;
  out[13] = 0;
  out[15] = 0;
  if (far != null && far !== Infinity) {
    nf = 1 / (near - far);
    out[10] = (far + near) * nf;
    out[14] = 2 * far * near * nf;
  } else {
    out[10] = -1;
    out[14] = -2 * near;
  }
  return out;
}
__name(perspectiveNO, "perspectiveNO");
var perspective = perspectiveNO;
function perspectiveZO(out, fovy, aspect, near, far) {
  var f = 1 / Math.tan(fovy / 2), nf;
  out[0] = f / aspect;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = f;
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[11] = -1;
  out[12] = 0;
  out[13] = 0;
  out[15] = 0;
  if (far != null && far !== Infinity) {
    nf = 1 / (near - far);
    out[10] = far * nf;
    out[14] = far * near * nf;
  } else {
    out[10] = -1;
    out[14] = -near;
  }
  return out;
}
__name(perspectiveZO, "perspectiveZO");
function perspectiveFromFieldOfView(out, fov, near, far) {
  var upTan = Math.tan(fov.upDegrees * Math.PI / 180);
  var downTan = Math.tan(fov.downDegrees * Math.PI / 180);
  var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180);
  var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180);
  var xScale = 2 / (leftTan + rightTan);
  var yScale = 2 / (upTan + downTan);
  out[0] = xScale;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = yScale;
  out[6] = 0;
  out[7] = 0;
  out[8] = -((leftTan - rightTan) * xScale * 0.5);
  out[9] = (upTan - downTan) * yScale * 0.5;
  out[10] = far / (near - far);
  out[11] = -1;
  out[12] = 0;
  out[13] = 0;
  out[14] = far * near / (near - far);
  out[15] = 0;
  return out;
}
__name(perspectiveFromFieldOfView, "perspectiveFromFieldOfView");
function orthoNO(out, left, right, bottom, top, near, far) {
  var lr = 1 / (left - right);
  var bt = 1 / (bottom - top);
  var nf = 1 / (near - far);
  out[0] = -2 * lr;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = -2 * bt;
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[10] = 2 * nf;
  out[11] = 0;
  out[12] = (left + right) * lr;
  out[13] = (top + bottom) * bt;
  out[14] = (far + near) * nf;
  out[15] = 1;
  return out;
}
__name(orthoNO, "orthoNO");
var ortho = orthoNO;
function orthoZO(out, left, right, bottom, top, near, far) {
  var lr = 1 / (left - right);
  var bt = 1 / (bottom - top);
  var nf = 1 / (near - far);
  out[0] = -2 * lr;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 0;
  out[5] = -2 * bt;
  out[6] = 0;
  out[7] = 0;
  out[8] = 0;
  out[9] = 0;
  out[10] = nf;
  out[11] = 0;
  out[12] = (left + right) * lr;
  out[13] = (top + bottom) * bt;
  out[14] = near * nf;
  out[15] = 1;
  return out;
}
__name(orthoZO, "orthoZO");
function lookAt(out, eye, center, up) {
  var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  var eyex = eye[0];
  var eyey = eye[1];
  var eyez = eye[2];
  var upx = up[0];
  var upy = up[1];
  var upz = up[2];
  var centerx = center[0];
  var centery = center[1];
  var centerz = center[2];
  if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
    return identity$2(out);
  }
  z0 = eyex - centerx;
  z1 = eyey - centery;
  z2 = eyez - centerz;
  len = 1 / Math.hypot(z0, z1, z2);
  z0 *= len;
  z1 *= len;
  z2 *= len;
  x0 = upy * z2 - upz * z1;
  x1 = upz * z0 - upx * z2;
  x2 = upx * z1 - upy * z0;
  len = Math.hypot(x0, x1, x2);
  if (!len) {
    x0 = 0;
    x1 = 0;
    x2 = 0;
  } else {
    len = 1 / len;
    x0 *= len;
    x1 *= len;
    x2 *= len;
  }
  y0 = z1 * x2 - z2 * x1;
  y1 = z2 * x0 - z0 * x2;
  y2 = z0 * x1 - z1 * x0;
  len = Math.hypot(y0, y1, y2);
  if (!len) {
    y0 = 0;
    y1 = 0;
    y2 = 0;
  } else {
    len = 1 / len;
    y0 *= len;
    y1 *= len;
    y2 *= len;
  }
  out[0] = x0;
  out[1] = y0;
  out[2] = z0;
  out[3] = 0;
  out[4] = x1;
  out[5] = y1;
  out[6] = z1;
  out[7] = 0;
  out[8] = x2;
  out[9] = y2;
  out[10] = z2;
  out[11] = 0;
  out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  out[15] = 1;
  return out;
}
__name(lookAt, "lookAt");
function targetTo(out, eye, target, up) {
  var eyex = eye[0], eyey = eye[1], eyez = eye[2], upx = up[0], upy = up[1], upz = up[2];
  var z0 = eyex - target[0], z1 = eyey - target[1], z2 = eyez - target[2];
  var len = z0 * z0 + z1 * z1 + z2 * z2;
  if (len > 0) {
    len = 1 / Math.sqrt(len);
    z0 *= len;
    z1 *= len;
    z2 *= len;
  }
  var x0 = upy * z2 - upz * z1, x1 = upz * z0 - upx * z2, x2 = upx * z1 - upy * z0;
  len = x0 * x0 + x1 * x1 + x2 * x2;
  if (len > 0) {
    len = 1 / Math.sqrt(len);
    x0 *= len;
    x1 *= len;
    x2 *= len;
  }
  out[0] = x0;
  out[1] = x1;
  out[2] = x2;
  out[3] = 0;
  out[4] = z1 * x2 - z2 * x1;
  out[5] = z2 * x0 - z0 * x2;
  out[6] = z0 * x1 - z1 * x0;
  out[7] = 0;
  out[8] = z0;
  out[9] = z1;
  out[10] = z2;
  out[11] = 0;
  out[12] = eyex;
  out[13] = eyey;
  out[14] = eyez;
  out[15] = 1;
  return out;
}
__name(targetTo, "targetTo");
function str$5(a) {
  return "mat4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ", " + a[9] + ", " + a[10] + ", " + a[11] + ", " + a[12] + ", " + a[13] + ", " + a[14] + ", " + a[15] + ")";
}
__name(str$5, "str$5");
function frob(a) {
  return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);
}
__name(frob, "frob");
function add$5(out, a, b) {
  out[0] = a[0] + b[0];
  out[1] = a[1] + b[1];
  out[2] = a[2] + b[2];
  out[3] = a[3] + b[3];
  out[4] = a[4] + b[4];
  out[5] = a[5] + b[5];
  out[6] = a[6] + b[6];
  out[7] = a[7] + b[7];
  out[8] = a[8] + b[8];
  out[9] = a[9] + b[9];
  out[10] = a[10] + b[10];
  out[11] = a[11] + b[11];
  out[12] = a[12] + b[12];
  out[13] = a[13] + b[13];
  out[14] = a[14] + b[14];
  out[15] = a[15] + b[15];
  return out;
}
__name(add$5, "add$5");
function subtract$3(out, a, b) {
  out[0] = a[0] - b[0];
  out[1] = a[1] - b[1];
  out[2] = a[2] - b[2];
  out[3] = a[3] - b[3];
  out[4] = a[4] - b[4];
  out[5] = a[5] - b[5];
  out[6] = a[6] - b[6];
  out[7] = a[7] - b[7];
  out[8] = a[8] - b[8];
  out[9] = a[9] - b[9];
  out[10] = a[10] - b[10];
  out[11] = a[11] - b[11];
  out[12] = a[12] - b[12];
  out[13] = a[13] - b[13];
  out[14] = a[14] - b[14];
  out[15] = a[15] - b[15];
  return out;
}
__name(subtract$3, "subtract$3");
function multiplyScalar(out, a, b) {
  out[0] = a[0] * b;
  out[1] = a[1] * b;
  out[2] = a[2] * b;
  out[3] = a[3] * b;
  out[4] = a[4] * b;
  out[5] = a[5] * b;
  out[6] = a[6] * b;
  out[7] = a[7] * b;
  out[8] = a[8] * b;
  out[9] = a[9] * b;
  out[10] = a[10] * b;
  out[11] = a[11] * b;
  out[12] = a[12] * b;
  out[13] = a[13] * b;
  out[14] = a[14] * b;
  out[15] = a[15] * b;
  return out;
}
__name(multiplyScalar, "multiplyScalar");
function multiplyScalarAndAdd(out, a, b, scale) {
  out[0] = a[0] + b[0] * scale;
  out[1] = a[1] + b[1] * scale;
  out[2] = a[2] + b[2] * scale;
  out[3] = a[3] + b[3] * scale;
  out[4] = a[4] + b[4] * scale;
  out[5] = a[5] + b[5] * scale;
  out[6] = a[6] + b[6] * scale;
  out[7] = a[7] + b[7] * scale;
  out[8] = a[8] + b[8] * scale;
  out[9] = a[9] + b[9] * scale;
  out[10] = a[10] + b[10] * scale;
  out[11] = a[11] + b[11] * scale;
  out[12] = a[12] + b[12] * scale;
  out[13] = a[13] + b[13] * scale;
  out[14] = a[14] + b[14] * scale;
  out[15] = a[15] + b[15] * scale;
  return out;
}
__name(multiplyScalarAndAdd, "multiplyScalarAndAdd");
function exactEquals$5(a, b) {
  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];
}
__name(exactEquals$5, "exactEquals$5");
function equals$5(a, b) {
  var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
  var a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7];
  var a8 = a[8], a9 = a[9], a10 = a[10], a11 = a[11];
  var a12 = a[12], a13 = a[13], a14 = a[14], a15 = a[15];
  var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
  var b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7];
  var b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11];
  var b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
  return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1, Math.abs(a15), Math.abs(b15));
}
__name(equals$5, "equals$5");
var mul$5 = multiply$5;
var sub$3 = subtract$3;
const mat4 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  add: add$5,
  adjoint,
  clone: clone$5,
  copy: copy$5,
  create: create$5,
  determinant,
  equals: equals$5,
  exactEquals: exactEquals$5,
  frob,
  fromQuat,
  fromQuat2,
  fromRotation: fromRotation$1,
  fromRotationTranslation: fromRotationTranslation$1,
  fromRotationTranslationScale,
  fromRotationTranslationScaleOrigin,
  fromScaling,
  fromTranslation: fromTranslation$1,
  fromValues: fromValues$5,
  fromXRotation,
  fromYRotation,
  fromZRotation,
  frustum,
  getRotation,
  getScaling,
  getTranslation: getTranslation$1,
  identity: identity$2,
  invert: invert$2,
  lookAt,
  mul: mul$5,
  multiply: multiply$5,
  multiplyScalar,
  multiplyScalarAndAdd,
  ortho,
  orthoNO,
  orthoZO,
  perspective,
  perspectiveFromFieldOfView,
  perspectiveNO,
  perspectiveZO,
  rotate: rotate$1,
  rotateX: rotateX$3,
  rotateY: rotateY$3,
  rotateZ: rotateZ$3,
  scale: scale$5,
  set: set$5,
  str: str$5,
  sub: sub$3,
  subtract: subtract$3,
  targetTo,
  translate: translate$1,
  transpose
});
function create$4() {
  var out = new ARRAY_TYPE(3);
  if (ARRAY_TYPE != Float32Array) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
  }
  return out;
}
__name(create$4, "create$4");
function clone$4(a) {
  var out = new ARRAY_TYPE(3);
  out[0] = a[0];
  out[1] = a[1];
  out[2] = a[2];
  return out;
}
__name(clone$4, "clone$4");
function length$4(a) {
  var x = a[0];
  var y = a[1];
  var z = a[2];
  return Math.hypot(x, y, z);
}
__name(length$4, "length$4");
function fromValues$4(x, y, z) {
  var out = new ARRAY_TYPE(3);
  out[0] = x;
  out[1] = y;
  out[2] = z;
  return out;
}
__name(fromValues$4, "fromValues$4");
function copy$4(out, a) {
  out[0] = a[0];
  out[1] = a[1];
  out[2] = a[2];
  return out;
}
__name(copy$4, "copy$4");
function set$4(out, x, y, z) {
  out[0] = x;
  out[1] = y;
  out[2] = z;
  return out;
}
__name(set$4, "set$4");
function add$4(out, a, b) {
  out[0] = a[0] + b[0];
  out[1] = a[1] + b[1];
  out[2] = a[2] + b[2];
  return out;
}
__name(add$4, "add$4");
function subtract$2(out, a, b) {
  out[0] = a[0] - b[0];
  out[1] = a[1] - b[1];
  out[2] = a[2] - b[2];
  return out;
}
__name(subtract$2, "subtract$2");
function multiply$4(out, a, b) {
  out[0] = a[0] * b[0];
  out[1] = a[1] * b[1];
  out[2] = a[2] * b[2];
  return out;
}
__name(multiply$4, "multiply$4");
function divide$2(out, a, b) {
  out[0] = a[0] / b[0];
  out[1] = a[1] / b[1];
  out[2] = a[2] / b[2];
  return out;
}
__name(divide$2, "divide$2");
function ceil$2(out, a) {
  out[0] = Math.ceil(a[0]);
  out[1] = Math.ceil(a[1]);
  out[2] = Math.ceil(a[2]);
  return out;
}
__name(ceil$2, "ceil$2");
function floor$2(out, a) {
  out[0] = Math.floor(a[0]);
  out[1] = Math.floor(a[1]);
  out[2] = Math.floor(a[2]);
  return out;
}
__name(floor$2, "floor$2");
function min$2(out, a, b) {
  out[0] = Math.min(a[0], b[0]);
  out[1] = Math.min(a[1], b[1]);
  out[2] = Math.min(a[2], b[2]);
  return out;
}
__name(min$2, "min$2");
function max$2(out, a, b) {
  out[0] = Math.max(a[0], b[0]);
  out[1] = Math.max(a[1], b[1]);
  out[2] = Math.max(a[2], b[2]);
  return out;
}
__name(max$2, "max$2");
function round$2(out, a) {
  out[0] = Math.round(a[0]);
  out[1] = Math.round(a[1]);
  out[2] = Math.round(a[2]);
  return out;
}
__name(round$2, "round$2");
function scale$4(out, a, b) {
  out[0] = a[0] * b;
  out[1] = a[1] * b;
  out[2] = a[2] * b;
  return out;
}
__name(scale$4, "scale$4");
function scaleAndAdd$2(out, a, b, scale) {
  out[0] = a[0] + b[0] * scale;
  out[1] = a[1] + b[1] * scale;
  out[2] = a[2] + b[2] * scale;
  return out;
}
__name(scaleAndAdd$2, "scaleAndAdd$2");
function distance$2(a, b) {
  var x = b[0] - a[0];
  var y = b[1] - a[1];
  var z = b[2] - a[2];
  return Math.hypot(x, y, z);
}
__name(distance$2, "distance$2");
function squaredDistance$2(a, b) {
  var x = b[0] - a[0];
  var y = b[1] - a[1];
  var z = b[2] - a[2];
  return x * x + y * y + z * z;
}
__name(squaredDistance$2, "squaredDistance$2");
function squaredLength$4(a) {
  var x = a[0];
  var y = a[1];
  var z = a[2];
  return x * x + y * y + z * z;
}
__name(squaredLength$4, "squaredLength$4");
function negate$2(out, a) {
  out[0] = -a[0];
  out[1] = -a[1];
  out[2] = -a[2];
  return out;
}
__name(negate$2, "negate$2");
function inverse$2(out, a) {
  out[0] = 1 / a[0];
  out[1] = 1 / a[1];
  out[2] = 1 / a[2];
  return out;
}
__name(inverse$2, "inverse$2");
function normalize$4(out, a) {
  var x = a[0];
  var y = a[1];
  var z = a[2];
  var len = x * x + y * y + z * z;
  if (len > 0) {
    len = 1 / Math.sqrt(len);
  }
  out[0] = a[0] * len;
  out[1] = a[1] * len;
  out[2] = a[2] * len;
  return out;
}
__name(normalize$4, "normalize$4");
function dot$4(a, b) {
  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
__name(dot$4, "dot$4");
function cross$2(out, a, b) {
  var ax = a[0], ay = a[1], az = a[2];
  var bx = b[0], by = b[1], bz = b[2];
  out[0] = ay * bz - az * by;
  out[1] = az * bx - ax * bz;
  out[2] = ax * by - ay * bx;
  return out;
}
__name(cross$2, "cross$2");
function lerp$4(out, a, b, t) {
  var ax = a[0];
  var ay = a[1];
  var az = a[2];
  out[0] = ax + t * (b[0] - ax);
  out[1] = ay + t * (b[1] - ay);
  out[2] = az + t * (b[2] - az);
  return out;
}
__name(lerp$4, "lerp$4");
function hermite(out, a, b, c, d, t) {
  var factorTimes2 = t * t;
  var factor1 = factorTimes2 * (2 * t - 3) + 1;
  var factor2 = factorTimes2 * (t - 2) + t;
  var factor3 = factorTimes2 * (t - 1);
  var factor4 = factorTimes2 * (3 - 2 * t);
  out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;
  out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;
  out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;
  return out;
}
__name(hermite, "hermite");
function bezier(out, a, b, c, d, t) {
  var inverseFactor = 1 - t;
  var inverseFactorTimesTwo = inverseFactor * inverseFactor;
  var factorTimes2 = t * t;
  var factor1 = inverseFactorTimesTwo * inverseFactor;
  var factor2 = 3 * t * inverseFactorTimesTwo;
  var factor3 = 3 * factorTimes2 * inverseFactor;
  var factor4 = factorTimes2 * t;
  out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;
  out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;
  out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;
  return out;
}
__name(bezier, "bezier");
function random$3(out, scale) {
  scale = scale || 1;
  var r = RANDOM() * 2 * Math.PI;
  var z = RANDOM() * 2 - 1;
  var zScale = Math.sqrt(1 - z * z) * scale;
  out[0] = Math.cos(r) * zScale;
  out[1] = Math.sin(r) * zScale;
  out[2] = z * scale;
  return out;
}
__name(random$3, "random$3");
function transformMat4$2(out, a, m) {
  var x = a[0], y = a[1], z = a[2];
  var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  w = w || 1;
  out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  return out;
}
__name(transformMat4$2, "transformMat4$2");
function transformMat3$1(out, a, m) {
  var x = a[0], y = a[1], z = a[2];
  out[0] = x * m[0] + y * m[3] + z * m[6];
  out[1] = x * m[1] + y * m[4] + z * m[7];
  out[2] = x * m[2] + y * m[5] + z * m[8];
  return out;
}
__name(transformMat3$1, "transformMat3$1");
function transformQuat$1(out, a, q) {
  var qx = q[0], qy = q[1], qz = q[2], qw = q[3];
  var x = a[0], y = a[1], z = a[2];
  var uvx = qy * z - qz * y, uvy = qz * x - qx * z, uvz = qx * y - qy * x;
  var uuvx = qy * uvz - qz * uvy, uuvy = qz * uvx - qx * uvz, uuvz = qx * uvy - qy * uvx;
  var w2 = qw * 2;
  uvx *= w2;
  uvy *= w2;
  uvz *= w2;
  uuvx *= 2;
  uuvy *= 2;
  uuvz *= 2;
  out[0] = x + uvx + uuvx;
  out[1] = y + uvy + uuvy;
  out[2] = z + uvz + uuvz;
  return out;
}
__name(transformQuat$1, "transformQuat$1");
function rotateX$2(out, a, b, rad) {
  var p = [], r = [];
  p[0] = a[0] - b[0];
  p[1] = a[1] - b[1];
  p[2] = a[2] - b[2];
  r[0] = p[0];
  r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad);
  out[0] = r[0] + b[0];
  out[1] = r[1] + b[1];
  out[2] = r[2] + b[2];
  return out;
}
__name(rotateX$2, "rotateX$2");
function rotateY$2(out, a, b, rad) {
  var p = [], r = [];
  p[0] = a[0] - b[0];
  p[1] = a[1] - b[1];
  p[2] = a[2] - b[2];
  r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  r[1] = p[1];
  r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad);
  out[0] = r[0] + b[0];
  out[1] = r[1] + b[1];
  out[2] = r[2] + b[2];
  return out;
}
__name(rotateY$2, "rotateY$2");
function rotateZ$2(out, a, b, rad) {
  var p = [], r = [];
  p[0] = a[0] - b[0];
  p[1] = a[1] - b[1];
  p[2] = a[2] - b[2];
  r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  r[2] = p[2];
  out[0] = r[0] + b[0];
  out[1] = r[1] + b[1];
  out[2] = r[2] + b[2];
  return out;
}
__name(rotateZ$2, "rotateZ$2");
function angle$1(a, b) {
  var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2], mag1 = Math.sqrt(ax * ax + ay * ay + az * az), mag2 = Math.sqrt(bx * bx + by * by + bz * bz), mag = mag1 * mag2, cosine = mag && dot$4(a, b) / mag;
  return Math.acos(Math.min(Math.max(cosine, -1), 1));
}
__name(angle$1, "angle$1");
function zero$2(out) {
  out[0] = 0;
  out[1] = 0;
  out[2] = 0;
  return out;
}
__name(zero$2, "zero$2");
function str$4(a) {
  return "vec3(" + a[0] + ", " + a[1] + ", " + a[2] + ")";
}
__name(str$4, "str$4");
function exactEquals$4(a, b) {
  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
}
__name(exactEquals$4, "exactEquals$4");
function equals$4(a, b) {
  var a0 = a[0], a1 = a[1], a2 = a[2];
  var b0 = b[0], b1 = b[1], b2 = b[2];
  return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2));
}
__name(equals$4, "equals$4");
var sub$2 = subtract$2;
var mul$4 = multiply$4;
var div$2 = divide$2;
var dist$2 = distance$2;
var sqrDist$2 = squaredDistance$2;
var len$4 = length$4;
var sqrLen$4 = squaredLength$4;
var forEach$2 = function() {
  var vec = create$4();
  return function(a, stride, offset2, count, fn, arg) {
    var i, l;
    if (!stride) {
      stride = 3;
    }
    if (!offset2) {
      offset2 = 0;
    }
    if (count) {
      l = Math.min(count * stride + offset2, a.length);
    } else {
      l = a.length;
    }
    for (i = offset2; i < l; i += stride) {
      vec[0] = a[i];
      vec[1] = a[i + 1];
      vec[2] = a[i + 2];
      fn(vec, vec, arg);
      a[i] = vec[0];
      a[i + 1] = vec[1];
      a[i + 2] = vec[2];
    }
    return a;
  };
}();
const vec3 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  add: add$4,
  angle: angle$1,
  bezier,
  ceil: ceil$2,
  clone: clone$4,
  copy: copy$4,
  create: create$4,
  cross: cross$2,
  dist: dist$2,
  distance: distance$2,
  div: div$2,
  divide: divide$2,
  dot: dot$4,
  equals: equals$4,
  exactEquals: exactEquals$4,
  floor: floor$2,
  forEach: forEach$2,
  fromValues: fromValues$4,
  hermite,
  inverse: inverse$2,
  len: len$4,
  length: length$4,
  lerp: lerp$4,
  max: max$2,
  min: min$2,
  mul: mul$4,
  multiply: multiply$4,
  negate: negate$2,
  normalize: normalize$4,
  random: random$3,
  rotateX: rotateX$2,
  rotateY: rotateY$2,
  rotateZ: rotateZ$2,
  round: round$2,
  scale: scale$4,
  scaleAndAdd: scaleAndAdd$2,
  set: set$4,
  sqrDist: sqrDist$2,
  sqrLen: sqrLen$4,
  squaredDistance: squaredDistance$2,
  squaredLength: squaredLength$4,
  str: str$4,
  sub: sub$2,
  subtract: subtract$2,
  transformMat3: transformMat3$1,
  transformMat4: transformMat4$2,
  transformQuat: transformQuat$1,
  zero: zero$2
});
function create$3() {
  var out = new ARRAY_TYPE(4);
  if (ARRAY_TYPE != Float32Array) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
  }
  return out;
}
__name(create$3, "create$3");
function normalize$3(out, a) {
  var x = a[0];
  var y = a[1];
  var z = a[2];
  var w = a[3];
  var len = x * x + y * y + z * z + w * w;
  if (len > 0) {
    len = 1 / Math.sqrt(len);
  }
  out[0] = x * len;
  out[1] = y * len;
  out[2] = z * len;
  out[3] = w * len;
  return out;
}
__name(normalize$3, "normalize$3");
(function() {
  var vec = create$3();
  return function(a, stride, offset2, count, fn, arg) {
    var i, l;
    if (!stride) {
      stride = 4;
    }
    if (!offset2) {
      offset2 = 0;
    }
    if (count) {
      l = Math.min(count * stride + offset2, a.length);
    } else {
      l = a.length;
    }
    for (i = offset2; i < l; i += stride) {
      vec[0] = a[i];
      vec[1] = a[i + 1];
      vec[2] = a[i + 2];
      vec[3] = a[i + 3];
      fn(vec, vec, arg);
      a[i] = vec[0];
      a[i + 1] = vec[1];
      a[i + 2] = vec[2];
      a[i + 3] = vec[3];
    }
    return a;
  };
})();
function create$2() {
  var out = new ARRAY_TYPE(4);
  if (ARRAY_TYPE != Float32Array) {
    out[0] = 0;
    out[1] = 0;
    out[2] = 0;
  }
  out[3] = 1;
  return out;
}
__name(create$2, "create$2");
function setAxisAngle(out, axis, rad) {
  rad = rad * 0.5;
  var s = Math.sin(rad);
  out[0] = s * axis[0];
  out[1] = s * axis[1];
  out[2] = s * axis[2];
  out[3] = Math.cos(rad);
  return out;
}
__name(setAxisAngle, "setAxisAngle");
function slerp(out, a, b, t) {
  var ax = a[0], ay = a[1], az = a[2], aw = a[3];
  var bx = b[0], by = b[1], bz = b[2], bw = b[3];
  var omega, cosom, sinom, scale0, scale1;
  cosom = ax * bx + ay * by + az * bz + aw * bw;
  if (cosom < 0) {
    cosom = -cosom;
    bx = -bx;
    by = -by;
    bz = -bz;
    bw = -bw;
  }
  if (1 - cosom > EPSILON) {
    omega = Math.acos(cosom);
    sinom = Math.sin(omega);
    scale0 = Math.sin((1 - t) * omega) / sinom;
    scale1 = Math.sin(t * omega) / sinom;
  } else {
    scale0 = 1 - t;
    scale1 = t;
  }
  out[0] = scale0 * ax + scale1 * bx;
  out[1] = scale0 * ay + scale1 * by;
  out[2] = scale0 * az + scale1 * bz;
  out[3] = scale0 * aw + scale1 * bw;
  return out;
}
__name(slerp, "slerp");
function fromMat3(out, m) {
  var fTrace = m[0] + m[4] + m[8];
  var fRoot;
  if (fTrace > 0) {
    fRoot = Math.sqrt(fTrace + 1);
    out[3] = 0.5 * fRoot;
    fRoot = 0.5 / fRoot;
    out[0] = (m[5] - m[7]) * fRoot;
    out[1] = (m[6] - m[2]) * fRoot;
    out[2] = (m[1] - m[3]) * fRoot;
  } else {
    var i = 0;
    if (m[4] > m[0])
      i = 1;
    if (m[8] > m[i * 3 + i])
      i = 2;
    var j = (i + 1) % 3;
    var k = (i + 2) % 3;
    fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1);
    out[i] = 0.5 * fRoot;
    fRoot = 0.5 / fRoot;
    out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
    out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
    out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  }
  return out;
}
__name(fromMat3, "fromMat3");
var normalize$2 = normalize$3;
(function() {
  var tmpvec3 = create$4();
  var xUnitVec3 = fromValues$4(1, 0, 0);
  var yUnitVec3 = fromValues$4(0, 1, 0);
  return function(out, a, b) {
    var dot = dot$4(a, b);
    if (dot < -0.999999) {
      cross$2(tmpvec3, xUnitVec3, a);
      if (len$4(tmpvec3) < 1e-6)
        cross$2(tmpvec3, yUnitVec3, a);
      normalize$4(tmpvec3, tmpvec3);
      setAxisAngle(out, tmpvec3, Math.PI);
      return out;
    } else if (dot > 0.999999) {
      out[0] = 0;
      out[1] = 0;
      out[2] = 0;
      out[3] = 1;
      return out;
    } else {
      cross$2(tmpvec3, a, b);
      out[0] = tmpvec3[0];
      out[1] = tmpvec3[1];
      out[2] = tmpvec3[2];
      out[3] = 1 + dot;
      return normalize$2(out, out);
    }
  };
})();
(function() {
  var temp1 = create$2();
  var temp2 = create$2();
  return function(out, a, b, c, d, t) {
    slerp(temp1, a, d, t);
    slerp(temp2, b, c, t);
    slerp(out, temp1, temp2, 2 * t * (1 - t));
    return out;
  };
})();
(function() {
  var matr = create$6();
  return function(out, view, right, up) {
    matr[0] = right[0];
    matr[3] = right[1];
    matr[6] = right[2];
    matr[1] = up[0];
    matr[4] = up[1];
    matr[7] = up[2];
    matr[2] = -view[0];
    matr[5] = -view[1];
    matr[8] = -view[2];
    return normalize$2(out, fromMat3(out, matr));
  };
})();
function create() {
  var out = new ARRAY_TYPE(2);
  if (ARRAY_TYPE != Float32Array) {
    out[0] = 0;
    out[1] = 0;
  }
  return out;
}
__name(create, "create");
(function() {
  var vec = create();
  return function(a, stride, offset2, count, fn, arg) {
    var i, l;
    if (!stride) {
      stride = 2;
    }
    if (!offset2) {
      offset2 = 0;
    }
    if (count) {
      l = Math.min(count * stride + offset2, a.length);
    } else {
      l = a.length;
    }
    for (i = offset2; i < l; i += stride) {
      vec[0] = a[i];
      vec[1] = a[i + 1];
      fn(vec, vec, arg);
      a[i] = vec[0];
      a[i + 1] = vec[1];
    }
    return a;
  };
})();
function fade(node, { delay = 0, duration = 400, easing = identity } = {}) {
  const o = +getComputedStyle(node).opacity;
  return {
    delay,
    duration,
    easing,
    css: (t) => `opacity: ${t * o}`
  };
}
__name(fade, "fade");
function slide(node, { delay = 0, duration = 400, easing = cubicOut, axis = "y" } = {}) {
  const style = getComputedStyle(node);
  const opacity = +style.opacity;
  const primary_property = axis === "y" ? "height" : "width";
  const primary_property_value = parseFloat(style[primary_property]);
  const secondary_properties = axis === "y" ? ["top", "bottom"] : ["left", "right"];
  const capitalized_secondary_properties = secondary_properties.map((e) => `${e[0].toUpperCase()}${e.slice(1)}`);
  const padding_start_value = parseFloat(style[`padding${capitalized_secondary_properties[0]}`]);
  const padding_end_value = parseFloat(style[`padding${capitalized_secondary_properties[1]}`]);
  const margin_start_value = parseFloat(style[`margin${capitalized_secondary_properties[0]}`]);
  const margin_end_value = parseFloat(style[`margin${capitalized_secondary_properties[1]}`]);
  const border_width_start_value = parseFloat(style[`border${capitalized_secondary_properties[0]}Width`]);
  const border_width_end_value = parseFloat(style[`border${capitalized_secondary_properties[1]}Width`]);
  return {
    delay,
    duration,
    easing,
    css: (t) => `overflow: hidden;opacity: ${Math.min(t * 20, 1) * opacity};${primary_property}: ${t * primary_property_value}px;padding-${secondary_properties[0]}: ${t * padding_start_value}px;padding-${secondary_properties[1]}: ${t * padding_end_value}px;margin-${secondary_properties[0]}: ${t * margin_start_value}px;margin-${secondary_properties[1]}: ${t * margin_end_value}px;border-${secondary_properties[0]}-width: ${t * border_width_start_value}px;border-${secondary_properties[1]}-width: ${t * border_width_end_value}px;`
  };
}
__name(slide, "slide");
function slideFade(node, options) {
  const fadeEasing = options.easingFade || options.easing || identity;
  const slideEasing = options.easingSlide || options.easing || identity;
  const fadeTransition = fade(node);
  const slideTransition = slide(node);
  return {
    delay: options.delay || 0,
    duration: options.duration || 500,
    easing: identity,
    css: (t) => {
      const fadeT = fadeEasing(t);
      const slideT = slideEasing(t);
      return `${slideTransition.css(slideT, 1 - slideT)}; ${fadeTransition.css(fadeT, 1 - fadeT)}`;
    }
  };
}
__name(slideFade, "slideFade");
const s_DEFAULT_TRANSITION = /* @__PURE__ */ __name(() => void 0, "s_DEFAULT_TRANSITION");
const s_DEFAULT_TRANSITION_OPTIONS = {};
const TJSGlassPane_svelte_svelte_type_style_lang = "";
function create_else_block$s(ctx) {
  let div;
  let applyStyles_action;
  let div_intro;
  let div_outro;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[19].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[18],
    null
  );
  return {
    c() {
      div = element("div");
      if (default_slot)
        default_slot.c();
      attr(div, "class", "tjs-glass-pane-background svelte-hqedxf");
      set_style(
        div,
        "background",
        /*background*/
        ctx[5]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (default_slot) {
        default_slot.m(div, null);
      }
      ctx[22](div);
      current = true;
      if (!mounted) {
        dispose = action_destroyer(applyStyles_action = applyStyles.call(
          null,
          div,
          /*styles*/
          ctx[7]
        ));
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        262144)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx,
            /*$$scope*/
            ctx[18],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[18]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx[18],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*styles*/
      128)
        applyStyles_action.update.call(
          null,
          /*styles*/
          ctx[7]
        );
      if (dirty & /*background*/
      32) {
        set_style(
          div,
          "background",
          /*background*/
          ctx[5]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      add_render_callback(() => {
        if (!current)
          return;
        if (div_outro)
          div_outro.end(1);
        div_intro = create_in_transition(
          div,
          /*inTransition*/
          ctx[1],
          /*inTransitionOptions*/
          ctx[3]
        );
        div_intro.start();
      });
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      if (div_intro)
        div_intro.invalidate();
      div_outro = create_out_transition(
        div,
        /*outTransition*/
        ctx[2],
        /*outTransitionOptions*/
        ctx[4]
      );
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (default_slot)
        default_slot.d(detaching);
      ctx[22](null);
      if (detaching && div_outro)
        div_outro.end();
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$s, "create_else_block$s");
function create_if_block$11(ctx) {
  let div0;
  let applyStyles_action;
  let div0_intro;
  let div0_outro;
  let t;
  let div1;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[19].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[18],
    null
  );
  return {
    c() {
      div0 = element("div");
      t = space();
      div1 = element("div");
      if (default_slot)
        default_slot.c();
      attr(div0, "class", "tjs-glass-pane-background svelte-hqedxf");
      set_style(
        div0,
        "background",
        /*background*/
        ctx[5]
      );
      attr(div1, "class", "tjs-glass-pane-container svelte-hqedxf");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      ctx[20](div0);
      insert(target, t, anchor);
      insert(target, div1, anchor);
      if (default_slot) {
        default_slot.m(div1, null);
      }
      ctx[21](div1);
      current = true;
      if (!mounted) {
        dispose = action_destroyer(applyStyles_action = applyStyles.call(
          null,
          div0,
          /*styles*/
          ctx[7]
        ));
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*styles*/
      128)
        applyStyles_action.update.call(
          null,
          /*styles*/
          ctx[7]
        );
      if (dirty & /*background*/
      32) {
        set_style(
          div0,
          "background",
          /*background*/
          ctx[5]
        );
      }
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        262144)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx,
            /*$$scope*/
            ctx[18],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[18]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx[18],
              dirty,
              null
            ),
            null
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      add_render_callback(() => {
        if (!current)
          return;
        if (div0_outro)
          div0_outro.end(1);
        div0_intro = create_in_transition(
          div0,
          /*inTransition*/
          ctx[1],
          /*inTransitionOptions*/
          ctx[3]
        );
        div0_intro.start();
      });
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      if (div0_intro)
        div0_intro.invalidate();
      div0_outro = create_out_transition(
        div0,
        /*outTransition*/
        ctx[2],
        /*outTransitionOptions*/
        ctx[4]
      );
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      ctx[20](null);
      if (detaching && div0_outro)
        div0_outro.end();
      if (detaching)
        detach(t);
      if (detaching)
        detach(div1);
      if (default_slot)
        default_slot.d(detaching);
      ctx[21](null);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$11, "create_if_block$11");
function create_fragment$1r(ctx) {
  let div;
  let current_block_type_index;
  let if_block;
  let current;
  let mounted;
  let dispose;
  const if_block_creators = [create_if_block$11, create_else_block$s];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*slotSeparate*/
      ctx2[0]
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      div = element("div");
      if_block.c();
      attr(
        div,
        "id",
        /*id*/
        ctx[6]
      );
      attr(div, "class", "tjs-glass-pane svelte-hqedxf");
      set_style(
        div,
        "z-index",
        /*zIndex*/
        ctx[8]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if_blocks[current_block_type_index].m(div, null);
      ctx[23](div);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            window,
            "contextmenu",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "dblclick",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "keydown",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "keyup",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "mousedown",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "mousemove",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "mouseup",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "pointerdown",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "pointermove",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "pointerup",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "touchend",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "touchmove",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "touchstart",
            /*swallow*/
            ctx[12],
            true
          ),
          listen(
            window,
            "wheel",
            /*swallow*/
            ctx[12],
            true
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(div, null);
      }
      if (!current || dirty & /*id*/
      64) {
        attr(
          div,
          "id",
          /*id*/
          ctx2[6]
        );
      }
      if (dirty & /*zIndex*/
      256) {
        set_style(
          div,
          "z-index",
          /*zIndex*/
          ctx2[8]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if_blocks[current_block_type_index].d();
      ctx[23](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$1r, "create_fragment$1r");
function instance$1o($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { background = "#50505080" } = $$props;
  let { captureInput = true } = $$props;
  let { id = void 0 } = $$props;
  let { slotSeparate = void 0 } = $$props;
  let { styles: styles2 = void 0 } = $$props;
  let { zIndex = Number.MAX_SAFE_INTEGER } = $$props;
  let backgroundEl, containerEl, glassPaneEl;
  let { transition = void 0 } = $$props;
  let { inTransition = s_DEFAULT_TRANSITION } = $$props;
  let { outTransition = s_DEFAULT_TRANSITION } = $$props;
  let { transitionOptions = void 0 } = $$props;
  let { inTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS } = $$props;
  let { outTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS } = $$props;
  let oldTransition = void 0;
  let oldTransitionOptions = void 0;
  function swallow(event) {
    const targetEl = event.target;
    if (targetEl !== glassPaneEl && targetEl !== backgroundEl && targetEl !== containerEl && glassPaneEl.contains(targetEl)) {
      return;
    }
    if (captureInput) {
      event.preventDefault();
      event.stopImmediatePropagation();
    }
  }
  __name(swallow, "swallow");
  function div0_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      backgroundEl = $$value;
      $$invalidate(9, backgroundEl);
    });
  }
  __name(div0_binding, "div0_binding");
  function div1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      containerEl = $$value;
      $$invalidate(10, containerEl);
    });
  }
  __name(div1_binding, "div1_binding");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      backgroundEl = $$value;
      $$invalidate(9, backgroundEl);
    });
  }
  __name(div_binding, "div_binding");
  function div_binding_1($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      glassPaneEl = $$value;
      $$invalidate(11, glassPaneEl);
    });
  }
  __name(div_binding_1, "div_binding_1");
  $$self.$$set = ($$props2) => {
    if ("background" in $$props2)
      $$invalidate(5, background = $$props2.background);
    if ("captureInput" in $$props2)
      $$invalidate(13, captureInput = $$props2.captureInput);
    if ("id" in $$props2)
      $$invalidate(6, id = $$props2.id);
    if ("slotSeparate" in $$props2)
      $$invalidate(0, slotSeparate = $$props2.slotSeparate);
    if ("styles" in $$props2)
      $$invalidate(7, styles2 = $$props2.styles);
    if ("zIndex" in $$props2)
      $$invalidate(8, zIndex = $$props2.zIndex);
    if ("transition" in $$props2)
      $$invalidate(14, transition = $$props2.transition);
    if ("inTransition" in $$props2)
      $$invalidate(1, inTransition = $$props2.inTransition);
    if ("outTransition" in $$props2)
      $$invalidate(2, outTransition = $$props2.outTransition);
    if ("transitionOptions" in $$props2)
      $$invalidate(15, transitionOptions = $$props2.transitionOptions);
    if ("inTransitionOptions" in $$props2)
      $$invalidate(3, inTransitionOptions = $$props2.inTransitionOptions);
    if ("outTransitionOptions" in $$props2)
      $$invalidate(4, outTransitionOptions = $$props2.outTransitionOptions);
    if ("$$scope" in $$props2)
      $$invalidate(18, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*slotSeparate*/
    1) {
      $$invalidate(0, slotSeparate = typeof slotSeparate === "boolean" ? slotSeparate : false);
    }
    if ($$self.$$.dirty & /*oldTransition, transition*/
    81920) {
      if (oldTransition !== transition) {
        const newTransition = s_DEFAULT_TRANSITION !== transition && typeof transition === "function" ? transition : s_DEFAULT_TRANSITION;
        $$invalidate(1, inTransition = newTransition);
        $$invalidate(2, outTransition = newTransition);
        $$invalidate(16, oldTransition = newTransition);
      }
    }
    if ($$self.$$.dirty & /*oldTransitionOptions, transitionOptions*/
    163840) {
      if (oldTransitionOptions !== transitionOptions) {
        const newOptions = transitionOptions !== s_DEFAULT_TRANSITION_OPTIONS && isObject(transitionOptions) ? transitionOptions : s_DEFAULT_TRANSITION_OPTIONS;
        $$invalidate(3, inTransitionOptions = newOptions);
        $$invalidate(4, outTransitionOptions = newOptions);
        $$invalidate(17, oldTransitionOptions = newOptions);
      }
    }
    if ($$self.$$.dirty & /*inTransition*/
    2) {
      if (typeof inTransition !== "function") {
        $$invalidate(1, inTransition = s_DEFAULT_TRANSITION);
      }
    }
    if ($$self.$$.dirty & /*outTransition*/
    4) {
      if (typeof outTransition !== "function") {
        $$invalidate(2, outTransition = s_DEFAULT_TRANSITION);
      }
    }
    if ($$self.$$.dirty & /*inTransitionOptions*/
    8) {
      if (typeof inTransitionOptions !== "object") {
        $$invalidate(3, inTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS);
      }
    }
    if ($$self.$$.dirty & /*outTransitionOptions*/
    16) {
      if (typeof outTransitionOptions !== "object") {
        $$invalidate(4, outTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS);
      }
    }
  };
  return [
    slotSeparate,
    inTransition,
    outTransition,
    inTransitionOptions,
    outTransitionOptions,
    background,
    id,
    styles2,
    zIndex,
    backgroundEl,
    containerEl,
    glassPaneEl,
    swallow,
    captureInput,
    transition,
    transitionOptions,
    oldTransition,
    oldTransitionOptions,
    $$scope,
    slots,
    div0_binding,
    div1_binding,
    div_binding,
    div_binding_1
  ];
}
__name(instance$1o, "instance$1o");
const _TJSGlassPane = class _TJSGlassPane extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1o, create_fragment$1r, safe_not_equal, {
      background: 5,
      captureInput: 13,
      id: 6,
      slotSeparate: 0,
      styles: 7,
      zIndex: 8,
      transition: 14,
      inTransition: 1,
      outTransition: 2,
      transitionOptions: 15,
      inTransitionOptions: 3,
      outTransitionOptions: 4
    });
  }
};
__name(_TJSGlassPane, "TJSGlassPane");
let TJSGlassPane = _TJSGlassPane;
const _AppShellContextInternal = class _AppShellContextInternal {
  constructor() {
    /** @type {InternalAppStores} */
    __privateAdd(this, _stores2, void 0);
    __privateSet(this, _stores2, {
      elementContent: writable$1(void 0),
      elementRoot: writable$1(void 0)
    });
    Object.freeze(__privateGet(this, _stores2));
    Object.seal(this);
  }
  /**
   * @returns {InternalAppStores} The internal context stores for elementContent / elementRoot
   */
  get stores() {
    return __privateGet(this, _stores2);
  }
};
_stores2 = new WeakMap();
__name(_AppShellContextInternal, "AppShellContextInternal");
let AppShellContextInternal = _AppShellContextInternal;
function localize(stringId, data2) {
  const result = typeof data2 !== "object" ? globalThis.game.i18n.localize(stringId) : globalThis.game.i18n.format(stringId, data2);
  return result !== void 0 ? result : "";
}
__name(localize, "localize");
const TJSHeaderButton_svelte_svelte_type_style_lang = "";
function create_if_block$10(ctx) {
  let span;
  let t;
  return {
    c() {
      span = element("span");
      t = text(
        /*label*/
        ctx[3]
      );
      attr(span, "class", "svelte-166l8wd");
      toggle_class(
        span,
        "has-icon",
        /*icon*/
        ctx[4] !== void 0
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*label*/
      8)
        set_data(
          t,
          /*label*/
          ctx2[3]
        );
      if (dirty & /*icon*/
      16) {
        toggle_class(
          span,
          "has-icon",
          /*icon*/
          ctx2[4] !== void 0
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_if_block$10, "create_if_block$10");
function create_fragment$1q(ctx) {
  let a;
  let html_tag;
  let html_anchor;
  let a_class_value;
  let applyStyles_action;
  let mounted;
  let dispose;
  let if_block = (
    /*label*/
    ctx[3] && create_if_block$10(ctx)
  );
  return {
    c() {
      a = element("a");
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      if (if_block)
        if_block.c();
      html_tag.a = html_anchor;
      attr(a, "class", a_class_value = "header-button " + /*button*/
      ctx[0].class + " svelte-166l8wd");
      attr(
        a,
        "aria-label",
        /*label*/
        ctx[3]
      );
      attr(a, "tabindex", "0");
      attr(a, "role", "button");
      toggle_class(
        a,
        "keep-minimized",
        /*keepMinimized*/
        ctx[2]
      );
    },
    m(target, anchor) {
      insert(target, a, anchor);
      html_tag.m(
        /*icon*/
        ctx[4],
        a
      );
      append(a, html_anchor);
      if (if_block)
        if_block.m(a, null);
      if (!mounted) {
        dispose = [
          listen(a, "click", stop_propagation(prevent_default(
            /*onClick*/
            ctx[5]
          ))),
          listen(a, "contextmenu", stop_propagation(prevent_default(
            /*onContextMenu*/
            ctx[6]
          ))),
          listen(
            a,
            "keydown",
            /*onKeydown*/
            ctx[7]
          ),
          listen(
            a,
            "keyup",
            /*onKeyup*/
            ctx[8]
          ),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            a,
            /*styles*/
            ctx[1]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*icon*/
      16)
        html_tag.p(
          /*icon*/
          ctx2[4]
        );
      if (
        /*label*/
        ctx2[3]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$10(ctx2);
          if_block.c();
          if_block.m(a, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*button*/
      1 && a_class_value !== (a_class_value = "header-button " + /*button*/
      ctx2[0].class + " svelte-166l8wd")) {
        attr(a, "class", a_class_value);
      }
      if (dirty & /*label*/
      8) {
        attr(
          a,
          "aria-label",
          /*label*/
          ctx2[3]
        );
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*styles*/
      2)
        applyStyles_action.update.call(
          null,
          /*styles*/
          ctx2[1]
        );
      if (dirty & /*button, keepMinimized*/
      5) {
        toggle_class(
          a,
          "keep-minimized",
          /*keepMinimized*/
          ctx2[2]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$1q, "create_fragment$1q");
const s_REGEX_HTML$1 = /^\s*<.*>$/;
function instance$1n($$self, $$props, $$invalidate) {
  let title;
  let icon;
  let label;
  let keepMinimized;
  let keyCode;
  let styles2;
  let { button = void 0 } = $$props;
  function onClick(event) {
    const invoke = button?.onPress ?? button?.onclick;
    if (typeof invoke === "function") {
      invoke.call(button, event);
      $$invalidate(0, button);
    }
  }
  __name(onClick, "onClick");
  function onContextMenu(event) {
    const invoke = button?.onContextMenu;
    if (typeof invoke === "function") {
      invoke.call(button, event);
      $$invalidate(0, button);
    }
  }
  __name(onContextMenu, "onContextMenu");
  function onKeydown(event) {
    if (event.code === keyCode) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onKeydown, "onKeydown");
  function onKeyup(event) {
    if (event.code === keyCode) {
      const invoke = button.onPress ?? button.onclick;
      if (typeof invoke === "function") {
        invoke.call(button, event);
        $$invalidate(0, button);
      }
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onKeyup, "onKeyup");
  $$self.$$set = ($$props2) => {
    if ("button" in $$props2)
      $$invalidate(0, button = $$props2.button);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*button*/
    1) {
      $$invalidate(9, title = isObject(button) && typeof button.title === "string" ? localize(button.title) : "");
    }
    if ($$self.$$.dirty & /*button, title*/
    513) {
      $$invalidate(4, icon = isObject(button) && typeof button.icon !== "string" ? void 0 : s_REGEX_HTML$1.test(button.icon) ? button.icon : `<i class="${button.icon}" title="${title}"></i>`);
    }
    if ($$self.$$.dirty & /*button*/
    1) {
      $$invalidate(3, label = isObject(button) && typeof button.label === "string" ? localize(button.label) : void 0);
    }
    if ($$self.$$.dirty & /*button*/
    1) {
      $$invalidate(2, keepMinimized = isObject(button) && typeof button.keepMinimized === "boolean" ? button.keepMinimized : false);
    }
    if ($$self.$$.dirty & /*button*/
    1) {
      keyCode = isObject(button) && typeof button.keyCode === "string" ? button.keyCode : "Enter";
    }
    if ($$self.$$.dirty & /*button*/
    1) {
      $$invalidate(1, styles2 = isObject(button) && isObject(button.styles) ? button.styles : void 0);
    }
  };
  return [
    button,
    styles2,
    keepMinimized,
    label,
    icon,
    onClick,
    onContextMenu,
    onKeydown,
    onKeyup,
    title
  ];
}
__name(instance$1n, "instance$1n");
const _TJSHeaderButton = class _TJSHeaderButton extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1n, create_fragment$1q, safe_not_equal, { button: 0 });
  }
  get button() {
    return this.$$.ctx[0];
  }
  set button(button) {
    this.$$set({ button });
    flush();
  }
};
__name(_TJSHeaderButton, "TJSHeaderButton");
let TJSHeaderButton = _TJSHeaderButton;
const TJSApplicationHeader_svelte_svelte_type_style_lang = "";
function get_each_context$H(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[31] = list[i];
  return child_ctx;
}
__name(get_each_context$H, "get_each_context$H");
function get_each_context_1$j(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[31] = list[i];
  return child_ctx;
}
__name(get_each_context_1$j, "get_each_context_1$j");
function create_if_block$$(ctx) {
  let img;
  let img_src_value;
  return {
    c() {
      img = element("img");
      attr(img, "class", "tjs-app-icon keep-minimized svelte-1wviwl9");
      if (!src_url_equal(img.src, img_src_value = /*$storeHeaderIcon*/
      ctx[6]))
        attr(img, "src", img_src_value);
      attr(img, "alt", "icon");
    },
    m(target, anchor) {
      insert(target, img, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$storeHeaderIcon*/
      64 && !src_url_equal(img.src, img_src_value = /*$storeHeaderIcon*/
      ctx2[6])) {
        attr(img, "src", img_src_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(img);
    }
  };
}
__name(create_if_block$$, "create_if_block$$");
function create_each_block_1$j(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  const switch_instance_spread_levels = [
    /*button*/
    ctx[31].props
  ];
  var switch_value = (
    /*button*/
    ctx[31].class
  );
  function switch_props(ctx2) {
    let switch_instance_props = {};
    for (let i = 0; i < switch_instance_spread_levels.length; i += 1) {
      switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]);
    }
    return { props: switch_instance_props };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const switch_instance_changes = dirty[0] & /*buttonsLeft*/
      2 ? get_spread_update(switch_instance_spread_levels, [get_spread_object(
        /*button*/
        ctx2[31].props
      )]) : {};
      if (dirty[0] & /*buttonsLeft*/
      2 && switch_value !== (switch_value = /*button*/
      ctx2[31].class)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
__name(create_each_block_1$j, "create_each_block_1$j");
function create_each_block$H(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  const switch_instance_spread_levels = [
    /*button*/
    ctx[31].props
  ];
  var switch_value = (
    /*button*/
    ctx[31].class
  );
  function switch_props(ctx2) {
    let switch_instance_props = {};
    for (let i = 0; i < switch_instance_spread_levels.length; i += 1) {
      switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]);
    }
    return { props: switch_instance_props };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const switch_instance_changes = dirty[0] & /*buttonsRight*/
      4 ? get_spread_update(switch_instance_spread_levels, [get_spread_object(
        /*button*/
        ctx2[31].props
      )]) : {};
      if (dirty[0] & /*buttonsRight*/
      4 && switch_value !== (switch_value = /*button*/
      ctx2[31].class)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
__name(create_each_block$H, "create_each_block$H");
function create_key_block(ctx) {
  let header;
  let t0;
  let h4;
  let t1_value = localize(
    /*$storeTitle*/
    ctx[7]
  ) + "";
  let t1;
  let t2;
  let t3;
  let span;
  let t4;
  let draggable_action;
  let minimizable_action;
  let current;
  let mounted;
  let dispose;
  let if_block = typeof /*$storeHeaderIcon*/
  ctx[6] === "string" && create_if_block$$(ctx);
  let each_value_1 = (
    /*buttonsLeft*/
    ctx[1]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_1$j(get_each_context_1$j(ctx, each_value_1, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  }), "out");
  let each_value = (
    /*buttonsRight*/
    ctx[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$H(get_each_context$H(ctx, each_value, i));
  }
  const out_1 = /* @__PURE__ */ __name((i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  }), "out_1");
  return {
    c() {
      header = element("header");
      if (if_block)
        if_block.c();
      t0 = space();
      h4 = element("h4");
      t1 = text(t1_value);
      t2 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t3 = space();
      span = element("span");
      t4 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(h4, "class", "window-title svelte-1wviwl9");
      set_style(
        h4,
        "display",
        /*displayHeaderTitle*/
        ctx[4]
      );
      attr(span, "class", "tjs-window-header-spacer keep-minimized svelte-1wviwl9");
      attr(header, "class", "window-header flexrow svelte-1wviwl9");
    },
    m(target, anchor) {
      insert(target, header, anchor);
      if (if_block)
        if_block.m(header, null);
      append(header, t0);
      append(header, h4);
      append(h4, t1);
      append(header, t2);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(header, null);
        }
      }
      append(header, t3);
      append(header, span);
      append(header, t4);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(header, null);
        }
      }
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(draggable_action = /*draggable*/
          ctx[0].call(
            null,
            header,
            /*dragOptions*/
            ctx[3]
          )),
          action_destroyer(minimizable_action = /*minimizable*/
          ctx[18].call(
            null,
            header,
            /*$storeMinimizable*/
            ctx[5]
          )),
          listen(
            header,
            "pointerdown",
            /*onPointerdown*/
            ctx[19]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (typeof /*$storeHeaderIcon*/
      ctx2[6] === "string") {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$$(ctx2);
          if_block.c();
          if_block.m(header, t0);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if ((!current || dirty[0] & /*$storeTitle*/
      128) && t1_value !== (t1_value = localize(
        /*$storeTitle*/
        ctx2[7]
      ) + ""))
        set_data(t1, t1_value);
      if (dirty[0] & /*displayHeaderTitle*/
      16) {
        set_style(
          h4,
          "display",
          /*displayHeaderTitle*/
          ctx2[4]
        );
      }
      if (dirty[0] & /*buttonsLeft*/
      2) {
        each_value_1 = /*buttonsLeft*/
        ctx2[1];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1$j(ctx2, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_1$j(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(header, t3);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out(i);
        }
        check_outros();
      }
      if (dirty[0] & /*buttonsRight*/
      4) {
        each_value = /*buttonsRight*/
        ctx2[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$H(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block$H(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(header, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out_1(i);
        }
        check_outros();
      }
      if (draggable_action && is_function(draggable_action.update) && dirty[0] & /*dragOptions*/
      8)
        draggable_action.update.call(
          null,
          /*dragOptions*/
          ctx2[3]
        );
      if (minimizable_action && is_function(minimizable_action.update) && dirty[0] & /*$storeMinimizable*/
      32)
        minimizable_action.update.call(
          null,
          /*$storeMinimizable*/
          ctx2[5]
        );
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(header);
      if (if_block)
        if_block.d();
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_key_block, "create_key_block");
function create_fragment$1p(ctx) {
  let previous_key = (
    /*draggable*/
    ctx[0]
  );
  let key_block_anchor;
  let current;
  let key_block = create_key_block(ctx);
  return {
    c() {
      key_block.c();
      key_block_anchor = empty();
    },
    m(target, anchor) {
      key_block.m(target, anchor);
      insert(target, key_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*draggable*/
      1 && safe_not_equal(previous_key, previous_key = /*draggable*/
      ctx2[0])) {
        group_outros();
        transition_out(key_block, 1, 1, noop);
        check_outros();
        key_block = create_key_block(ctx2);
        key_block.c();
        transition_in(key_block, 1);
        key_block.m(key_block_anchor.parentNode, key_block_anchor);
      } else {
        key_block.p(ctx2, dirty);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(key_block);
      current = true;
    },
    o(local) {
      transition_out(key_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(key_block_anchor);
      key_block.d(detaching);
    }
  };
}
__name(create_fragment$1p, "create_fragment$1p");
function instance$1m($$self, $$props, $$invalidate) {
  let $focusKeep;
  let $focusAuto;
  let $elementRoot;
  let $storeHeaderButtons;
  let $storeMinimized;
  let $storeHeaderNoTitleMinimized;
  let $storeDraggable;
  let $storeMinimizable;
  let $storeHeaderIcon;
  let $storeTitle;
  let { draggable: draggable$1 = void 0 } = $$props;
  let { draggableOptions = void 0 } = $$props;
  const { application } = getContext("#external");
  const { focusAuto, focusKeep } = application.reactive.storeAppOptions;
  component_subscribe($$self, focusAuto, (value) => $$invalidate(26, $focusAuto = value));
  component_subscribe($$self, focusKeep, (value) => $$invalidate(25, $focusKeep = value));
  const { elementRoot } = getContext("#internal").stores;
  component_subscribe($$self, elementRoot, (value) => $$invalidate(27, $elementRoot = value));
  const storeTitle = application.reactive.storeAppOptions.title;
  component_subscribe($$self, storeTitle, (value) => $$invalidate(7, $storeTitle = value));
  const storeDraggable = application.reactive.storeAppOptions.draggable;
  component_subscribe($$self, storeDraggable, (value) => $$invalidate(24, $storeDraggable = value));
  const storeDragging = application.reactive.storeUIState.dragging;
  const storeHeaderButtons = application.reactive.storeUIState.headerButtons;
  component_subscribe($$self, storeHeaderButtons, (value) => $$invalidate(21, $storeHeaderButtons = value));
  const storeHeaderIcon = application.reactive.storeAppOptions.headerIcon;
  component_subscribe($$self, storeHeaderIcon, (value) => $$invalidate(6, $storeHeaderIcon = value));
  const storeHeaderNoTitleMinimized = application.reactive.storeAppOptions.headerNoTitleMinimized;
  component_subscribe($$self, storeHeaderNoTitleMinimized, (value) => $$invalidate(23, $storeHeaderNoTitleMinimized = value));
  const storeMinimizable = application.reactive.storeAppOptions.minimizable;
  component_subscribe($$self, storeMinimizable, (value) => $$invalidate(5, $storeMinimizable = value));
  const storeMinimized = application.reactive.storeUIState.minimized;
  component_subscribe($$self, storeMinimized, (value) => $$invalidate(22, $storeMinimized = value));
  const s_DRAG_TARGET_CLASSLIST = Object.freeze(["tjs-app-icon", "tjs-window-header-spacer", "window-header", "window-title"]);
  let dragOptions;
  let displayHeaderTitle;
  let buttonsLeft;
  let buttonsRight;
  function minimizable(node, booleanStore) {
    const callback = /* @__PURE__ */ __name((event) => {
      if (event.target.classList.contains("window-title") || event.target.classList.contains("window-header") || event.target.classList.contains("keep-minimized")) {
        application._onToggleMinimize(event);
      }
    }, "callback");
    function activateListeners() {
      node.addEventListener("dblclick", callback);
    }
    __name(activateListeners, "activateListeners");
    function removeListeners() {
      node.removeEventListener("dblclick", callback);
    }
    __name(removeListeners, "removeListeners");
    if (booleanStore) {
      activateListeners();
    }
    return {
      update: (booleanStore2) => {
        if (booleanStore2) {
          activateListeners();
        } else {
          removeListeners();
        }
      },
      destroy: () => removeListeners()
    };
  }
  __name(minimizable, "minimizable");
  function onPointerdown(event) {
    const rootEl = $elementRoot;
    if ($focusAuto && rootEl instanceof HTMLElement && rootEl?.isConnected) {
      if ($focusKeep) {
        const focusOutside = document.activeElement instanceof HTMLElement && !rootEl.contains(document.activeElement);
        if (focusOutside) {
          rootEl.focus();
        } else {
          event.preventDefault();
        }
      } else {
        rootEl.focus();
      }
    }
  }
  __name(onPointerdown, "onPointerdown");
  $$self.$$set = ($$props2) => {
    if ("draggable" in $$props2)
      $$invalidate(0, draggable$1 = $$props2.draggable);
    if ("draggableOptions" in $$props2)
      $$invalidate(20, draggableOptions = $$props2.draggableOptions);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*draggable*/
    1) {
      $$invalidate(0, draggable$1 = typeof draggable$1 === "function" ? draggable$1 : draggable);
    }
    if ($$self.$$.dirty[0] & /*draggableOptions, $storeDraggable*/
    17825792) {
      $$invalidate(3, dragOptions = Object.assign(
        {},
        {
          ease: true,
          easeOptions: { duration: 0.08, ease: cubicOut }
        },
        isObject(draggableOptions) ? draggableOptions : {},
        {
          position: application.position,
          active: $storeDraggable,
          storeDragging,
          hasTargetClassList: s_DRAG_TARGET_CLASSLIST
        }
      ));
    }
    if ($$self.$$.dirty[0] & /*$storeHeaderNoTitleMinimized, $storeMinimized*/
    12582912) {
      $$invalidate(4, displayHeaderTitle = $storeHeaderNoTitleMinimized && $storeMinimized ? "none" : null);
    }
    if ($$self.$$.dirty[0] & /*$storeHeaderButtons, buttonsLeft, buttonsRight*/
    2097158) {
      {
        $$invalidate(1, buttonsLeft = []);
        $$invalidate(2, buttonsRight = []);
        for (const button of $storeHeaderButtons) {
          const buttonsList = typeof button?.alignLeft === "boolean" && button?.alignLeft ? buttonsLeft : buttonsRight;
          buttonsList.push(isSvelteComponent(button) ? { class: button, props: {} } : {
            class: TJSHeaderButton,
            props: { button }
          });
        }
      }
    }
  };
  return [
    draggable$1,
    buttonsLeft,
    buttonsRight,
    dragOptions,
    displayHeaderTitle,
    $storeMinimizable,
    $storeHeaderIcon,
    $storeTitle,
    focusAuto,
    focusKeep,
    elementRoot,
    storeTitle,
    storeDraggable,
    storeHeaderButtons,
    storeHeaderIcon,
    storeHeaderNoTitleMinimized,
    storeMinimizable,
    storeMinimized,
    minimizable,
    onPointerdown,
    draggableOptions,
    $storeHeaderButtons,
    $storeMinimized,
    $storeHeaderNoTitleMinimized,
    $storeDraggable
  ];
}
__name(instance$1m, "instance$1m");
const _TJSApplicationHeader = class _TJSApplicationHeader extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1m, create_fragment$1p, safe_not_equal, { draggable: 0, draggableOptions: 20 }, null, [-1, -1]);
  }
};
__name(_TJSApplicationHeader, "TJSApplicationHeader");
let TJSApplicationHeader = _TJSApplicationHeader;
const TJSFocusWrap_svelte_svelte_type_style_lang = "";
function create_fragment$1o(ctx) {
  let div;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      attr(div, "class", "tjs-focus-wrap svelte-kjcljd");
      attr(div, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      ctx[4](div);
      if (!mounted) {
        dispose = listen(
          div,
          "focus",
          /*onFocus*/
          ctx[1]
        );
        mounted = true;
      }
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      ctx[4](null);
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$1o, "create_fragment$1o");
function instance$1l($$self, $$props, $$invalidate) {
  let { elementRoot = void 0 } = $$props;
  let { enabled = true } = $$props;
  let ignoreElements, wrapEl;
  function onFocus() {
    if (!enabled) {
      return;
    }
    if (elementRoot instanceof HTMLElement) {
      const firstFocusEl = A11yHelper.getFirstFocusableElement(elementRoot, ignoreElements);
      if (firstFocusEl instanceof HTMLElement && firstFocusEl !== wrapEl) {
        firstFocusEl.focus();
      } else {
        elementRoot.focus();
      }
    }
  }
  __name(onFocus, "onFocus");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      wrapEl = $$value;
      $$invalidate(0, wrapEl);
    });
  }
  __name(div_binding, "div_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(2, elementRoot = $$props2.elementRoot);
    if ("enabled" in $$props2)
      $$invalidate(3, enabled = $$props2.enabled);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*wrapEl*/
    1) {
      if (wrapEl) {
        ignoreElements = /* @__PURE__ */ new Set([wrapEl]);
      }
    }
  };
  return [wrapEl, onFocus, elementRoot, enabled, div_binding];
}
__name(instance$1l, "instance$1l");
const _TJSFocusWrap = class _TJSFocusWrap extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1l, create_fragment$1o, safe_not_equal, { elementRoot: 2, enabled: 3 });
  }
};
__name(_TJSFocusWrap, "TJSFocusWrap");
let TJSFocusWrap = _TJSFocusWrap;
function create_fragment$1n(ctx) {
  let div;
  let resizable_action;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      div.innerHTML = `<i class="fas fa-arrows-alt-h"></i>`;
      attr(div, "class", "window-resizable-handle");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      ctx[10](div);
      if (!mounted) {
        dispose = action_destroyer(resizable_action = /*resizable*/
        ctx[6].call(null, div, {
          active: (
            /*$storeResizable*/
            ctx[1]
          ),
          storeResizing: (
            /*storeResizing*/
            ctx[5]
          )
        }));
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (resizable_action && is_function(resizable_action.update) && dirty & /*$storeResizable*/
      2)
        resizable_action.update.call(null, {
          active: (
            /*$storeResizable*/
            ctx2[1]
          ),
          storeResizing: (
            /*storeResizing*/
            ctx2[5]
          )
        });
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      ctx[10](null);
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$1n, "create_fragment$1n");
function instance$1k($$self, $$props, $$invalidate) {
  let $storeElementRoot;
  let $storeMinimized;
  let $storeResizable;
  let { isResizable = false } = $$props;
  const application = getContext("#external").application;
  const storeElementRoot = getContext("storeElementRoot");
  component_subscribe($$self, storeElementRoot, (value) => $$invalidate(8, $storeElementRoot = value));
  const storeResizable = application.reactive.storeAppOptions.resizable;
  component_subscribe($$self, storeResizable, (value) => $$invalidate(1, $storeResizable = value));
  const storeMinimized = application.reactive.storeUIState.minimized;
  component_subscribe($$self, storeMinimized, (value) => $$invalidate(9, $storeMinimized = value));
  const storeResizing = application.reactive.storeUIState.resizing;
  let elementResize;
  function resizable(node, { active: active2 = true, storeResizing: storeResizing2 = void 0 } = {}) {
    let position = null;
    let initialPosition = {};
    let resizing = false;
    const handlers = {
      resizeDown: ["pointerdown", (e) => onResizePointerDown(e), false],
      resizeMove: ["pointermove", (e) => onResizePointerMove(e), false],
      resizeUp: ["pointerup", (e) => onResizePointerUp(e), false]
    };
    function activateListeners() {
      node.addEventListener(...handlers.resizeDown);
      $$invalidate(7, isResizable = true);
      node.style.display = "block";
    }
    __name(activateListeners, "activateListeners");
    function removeListeners() {
      if (typeof storeResizing2?.set === "function") {
        storeResizing2.set(false);
      }
      node.removeEventListener(...handlers.resizeDown);
      node.removeEventListener(...handlers.resizeMove);
      node.removeEventListener(...handlers.resizeUp);
      node.style.display = "none";
      $$invalidate(7, isResizable = false);
    }
    __name(removeListeners, "removeListeners");
    if (active2) {
      activateListeners();
    } else {
      node.style.display = "none";
    }
    function onResizePointerDown(event) {
      event.preventDefault();
      resizing = false;
      position = application.position.get();
      if (position.height === "auto") {
        position.height = $storeElementRoot.clientHeight;
      }
      if (position.width === "auto") {
        position.width = $storeElementRoot.clientWidth;
      }
      initialPosition = { x: event.clientX, y: event.clientY };
      node.addEventListener(...handlers.resizeMove);
      node.addEventListener(...handlers.resizeUp);
      node.setPointerCapture(event.pointerId);
    }
    __name(onResizePointerDown, "onResizePointerDown");
    function onResizePointerMove(event) {
      event.preventDefault();
      if (!resizing && typeof storeResizing2?.set === "function") {
        resizing = true;
        storeResizing2.set(true);
      }
      application.position.set({
        width: position.width + (event.clientX - initialPosition.x),
        height: position.height + (event.clientY - initialPosition.y)
      });
    }
    __name(onResizePointerMove, "onResizePointerMove");
    function onResizePointerUp(event) {
      resizing = false;
      if (typeof storeResizing2?.set === "function") {
        storeResizing2.set(false);
      }
      event.preventDefault();
      node.removeEventListener(...handlers.resizeMove);
      node.removeEventListener(...handlers.resizeUp);
      application._onResize(event);
    }
    __name(onResizePointerUp, "onResizePointerUp");
    return {
      update: ({ active: active3 }) => {
        if (active3) {
          activateListeners();
        } else {
          removeListeners();
        }
      },
      destroy: () => removeListeners()
    };
  }
  __name(resizable, "resizable");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      elementResize = $$value;
      $$invalidate(0, elementResize), $$invalidate(7, isResizable), $$invalidate(9, $storeMinimized), $$invalidate(8, $storeElementRoot);
    });
  }
  __name(div_binding, "div_binding");
  $$self.$$set = ($$props2) => {
    if ("isResizable" in $$props2)
      $$invalidate(7, isResizable = $$props2.isResizable);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*elementResize, isResizable, $storeMinimized, $storeElementRoot*/
    897) {
      if (elementResize) {
        $$invalidate(0, elementResize.style.display = isResizable && !$storeMinimized ? "block" : "none", elementResize);
        const elementRoot = $storeElementRoot;
        if (elementRoot) {
          elementRoot.classList[isResizable ? "add" : "remove"]("resizable");
        }
      }
    }
  };
  return [
    elementResize,
    $storeResizable,
    storeElementRoot,
    storeResizable,
    storeMinimized,
    storeResizing,
    resizable,
    isResizable,
    $storeElementRoot,
    $storeMinimized,
    div_binding
  ];
}
__name(instance$1k, "instance$1k");
const _ResizableHandle = class _ResizableHandle extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1k, create_fragment$1n, safe_not_equal, { isResizable: 7 });
  }
};
__name(_ResizableHandle, "ResizableHandle");
let ResizableHandle = _ResizableHandle;
const ApplicationShell_svelte_svelte_type_style_lang = "";
function create_else_block$r(ctx) {
  let div;
  let tjsapplicationheader;
  let t0;
  let section;
  let applyStyles_action;
  let t1;
  let resizablehandle;
  let t2;
  let tjsfocuswrap;
  let div_id_value;
  let div_class_value;
  let div_data_appid_value;
  let applyStyles_action_1;
  let current;
  let mounted;
  let dispose;
  tjsapplicationheader = new TJSApplicationHeader({
    props: {
      draggable: (
        /*draggable*/
        ctx[6]
      ),
      draggableOptions: (
        /*draggableOptions*/
        ctx[7]
      )
    }
  });
  const default_slot_template = (
    /*#slots*/
    ctx[36].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[35],
    null
  );
  resizablehandle = new ResizableHandle({});
  tjsfocuswrap = new TJSFocusWrap({
    props: {
      elementRoot: (
        /*elementRoot*/
        ctx[1]
      ),
      enabled: (
        /*focusWrapEnabled*/
        ctx[11]
      )
    }
  });
  return {
    c() {
      div = element("div");
      create_component(tjsapplicationheader.$$.fragment);
      t0 = space();
      section = element("section");
      if (default_slot)
        default_slot.c();
      t1 = space();
      create_component(resizablehandle.$$.fragment);
      t2 = space();
      create_component(tjsfocuswrap.$$.fragment);
      attr(section, "class", "window-content svelte-oz81f7");
      attr(section, "tabindex", "-1");
      attr(div, "id", div_id_value = /*application*/
      ctx[10].id);
      attr(div, "class", div_class_value = "app window-app " + /*application*/
      ctx[10].options.classes.join(" ") + " svelte-oz81f7");
      attr(div, "data-appid", div_data_appid_value = /*application*/
      ctx[10].appId);
      attr(div, "tabindex", "-1");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(tjsapplicationheader, div, null);
      append(div, t0);
      append(div, section);
      if (default_slot) {
        default_slot.m(section, null);
      }
      ctx[39](section);
      append(div, t1);
      mount_component(resizablehandle, div, null);
      append(div, t2);
      mount_component(tjsfocuswrap, div, null);
      ctx[40](div);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            section,
            "pointerdown",
            /*onPointerdownContent*/
            ctx[21]
          ),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            section,
            /*stylesContent*/
            ctx[9]
          )),
          action_destroyer(
            /*contentResizeObserver*/
            ctx[13].call(
              null,
              section,
              /*resizeObservedContent*/
              ctx[22]
            )
          ),
          listen(div, "close:popup", stop_propagation(prevent_default(
            /*onClosePopup*/
            ctx[18]
          ))),
          listen(
            div,
            "keydown",
            /*onKeydown*/
            ctx[19],
            true
          ),
          listen(
            div,
            "pointerdown",
            /*onPointerdownApp*/
            ctx[20]
          ),
          action_destroyer(applyStyles_action_1 = applyStyles.call(
            null,
            div,
            /*stylesApp*/
            ctx[8]
          )),
          action_destroyer(
            /*appResizeObserver*/
            ctx[12].call(
              null,
              div,
              /*resizeObservedApp*/
              ctx[23]
            )
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const tjsapplicationheader_changes = {};
      if (dirty[0] & /*draggable*/
      64)
        tjsapplicationheader_changes.draggable = /*draggable*/
        ctx2[6];
      if (dirty[0] & /*draggableOptions*/
      128)
        tjsapplicationheader_changes.draggableOptions = /*draggableOptions*/
        ctx2[7];
      tjsapplicationheader.$set(tjsapplicationheader_changes);
      if (default_slot) {
        if (default_slot.p && (!current || dirty[1] & /*$$scope*/
        16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[35],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[35]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[35],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty[0] & /*stylesContent*/
      512)
        applyStyles_action.update.call(
          null,
          /*stylesContent*/
          ctx2[9]
        );
      const tjsfocuswrap_changes = {};
      if (dirty[0] & /*elementRoot*/
      2)
        tjsfocuswrap_changes.elementRoot = /*elementRoot*/
        ctx2[1];
      if (dirty[0] & /*focusWrapEnabled*/
      2048)
        tjsfocuswrap_changes.enabled = /*focusWrapEnabled*/
        ctx2[11];
      tjsfocuswrap.$set(tjsfocuswrap_changes);
      if (!current || dirty[0] & /*application*/
      1024 && div_id_value !== (div_id_value = /*application*/
      ctx2[10].id)) {
        attr(div, "id", div_id_value);
      }
      if (!current || dirty[0] & /*application*/
      1024 && div_class_value !== (div_class_value = "app window-app " + /*application*/
      ctx2[10].options.classes.join(" ") + " svelte-oz81f7")) {
        attr(div, "class", div_class_value);
      }
      if (!current || dirty[0] & /*application*/
      1024 && div_data_appid_value !== (div_data_appid_value = /*application*/
      ctx2[10].appId)) {
        attr(div, "data-appid", div_data_appid_value);
      }
      if (applyStyles_action_1 && is_function(applyStyles_action_1.update) && dirty[0] & /*stylesApp*/
      256)
        applyStyles_action_1.update.call(
          null,
          /*stylesApp*/
          ctx2[8]
        );
    },
    i(local) {
      if (current)
        return;
      transition_in(tjsapplicationheader.$$.fragment, local);
      transition_in(default_slot, local);
      transition_in(resizablehandle.$$.fragment, local);
      transition_in(tjsfocuswrap.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tjsapplicationheader.$$.fragment, local);
      transition_out(default_slot, local);
      transition_out(resizablehandle.$$.fragment, local);
      transition_out(tjsfocuswrap.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(tjsapplicationheader);
      if (default_slot)
        default_slot.d(detaching);
      ctx[39](null);
      destroy_component(resizablehandle);
      destroy_component(tjsfocuswrap);
      ctx[40](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_else_block$r, "create_else_block$r");
function create_if_block$_(ctx) {
  let div;
  let tjsapplicationheader;
  let t0;
  let section;
  let applyStyles_action;
  let t1;
  let resizablehandle;
  let t2;
  let tjsfocuswrap;
  let div_id_value;
  let div_class_value;
  let div_data_appid_value;
  let applyStyles_action_1;
  let div_intro;
  let div_outro;
  let current;
  let mounted;
  let dispose;
  tjsapplicationheader = new TJSApplicationHeader({
    props: {
      draggable: (
        /*draggable*/
        ctx[6]
      ),
      draggableOptions: (
        /*draggableOptions*/
        ctx[7]
      )
    }
  });
  const default_slot_template = (
    /*#slots*/
    ctx[36].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[35],
    null
  );
  resizablehandle = new ResizableHandle({});
  tjsfocuswrap = new TJSFocusWrap({
    props: { elementRoot: (
      /*elementRoot*/
      ctx[1]
    ) }
  });
  return {
    c() {
      div = element("div");
      create_component(tjsapplicationheader.$$.fragment);
      t0 = space();
      section = element("section");
      if (default_slot)
        default_slot.c();
      t1 = space();
      create_component(resizablehandle.$$.fragment);
      t2 = space();
      create_component(tjsfocuswrap.$$.fragment);
      attr(section, "class", "window-content svelte-oz81f7");
      attr(section, "tabindex", "-1");
      attr(div, "id", div_id_value = /*application*/
      ctx[10].id);
      attr(div, "class", div_class_value = "app window-app " + /*application*/
      ctx[10].options.classes.join(" ") + " svelte-oz81f7");
      attr(div, "data-appid", div_data_appid_value = /*application*/
      ctx[10].appId);
      attr(div, "tabindex", "-1");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(tjsapplicationheader, div, null);
      append(div, t0);
      append(div, section);
      if (default_slot) {
        default_slot.m(section, null);
      }
      ctx[37](section);
      append(div, t1);
      mount_component(resizablehandle, div, null);
      append(div, t2);
      mount_component(tjsfocuswrap, div, null);
      ctx[38](div);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            section,
            "pointerdown",
            /*onPointerdownContent*/
            ctx[21]
          ),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            section,
            /*stylesContent*/
            ctx[9]
          )),
          action_destroyer(
            /*contentResizeObserver*/
            ctx[13].call(
              null,
              section,
              /*resizeObservedContent*/
              ctx[22]
            )
          ),
          listen(div, "close:popup", stop_propagation(prevent_default(
            /*onClosePopup*/
            ctx[18]
          ))),
          listen(
            div,
            "keydown",
            /*onKeydown*/
            ctx[19],
            true
          ),
          listen(
            div,
            "pointerdown",
            /*onPointerdownApp*/
            ctx[20]
          ),
          action_destroyer(applyStyles_action_1 = applyStyles.call(
            null,
            div,
            /*stylesApp*/
            ctx[8]
          )),
          action_destroyer(
            /*appResizeObserver*/
            ctx[12].call(
              null,
              div,
              /*resizeObservedApp*/
              ctx[23]
            )
          )
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tjsapplicationheader_changes = {};
      if (dirty[0] & /*draggable*/
      64)
        tjsapplicationheader_changes.draggable = /*draggable*/
        ctx[6];
      if (dirty[0] & /*draggableOptions*/
      128)
        tjsapplicationheader_changes.draggableOptions = /*draggableOptions*/
        ctx[7];
      tjsapplicationheader.$set(tjsapplicationheader_changes);
      if (default_slot) {
        if (default_slot.p && (!current || dirty[1] & /*$$scope*/
        16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx,
            /*$$scope*/
            ctx[35],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[35]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx[35],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty[0] & /*stylesContent*/
      512)
        applyStyles_action.update.call(
          null,
          /*stylesContent*/
          ctx[9]
        );
      const tjsfocuswrap_changes = {};
      if (dirty[0] & /*elementRoot*/
      2)
        tjsfocuswrap_changes.elementRoot = /*elementRoot*/
        ctx[1];
      tjsfocuswrap.$set(tjsfocuswrap_changes);
      if (!current || dirty[0] & /*application*/
      1024 && div_id_value !== (div_id_value = /*application*/
      ctx[10].id)) {
        attr(div, "id", div_id_value);
      }
      if (!current || dirty[0] & /*application*/
      1024 && div_class_value !== (div_class_value = "app window-app " + /*application*/
      ctx[10].options.classes.join(" ") + " svelte-oz81f7")) {
        attr(div, "class", div_class_value);
      }
      if (!current || dirty[0] & /*application*/
      1024 && div_data_appid_value !== (div_data_appid_value = /*application*/
      ctx[10].appId)) {
        attr(div, "data-appid", div_data_appid_value);
      }
      if (applyStyles_action_1 && is_function(applyStyles_action_1.update) && dirty[0] & /*stylesApp*/
      256)
        applyStyles_action_1.update.call(
          null,
          /*stylesApp*/
          ctx[8]
        );
    },
    i(local) {
      if (current)
        return;
      transition_in(tjsapplicationheader.$$.fragment, local);
      transition_in(default_slot, local);
      transition_in(resizablehandle.$$.fragment, local);
      transition_in(tjsfocuswrap.$$.fragment, local);
      add_render_callback(() => {
        if (!current)
          return;
        if (div_outro)
          div_outro.end(1);
        div_intro = create_in_transition(
          div,
          /*inTransition*/
          ctx[2],
          /*inTransitionOptions*/
          ctx[4]
        );
        div_intro.start();
      });
      current = true;
    },
    o(local) {
      transition_out(tjsapplicationheader.$$.fragment, local);
      transition_out(default_slot, local);
      transition_out(resizablehandle.$$.fragment, local);
      transition_out(tjsfocuswrap.$$.fragment, local);
      if (div_intro)
        div_intro.invalidate();
      div_outro = create_out_transition(
        div,
        /*outTransition*/
        ctx[3],
        /*outTransitionOptions*/
        ctx[5]
      );
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(tjsapplicationheader);
      if (default_slot)
        default_slot.d(detaching);
      ctx[37](null);
      destroy_component(resizablehandle);
      destroy_component(tjsfocuswrap);
      ctx[38](null);
      if (detaching && div_outro)
        div_outro.end();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block$_, "create_if_block$_");
function create_fragment$1m(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block$_, create_else_block$r];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*inTransition*/
      ctx2[2] || /*outTransition*/
      ctx2[3]
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if_blocks[current_block_type_index].d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_fragment$1m, "create_fragment$1m");
function instance$1j($$self, $$props, $$invalidate) {
  let $focusKeep;
  let $focusAuto;
  let $minimized;
  let $focusTrap;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { elementContent = void 0 } = $$props;
  let { elementRoot = void 0 } = $$props;
  let { draggable: draggable2 = void 0 } = $$props;
  let { draggableOptions = void 0 } = $$props;
  let { stylesApp = void 0 } = $$props;
  let { stylesContent = void 0 } = $$props;
  let { appOffsetHeight = false } = $$props;
  let { appOffsetWidth = false } = $$props;
  const appResizeObserver = !!appOffsetHeight || !!appOffsetWidth ? resizeObserver : () => null;
  let { contentOffsetHeight = false } = $$props;
  let { contentOffsetWidth = false } = $$props;
  const contentResizeObserver = !!contentOffsetHeight || !!contentOffsetWidth ? resizeObserver : () => null;
  const internal = new AppShellContextInternal();
  const s_IGNORE_CLASSES = { ignoreClasses: ["tjs-focus-wrap"] };
  setContext("#internal", internal);
  const { application } = getContext("#external");
  const { focusAuto, focusKeep, focusTrap } = application.reactive.storeAppOptions;
  component_subscribe($$self, focusAuto, (value) => $$invalidate(32, $focusAuto = value));
  component_subscribe($$self, focusKeep, (value) => $$invalidate(41, $focusKeep = value));
  component_subscribe($$self, focusTrap, (value) => $$invalidate(34, $focusTrap = value));
  const { minimized } = application.reactive.storeUIState;
  component_subscribe($$self, minimized, (value) => $$invalidate(33, $minimized = value));
  let focusWrapEnabled;
  let { transition = void 0 } = $$props;
  let { inTransition = void 0 } = $$props;
  let { outTransition = void 0 } = $$props;
  let { transitionOptions = void 0 } = $$props;
  let { inTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS } = $$props;
  let { outTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS } = $$props;
  let oldTransition = void 0;
  let oldTransitionOptions = void 0;
  onMount(() => elementRoot.focus());
  function onClosePopup(event) {
    if (!$focusAuto) {
      return;
    }
    const targetEl = event?.detail?.target;
    if (!(targetEl instanceof HTMLElement)) {
      return;
    }
    if (A11yHelper.isFocusable(targetEl)) {
      return;
    }
    const elementRootContains = elementRoot.contains(targetEl);
    if (targetEl === elementRoot) {
      elementRoot.focus();
    } else if (targetEl === elementContent) {
      elementContent.focus();
    } else if (elementRootContains) {
      if (elementContent.contains(targetEl)) {
        elementContent.focus();
      } else {
        elementRoot.focus();
      }
    }
  }
  __name(onClosePopup, "onClosePopup");
  function onKeydown(event) {
    if (focusWrapEnabled && event.shiftKey && event.code === "Tab") {
      const allFocusable = A11yHelper.getFocusableElements(elementRoot, s_IGNORE_CLASSES);
      const firstFocusEl = allFocusable.length > 0 ? allFocusable[0] : void 0;
      const lastFocusEl = allFocusable.length > 0 ? allFocusable[allFocusable.length - 1] : void 0;
      if (elementRoot === document.activeElement || firstFocusEl === document.activeElement) {
        if (lastFocusEl instanceof HTMLElement && firstFocusEl !== lastFocusEl) {
          lastFocusEl.focus();
        }
        event.preventDefault();
        event.stopPropagation();
      }
    }
    if (typeof application?.options?.popOut === "boolean" && application.options.popOut && application !== globalThis.ui?.activeWindow) {
      application.bringToTop.call(application);
    }
  }
  __name(onKeydown, "onKeydown");
  function onPointerdownApp() {
    if (typeof application?.options?.popOut === "boolean" && application.options.popOut && application !== globalThis.ui?.activeWindow) {
      application.bringToTop.call(application);
    }
  }
  __name(onPointerdownApp, "onPointerdownApp");
  function onPointerdownContent(event) {
    const focusable = A11yHelper.isFocusable(event.target);
    if (!focusable && $focusAuto) {
      if ($focusKeep) {
        const focusOutside = document.activeElement instanceof HTMLElement && !elementRoot.contains(document.activeElement);
        if (focusOutside) {
          elementContent.focus();
        } else {
          event.preventDefault();
        }
      } else {
        elementContent.focus();
      }
    }
  }
  __name(onPointerdownContent, "onPointerdownContent");
  function resizeObservedContent(offsetWidth, offsetHeight) {
    $$invalidate(27, contentOffsetWidth = offsetWidth);
    $$invalidate(26, contentOffsetHeight = offsetHeight);
  }
  __name(resizeObservedContent, "resizeObservedContent");
  function resizeObservedApp(offsetWidth, offsetHeight, contentWidth, contentHeight) {
    application.position.stores.resizeObserved.update((object) => {
      object.contentWidth = contentWidth;
      object.contentHeight = contentHeight;
      object.offsetWidth = offsetWidth;
      object.offsetHeight = offsetHeight;
      return object;
    });
    $$invalidate(24, appOffsetHeight = offsetHeight);
    $$invalidate(25, appOffsetWidth = offsetWidth);
  }
  __name(resizeObservedApp, "resizeObservedApp");
  function section_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      elementContent = $$value;
      $$invalidate(0, elementContent);
    });
  }
  __name(section_binding, "section_binding");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      elementRoot = $$value;
      $$invalidate(1, elementRoot);
    });
  }
  __name(div_binding, "div_binding");
  function section_binding_1($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      elementContent = $$value;
      $$invalidate(0, elementContent);
    });
  }
  __name(section_binding_1, "section_binding_1");
  function div_binding_1($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      elementRoot = $$value;
      $$invalidate(1, elementRoot);
    });
  }
  __name(div_binding_1, "div_binding_1");
  $$self.$$set = ($$props2) => {
    if ("elementContent" in $$props2)
      $$invalidate(0, elementContent = $$props2.elementContent);
    if ("elementRoot" in $$props2)
      $$invalidate(1, elementRoot = $$props2.elementRoot);
    if ("draggable" in $$props2)
      $$invalidate(6, draggable2 = $$props2.draggable);
    if ("draggableOptions" in $$props2)
      $$invalidate(7, draggableOptions = $$props2.draggableOptions);
    if ("stylesApp" in $$props2)
      $$invalidate(8, stylesApp = $$props2.stylesApp);
    if ("stylesContent" in $$props2)
      $$invalidate(9, stylesContent = $$props2.stylesContent);
    if ("appOffsetHeight" in $$props2)
      $$invalidate(24, appOffsetHeight = $$props2.appOffsetHeight);
    if ("appOffsetWidth" in $$props2)
      $$invalidate(25, appOffsetWidth = $$props2.appOffsetWidth);
    if ("contentOffsetHeight" in $$props2)
      $$invalidate(26, contentOffsetHeight = $$props2.contentOffsetHeight);
    if ("contentOffsetWidth" in $$props2)
      $$invalidate(27, contentOffsetWidth = $$props2.contentOffsetWidth);
    if ("transition" in $$props2)
      $$invalidate(28, transition = $$props2.transition);
    if ("inTransition" in $$props2)
      $$invalidate(2, inTransition = $$props2.inTransition);
    if ("outTransition" in $$props2)
      $$invalidate(3, outTransition = $$props2.outTransition);
    if ("transitionOptions" in $$props2)
      $$invalidate(29, transitionOptions = $$props2.transitionOptions);
    if ("inTransitionOptions" in $$props2)
      $$invalidate(4, inTransitionOptions = $$props2.inTransitionOptions);
    if ("outTransitionOptions" in $$props2)
      $$invalidate(5, outTransitionOptions = $$props2.outTransitionOptions);
    if ("$$scope" in $$props2)
      $$invalidate(35, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*elementContent*/
    1) {
      if (elementContent !== void 0 && elementContent !== null) {
        getContext("#internal").stores.elementContent.set(elementContent);
      }
    }
    if ($$self.$$.dirty[0] & /*elementRoot*/
    2) {
      if (elementRoot !== void 0 && elementRoot !== null) {
        getContext("#internal").stores.elementRoot.set(elementRoot);
      }
    }
    if ($$self.$$.dirty[1] & /*$focusAuto, $focusTrap, $minimized*/
    14) {
      $$invalidate(11, focusWrapEnabled = $focusAuto && $focusTrap && !$minimized);
    }
    if ($$self.$$.dirty[0] & /*oldTransition, transition*/
    1342177280) {
      if (oldTransition !== transition) {
        const newTransition = typeof transition === "function" ? transition : void 0;
        $$invalidate(2, inTransition = newTransition);
        $$invalidate(3, outTransition = newTransition);
        $$invalidate(30, oldTransition = newTransition);
      }
    }
    if ($$self.$$.dirty[0] & /*transitionOptions*/
    536870912 | $$self.$$.dirty[1] & /*oldTransitionOptions*/
    1) {
      if (oldTransitionOptions !== transitionOptions) {
        const newOptions = transitionOptions !== s_DEFAULT_TRANSITION_OPTIONS && isObject(transitionOptions) ? transitionOptions : s_DEFAULT_TRANSITION_OPTIONS;
        $$invalidate(4, inTransitionOptions = newOptions);
        $$invalidate(5, outTransitionOptions = newOptions);
        $$invalidate(31, oldTransitionOptions = newOptions);
      }
    }
    if ($$self.$$.dirty[0] & /*inTransition*/
    4) {
      if (typeof inTransition !== "function") {
        $$invalidate(2, inTransition = void 0);
      }
    }
    if ($$self.$$.dirty[0] & /*outTransition, application*/
    1032) {
      {
        if (typeof outTransition !== "function") {
          $$invalidate(3, outTransition = void 0);
        }
        if (application && typeof application?.options?.defaultCloseAnimation === "boolean") {
          $$invalidate(10, application.options.defaultCloseAnimation = outTransition === void 0, application);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*inTransitionOptions*/
    16) {
      if (typeof inTransitionOptions !== "object") {
        $$invalidate(4, inTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS);
      }
    }
    if ($$self.$$.dirty[0] & /*outTransitionOptions*/
    32) {
      if (typeof outTransitionOptions !== "object") {
        $$invalidate(5, outTransitionOptions = s_DEFAULT_TRANSITION_OPTIONS);
      }
    }
  };
  return [
    elementContent,
    elementRoot,
    inTransition,
    outTransition,
    inTransitionOptions,
    outTransitionOptions,
    draggable2,
    draggableOptions,
    stylesApp,
    stylesContent,
    application,
    focusWrapEnabled,
    appResizeObserver,
    contentResizeObserver,
    focusAuto,
    focusKeep,
    focusTrap,
    minimized,
    onClosePopup,
    onKeydown,
    onPointerdownApp,
    onPointerdownContent,
    resizeObservedContent,
    resizeObservedApp,
    appOffsetHeight,
    appOffsetWidth,
    contentOffsetHeight,
    contentOffsetWidth,
    transition,
    transitionOptions,
    oldTransition,
    oldTransitionOptions,
    $focusAuto,
    $minimized,
    $focusTrap,
    $$scope,
    slots,
    section_binding,
    div_binding,
    section_binding_1,
    div_binding_1
  ];
}
__name(instance$1j, "instance$1j");
const _ApplicationShell = class _ApplicationShell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$1j,
      create_fragment$1m,
      safe_not_equal,
      {
        elementContent: 0,
        elementRoot: 1,
        draggable: 6,
        draggableOptions: 7,
        stylesApp: 8,
        stylesContent: 9,
        appOffsetHeight: 24,
        appOffsetWidth: 25,
        contentOffsetHeight: 26,
        contentOffsetWidth: 27,
        transition: 28,
        inTransition: 2,
        outTransition: 3,
        transitionOptions: 29,
        inTransitionOptions: 4,
        outTransitionOptions: 5
      },
      null,
      [-1, -1]
    );
  }
  get elementContent() {
    return this.$$.ctx[0];
  }
  set elementContent(elementContent) {
    this.$$set({ elementContent });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[1];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get draggable() {
    return this.$$.ctx[6];
  }
  set draggable(draggable2) {
    this.$$set({ draggable: draggable2 });
    flush();
  }
  get draggableOptions() {
    return this.$$.ctx[7];
  }
  set draggableOptions(draggableOptions) {
    this.$$set({ draggableOptions });
    flush();
  }
  get stylesApp() {
    return this.$$.ctx[8];
  }
  set stylesApp(stylesApp) {
    this.$$set({ stylesApp });
    flush();
  }
  get stylesContent() {
    return this.$$.ctx[9];
  }
  set stylesContent(stylesContent) {
    this.$$set({ stylesContent });
    flush();
  }
  get appOffsetHeight() {
    return this.$$.ctx[24];
  }
  set appOffsetHeight(appOffsetHeight) {
    this.$$set({ appOffsetHeight });
    flush();
  }
  get appOffsetWidth() {
    return this.$$.ctx[25];
  }
  set appOffsetWidth(appOffsetWidth) {
    this.$$set({ appOffsetWidth });
    flush();
  }
  get contentOffsetHeight() {
    return this.$$.ctx[26];
  }
  set contentOffsetHeight(contentOffsetHeight) {
    this.$$set({ contentOffsetHeight });
    flush();
  }
  get contentOffsetWidth() {
    return this.$$.ctx[27];
  }
  set contentOffsetWidth(contentOffsetWidth) {
    this.$$set({ contentOffsetWidth });
    flush();
  }
  get transition() {
    return this.$$.ctx[28];
  }
  set transition(transition) {
    this.$$set({ transition });
    flush();
  }
  get inTransition() {
    return this.$$.ctx[2];
  }
  set inTransition(inTransition) {
    this.$$set({ inTransition });
    flush();
  }
  get outTransition() {
    return this.$$.ctx[3];
  }
  set outTransition(outTransition) {
    this.$$set({ outTransition });
    flush();
  }
  get transitionOptions() {
    return this.$$.ctx[29];
  }
  set transitionOptions(transitionOptions) {
    this.$$set({ transitionOptions });
    flush();
  }
  get inTransitionOptions() {
    return this.$$.ctx[4];
  }
  set inTransitionOptions(inTransitionOptions) {
    this.$$set({ inTransitionOptions });
    flush();
  }
  get outTransitionOptions() {
    return this.$$.ctx[5];
  }
  set outTransitionOptions(outTransitionOptions) {
    this.$$set({ outTransitionOptions });
    flush();
  }
};
__name(_ApplicationShell, "ApplicationShell");
let ApplicationShell = _ApplicationShell;
const EmptyApplicationShell_svelte_svelte_type_style_lang = "";
const TJSApplicationShell_svelte_svelte_type_style_lang = "";
const DialogContent_svelte_svelte_type_style_lang = "";
function get_each_context$G(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[26] = list[i];
  return child_ctx;
}
__name(get_each_context$G, "get_each_context$G");
function create_if_block_3$q(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  const switch_instance_spread_levels = [
    /*dialogProps*/
    ctx[7]
  ];
  var switch_value = (
    /*dialogClass*/
    ctx[6]
  );
  function switch_props(ctx2) {
    let switch_instance_props = {};
    for (let i = 0; i < switch_instance_spread_levels.length; i += 1) {
      switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]);
    }
    return { props: switch_instance_props };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
    ctx[16](switch_instance);
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const switch_instance_changes = dirty & /*dialogProps*/
      128 ? get_spread_update(switch_instance_spread_levels, [get_spread_object(
        /*dialogProps*/
        ctx2[7]
      )]) : {};
      if (dirty & /*dialogClass*/
      64 && switch_value !== (switch_value = /*dialogClass*/
      ctx2[6])) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          ctx2[16](switch_instance);
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      ctx[16](null);
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
__name(create_if_block_3$q, "create_if_block_3$q");
function create_if_block_2$w(ctx) {
  let html_tag;
  let html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(
        /*content*/
        ctx[3],
        target,
        anchor
      );
      insert(target, html_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*content*/
      8)
        html_tag.p(
          /*content*/
          ctx2[3]
        );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(html_anchor);
      if (detaching)
        html_tag.d();
    }
  };
}
__name(create_if_block_2$w, "create_if_block_2$w");
function create_if_block$Z(ctx) {
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_value = (
    /*buttons*/
    ctx[1]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*button*/
    ctx2[26].id
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$G(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$G(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "dialog-buttons svelte-1r3281l");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      ctx[20](div);
    },
    p(ctx2, dirty) {
      if (dirty & /*buttons, onClick, currentButtonId*/
      530) {
        each_value = /*buttons*/
        ctx2[1];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, destroy_block, create_each_block$G, null, get_each_context$G);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[20](null);
    }
  };
}
__name(create_if_block$Z, "create_if_block$Z");
function create_if_block_1$I(ctx) {
  let html_tag;
  let raw_value = (
    /*button*/
    ctx[26].icon + ""
  );
  let html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(raw_value, target, anchor);
      insert(target, html_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*buttons*/
      2 && raw_value !== (raw_value = /*button*/
      ctx2[26].icon + ""))
        html_tag.p(raw_value);
    },
    d(detaching) {
      if (detaching)
        detach(html_anchor);
      if (detaching)
        html_tag.d();
    }
  };
}
__name(create_if_block_1$I, "create_if_block_1$I");
function create_each_block$G(key_1, ctx) {
  let button;
  let span;
  let t0_value = (
    /*button*/
    ctx[26].label + ""
  );
  let t0;
  let span_title_value;
  let t1;
  let button_class_value;
  let button_disabled_value;
  let applyStyles_action;
  let mounted;
  let dispose;
  let if_block = (
    /*button*/
    ctx[26].icon && create_if_block_1$I(ctx)
  );
  function click_handler() {
    return (
      /*click_handler*/
      ctx[18](
        /*button*/
        ctx[26]
      )
    );
  }
  __name(click_handler, "click_handler");
  function focus_handler() {
    return (
      /*focus_handler*/
      ctx[19](
        /*button*/
        ctx[26]
      )
    );
  }
  __name(focus_handler, "focus_handler");
  return {
    key: key_1,
    first: null,
    c() {
      button = element("button");
      span = element("span");
      if (if_block)
        if_block.c();
      t0 = text(t0_value);
      t1 = space();
      attr(span, "title", span_title_value = /*button*/
      ctx[26].title);
      attr(button, "class", button_class_value = "dialog-button " + /*button*/
      ctx[26].id + " svelte-1r3281l");
      button.disabled = button_disabled_value = /*button*/
      ctx[26].disabled;
      this.first = button;
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, span);
      if (if_block)
        if_block.m(span, null);
      append(span, t0);
      append(button, t1);
      if (!mounted) {
        dispose = [
          listen(button, "click", stop_propagation(prevent_default(click_handler))),
          listen(button, "focus", focus_handler),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            button,
            /*button*/
            ctx[26].styles
          ))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (
        /*button*/
        ctx[26].icon
      ) {
        if (if_block) {
          if_block.p(ctx, dirty);
        } else {
          if_block = create_if_block_1$I(ctx);
          if_block.c();
          if_block.m(span, t0);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*buttons*/
      2 && t0_value !== (t0_value = /*button*/
      ctx[26].label + ""))
        set_data(t0, t0_value);
      if (dirty & /*buttons*/
      2 && span_title_value !== (span_title_value = /*button*/
      ctx[26].title)) {
        attr(span, "title", span_title_value);
      }
      if (dirty & /*buttons*/
      2 && button_class_value !== (button_class_value = "dialog-button " + /*button*/
      ctx[26].id + " svelte-1r3281l")) {
        attr(button, "class", button_class_value);
      }
      if (dirty & /*buttons*/
      2 && button_disabled_value !== (button_disabled_value = /*button*/
      ctx[26].disabled)) {
        button.disabled = button_disabled_value;
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*buttons*/
      2)
        applyStyles_action.update.call(
          null,
          /*button*/
          ctx[26].styles
        );
    },
    d(detaching) {
      if (detaching)
        detach(button);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$G, "create_each_block$G");
function create_fragment$1l(ctx) {
  let main;
  let div;
  let current_block_type_index;
  let if_block0;
  let t;
  let current;
  const if_block_creators = [create_if_block_2$w, create_if_block_3$q];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (typeof /*content*/
    ctx2[3] === "string")
      return 0;
    if (
      /*dialogClass*/
      ctx2[6]
    )
      return 1;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  let if_block1 = (
    /*buttons*/
    ctx[1].length && create_if_block$Z(ctx)
  );
  return {
    c() {
      main = element("main");
      div = element("div");
      if (if_block0)
        if_block0.c();
      t = space();
      if (if_block1)
        if_block1.c();
      attr(div, "class", "dialog-content");
    },
    m(target, anchor) {
      insert(target, main, anchor);
      append(main, div);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div, null);
      }
      ctx[17](div);
      append(main, t);
      if (if_block1)
        if_block1.m(main, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block0) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block0 = if_blocks[current_block_type_index];
          if (!if_block0) {
            if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block0.c();
          } else {
            if_block0.p(ctx2, dirty);
          }
          transition_in(if_block0, 1);
          if_block0.m(div, null);
        } else {
          if_block0 = null;
        }
      }
      if (
        /*buttons*/
        ctx2[1].length
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block$Z(ctx2);
          if_block1.c();
          if_block1.m(main, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(main);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
      ctx[17](null);
      if (if_block1)
        if_block1.d();
    }
  };
}
__name(create_fragment$1l, "create_fragment$1l");
const s_REGEX_HTML = /^\s*<.*>$/;
function instance$1i($$self, $$props, $$invalidate) {
  let autoClose;
  let focusFirst;
  let resolveId;
  let $elementRoot;
  let { data: data2 = void 0 } = $$props;
  let { preventDefault: preventDefault2 = false } = $$props;
  let { stopPropagation = false } = $$props;
  let { dialogComponent = void 0 } = $$props;
  let buttons;
  let contentEl;
  let buttonsEl;
  let content = void 0;
  let dialogClass;
  let dialogProps = {};
  let { elementRoot } = getContext("#internal").stores;
  component_subscribe($$self, elementRoot, (value) => $$invalidate(15, $elementRoot = value));
  let { application } = getContext("#external");
  let managedPromise = getContext("#managedPromise");
  let currentButtonId = data2.default;
  onDestroy(() => {
    const rootEl = $elementRoot;
    if (rootEl instanceof HTMLElement) {
      rootEl.removeEventListener("keydown", onKeydown);
      rootEl.removeEventListener("keyup", onKeyup);
    }
  });
  onMount(() => {
    if (focusFirst) {
      const focusEl = A11yHelper.getFirstFocusableElement(contentEl);
      if (focusEl instanceof HTMLElement) {
        setTimeout(() => focusEl.focus(), 0);
      }
    }
  });
  function onClick(button) {
    try {
      let result = void 0;
      const callback = button?.onPress;
      switch (typeof callback) {
        case "function":
          result = callback(application);
          break;
        case "string":
          if (dialogComponent !== void 0 && typeof dialogComponent[callback] === "function") {
            result = dialogComponent[callback](application);
          } else {
            if (dialogComponent === void 0) {
              console.warn(`[TRL] TJSDialog warning: 'onPress' defined as a string with no associated content Svelte component.`);
            } else if (typeof dialogComponent?.[callback] !== "function") {
              console.warn(`[TRL] TJSDialog warning: The content Svelte component does not contain an associated function '${callback}'. Did you remember to add '<svelte:options accessors={true} />' and export the function?`);
            }
          }
          break;
      }
      if (button.autoClose && autoClose) {
        if (resolveId && result === void 0) {
          result = button.id;
        }
        managedPromise.resolve(result);
      }
    } catch (err) {
      const notifyError = typeof data2.notifyError === "boolean" ? data2.notifyError : true;
      if (notifyError) {
        globalThis.ui.notifications.error(err, { console: false });
      }
      if (!managedPromise.reject(err)) {
        throw err;
      }
    } finally {
      if (button.autoClose && autoClose) {
        application.close();
      }
    }
  }
  __name(onClick, "onClick");
  function onKeydown(event) {
    switch (event.code) {
      case "ArrowLeft":
      case "ArrowRight":
      case "Enter":
        event.stopPropagation();
        break;
      case "Tab":
        event.stopPropagation();
        setTimeout(
          () => {
            const activeElement = document.activeElement;
            if (activeElement instanceof HTMLElement && buttonsEl instanceof HTMLElement && buttonsEl.contains(activeElement)) {
              for (let cntr = 0; cntr < activeElement.classList.length; cntr++) {
                const item = activeElement.classList.item(cntr);
                if (item !== "dialog-button" && item !== "default" && typeof data2.buttons[item] !== void 0) {
                  $$invalidate(4, currentButtonId = item);
                  break;
                }
              }
            }
          },
          0
        );
        break;
      default:
        if (preventDefault2) {
          event.preventDefault();
        }
        if (stopPropagation) {
          event.stopPropagation();
        }
        break;
    }
  }
  __name(onKeydown, "onKeydown");
  function onKeyup(event) {
    switch (event.code) {
      case "ArrowLeft": {
        event.preventDefault();
        event.stopPropagation();
        const activeEl = document.activeElement;
        if (buttonsEl instanceof HTMLElement) {
          if (activeEl instanceof HTMLElement && buttonsEl.contains(activeEl)) {
            const currentIndex = buttons.findIndex((button) => button.id === currentButtonId);
            if (buttons.length && currentIndex > 0) {
              $$invalidate(4, currentButtonId = buttons[currentIndex - 1].id);
            }
          }
          const buttonEl = buttonsEl.querySelector(`.${currentButtonId}`);
          if (buttonEl instanceof HTMLElement) {
            buttonEl.focus();
          }
        }
        break;
      }
      case "ArrowRight": {
        event.preventDefault();
        event.stopPropagation();
        const activeEl = document.activeElement;
        if (buttonsEl instanceof HTMLElement) {
          if (activeEl instanceof HTMLElement && (buttonsEl.contains(activeEl) || currentButtonId === void 0)) {
            const currentIndex = buttons.findIndex((button) => button.id === currentButtonId);
            if (buttons.length && currentIndex < buttons.length - 1) {
              $$invalidate(4, currentButtonId = buttons[currentIndex + 1].id);
            }
          }
          const buttonEl = buttonsEl.querySelector(`.${currentButtonId}`);
          if (buttonEl instanceof HTMLElement) {
            buttonEl.focus();
          }
        }
        break;
      }
      case "Enter":
        event.preventDefault();
        event.stopPropagation();
        break;
      default:
        if (preventDefault2) {
          event.preventDefault();
        }
        if (stopPropagation) {
          event.stopPropagation();
        }
        break;
    }
  }
  __name(onKeyup, "onKeyup");
  function switch_instance_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      dialogComponent = $$value;
      $$invalidate(0, dialogComponent);
    });
  }
  __name(switch_instance_binding, "switch_instance_binding");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      contentEl = $$value;
      $$invalidate(5, contentEl);
    });
  }
  __name(div_binding, "div_binding");
  const click_handler = /* @__PURE__ */ __name((button) => onClick(button), "click_handler");
  const focus_handler = /* @__PURE__ */ __name((button) => $$invalidate(4, currentButtonId = button.id), "focus_handler");
  function div_binding_1($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      buttonsEl = $$value;
      $$invalidate(2, buttonsEl);
    });
  }
  __name(div_binding_1, "div_binding_1");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(10, data2 = $$props2.data);
    if ("preventDefault" in $$props2)
      $$invalidate(11, preventDefault2 = $$props2.preventDefault);
    if ("stopPropagation" in $$props2)
      $$invalidate(12, stopPropagation = $$props2.stopPropagation);
    if ("dialogComponent" in $$props2)
      $$invalidate(0, dialogComponent = $$props2.dialogComponent);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$elementRoot*/
    32768) {
      if ($elementRoot) {
        const rootEl = $elementRoot;
        if (rootEl instanceof HTMLElement) {
          rootEl.addEventListener("keydown", onKeydown);
          rootEl.addEventListener("keyup", onKeyup);
        }
      }
    }
    if ($$self.$$.dirty & /*data*/
    1024) {
      $$invalidate(13, autoClose = typeof data2.autoClose === "boolean" ? data2.autoClose : true);
    }
    if ($$self.$$.dirty & /*data*/
    1024) {
      $$invalidate(14, focusFirst = typeof data2.focusFirst === "boolean" ? data2.focusFirst : false);
    }
    if ($$self.$$.dirty & /*data*/
    1024) {
      {
        $$invalidate(1, buttons = !isObject(data2.buttons) ? [] : Object.keys(data2.buttons).reduce(
          (array, key) => {
            const b = data2.buttons[key];
            const icon = typeof b.icon !== "string" ? void 0 : s_REGEX_HTML.test(b.icon) ? b.icon : `<i class="${b.icon}"></i>`;
            const autoClose2 = typeof b.autoClose === "boolean" ? b.autoClose : true;
            const disabled = typeof b.disabled === "boolean" ? b.disabled : false;
            const label = typeof b.label === "string" ? `${icon !== void 0 ? " " : ""}${localize(b.label)}` : "";
            const title = typeof b.title === "string" ? localize(b.title) : void 0;
            const condition = typeof b.condition === "function" ? b.condition.call(b) : b.condition ?? true;
            if (condition) {
              array.push({
                ...b,
                id: key,
                autoClose: autoClose2,
                icon,
                label,
                title,
                disabled
              });
            }
            return array;
          },
          []
        ));
      }
    }
    if ($$self.$$.dirty & /*buttons, currentButtonId*/
    18) {
      if (!buttons.find((button) => button.id === currentButtonId)) {
        $$invalidate(4, currentButtonId = void 0);
      }
    }
    if ($$self.$$.dirty & /*focusFirst, buttonsEl, currentButtonId*/
    16404) {
      if (!focusFirst && buttonsEl instanceof HTMLElement) {
        const buttonEl = buttonsEl.querySelector(`.${currentButtonId}`);
        if (buttonEl instanceof HTMLElement) {
          buttonEl.focus();
        }
      }
    }
    if ($$self.$$.dirty & /*data*/
    1024) {
      resolveId = typeof data2.resolveId === "boolean" ? data2.resolveId : false;
    }
    if ($$self.$$.dirty & /*content, data*/
    1032) {
      if (content !== data2.content) {
        $$invalidate(3, content = data2.content);
        try {
          if (isSvelteComponent(content)) {
            $$invalidate(6, dialogClass = content);
            $$invalidate(7, dialogProps = {});
          } else if (isObject(content)) {
            const svelteConfig = parseSvelteConfig(content, application);
            $$invalidate(6, dialogClass = svelteConfig.class);
            $$invalidate(7, dialogProps = svelteConfig.props ?? {});
            const children2 = svelteConfig?.context?.get("external")?.children;
            if (Array.isArray(children2)) {
              $$invalidate(7, dialogProps.children = children2, dialogProps);
            }
          } else {
            $$invalidate(6, dialogClass = void 0);
            $$invalidate(7, dialogProps = {});
          }
        } catch (err) {
          $$invalidate(6, dialogClass = void 0);
          $$invalidate(7, dialogProps = {});
          $$invalidate(3, content = err.message);
          console.error(err);
        }
      }
    }
  };
  return [
    dialogComponent,
    buttons,
    buttonsEl,
    content,
    currentButtonId,
    contentEl,
    dialogClass,
    dialogProps,
    elementRoot,
    onClick,
    data2,
    preventDefault2,
    stopPropagation,
    autoClose,
    focusFirst,
    $elementRoot,
    switch_instance_binding,
    div_binding,
    click_handler,
    focus_handler,
    div_binding_1
  ];
}
__name(instance$1i, "instance$1i");
const _DialogContent = class _DialogContent extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1i, create_fragment$1l, safe_not_equal, {
      data: 10,
      preventDefault: 11,
      stopPropagation: 12,
      dialogComponent: 0
    });
  }
};
__name(_DialogContent, "DialogContent");
let DialogContent = _DialogContent;
function create_else_block$q(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let updating_elementContent;
  let current;
  const applicationshell_spread_levels = [
    /*appProps*/
    ctx[6],
    { appOffsetHeight: true }
  ];
  function applicationshell_elementRoot_binding_1(value) {
    ctx[14](value);
  }
  __name(applicationshell_elementRoot_binding_1, "applicationshell_elementRoot_binding_1");
  function applicationshell_elementContent_binding_1(value) {
    ctx[15](value);
  }
  __name(applicationshell_elementContent_binding_1, "applicationshell_elementContent_binding_1");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot_2$1] },
    $$scope: { ctx }
  };
  for (let i = 0; i < applicationshell_spread_levels.length; i += 1) {
    applicationshell_props = assign(applicationshell_props, applicationshell_spread_levels[i]);
  }
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  if (
    /*elementContent*/
    ctx[1] !== void 0
  ) {
    applicationshell_props.elementContent = /*elementContent*/
    ctx[1];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding_1));
  binding_callbacks.push(() => bind(applicationshell, "elementContent", applicationshell_elementContent_binding_1));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = dirty & /*appProps*/
      64 ? get_spread_update(applicationshell_spread_levels, [
        get_spread_object(
          /*appProps*/
          ctx2[6]
        ),
        applicationshell_spread_levels[1]
      ]) : {};
      if (dirty & /*$$scope, data, dialogComponent*/
      1048588) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      if (!updating_elementContent && dirty & /*elementContent*/
      2) {
        updating_elementContent = true;
        applicationshell_changes.elementContent = /*elementContent*/
        ctx2[1];
        add_flush_callback(() => updating_elementContent = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_else_block$q, "create_else_block$q");
function create_if_block$Y(ctx) {
  let tjsglasspane;
  let current;
  const tjsglasspane_spread_levels = [
    {
      id: `${/*application*/
      ctx[4].id}-glasspane`
    },
    /*modalProps*/
    ctx[7],
    { zIndex: (
      /*zIndex*/
      ctx[8]
    ) }
  ];
  let tjsglasspane_props = {
    $$slots: { default: [create_default_slot$u] },
    $$scope: { ctx }
  };
  for (let i = 0; i < tjsglasspane_spread_levels.length; i += 1) {
    tjsglasspane_props = assign(tjsglasspane_props, tjsglasspane_spread_levels[i]);
  }
  tjsglasspane = new TJSGlassPane({ props: tjsglasspane_props });
  return {
    c() {
      create_component(tjsglasspane.$$.fragment);
    },
    m(target, anchor) {
      mount_component(tjsglasspane, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const tjsglasspane_changes = dirty & /*application, modalProps, zIndex*/
      400 ? get_spread_update(tjsglasspane_spread_levels, [
        dirty & /*application*/
        16 && {
          id: `${/*application*/
          ctx2[4].id}-glasspane`
        },
        dirty & /*modalProps*/
        128 && get_spread_object(
          /*modalProps*/
          ctx2[7]
        ),
        dirty & /*zIndex*/
        256 && { zIndex: (
          /*zIndex*/
          ctx2[8]
        ) }
      ]) : {};
      if (dirty & /*$$scope, appProps, elementRoot, elementContent, data, dialogComponent*/
      1048655) {
        tjsglasspane_changes.$$scope = { dirty, ctx: ctx2 };
      }
      tjsglasspane.$set(tjsglasspane_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tjsglasspane.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tjsglasspane.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(tjsglasspane, detaching);
    }
  };
}
__name(create_if_block$Y, "create_if_block$Y");
function create_default_slot_2$1(ctx) {
  let dialogcontent;
  let updating_dialogComponent;
  let current;
  function dialogcontent_dialogComponent_binding_1(value) {
    ctx[13](value);
  }
  __name(dialogcontent_dialogComponent_binding_1, "dialogcontent_dialogComponent_binding_1");
  let dialogcontent_props = { data: (
    /*data*/
    ctx[3]
  ) };
  if (
    /*dialogComponent*/
    ctx[2] !== void 0
  ) {
    dialogcontent_props.dialogComponent = /*dialogComponent*/
    ctx[2];
  }
  dialogcontent = new DialogContent({ props: dialogcontent_props });
  binding_callbacks.push(() => bind(dialogcontent, "dialogComponent", dialogcontent_dialogComponent_binding_1));
  return {
    c() {
      create_component(dialogcontent.$$.fragment);
    },
    m(target, anchor) {
      mount_component(dialogcontent, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const dialogcontent_changes = {};
      if (dirty & /*data*/
      8)
        dialogcontent_changes.data = /*data*/
        ctx2[3];
      if (!updating_dialogComponent && dirty & /*dialogComponent*/
      4) {
        updating_dialogComponent = true;
        dialogcontent_changes.dialogComponent = /*dialogComponent*/
        ctx2[2];
        add_flush_callback(() => updating_dialogComponent = false);
      }
      dialogcontent.$set(dialogcontent_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dialogcontent.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dialogcontent.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(dialogcontent, detaching);
    }
  };
}
__name(create_default_slot_2$1, "create_default_slot_2$1");
function create_default_slot_1$4(ctx) {
  let dialogcontent;
  let updating_dialogComponent;
  let current;
  function dialogcontent_dialogComponent_binding(value) {
    ctx[10](value);
  }
  __name(dialogcontent_dialogComponent_binding, "dialogcontent_dialogComponent_binding");
  let dialogcontent_props = {
    data: (
      /*data*/
      ctx[3]
    ),
    stopPropagation: true
  };
  if (
    /*dialogComponent*/
    ctx[2] !== void 0
  ) {
    dialogcontent_props.dialogComponent = /*dialogComponent*/
    ctx[2];
  }
  dialogcontent = new DialogContent({ props: dialogcontent_props });
  binding_callbacks.push(() => bind(dialogcontent, "dialogComponent", dialogcontent_dialogComponent_binding));
  return {
    c() {
      create_component(dialogcontent.$$.fragment);
    },
    m(target, anchor) {
      mount_component(dialogcontent, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const dialogcontent_changes = {};
      if (dirty & /*data*/
      8)
        dialogcontent_changes.data = /*data*/
        ctx2[3];
      if (!updating_dialogComponent && dirty & /*dialogComponent*/
      4) {
        updating_dialogComponent = true;
        dialogcontent_changes.dialogComponent = /*dialogComponent*/
        ctx2[2];
        add_flush_callback(() => updating_dialogComponent = false);
      }
      dialogcontent.$set(dialogcontent_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dialogcontent.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dialogcontent.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(dialogcontent, detaching);
    }
  };
}
__name(create_default_slot_1$4, "create_default_slot_1$4");
function create_default_slot$u(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let updating_elementContent;
  let current;
  const applicationshell_spread_levels = [
    /*appProps*/
    ctx[6],
    { appOffsetHeight: true }
  ];
  function applicationshell_elementRoot_binding(value) {
    ctx[11](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  function applicationshell_elementContent_binding(value) {
    ctx[12](value);
  }
  __name(applicationshell_elementContent_binding, "applicationshell_elementContent_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot_1$4] },
    $$scope: { ctx }
  };
  for (let i = 0; i < applicationshell_spread_levels.length; i += 1) {
    applicationshell_props = assign(applicationshell_props, applicationshell_spread_levels[i]);
  }
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  if (
    /*elementContent*/
    ctx[1] !== void 0
  ) {
    applicationshell_props.elementContent = /*elementContent*/
    ctx[1];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  binding_callbacks.push(() => bind(applicationshell, "elementContent", applicationshell_elementContent_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = dirty & /*appProps*/
      64 ? get_spread_update(applicationshell_spread_levels, [
        get_spread_object(
          /*appProps*/
          ctx2[6]
        ),
        applicationshell_spread_levels[1]
      ]) : {};
      if (dirty & /*$$scope, data, dialogComponent*/
      1048588) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      if (!updating_elementContent && dirty & /*elementContent*/
      2) {
        updating_elementContent = true;
        applicationshell_changes.elementContent = /*elementContent*/
        ctx2[1];
        add_flush_callback(() => updating_elementContent = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_default_slot$u, "create_default_slot$u");
function create_fragment$1k(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block$Y, create_else_block$q];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*modal*/
      ctx2[5]
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if_blocks[current_block_type_index].d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_fragment$1k, "create_fragment$1k");
const s_MODAL_BACKGROUND = "#50505080";
function instance$1h($$self, $$props, $$invalidate) {
  let { elementContent = void 0 } = $$props;
  let { elementRoot = void 0 } = $$props;
  let { data: data2 = {} } = $$props;
  let { dialogComponent = void 0 } = $$props;
  let { managedPromise = void 0 } = $$props;
  const application = getContext("#external").application;
  setContext("#managedPromise", managedPromise);
  const s_MODAL_TRANSITION = fade;
  const s_MODAL_TRANSITION_OPTIONS = { duration: 200 };
  let modal = void 0;
  const appProps = {
    // Stores any transition functions.
    transition: void 0,
    inTransition: void 0,
    outTransition: void 0,
    // Stores properties to set for options for any transitions.
    transitionOptions: void 0,
    inTransitionOptions: void 0,
    outTransitionOptions: void 0,
    // Stores any style overrides for application shell.
    stylesApp: void 0,
    stylesContent: void 0
  };
  const modalProps = {
    // Background CSS style string.
    background: void 0,
    slotSeparate: void 0,
    styles: void 0,
    // Stores any transition functions.
    transition: void 0,
    inTransition: void 0,
    outTransition: void 0,
    // Stores properties to set for options for any transitions.
    transitionOptions: void 0,
    inTransitionOptions: void 0,
    outTransitionOptions: void 0
  };
  let zIndex = void 0;
  if (modal === void 0) {
    modal = typeof data2?.modal === "boolean" ? data2.modal : false;
  }
  if (modal) {
    onDestroy(() => window.removeEventListener("keydown", onKeydownModal, { capture: true }));
    onMount(() => window.addEventListener("keydown", onKeydownModal, { capture: true }));
  } else {
    onDestroy(() => document.removeEventListener("keydown", onKeydown));
    onMount(() => document.addEventListener("keydown", onKeydown));
  }
  function onKeydown(event) {
    if (event.code === "Escape") {
      event.preventDefault();
      event.stopPropagation();
      application.close();
    }
  }
  __name(onKeydown, "onKeydown");
  function onKeydownModal(event) {
    if (event.code === "Escape") {
      event.preventDefault();
      event.stopImmediatePropagation();
      application.close();
    }
  }
  __name(onKeydownModal, "onKeydownModal");
  function dialogcontent_dialogComponent_binding(value) {
    dialogComponent = value;
    $$invalidate(2, dialogComponent);
  }
  __name(dialogcontent_dialogComponent_binding, "dialogcontent_dialogComponent_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  function applicationshell_elementContent_binding(value) {
    elementContent = value;
    $$invalidate(1, elementContent);
  }
  __name(applicationshell_elementContent_binding, "applicationshell_elementContent_binding");
  function dialogcontent_dialogComponent_binding_1(value) {
    dialogComponent = value;
    $$invalidate(2, dialogComponent);
  }
  __name(dialogcontent_dialogComponent_binding_1, "dialogcontent_dialogComponent_binding_1");
  function applicationshell_elementRoot_binding_1(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding_1, "applicationshell_elementRoot_binding_1");
  function applicationshell_elementContent_binding_1(value) {
    elementContent = value;
    $$invalidate(1, elementContent);
  }
  __name(applicationshell_elementContent_binding_1, "applicationshell_elementContent_binding_1");
  $$self.$$set = ($$props2) => {
    if ("elementContent" in $$props2)
      $$invalidate(1, elementContent = $$props2.elementContent);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("data" in $$props2)
      $$invalidate(3, data2 = $$props2.data);
    if ("dialogComponent" in $$props2)
      $$invalidate(2, dialogComponent = $$props2.dialogComponent);
    if ("managedPromise" in $$props2)
      $$invalidate(9, managedPromise = $$props2.managedPromise);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*elementRoot, modal*/
    33) {
      if (elementRoot instanceof HTMLElement) {
        elementRoot.setAttribute("role", "dialog");
        if (modal) {
          elementRoot.setAttribute("aria-modal", "true");
        }
      }
    }
    if ($$self.$$.dirty & /*data, modal, zIndex, application*/
    312) {
      if (isObject(data2)) {
        const newZIndex = Number.isInteger(data2.zIndex) || data2.zIndex === null ? data2.zIndex : modal ? Number.MAX_SAFE_INTEGER : Number.MAX_SAFE_INTEGER - 1;
        if (zIndex !== newZIndex) {
          $$invalidate(8, zIndex = newZIndex);
        }
        const newDraggable = typeof data2.draggable === "boolean" ? data2.draggable : void 0;
        if (newDraggable !== void 0 && application.reactive.draggable !== newDraggable) {
          $$invalidate(4, application.reactive.draggable = newDraggable, application);
        }
        const newFocusAuto = typeof data2.focusAuto === "boolean" ? data2.focusAuto : void 0;
        if (newFocusAuto !== void 0 && application.reactive.focusAuto !== newFocusAuto) {
          $$invalidate(4, application.reactive.focusAuto = newFocusAuto, application);
        }
        const newFocusKeep = typeof data2.focusKeep === "boolean" ? data2.focusKeep : void 0;
        if (newFocusKeep !== void 0 && application.reactive.focusKeep !== newFocusKeep) {
          $$invalidate(4, application.reactive.focusKeep = newFocusKeep, application);
        }
        const newFocusTrap = typeof data2.focusTrap === "boolean" ? data2.focusTrap : void 0;
        if (newFocusTrap !== void 0 && application.reactive.focusTrap !== newFocusTrap) {
          $$invalidate(4, application.reactive.focusTrap = newFocusTrap, application);
        }
        const newMinimizable = typeof data2.minimizable === "boolean" ? data2.minimizable : void 0;
        if (newMinimizable !== void 0 && application.reactive.minimizable !== newMinimizable) {
          $$invalidate(4, application.reactive.minimizable = newMinimizable, application);
        }
        const newResizable = typeof data2.resizable === "boolean" ? data2.resizable : void 0;
        if (newResizable !== void 0 && application.reactive.resizable !== newResizable) {
          $$invalidate(4, application.reactive.resizable = newResizable, application);
        }
        const newTitle = data2.title ?? "Dialog";
        if (newTitle !== application?.options?.title) {
          $$invalidate(4, application.reactive.title = newTitle, application);
        }
        if (application.position.zIndex !== zIndex) {
          $$invalidate(4, application.position.zIndex = zIndex, application);
        }
      }
    }
    if ($$self.$$.dirty & /*data, appProps*/
    72) {
      if (isObject(data2?.transition)) {
        const d = data2.transition;
        if (d?.transition !== appProps.transition) {
          $$invalidate(6, appProps.transition = d.transition, appProps);
        }
        if (d?.inTransition !== appProps.inTransition) {
          $$invalidate(6, appProps.inTransition = d.inTransition, appProps);
        }
        if (d?.outTransition !== appProps.outTransition) {
          $$invalidate(6, appProps.outTransition = d.outTransition, appProps);
        }
        if (d?.transitionOptions !== appProps.transitionOptions) {
          $$invalidate(6, appProps.transitionOptions = d.transitionOptions, appProps);
        }
        if (d?.inTransitionOptions !== appProps.inTransitionOptions) {
          $$invalidate(6, appProps.inTransitionOptions = d.inTransitionOptions, appProps);
        }
        if (d?.outTransitionOptions !== appProps.outTransitionOptions) {
          $$invalidate(6, appProps.outTransitionOptions = d.outTransitionOptions, appProps);
        }
      }
    }
    if ($$self.$$.dirty & /*data, modalProps*/
    136) {
      {
        const newModalBackground = typeof data2?.modalOptions?.background === "string" ? data2.modalOptions.background : s_MODAL_BACKGROUND;
        if (newModalBackground !== modalProps.background) {
          $$invalidate(7, modalProps.background = newModalBackground, modalProps);
        }
      }
    }
    if ($$self.$$.dirty & /*data, modalProps*/
    136) {
      {
        const newModalSlotSeparate = typeof data2?.modalOptions?.slotSeparate === "boolean" ? data2.modalOptions.slotSeparate : void 0;
        if (newModalSlotSeparate !== modalProps.slotSeparate) {
          $$invalidate(7, modalProps.slotSeparate = newModalSlotSeparate, modalProps);
        }
      }
    }
    if ($$self.$$.dirty & /*data, modalProps*/
    136) {
      {
        const newModalStyles = isObject(data2?.modalOptions?.styles) ? data2.modalOptions.styles : void 0;
        if (newModalStyles !== modalProps.styles) {
          $$invalidate(7, modalProps.styles = newModalStyles, modalProps);
        }
      }
    }
    if ($$self.$$.dirty & /*data, modalProps*/
    136) {
      if (isObject(data2?.modalOptions?.transition)) {
        const d = data2.modalOptions.transition;
        if (d?.transition !== modalProps.transition) {
          $$invalidate(
            7,
            modalProps.transition = typeof d?.transition === "function" ? d.transition : s_MODAL_TRANSITION,
            modalProps
          );
        }
        if (d?.inTransition !== modalProps.inTransition) {
          $$invalidate(7, modalProps.inTransition = d.inTransition, modalProps);
        }
        if (d?.outTransition !== modalProps.outTransition) {
          $$invalidate(7, modalProps.outTransition = d.outTransition, modalProps);
        }
        if (d?.transitionOptions !== modalProps.transitionOptions) {
          $$invalidate(
            7,
            modalProps.transitionOptions = isObject(d?.transitionOptions) ? d.transitionOptions : s_MODAL_TRANSITION_OPTIONS,
            modalProps
          );
        }
        if (d?.inTransitionOptions !== modalProps.inTransitionOptions) {
          $$invalidate(7, modalProps.inTransitionOptions = d.inTransitionOptions, modalProps);
        }
        if (d?.outTransitionOptions !== modalProps.outTransitionOptions) {
          $$invalidate(7, modalProps.outTransitionOptions = d.outTransitionOptions, modalProps);
        }
      } else {
        const newModalTransition = typeof data2?.modalOptions?.transition?.transition === "function" ? data2.modalOptions.transition.transition : s_MODAL_TRANSITION;
        if (newModalTransition !== modalProps.transition) {
          $$invalidate(7, modalProps.transition = newModalTransition, modalProps);
        }
        const newModalTransitionOptions = isObject(data2?.modalOptions?.transitionOptions) ? data2.modalOptions.transitionOptions : s_MODAL_TRANSITION_OPTIONS;
        if (newModalTransitionOptions !== modalProps.transitionOptions) {
          $$invalidate(7, modalProps.transitionOptions = newModalTransitionOptions, modalProps);
        }
      }
    }
  };
  return [
    elementRoot,
    elementContent,
    dialogComponent,
    data2,
    application,
    modal,
    appProps,
    modalProps,
    zIndex,
    managedPromise,
    dialogcontent_dialogComponent_binding,
    applicationshell_elementRoot_binding,
    applicationshell_elementContent_binding,
    dialogcontent_dialogComponent_binding_1,
    applicationshell_elementRoot_binding_1,
    applicationshell_elementContent_binding_1
  ];
}
__name(instance$1h, "instance$1h");
const _DialogShell = class _DialogShell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1h, create_fragment$1k, safe_not_equal, {
      elementContent: 1,
      elementRoot: 0,
      data: 3,
      dialogComponent: 2,
      managedPromise: 9
    });
  }
  get elementContent() {
    return this.$$.ctx[1];
  }
  set elementContent(elementContent) {
    this.$$set({ elementContent });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get data() {
    return this.$$.ctx[3];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get dialogComponent() {
    return this.$$.ctx[2];
  }
  set dialogComponent(dialogComponent) {
    this.$$set({ dialogComponent });
    flush();
  }
  get managedPromise() {
    return this.$$.ctx[9];
  }
  set managedPromise(managedPromise) {
    this.$$set({ managedPromise });
    flush();
  }
};
__name(_DialogShell, "DialogShell");
let DialogShell = _DialogShell;
cssVariables$1.setProperties({
  // Anchor text shadow / header buttons
  "--tjs-default-text-shadow-focus-hover": "0 0 8px var(--color-shadow-primary)",
  // TJSApplicationShell app background.
  "--tjs-app-background": `url("${globalThis.foundry.utils.getRoute("/ui/denim075.png")}")`
}, false);
const SliderInput_svelte_svelte_type_style_lang = "";
function create_fragment$1j(ctx) {
  let div;
  let input0;
  let t;
  let input1;
  let div_style_value;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      input0 = element("input");
      t = space();
      input1 = element("input");
      attr(
        input0,
        "max",
        /*max*/
        ctx[1]
      );
      attr(
        input0,
        "min",
        /*min*/
        ctx[0]
      );
      attr(
        input0,
        "step",
        /*step*/
        ctx[3]
      );
      attr(input0, "type", "range");
      attr(input0, "class", "svelte-zay8hl");
      attr(
        input1,
        "max",
        /*maxInput*/
        ctx[2]
      );
      attr(
        input1,
        "min",
        /*min*/
        ctx[0]
      );
      input1.required = true;
      attr(
        input1,
        "step",
        /*step*/
        ctx[3]
      );
      attr(input1, "type", "number");
      attr(input1, "class", "svelte-zay8hl");
      attr(div, "class", "slider-group svelte-zay8hl");
      attr(div, "style", div_style_value = /*$$props*/
      ctx[5].style);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input0);
      set_input_value(
        input0,
        /*displayValue*/
        ctx[4]
      );
      append(div, t);
      append(div, input1);
      set_input_value(
        input1,
        /*displayValue*/
        ctx[4]
      );
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_input_handler*/
            ctx[8]
          ),
          listen(
            input0,
            "input",
            /*input0_change_input_handler*/
            ctx[8]
          ),
          listen(
            input1,
            "input",
            /*input1_input_handler*/
            ctx[9]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*max*/
      2) {
        attr(
          input0,
          "max",
          /*max*/
          ctx2[1]
        );
      }
      if (dirty & /*min*/
      1) {
        attr(
          input0,
          "min",
          /*min*/
          ctx2[0]
        );
      }
      if (dirty & /*step*/
      8) {
        attr(
          input0,
          "step",
          /*step*/
          ctx2[3]
        );
      }
      if (dirty & /*displayValue*/
      16) {
        set_input_value(
          input0,
          /*displayValue*/
          ctx2[4]
        );
      }
      if (dirty & /*maxInput*/
      4) {
        attr(
          input1,
          "max",
          /*maxInput*/
          ctx2[2]
        );
      }
      if (dirty & /*min*/
      1) {
        attr(
          input1,
          "min",
          /*min*/
          ctx2[0]
        );
      }
      if (dirty & /*step*/
      8) {
        attr(
          input1,
          "step",
          /*step*/
          ctx2[3]
        );
      }
      if (dirty & /*displayValue*/
      16 && to_number(input1.value) !== /*displayValue*/
      ctx2[4]) {
        set_input_value(
          input1,
          /*displayValue*/
          ctx2[4]
        );
      }
      if (dirty & /*$$props*/
      32 && div_style_value !== (div_style_value = /*$$props*/
      ctx2[5].style)) {
        attr(div, "style", div_style_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$1j, "create_fragment$1j");
function instance$1g($$self, $$props, $$invalidate) {
  let { value } = $$props;
  let { min: min2 = 0 } = $$props;
  let { max: max2 = 200 } = $$props;
  let { maxInput = Infinity } = $$props;
  let { step = 1 } = $$props;
  let { divideBy = 100 } = $$props;
  let displayValue = value * divideBy;
  function input0_change_input_handler() {
    displayValue = to_number(this.value);
    $$invalidate(4, displayValue);
  }
  __name(input0_change_input_handler, "input0_change_input_handler");
  function input1_input_handler() {
    displayValue = to_number(this.value);
    $$invalidate(4, displayValue);
  }
  __name(input1_input_handler, "input1_input_handler");
  $$self.$$set = ($$new_props) => {
    $$invalidate(5, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
    if ("value" in $$new_props)
      $$invalidate(6, value = $$new_props.value);
    if ("min" in $$new_props)
      $$invalidate(0, min2 = $$new_props.min);
    if ("max" in $$new_props)
      $$invalidate(1, max2 = $$new_props.max);
    if ("maxInput" in $$new_props)
      $$invalidate(2, maxInput = $$new_props.maxInput);
    if ("step" in $$new_props)
      $$invalidate(3, step = $$new_props.step);
    if ("divideBy" in $$new_props)
      $$invalidate(7, divideBy = $$new_props.divideBy);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*displayValue, divideBy*/
    144) {
      {
        $$invalidate(6, value = displayValue / divideBy);
      }
    }
  };
  $$props = exclude_internal_props($$props);
  return [
    min2,
    max2,
    maxInput,
    step,
    displayValue,
    $$props,
    value,
    divideBy,
    input0_change_input_handler,
    input1_input_handler
  ];
}
__name(instance$1g, "instance$1g");
const _SliderInput = class _SliderInput extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1g, create_fragment$1j, safe_not_equal, {
      value: 6,
      min: 0,
      max: 1,
      maxInput: 2,
      step: 3,
      divideBy: 7
    });
  }
};
__name(_SliderInput, "SliderInput");
let SliderInput = _SliderInput;
function create_if_block_3$p(ctx) {
  let p;
  let t_value = localize(`ITEM-PILES.Applications.${/*application*/
  ctx[5].options.localizationTitle}.Content`, { target_name: (
    /*target*/
    ctx[2].name
  ) }) + "";
  let t;
  return {
    c() {
      p = element("p");
      t = text(t_value);
      attr(p, "class", "item-piles-text-center");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*target*/
      4 && t_value !== (t_value = localize(`ITEM-PILES.Applications.${/*application*/
      ctx2[5].options.localizationTitle}.Content`, { target_name: (
        /*target*/
        ctx2[2].name
      ) }) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_3$p, "create_if_block_3$p");
function create_if_block_1$H(ctx) {
  let div;
  let label;
  let t0_value = localize(
    `ITEM-PILES.Applications.${/*application*/
    ctx[5].options.localizationTitle}.${/*unlimitedQuantity*/
    ctx[6] ? "ContentInfiniteQuantity" : "ContentMultipleQuantity"}`,
    {
      target_name: (
        /*target*/
        ctx[2]?.name ?? ""
      ),
      quantity: (
        /*itemQuantity*/
        ctx[7]
      ),
      itemName: (
        /*item*/
        ctx[1].name
      )
    }
  ) + "";
  let t0;
  let t1;
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block_2$v, create_else_block_1$9];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*unlimitedQuantity*/
      ctx2[6]
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      div = element("div");
      label = element("label");
      t0 = text(t0_value);
      t1 = space();
      if_block.c();
      if_block_anchor = empty();
      attr(div, "class", "form-group item-piles-text-center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, t0);
      insert(target, t1, anchor);
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if ((!current || dirty & /*target, item*/
      6) && t0_value !== (t0_value = localize(
        `ITEM-PILES.Applications.${/*application*/
        ctx2[5].options.localizationTitle}.${/*unlimitedQuantity*/
        ctx2[6] ? "ContentInfiniteQuantity" : "ContentMultipleQuantity"}`,
        {
          target_name: (
            /*target*/
            ctx2[2]?.name ?? ""
          ),
          quantity: (
            /*itemQuantity*/
            ctx2[7]
          ),
          itemName: (
            /*item*/
            ctx2[1].name
          )
        }
      ) + ""))
        set_data(t0, t0_value);
      if_block.p(ctx2, dirty);
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t1);
      if_blocks[current_block_type_index].d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block_1$H, "create_if_block_1$H");
function create_else_block_1$9(ctx) {
  let sliderinput;
  let updating_value;
  let current;
  function sliderinput_value_binding(value) {
    ctx[13](value);
  }
  __name(sliderinput_value_binding, "sliderinput_value_binding");
  let sliderinput_props = {
    min: 1,
    max: (
      /*sliderQuantity*/
      ctx[8]
    ),
    maxInput: (
      /*sliderQuantity*/
      ctx[8]
    ),
    divideBy: 1
  };
  if (
    /*quantity*/
    ctx[4] !== void 0
  ) {
    sliderinput_props.value = /*quantity*/
    ctx[4];
  }
  sliderinput = new SliderInput({ props: sliderinput_props });
  binding_callbacks.push(() => bind(sliderinput, "value", sliderinput_value_binding));
  return {
    c() {
      create_component(sliderinput.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sliderinput, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const sliderinput_changes = {};
      if (!updating_value && dirty & /*quantity*/
      16) {
        updating_value = true;
        sliderinput_changes.value = /*quantity*/
        ctx2[4];
        add_flush_callback(() => updating_value = false);
      }
      sliderinput.$set(sliderinput_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sliderinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sliderinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sliderinput, detaching);
    }
  };
}
__name(create_else_block_1$9, "create_else_block_1$9");
function create_if_block_2$v(ctx) {
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      attr(input, "type", "number");
      attr(input, "min", "1");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*quantity*/
        ctx[4]
      );
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*quantity*/
      16 && to_number(input.value) !== /*quantity*/
      ctx2[4]) {
        set_input_value(
          input,
          /*quantity*/
          ctx2[4]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_2$v, "create_if_block_2$v");
function create_else_block$p(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize(`ITEM-PILES.Applications.${/*application*/
  ctx[5].options.localizationTitle}.SubmitNoTarget`) + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-box");
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*requestSubmit*/
          ctx[10],
          { once: true }
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$p, "create_else_block$p");
function create_if_block$X(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize(`ITEM-PILES.Applications.${/*application*/
  ctx[5].options.localizationTitle}.Submit`) + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-download");
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*requestSubmit*/
          ctx[10],
          { once: true }
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$X, "create_if_block$X");
function create_default_slot$t(ctx) {
  let form_1;
  let h3;
  let t0_value = localize(`ITEM-PILES.Applications.${/*application*/
  ctx[5].options.localizationTitle}.Header`, { item_name: (
    /*item*/
    ctx[1].name
  ) }) + "";
  let t0;
  let t1;
  let t2;
  let t3;
  let footer;
  let t4;
  let button;
  let i;
  let t5;
  let t6_value = localize("Cancel") + "";
  let t6;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*target*/
    ctx[2] && create_if_block_3$p(ctx)
  );
  let if_block1 = (
    /*itemQuantity*/
    (ctx[7] > 1 || /*unlimitedQuantity*/
    ctx[6]) && /*canItemStack*/
    ctx[9] && create_if_block_1$H(ctx)
  );
  function select_block_type_1(ctx2, dirty) {
    if (
      /*target*/
      ctx2[2]
    )
      return create_if_block$X;
    return create_else_block$p;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block2 = current_block_type(ctx);
  return {
    c() {
      form_1 = element("form");
      h3 = element("h3");
      t0 = text(t0_value);
      t1 = space();
      if (if_block0)
        if_block0.c();
      t2 = space();
      if (if_block1)
        if_block1.c();
      t3 = space();
      footer = element("footer");
      if_block2.c();
      t4 = space();
      button = element("button");
      i = element("i");
      t5 = space();
      t6 = text(t6_value);
      set_style(h3, "text-align", "center");
      attr(i, "class", "fas fa-times");
      attr(button, "type", "button");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
      set_style(footer, "margin-top", "1rem");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-flexcol");
      set_style(form_1, "padding", "0.5rem");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, h3);
      append(h3, t0);
      append(form_1, t1);
      if (if_block0)
        if_block0.m(form_1, null);
      append(form_1, t2);
      if (if_block1)
        if_block1.m(form_1, null);
      append(form_1, t3);
      append(form_1, footer);
      if_block2.m(footer, null);
      append(footer, t4);
      append(footer, button);
      append(button, i);
      append(button, t5);
      append(button, t6);
      ctx[15](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*click_handler*/
            ctx[14]
          ),
          listen(form_1, "submit", prevent_default(
            /*submit*/
            ctx[11]
          ), { once: true })
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if ((!current || dirty & /*item*/
      2) && t0_value !== (t0_value = localize(`ITEM-PILES.Applications.${/*application*/
      ctx2[5].options.localizationTitle}.Header`, { item_name: (
        /*item*/
        ctx2[1].name
      ) }) + ""))
        set_data(t0, t0_value);
      if (
        /*target*/
        ctx2[2]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_3$p(ctx2);
          if_block0.c();
          if_block0.m(form_1, t2);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*itemQuantity*/
        (ctx2[7] > 1 || /*unlimitedQuantity*/
        ctx2[6]) && /*canItemStack*/
        ctx2[9]
      )
        if_block1.p(ctx2, dirty);
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block2) {
        if_block2.p(ctx2, dirty);
      } else {
        if_block2.d(1);
        if_block2 = current_block_type(ctx2);
        if (if_block2) {
          if_block2.c();
          if_block2.m(footer, t4);
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if_block2.d();
      ctx[15](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$t, "create_default_slot$t");
function create_fragment$1i(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[16](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$t] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, target, quantity, item*/
      131102) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$1i, "create_fragment$1i");
function instance$1f($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { item } = $$props;
  let { elementRoot } = $$props;
  let { target = false } = $$props;
  const unlimitedQuantity = application.options?.unlimitedQuantity ?? false;
  let form;
  let quantity = 1;
  const itemQuantity = getItemQuantity(item);
  const sliderQuantity = itemQuantity + (application.options?.quantityAdjustment ?? 0);
  const canItemStack$1 = canItemStack(item, target);
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function submit() {
    application.options.resolve(quantity);
    application.close();
  }
  __name(submit, "submit");
  function input_input_handler() {
    quantity = to_number(this.value);
    $$invalidate(4, quantity);
  }
  __name(input_input_handler, "input_input_handler");
  function sliderinput_value_binding(value) {
    quantity = value;
    $$invalidate(4, quantity);
  }
  __name(sliderinput_value_binding, "sliderinput_value_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(3, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(1, item = $$props2.item);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("target" in $$props2)
      $$invalidate(2, target = $$props2.target);
  };
  return [
    elementRoot,
    item,
    target,
    form,
    quantity,
    application,
    unlimitedQuantity,
    itemQuantity,
    sliderQuantity,
    canItemStack$1,
    requestSubmit,
    submit,
    input_input_handler,
    sliderinput_value_binding,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$1f, "instance$1f");
const _Drop_item_dialog_shell = class _Drop_item_dialog_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1f, create_fragment$1i, safe_not_equal, { item: 1, elementRoot: 0, target: 2 });
  }
  get item() {
    return this.$$.ctx[1];
  }
  set item(item) {
    this.$$set({ item });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get target() {
    return this.$$.ctx[2];
  }
  set target(target) {
    this.$$set({ target });
    flush();
  }
};
__name(_Drop_item_dialog_shell, "Drop_item_dialog_shell");
let Drop_item_dialog_shell = _Drop_item_dialog_shell;
const _AnimationControl = class _AnimationControl {
  /**
   * @param {object|null} [animationData] - Animation data from {@link AnimationAPI}.
   *
   * @param {boolean}     [willFinish] - Promise that tracks animation finished state.
   */
  constructor(animationData, willFinish = false) {
    /** @type {object} */
    __privateAdd(this, _animationData, void 0);
    /** @type {Promise<void>} */
    __privateAdd(this, _finishedPromise, void 0);
    __privateAdd(this, _willFinish, void 0);
    __privateSet(this, _animationData, animationData);
    __privateSet(this, _willFinish, willFinish);
    if (isObject(animationData)) {
      animationData.control = this;
    }
  }
  /**
   * Provides a static void / undefined AnimationControl that is automatically resolved.
   *
   * @returns {AnimationControl} Void AnimationControl
   */
  static get voidControl() {
    return __privateGet(this, _voidControl);
  }
  /**
   * Get a promise that resolves when animation is finished.
   *
   * @returns {Promise<void>}
   */
  get finished() {
    if (!(__privateGet(this, _finishedPromise) instanceof Promise)) {
      __privateSet(this, _finishedPromise, __privateGet(this, _willFinish) ? new Promise((resolve) => __privateGet(this, _animationData).resolve = resolve) : Promise.resolve());
    }
    return __privateGet(this, _finishedPromise);
  }
  /**
   * Returns whether this animation is currently active / animating.
   *
   * Note: a delayed animation may not be started / active yet. Use {@link AnimationControl.isFinished} to determine
   * if an animation is actually finished.
   *
   * @returns {boolean} Animation active state.
   */
  get isActive() {
    return __privateGet(this, _animationData).active;
  }
  /**
   * Returns whether this animation is completely finished.
   *
   * @returns {boolean} Animation finished state.
   */
  get isFinished() {
    return __privateGet(this, _animationData).finished;
  }
  /**
   * Cancels the animation.
   */
  cancel() {
    const animationData = __privateGet(this, _animationData);
    if (animationData === null || animationData === void 0) {
      return;
    }
    animationData.cancelled = true;
  }
};
_animationData = new WeakMap();
_finishedPromise = new WeakMap();
_willFinish = new WeakMap();
_voidControl = new WeakMap();
__name(_AnimationControl, "AnimationControl");
/**
 * Defines a static empty / void animation control.
 *
 * @type {AnimationControl}
 */
__privateAdd(_AnimationControl, _voidControl, new _AnimationControl(null));
let AnimationControl = _AnimationControl;
const _AnimationManager = class _AnimationManager {
  /**
   * Add animation data.
   *
   * @param {object}   data -
   */
  static add(data2) {
    const now2 = performance.now();
    data2.start = now2 + (_AnimationManager.current - now2);
    _AnimationManager.newList.push(data2);
  }
  /**
   * Manage all animation
   */
  static animate() {
    const current = _AnimationManager.current = performance.now();
    if (_AnimationManager.activeList.length === 0 && _AnimationManager.newList.length === 0) {
      globalThis.requestAnimationFrame(_AnimationManager.animate);
      return;
    }
    if (_AnimationManager.newList.length) {
      for (let cntr = _AnimationManager.newList.length; --cntr >= 0; ) {
        const data2 = _AnimationManager.newList[cntr];
        if (data2.cancelled) {
          _AnimationManager.newList.splice(cntr, 1);
          data2.cleanup(data2);
        }
        if (data2.active) {
          _AnimationManager.newList.splice(cntr, 1);
          _AnimationManager.activeList.push(data2);
        }
      }
    }
    for (let cntr = _AnimationManager.activeList.length; --cntr >= 0; ) {
      const data2 = _AnimationManager.activeList[cntr];
      if (data2.cancelled || data2.el !== void 0 && !data2.el.isConnected) {
        _AnimationManager.activeList.splice(cntr, 1);
        data2.cleanup(data2);
        continue;
      }
      data2.current = current - data2.start;
      if (data2.current >= data2.duration) {
        for (let dataCntr = data2.keys.length; --dataCntr >= 0; ) {
          const key = data2.keys[dataCntr];
          data2.newData[key] = data2.destination[key];
        }
        data2.position.set(data2.newData);
        _AnimationManager.activeList.splice(cntr, 1);
        data2.cleanup(data2);
        continue;
      }
      const easedTime = data2.ease(data2.current / data2.duration);
      for (let dataCntr = data2.keys.length; --dataCntr >= 0; ) {
        const key = data2.keys[dataCntr];
        data2.newData[key] = data2.interpolate(data2.initial[key], data2.destination[key], easedTime);
      }
      data2.position.set(data2.newData);
    }
    globalThis.requestAnimationFrame(_AnimationManager.animate);
  }
  /**
   * Cancels all animations for given Position instance.
   *
   * @param {Position} position - Position instance.
   */
  static cancel(position) {
    for (let cntr = _AnimationManager.activeList.length; --cntr >= 0; ) {
      const data2 = _AnimationManager.activeList[cntr];
      if (data2.position === position) {
        _AnimationManager.activeList.splice(cntr, 1);
        data2.cancelled = true;
        data2.cleanup(data2);
      }
    }
    for (let cntr = _AnimationManager.newList.length; --cntr >= 0; ) {
      const data2 = _AnimationManager.newList[cntr];
      if (data2.position === position) {
        _AnimationManager.newList.splice(cntr, 1);
        data2.cancelled = true;
        data2.cleanup(data2);
      }
    }
  }
  /**
   * Cancels all active and delayed animations.
   */
  static cancelAll() {
    for (let cntr = _AnimationManager.activeList.length; --cntr >= 0; ) {
      const data2 = _AnimationManager.activeList[cntr];
      data2.cancelled = true;
      data2.cleanup(data2);
    }
    for (let cntr = _AnimationManager.newList.length; --cntr >= 0; ) {
      const data2 = _AnimationManager.newList[cntr];
      data2.cancelled = true;
      data2.cleanup(data2);
    }
    _AnimationManager.activeList.length = 0;
    _AnimationManager.newList.length = 0;
  }
  /**
   * Gets all {@link AnimationControl} instances for a given Position instance.
   *
   * @param {Position} position - Position instance.
   *
   * @returns {AnimationControl[]} All scheduled AnimationControl instances for the given Position instance.
   */
  static getScheduled(position) {
    const results = [];
    for (let cntr = _AnimationManager.activeList.length; --cntr >= 0; ) {
      const data2 = _AnimationManager.activeList[cntr];
      if (data2.position === position) {
        results.push(data2.control);
      }
    }
    for (let cntr = _AnimationManager.newList.length; --cntr >= 0; ) {
      const data2 = _AnimationManager.newList[cntr];
      if (data2.position === position) {
        results.push(data2.control);
      }
    }
    return results;
  }
};
__name(_AnimationManager, "AnimationManager");
/**
 * @type {object[]}
 */
__publicField(_AnimationManager, "activeList", []);
/**
 * @type {object[]}
 */
__publicField(_AnimationManager, "newList", []);
/**
 * @type {number}
 */
__publicField(_AnimationManager, "current");
let AnimationManager = _AnimationManager;
AnimationManager.animate();
const animateKeys = /* @__PURE__ */ new Set([
  // Main keys
  "left",
  "top",
  "maxWidth",
  "maxHeight",
  "minWidth",
  "minHeight",
  "width",
  "height",
  "rotateX",
  "rotateY",
  "rotateZ",
  "scale",
  "translateX",
  "translateY",
  "translateZ",
  "zIndex",
  // Aliases
  "rotation"
]);
const transformKeys = ["rotateX", "rotateY", "rotateZ", "scale", "translateX", "translateY", "translateZ"];
Object.freeze(transformKeys);
const relativeRegex = /^([-+*])=(-?[\d]*\.?[\d]+)$/;
const numericDefaults = {
  // Other keys
  height: 0,
  left: 0,
  maxHeight: null,
  maxWidth: null,
  minHeight: null,
  minWidth: null,
  top: 0,
  transformOrigin: null,
  width: 0,
  zIndex: null,
  rotateX: 0,
  rotateY: 0,
  rotateZ: 0,
  scale: 1,
  translateX: 0,
  translateY: 0,
  translateZ: 0,
  rotation: 0
};
Object.freeze(numericDefaults);
function setNumericDefaults(data2) {
  if (data2.rotateX === null) {
    data2.rotateX = 0;
  }
  if (data2.rotateY === null) {
    data2.rotateY = 0;
  }
  if (data2.rotateZ === null) {
    data2.rotateZ = 0;
  }
  if (data2.translateX === null) {
    data2.translateX = 0;
  }
  if (data2.translateY === null) {
    data2.translateY = 0;
  }
  if (data2.translateZ === null) {
    data2.translateZ = 0;
  }
  if (data2.scale === null) {
    data2.scale = 1;
  }
  if (data2.rotation === null) {
    data2.rotation = 0;
  }
}
__name(setNumericDefaults, "setNumericDefaults");
const transformKeysBitwise = {
  rotateX: 1,
  rotateY: 2,
  rotateZ: 4,
  scale: 8,
  translateX: 16,
  translateY: 32,
  translateZ: 64
};
Object.freeze(transformKeysBitwise);
const transformOriginDefault = "top left";
const transformOrigins = [
  "top left",
  "top center",
  "top right",
  "center left",
  "center",
  "center right",
  "bottom left",
  "bottom center",
  "bottom right"
];
Object.freeze(transformOrigins);
function convertRelative(positionData, position) {
  for (const key in positionData) {
    if (animateKeys.has(key)) {
      const value = positionData[key];
      if (typeof value !== "string") {
        continue;
      }
      if (value === "auto" || value === "inherit") {
        continue;
      }
      const regexResults = relativeRegex.exec(value);
      if (!regexResults) {
        throw new Error(
          `convertRelative error: malformed relative key (${key}) with value (${value})`
        );
      }
      const current = position[key];
      switch (regexResults[1]) {
        case "-":
          positionData[key] = current - parseFloat(regexResults[2]);
          break;
        case "+":
          positionData[key] = current + parseFloat(regexResults[2]);
          break;
        case "*":
          positionData[key] = current * parseFloat(regexResults[2]);
          break;
      }
    }
  }
}
__name(convertRelative, "convertRelative");
const _AnimationAPI = class _AnimationAPI {
  constructor(position, data2) {
    /**
     * Adds / schedules an animation w/ the AnimationManager. This contains the final steps common to all tweens.
     *
     * @param {object}      initial -
     *
     * @param {object}      destination -
     *
     * @param {number}      duration -
     *
     * @param {HTMLElement} el -
     *
     * @param {number}      delay -
     *
     * @param {Function}    ease -
     *
     * @param {Function}    interpolate -
     *
     * @returns {AnimationControl} The associated animation control.
     */
    __privateAdd(this, _addAnimation);
    /**
     * Cleans up an animation instance.
     *
     * @param {object}   data - Animation data for an animation instance.
     */
    __privateAdd(this, _cleanupInstance);
    /** @type {PositionData} */
    __privateAdd(this, _data, void 0);
    /** @type {Position} */
    __privateAdd(this, _position, void 0);
    /**
     * Tracks the number of animation control instances that are active.
     *
     * @type {number}
     */
    __privateAdd(this, _instanceCount, 0);
    /**
     * Provides a bound function to pass as data to AnimationManager to invoke
     *
     * @type {Function}
     * @see {AnimationAPI.#cleanupInstance}
     */
    __privateAdd(this, _cleanup, void 0);
    __privateSet(this, _position, position);
    __privateSet(this, _data, data2);
    __privateSet(this, _cleanup, __privateMethod(this, _cleanupInstance, cleanupInstance_fn).bind(this));
  }
  /**
   * Returns whether there are scheduled animations whether active or delayed for this Position.
   *
   * @returns {boolean} Are there active animation instances.
   */
  get isScheduled() {
    return __privateGet(this, _instanceCount) > 0;
  }
  /**
   * Cancels all animation instances for this Position instance.
   */
  cancel() {
    AnimationManager.cancel(__privateGet(this, _position));
  }
  /**
   * Returns all currently scheduled AnimationControl instances for this Position instance.
   *
   * @returns {AnimationControl[]} All currently scheduled animation controls for this Position instance.
   */
  getScheduled() {
    return AnimationManager.getScheduled(__privateGet(this, _position));
  }
  /**
   * Provides a tween from given position data to the current position.
   *
   * @param {PositionDataExtended} fromData - The starting position.
   *
   * @param {object}         [opts] - Optional parameters.
   *
   * @param {number}         [opts.delay=0] - Delay in seconds before animation starts.
   *
   * @param {number}         [opts.duration=1] - Duration in seconds.
   *
   * @param {Function}       [opts.ease=cubicOut] - Easing function.
   *
   * @param {Function}       [opts.interpolate=lerp] - Interpolation function.
   *
   * @returns {AnimationControl}  A control object that can cancel animation and provides a `finished` Promise.
   */
  from(fromData, { delay = 0, duration = 1, ease = cubicOut, interpolate = lerp$5 } = {}) {
    if (!isObject(fromData)) {
      throw new TypeError(`AnimationAPI.from error: 'fromData' is not an object.`);
    }
    const position = __privateGet(this, _position);
    const parent = position.parent;
    if (parent !== void 0 && typeof parent?.options?.positionable === "boolean" && !parent?.options?.positionable) {
      return AnimationControl.voidControl;
    }
    const targetEl = parent instanceof HTMLElement ? parent : parent?.elementTarget;
    const el = targetEl instanceof HTMLElement && targetEl.isConnected ? targetEl : void 0;
    if (!Number.isFinite(delay) || delay < 0) {
      throw new TypeError(`AnimationAPI.from error: 'delay' is not a positive number.`);
    }
    if (!Number.isFinite(duration) || duration < 0) {
      throw new TypeError(`AnimationAPI.from error: 'duration' is not a positive number.`);
    }
    if (typeof ease !== "function") {
      throw new TypeError(`AnimationAPI.from error: 'ease' is not a function.`);
    }
    if (typeof interpolate !== "function") {
      throw new TypeError(`AnimationAPI.from error: 'interpolate' is not a function.`);
    }
    const initial = {};
    const destination = {};
    const data2 = __privateGet(this, _data);
    for (const key in fromData) {
      if (data2[key] !== void 0 && fromData[key] !== data2[key]) {
        initial[key] = fromData[key];
        destination[key] = data2[key];
      }
    }
    convertRelative(initial, data2);
    return __privateMethod(this, _addAnimation, addAnimation_fn).call(this, initial, destination, duration, el, delay, ease, interpolate);
  }
  /**
   * Provides a tween from given position data to the current position.
   *
   * @param {PositionDataExtended} fromData - The starting position.
   *
   * @param {PositionDataExtended} toData - The ending position.
   *
   * @param {object}         [opts] - Optional parameters.
   *
   * @param {number}         [opts.delay=0] - Delay in seconds before animation starts.
   *
   * @param {number}         [opts.duration=1] - Duration in seconds.
   *
   * @param {Function}       [opts.ease=cubicOut] - Easing function.
   *
   * @param {Function}       [opts.interpolate=lerp] - Interpolation function.
   *
   * @returns {AnimationControl}  A control object that can cancel animation and provides a `finished` Promise.
   */
  fromTo(fromData, toData, { delay = 0, duration = 1, ease = cubicOut, interpolate = lerp$5 } = {}) {
    if (!isObject(fromData)) {
      throw new TypeError(`AnimationAPI.fromTo error: 'fromData' is not an object.`);
    }
    if (!isObject(toData)) {
      throw new TypeError(`AnimationAPI.fromTo error: 'toData' is not an object.`);
    }
    const parent = __privateGet(this, _position).parent;
    if (parent !== void 0 && typeof parent?.options?.positionable === "boolean" && !parent?.options?.positionable) {
      return AnimationControl.voidControl;
    }
    const targetEl = parent instanceof HTMLElement ? parent : parent?.elementTarget;
    const el = targetEl instanceof HTMLElement && targetEl.isConnected ? targetEl : void 0;
    if (!Number.isFinite(delay) || delay < 0) {
      throw new TypeError(`AnimationAPI.fromTo error: 'delay' is not a positive number.`);
    }
    if (!Number.isFinite(duration) || duration < 0) {
      throw new TypeError(`AnimationAPI.fromTo error: 'duration' is not a positive number.`);
    }
    if (typeof ease !== "function") {
      throw new TypeError(`AnimationAPI.fromTo error: 'ease' is not a function.`);
    }
    if (typeof interpolate !== "function") {
      throw new TypeError(`AnimationAPI.fromTo error: 'interpolate' is not a function.`);
    }
    const initial = {};
    const destination = {};
    const data2 = __privateGet(this, _data);
    for (const key in fromData) {
      if (toData[key] === void 0) {
        console.warn(
          `AnimationAPI.fromTo warning: key ('${key}') from 'fromData' missing in 'toData'; skipping this key.`
        );
        continue;
      }
      if (data2[key] !== void 0) {
        initial[key] = fromData[key];
        destination[key] = toData[key];
      }
    }
    convertRelative(initial, data2);
    convertRelative(destination, data2);
    return __privateMethod(this, _addAnimation, addAnimation_fn).call(this, initial, destination, duration, el, delay, ease, interpolate);
  }
  /**
   * Provides a tween to given position data from the current position.
   *
   * @param {PositionDataExtended} toData - The destination position.
   *
   * @param {object}         [opts] - Optional parameters.
   *
   * @param {number}         [opts.delay=0] - Delay in seconds before animation starts.
   *
   * @param {number}         [opts.duration=1] - Duration in seconds.
   *
   * @param {Function}       [opts.ease=cubicOut] - Easing function.
   *
   * @param {Function}       [opts.interpolate=lerp] - Interpolation function.
   *
   * @returns {AnimationControl}  A control object that can cancel animation and provides a `finished` Promise.
   */
  to(toData, { delay = 0, duration = 1, ease = cubicOut, interpolate = lerp$5 } = {}) {
    if (!isObject(toData)) {
      throw new TypeError(`AnimationAPI.to error: 'toData' is not an object.`);
    }
    const parent = __privateGet(this, _position).parent;
    if (parent !== void 0 && typeof parent?.options?.positionable === "boolean" && !parent?.options?.positionable) {
      return AnimationControl.voidControl;
    }
    const targetEl = parent instanceof HTMLElement ? parent : parent?.elementTarget;
    const el = targetEl instanceof HTMLElement && targetEl.isConnected ? targetEl : void 0;
    if (!Number.isFinite(delay) || delay < 0) {
      throw new TypeError(`AnimationAPI.to error: 'delay' is not a positive number.`);
    }
    if (!Number.isFinite(duration) || duration < 0) {
      throw new TypeError(`AnimationAPI.to error: 'duration' is not a positive number.`);
    }
    if (typeof ease !== "function") {
      throw new TypeError(`AnimationAPI.to error: 'ease' is not a function.`);
    }
    if (typeof interpolate !== "function") {
      throw new TypeError(`AnimationAPI.to error: 'interpolate' is not a function.`);
    }
    const initial = {};
    const destination = {};
    const data2 = __privateGet(this, _data);
    for (const key in toData) {
      if (data2[key] !== void 0 && toData[key] !== data2[key]) {
        destination[key] = toData[key];
        initial[key] = data2[key];
      }
    }
    convertRelative(destination, data2);
    return __privateMethod(this, _addAnimation, addAnimation_fn).call(this, initial, destination, duration, el, delay, ease, interpolate);
  }
  /**
   * Returns a function that provides an optimized way to constantly update a to-tween.
   *
   * @param {Iterable<string>}  keys - The keys for quickTo.
   *
   * @param {object}            [opts] - Optional parameters.
   *
   * @param {number}            [opts.duration=1] - Duration in seconds.
   *
   * @param {Function}          [opts.ease=cubicOut] - Easing function.
   *
   * @param {Function}          [opts.interpolate=lerp] - Interpolation function.
   *
   * @returns {quickToCallback} quick-to tween function.
   */
  quickTo(keys, { duration = 1, ease = cubicOut, interpolate = lerp$5 } = {}) {
    if (!isIterable(keys)) {
      throw new TypeError(`AnimationAPI.quickTo error: 'keys' is not an iterable list.`);
    }
    const parent = __privateGet(this, _position).parent;
    if (parent !== void 0 && typeof parent?.options?.positionable === "boolean" && !parent?.options?.positionable) {
      throw new Error(`AnimationAPI.quickTo error: 'parent' is not positionable.`);
    }
    if (!Number.isFinite(duration) || duration < 0) {
      throw new TypeError(`AnimationAPI.quickTo error: 'duration' is not a positive number.`);
    }
    if (typeof ease !== "function") {
      throw new TypeError(`AnimationAPI.quickTo error: 'ease' is not a function.`);
    }
    if (typeof interpolate !== "function") {
      throw new TypeError(`AnimationAPI.quickTo error: 'interpolate' is not a function.`);
    }
    const initial = {};
    const destination = {};
    const data2 = __privateGet(this, _data);
    for (const key of keys) {
      if (typeof key !== "string") {
        throw new TypeError(`AnimationAPI.quickTo error: key is not a string.`);
      }
      if (!animateKeys.has(key)) {
        throw new Error(`AnimationAPI.quickTo error: key ('${key}') is not animatable.`);
      }
      if (data2[key] !== void 0) {
        destination[key] = data2[key];
        initial[key] = data2[key];
      }
    }
    const keysArray = [...keys];
    Object.freeze(keysArray);
    const newData = Object.assign({ immediateElementUpdate: true }, initial);
    const animationData = {
      active: true,
      cleanup: __privateGet(this, _cleanup),
      cancelled: false,
      control: void 0,
      current: 0,
      destination,
      duration: duration * 1e3,
      // Internally the AnimationManager works in ms.
      ease,
      el: void 0,
      finished: true,
      // Note: start in finished state to add to AnimationManager on first callback.
      initial,
      interpolate,
      keys,
      newData,
      position: __privateGet(this, _position),
      resolve: void 0,
      start: void 0
    };
    const quickToCB = /* @__PURE__ */ __name((...args) => {
      const argsLength = args.length;
      if (argsLength === 0) {
        return;
      }
      for (let cntr = keysArray.length; --cntr >= 0; ) {
        const key = keysArray[cntr];
        if (data2[key] !== void 0) {
          initial[key] = data2[key];
        }
      }
      if (isObject(args[0])) {
        const objData = args[0];
        for (const key in objData) {
          if (destination[key] !== void 0) {
            destination[key] = objData[key];
          }
        }
      } else {
        for (let cntr = 0; cntr < argsLength && cntr < keysArray.length; cntr++) {
          const key = keysArray[cntr];
          if (destination[key] !== void 0) {
            destination[key] = args[cntr];
          }
        }
      }
      convertRelative(destination, data2);
      setNumericDefaults(initial);
      setNumericDefaults(destination);
      const targetEl = parent instanceof HTMLElement ? parent : parent?.elementTarget;
      animationData.el = targetEl instanceof HTMLElement && targetEl.isConnected ? targetEl : void 0;
      if (animationData.finished) {
        animationData.finished = false;
        animationData.active = true;
        animationData.current = 0;
        __privateWrapper(this, _instanceCount)._++;
        AnimationManager.add(animationData);
      } else {
        const now2 = performance.now();
        animationData.start = now2 + (AnimationManager.current - now2);
        animationData.current = 0;
      }
    }, "quickToCB");
    quickToCB.keys = keysArray;
    quickToCB.options = ({ duration: duration2, ease: ease2, interpolate: interpolate2 } = {}) => {
      if (duration2 !== void 0 && (!Number.isFinite(duration2) || duration2 < 0)) {
        throw new TypeError(`AnimationAPI.quickTo.options error: 'duration' is not a positive number.`);
      }
      if (ease2 !== void 0 && typeof ease2 !== "function") {
        throw new TypeError(`AnimationAPI.quickTo.options error: 'ease' is not a function.`);
      }
      if (interpolate2 !== void 0 && typeof interpolate2 !== "function") {
        throw new TypeError(`AnimationAPI.quickTo.options error: 'interpolate' is not a function.`);
      }
      if (duration2 >= 0) {
        animationData.duration = duration2 * 1e3;
      }
      if (ease2) {
        animationData.ease = ease2;
      }
      if (interpolate2) {
        animationData.interpolate = interpolate2;
      }
      return quickToCB;
    };
    return quickToCB;
  }
};
_data = new WeakMap();
_position = new WeakMap();
_instanceCount = new WeakMap();
_cleanup = new WeakMap();
_addAnimation = new WeakSet();
addAnimation_fn = /* @__PURE__ */ __name(function(initial, destination, duration, el, delay, ease, interpolate) {
  setNumericDefaults(initial);
  setNumericDefaults(destination);
  for (const key in initial) {
    if (!Number.isFinite(initial[key])) {
      delete initial[key];
    }
  }
  const keys = Object.keys(initial);
  const newData = Object.assign({ immediateElementUpdate: true }, initial);
  if (keys.length === 0) {
    return AnimationControl.voidControl;
  }
  const animationData = {
    active: true,
    cleanup: __privateGet(this, _cleanup),
    cancelled: false,
    control: void 0,
    current: 0,
    destination,
    duration: duration * 1e3,
    // Internally the AnimationManager works in ms.
    ease,
    el,
    finished: false,
    initial,
    interpolate,
    keys,
    newData,
    position: __privateGet(this, _position),
    resolve: void 0,
    start: void 0
  };
  if (delay > 0) {
    animationData.active = false;
    setTimeout(() => {
      if (!animationData.cancelled) {
        animationData.active = true;
        const now2 = performance.now();
        animationData.start = now2 + (AnimationManager.current - now2);
      }
    }, delay * 1e3);
  }
  __privateWrapper(this, _instanceCount)._++;
  AnimationManager.add(animationData);
  return new AnimationControl(animationData, true);
}, "#addAnimation");
_cleanupInstance = new WeakSet();
cleanupInstance_fn = /* @__PURE__ */ __name(function(data2) {
  __privateWrapper(this, _instanceCount)._--;
  data2.active = false;
  data2.finished = true;
  if (typeof data2.resolve === "function") {
    data2.resolve(data2.cancelled);
  }
}, "#cleanupInstance");
__name(_AnimationAPI, "AnimationAPI");
let AnimationAPI = _AnimationAPI;
const _AnimationGroupControl = class _AnimationGroupControl {
  /**
   * @param {AnimationControl[]} animationControls - An array of AnimationControl instances.
   */
  constructor(animationControls) {
    /** @type {AnimationControl[]} */
    __privateAdd(this, _animationControls, void 0);
    /** @type {Promise<Awaited<unknown>[]>} */
    __privateAdd(this, _finishedPromise2, void 0);
    __privateSet(this, _animationControls, animationControls);
  }
  /**
   * Provides a static void / undefined AnimationGroupControl that is automatically resolved.
   *
   * @returns {AnimationGroupControl} Void AnimationGroupControl
   */
  static get voidControl() {
    return __privateGet(this, _voidControl2);
  }
  /**
   * Get a promise that resolves when all animations are finished.
   *
   * @returns {Promise<Awaited<unknown>[]>|Promise<void>} Finished Promise for all animations.
   */
  get finished() {
    const animationControls = __privateGet(this, _animationControls);
    if (animationControls === null || animationControls === void 0) {
      return Promise.resolve();
    }
    if (!(__privateGet(this, _finishedPromise2) instanceof Promise)) {
      const promises = [];
      for (let cntr = animationControls.length; --cntr >= 0; ) {
        promises.push(animationControls[cntr].finished);
      }
      __privateSet(this, _finishedPromise2, Promise.all(promises));
    }
    return __privateGet(this, _finishedPromise2);
  }
  /**
   * Returns whether there are active animation instances for this group.
   *
   * Note: a delayed animation may not be started / active yet. Use {@link AnimationGroupControl.isFinished} to
   * determine if all animations in the group are finished.
   *
   * @returns {boolean} Are there active animation instances.
   */
  get isActive() {
    const animationControls = __privateGet(this, _animationControls);
    if (animationControls === null || animationControls === void 0) {
      return false;
    }
    for (let cntr = animationControls.length; --cntr >= 0; ) {
      if (animationControls[cntr].isActive) {
        return true;
      }
    }
    return false;
  }
  /**
   * Returns whether all animations in the group are finished.
   *
   * @returns {boolean} Are all animation instances finished.
   */
  get isFinished() {
    const animationControls = __privateGet(this, _animationControls);
    if (animationControls === null || animationControls === void 0) {
      return true;
    }
    for (let cntr = animationControls.length; --cntr >= 0; ) {
      if (!animationControls[cntr].isFinished) {
        return false;
      }
    }
    return false;
  }
  /**
   * Cancels the all animations.
   */
  cancel() {
    const animationControls = __privateGet(this, _animationControls);
    if (animationControls === null || animationControls === void 0) {
      return;
    }
    for (let cntr = __privateGet(this, _animationControls).length; --cntr >= 0; ) {
      __privateGet(this, _animationControls)[cntr].cancel();
    }
  }
};
_animationControls = new WeakMap();
_finishedPromise2 = new WeakMap();
_voidControl2 = new WeakMap();
__name(_AnimationGroupControl, "AnimationGroupControl");
/**
 * Defines a static empty / void animation control.
 *
 * @type {AnimationGroupControl}
 */
__privateAdd(_AnimationGroupControl, _voidControl2, new _AnimationGroupControl(null));
let AnimationGroupControl = _AnimationGroupControl;
const _AnimationGroupAPI = class _AnimationGroupAPI {
  /**
   * Cancels any animation for given Position data.
   *
   * @param {Position|{position: Position}|Iterable<Position>|Iterable<{position: Position}>} position -
   */
  static cancel(position) {
    if (isIterable(position)) {
      let index2 = -1;
      for (const entry of position) {
        index2++;
        const actualPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry) ? entry : entry.position;
        if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
          console.warn(`AnimationGroupAPI.cancel warning: No Position instance found at index: ${index2}.`);
          continue;
        }
        AnimationManager.cancel(actualPosition);
      }
    } else {
      const actualPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position) ? position : position.position;
      if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
        console.warn(`AnimationGroupAPI.cancel warning: No Position instance found.`);
        return;
      }
      AnimationManager.cancel(actualPosition);
    }
  }
  /**
   * Cancels all Position animation.
   */
  static cancelAll() {
    AnimationManager.cancelAll();
  }
  /**
   * Gets all animation controls for the given position data.
   *
   * @param {Position|{position: Position}|Iterable<Position>|Iterable<{position: Position}>} position -
   *
   * @returns {{position: Position, data: object|void, controls: AnimationControl[]}[]} Results array.
   */
  static getScheduled(position) {
    const results = [];
    if (isIterable(position)) {
      let index2 = -1;
      for (const entry of position) {
        index2++;
        const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry);
        const actualPosition = isPosition ? entry : entry.position;
        if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
          console.warn(`AnimationGroupAPI.getScheduled warning: No Position instance found at index: ${index2}.`);
          continue;
        }
        const controls = AnimationManager.getScheduled(actualPosition);
        results.push({ position: actualPosition, data: isPosition ? void 0 : entry, controls });
      }
    } else {
      const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position);
      const actualPosition = isPosition ? position : position.position;
      if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
        console.warn(`AnimationGroupAPI.getScheduled warning: No Position instance found.`);
        return results;
      }
      const controls = AnimationManager.getScheduled(actualPosition);
      results.push({ position: actualPosition, data: isPosition ? void 0 : position, controls });
    }
    return results;
  }
  /**
   * Provides the `from` animation tween for one or more Position instances as a group.
   *
   * @param {Position|{position: Position}|Iterable<Position>|Iterable<{position: Position}>} position -
   *
   * @param {object|Function}   fromData -
   *
   * @param {object|Function}   options -
   *
   * @returns {TJSBasicAnimation} Basic animation control.
   */
  static from(position, fromData, options) {
    if (!isObject(fromData) && typeof fromData !== "function") {
      throw new TypeError(`AnimationGroupAPI.from error: 'fromData' is not an object or function.`);
    }
    if (options !== void 0 && !isObject(options) && typeof options !== "function") {
      throw new TypeError(`AnimationGroupAPI.from error: 'options' is not an object or function.`);
    }
    const animationControls = [];
    let index2 = -1;
    let callbackOptions;
    const hasDataCallback = typeof fromData === "function";
    const hasOptionCallback = typeof options === "function";
    const hasCallback = hasDataCallback || hasOptionCallback;
    if (hasCallback) {
      callbackOptions = { index: index2, position: void 0, data: void 0 };
    }
    let actualFromData = fromData;
    let actualOptions = options;
    if (isIterable(position)) {
      for (const entry of position) {
        index2++;
        const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry);
        const actualPosition = isPosition ? entry : entry.position;
        if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
          console.warn(`AnimationGroupAPI.from warning: No Position instance found at index: ${index2}.`);
          continue;
        }
        if (hasCallback) {
          callbackOptions.index = index2;
          callbackOptions.position = position;
          callbackOptions.data = isPosition ? void 0 : entry;
        }
        if (hasDataCallback) {
          actualFromData = fromData(callbackOptions);
          if (actualFromData === null || actualFromData === void 0) {
            continue;
          }
          if (typeof actualFromData !== "object") {
            throw new TypeError(`AnimationGroupAPI.from error: fromData callback function iteration(${index2}) failed to return an object.`);
          }
        }
        if (hasOptionCallback) {
          actualOptions = options(callbackOptions);
          if (actualOptions === null || actualOptions === void 0) {
            continue;
          }
          if (typeof actualOptions !== "object") {
            throw new TypeError(`AnimationGroupAPI.from error: options callback function iteration(${index2}) failed to return an object.`);
          }
        }
        animationControls.push(actualPosition.animate.from(actualFromData, actualOptions));
      }
    } else {
      const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position);
      const actualPosition = isPosition ? position : position.position;
      if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
        console.warn(`AnimationGroupAPI.from warning: No Position instance found.`);
        return AnimationGroupControl.voidControl;
      }
      if (hasCallback) {
        callbackOptions.index = 0;
        callbackOptions.position = position;
        callbackOptions.data = isPosition ? void 0 : position;
      }
      if (hasDataCallback) {
        actualFromData = fromData(callbackOptions);
        if (typeof actualFromData !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.from error: fromData callback function failed to return an object.`
          );
        }
      }
      if (hasOptionCallback) {
        actualOptions = options(callbackOptions);
        if (typeof actualOptions !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.from error: options callback function failed to return an object.`
          );
        }
      }
      animationControls.push(actualPosition.animate.from(actualFromData, actualOptions));
    }
    return new AnimationGroupControl(animationControls);
  }
  /**
   * Provides the `fromTo` animation tween for one or more Position instances as a group.
   *
   * @param {Position|{position: Position}|Iterable<Position>|Iterable<{position: Position}>} position -
   *
   * @param {object|Function}   fromData -
   *
   * @param {object|Function}   toData -
   *
   * @param {object|Function}   options -
   *
   * @returns {TJSBasicAnimation} Basic animation control.
   */
  static fromTo(position, fromData, toData, options) {
    if (!isObject(fromData) && typeof fromData !== "function") {
      throw new TypeError(`AnimationGroupAPI.fromTo error: 'fromData' is not an object or function.`);
    }
    if (!isObject(toData) && typeof toData !== "function") {
      throw new TypeError(`AnimationGroupAPI.fromTo error: 'toData' is not an object or function.`);
    }
    if (options !== void 0 && !isObject(options) && typeof options !== "function") {
      throw new TypeError(`AnimationGroupAPI.fromTo error: 'options' is not an object or function.`);
    }
    const animationControls = [];
    let index2 = -1;
    let callbackOptions;
    const hasFromCallback = typeof fromData === "function";
    const hasToCallback = typeof toData === "function";
    const hasOptionCallback = typeof options === "function";
    const hasCallback = hasFromCallback || hasToCallback || hasOptionCallback;
    if (hasCallback) {
      callbackOptions = { index: index2, position: void 0, data: void 0 };
    }
    let actualFromData = fromData;
    let actualToData = toData;
    let actualOptions = options;
    if (isIterable(position)) {
      for (const entry of position) {
        index2++;
        const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry);
        const actualPosition = isPosition ? entry : entry.position;
        if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
          console.warn(`AnimationGroupAPI.fromTo warning: No Position instance found at index: ${index2}.`);
          continue;
        }
        if (hasCallback) {
          callbackOptions.index = index2;
          callbackOptions.position = position;
          callbackOptions.data = isPosition ? void 0 : entry;
        }
        if (hasFromCallback) {
          actualFromData = fromData(callbackOptions);
          if (actualFromData === null || actualFromData === void 0) {
            continue;
          }
          if (typeof actualFromData !== "object") {
            throw new TypeError(`AnimationGroupAPI.fromTo error: fromData callback function iteration(${index2}) failed to return an object.`);
          }
        }
        if (hasToCallback) {
          actualToData = toData(callbackOptions);
          if (actualToData === null || actualToData === void 0) {
            continue;
          }
          if (typeof actualToData !== "object") {
            throw new TypeError(`AnimationGroupAPI.fromTo error: toData callback function iteration(${index2}) failed to return an object.`);
          }
        }
        if (hasOptionCallback) {
          actualOptions = options(callbackOptions);
          if (actualOptions === null || actualOptions === void 0) {
            continue;
          }
          if (typeof actualOptions !== "object") {
            throw new TypeError(`AnimationGroupAPI.fromTo error: options callback function iteration(${index2}) failed to return an object.`);
          }
        }
        animationControls.push(actualPosition.animate.fromTo(actualFromData, actualToData, actualOptions));
      }
    } else {
      const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position);
      const actualPosition = isPosition ? position : position.position;
      if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
        console.warn(`AnimationGroupAPI.fromTo warning: No Position instance found.`);
        return AnimationGroupControl.voidControl;
      }
      if (hasCallback) {
        callbackOptions.index = 0;
        callbackOptions.position = position;
        callbackOptions.data = isPosition ? void 0 : position;
      }
      if (hasFromCallback) {
        actualFromData = fromData(callbackOptions);
        if (typeof actualFromData !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.fromTo error: fromData callback function failed to return an object.`
          );
        }
      }
      if (hasToCallback) {
        actualToData = toData(callbackOptions);
        if (typeof actualToData !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.fromTo error: toData callback function failed to return an object.`
          );
        }
      }
      if (hasOptionCallback) {
        actualOptions = options(callbackOptions);
        if (typeof actualOptions !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.fromTo error: options callback function failed to return an object.`
          );
        }
      }
      animationControls.push(actualPosition.animate.fromTo(actualFromData, actualToData, actualOptions));
    }
    return new AnimationGroupControl(animationControls);
  }
  /**
   * Provides the `to` animation tween for one or more Position instances as a group.
   *
   * @param {Position|{position: Position}|Iterable<Position>|Iterable<{position: Position}>} position -
   *
   * @param {object|Function}   toData -
   *
   * @param {object|Function}   options -
   *
   * @returns {TJSBasicAnimation} Basic animation control.
   */
  static to(position, toData, options) {
    if (!isObject(toData) && typeof toData !== "function") {
      throw new TypeError(`AnimationGroupAPI.to error: 'toData' is not an object or function.`);
    }
    if (options !== void 0 && !isObject(options) && typeof options !== "function") {
      throw new TypeError(`AnimationGroupAPI.to error: 'options' is not an object or function.`);
    }
    const animationControls = [];
    let index2 = -1;
    let callbackOptions;
    const hasDataCallback = typeof toData === "function";
    const hasOptionCallback = typeof options === "function";
    const hasCallback = hasDataCallback || hasOptionCallback;
    if (hasCallback) {
      callbackOptions = { index: index2, position: void 0, data: void 0 };
    }
    let actualToData = toData;
    let actualOptions = options;
    if (isIterable(position)) {
      for (const entry of position) {
        index2++;
        const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry);
        const actualPosition = isPosition ? entry : entry.position;
        if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
          console.warn(`AnimationGroupAPI.to warning: No Position instance found at index: ${index2}.`);
          continue;
        }
        if (hasCallback) {
          callbackOptions.index = index2;
          callbackOptions.position = position;
          callbackOptions.data = isPosition ? void 0 : entry;
        }
        if (hasDataCallback) {
          actualToData = toData(callbackOptions);
          if (actualToData === null || actualToData === void 0) {
            continue;
          }
          if (typeof actualToData !== "object") {
            throw new TypeError(`AnimationGroupAPI.to error: toData callback function iteration(${index2}) failed to return an object.`);
          }
        }
        if (hasOptionCallback) {
          actualOptions = options(callbackOptions);
          if (actualOptions === null || actualOptions === void 0) {
            continue;
          }
          if (typeof actualOptions !== "object") {
            throw new TypeError(`AnimationGroupAPI.to error: options callback function iteration(${index2}) failed to return an object.`);
          }
        }
        animationControls.push(actualPosition.animate.to(actualToData, actualOptions));
      }
    } else {
      const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position);
      const actualPosition = isPosition ? position : position.position;
      if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
        console.warn(`AnimationGroupAPI.to warning: No Position instance found.`);
        return AnimationGroupControl.voidControl;
      }
      if (hasCallback) {
        callbackOptions.index = 0;
        callbackOptions.position = position;
        callbackOptions.data = isPosition ? void 0 : position;
      }
      if (hasDataCallback) {
        actualToData = toData(callbackOptions);
        if (typeof actualToData !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.to error: toData callback function failed to return an object.`
          );
        }
      }
      if (hasOptionCallback) {
        actualOptions = options(callbackOptions);
        if (typeof actualOptions !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.to error: options callback function failed to return an object.`
          );
        }
      }
      animationControls.push(actualPosition.animate.to(actualToData, actualOptions));
    }
    return new AnimationGroupControl(animationControls);
  }
  /**
   * Provides the `to` animation tween for one or more Position instances as a group.
   *
   * @param {Position|{position: Position}|Iterable<Position>|Iterable<{position: Position}>} position -
   *
   * @param {Iterable<string>}  keys -
   *
   * @param {object|Function}   options -
   *
   * @returns {quickToCallback} Basic animation control.
   */
  static quickTo(position, keys, options) {
    if (!isIterable(keys)) {
      throw new TypeError(`AnimationGroupAPI.quickTo error: 'keys' is not an iterable list.`);
    }
    if (options !== void 0 && !isObject(options) && typeof options !== "function") {
      throw new TypeError(`AnimationGroupAPI.quickTo error: 'options' is not an object or function.`);
    }
    const quickToCallbacks = [];
    let index2 = -1;
    const hasOptionCallback = typeof options === "function";
    const callbackOptions = { index: index2, position: void 0, data: void 0 };
    let actualOptions = options;
    if (isIterable(position)) {
      for (const entry of position) {
        index2++;
        const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry);
        const actualPosition = isPosition ? entry : entry.position;
        if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
          console.warn(`AnimationGroupAPI.quickTo warning: No Position instance found at index: ${index2}.`);
          continue;
        }
        callbackOptions.index = index2;
        callbackOptions.position = position;
        callbackOptions.data = isPosition ? void 0 : entry;
        if (hasOptionCallback) {
          actualOptions = options(callbackOptions);
          if (actualOptions === null || actualOptions === void 0) {
            continue;
          }
          if (typeof actualOptions !== "object") {
            throw new TypeError(`AnimationGroupAPI.quickTo error: options callback function iteration(${index2}) failed to return an object.`);
          }
        }
        quickToCallbacks.push(actualPosition.animate.quickTo(keys, actualOptions));
      }
    } else {
      const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position);
      const actualPosition = isPosition ? position : position.position;
      if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
        console.warn(`AnimationGroupAPI.quickTo warning: No Position instance found.`);
        return () => null;
      }
      callbackOptions.index = 0;
      callbackOptions.position = position;
      callbackOptions.data = isPosition ? void 0 : position;
      if (hasOptionCallback) {
        actualOptions = options(callbackOptions);
        if (typeof actualOptions !== "object") {
          throw new TypeError(
            `AnimationGroupAPI.quickTo error: options callback function failed to return an object.`
          );
        }
      }
      quickToCallbacks.push(actualPosition.animate.quickTo(keys, actualOptions));
    }
    const keysArray = [...keys];
    Object.freeze(keysArray);
    const quickToCB = /* @__PURE__ */ __name((...args) => {
      const argsLength = args.length;
      if (argsLength === 0) {
        return;
      }
      if (typeof args[0] === "function") {
        const dataCallback = args[0];
        index2 = -1;
        let cntr = 0;
        if (isIterable(position)) {
          for (const entry of position) {
            index2++;
            const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry);
            const actualPosition = isPosition ? entry : entry.position;
            if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
              continue;
            }
            callbackOptions.index = index2;
            callbackOptions.position = position;
            callbackOptions.data = isPosition ? void 0 : entry;
            const toData = dataCallback(callbackOptions);
            if (toData === null || toData === void 0) {
              continue;
            }
            const toDataIterable = isIterable(toData);
            if (!Number.isFinite(toData) && !toDataIterable && typeof toData !== "object") {
              throw new TypeError(`AnimationGroupAPI.quickTo error: toData callback function iteration(${index2}) failed to return a finite number, iterable list, or object.`);
            }
            if (toDataIterable) {
              quickToCallbacks[cntr++](...toData);
            } else {
              quickToCallbacks[cntr++](toData);
            }
          }
        } else {
          const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position);
          const actualPosition = isPosition ? position : position.position;
          if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
            return;
          }
          callbackOptions.index = 0;
          callbackOptions.position = position;
          callbackOptions.data = isPosition ? void 0 : position;
          const toData = dataCallback(callbackOptions);
          if (toData === null || toData === void 0) {
            return;
          }
          const toDataIterable = isIterable(toData);
          if (!Number.isFinite(toData) && !toDataIterable && typeof toData !== "object") {
            throw new TypeError(`AnimationGroupAPI.quickTo error: toData callback function iteration(${index2}) failed to return a finite number, iterable list, or object.`);
          }
          if (toDataIterable) {
            quickToCallbacks[cntr++](...toData);
          } else {
            quickToCallbacks[cntr++](toData);
          }
        }
      } else {
        for (let cntr = quickToCallbacks.length; --cntr >= 0; ) {
          quickToCallbacks[cntr](...args);
        }
      }
    }, "quickToCB");
    quickToCB.keys = keysArray;
    quickToCB.options = (options2) => {
      if (options2 !== void 0 && !isObject(options2) && typeof options2 !== "function") {
        throw new TypeError(`AnimationGroupAPI.quickTo error: 'options' is not an object or function.`);
      }
      if (isObject(options2)) {
        for (let cntr = quickToCallbacks.length; --cntr >= 0; ) {
          quickToCallbacks[cntr].options(options2);
        }
      } else if (typeof options2 === "function") {
        if (isIterable(position)) {
          index2 = -1;
          let cntr = 0;
          for (const entry of position) {
            index2++;
            const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, entry);
            const actualPosition = isPosition ? entry : entry.position;
            if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
              console.warn(
                `AnimationGroupAPI.quickTo.options warning: No Position instance found at index: ${index2}.`
              );
              continue;
            }
            callbackOptions.index = index2;
            callbackOptions.position = position;
            callbackOptions.data = isPosition ? void 0 : entry;
            actualOptions = options2(callbackOptions);
            if (actualOptions === null || actualOptions === void 0) {
              continue;
            }
            if (typeof actualOptions !== "object") {
              throw new TypeError(
                `AnimationGroupAPI.quickTo.options error: options callback function iteration(${index2}) failed to return an object.`
              );
            }
            quickToCallbacks[cntr++].options(actualOptions);
          }
        } else {
          const isPosition = __privateMethod(this, _isPosition, isPosition_fn).call(this, position);
          const actualPosition = isPosition ? position : position.position;
          if (!__privateMethod(this, _isPosition, isPosition_fn).call(this, actualPosition)) {
            console.warn(`AnimationGroupAPI.quickTo.options warning: No Position instance found.`);
            return quickToCB;
          }
          callbackOptions.index = 0;
          callbackOptions.position = position;
          callbackOptions.data = isPosition ? void 0 : position;
          actualOptions = options2(callbackOptions);
          if (typeof actualOptions !== "object") {
            throw new TypeError(
              `AnimationGroupAPI.quickTo error: options callback function failed to return an object.`
            );
          }
          quickToCallbacks[0].options(actualOptions);
        }
      }
      return quickToCB;
    };
    return quickToCB;
  }
};
_isPosition = new WeakSet();
isPosition_fn = /* @__PURE__ */ __name(function(object) {
  return isObject(object) && object.animate instanceof AnimationAPI;
}, "#isPosition");
/**
 * Checks of the given object is a Position instance by checking for AnimationAPI.
 *
 * @param {*}  object - Any data.
 *
 * @returns {boolean} Is Position.
 */
__privateAdd(_AnimationGroupAPI, _isPosition);
__name(_AnimationGroupAPI, "AnimationGroupAPI");
let AnimationGroupAPI = _AnimationGroupAPI;
const _Centered = class _Centered {
  constructor({ element: element2, lock = false, width, height } = {}) {
    /**
     * @type {HTMLElement}
     */
    __privateAdd(this, _element, void 0);
    /**
     * Provides a manual setting of the element height. As things go `offsetHeight` causes a browser layout and is not
     * performance oriented. If manually set this height is used instead of `offsetHeight`.
     *
     * @type {number}
     */
    __privateAdd(this, _height, void 0);
    /**
     * Set from an optional value in the constructor to lock accessors preventing modification.
     */
    __privateAdd(this, _lock, void 0);
    /**
     * Provides a manual setting of the element width. As things go `offsetWidth` causes a browser layout and is not
     * performance oriented. If manually set this width is used instead of `offsetWidth`.
     *
     * @type {number}
     */
    __privateAdd(this, _width, void 0);
    this.element = element2;
    this.width = width;
    this.height = height;
    __privateSet(this, _lock, typeof lock === "boolean" ? lock : false);
  }
  get element() {
    return __privateGet(this, _element);
  }
  get height() {
    return __privateGet(this, _height);
  }
  get width() {
    return __privateGet(this, _width);
  }
  set element(element2) {
    if (__privateGet(this, _lock)) {
      return;
    }
    if (element2 === void 0 || element2 === null || element2 instanceof HTMLElement) {
      __privateSet(this, _element, element2);
    } else {
      throw new TypeError(`'element' is not a HTMLElement, undefined, or null.`);
    }
  }
  set height(height) {
    if (__privateGet(this, _lock)) {
      return;
    }
    if (height === void 0 || Number.isFinite(height)) {
      __privateSet(this, _height, height);
    } else {
      throw new TypeError(`'height' is not a finite number or undefined.`);
    }
  }
  set width(width) {
    if (__privateGet(this, _lock)) {
      return;
    }
    if (width === void 0 || Number.isFinite(width)) {
      __privateSet(this, _width, width);
    } else {
      throw new TypeError(`'width' is not a finite number or undefined.`);
    }
  }
  setDimension(width, height) {
    if (__privateGet(this, _lock)) {
      return;
    }
    if (width === void 0 || Number.isFinite(width)) {
      __privateSet(this, _width, width);
    } else {
      throw new TypeError(`'width' is not a finite number or undefined.`);
    }
    if (height === void 0 || Number.isFinite(height)) {
      __privateSet(this, _height, height);
    } else {
      throw new TypeError(`'height' is not a finite number or undefined.`);
    }
  }
  getLeft(width) {
    const boundsWidth = __privateGet(this, _width) ?? __privateGet(this, _element)?.offsetWidth ?? globalThis.innerWidth;
    return (boundsWidth - width) / 2;
  }
  getTop(height) {
    const boundsHeight = __privateGet(this, _height) ?? __privateGet(this, _element)?.offsetHeight ?? globalThis.innerHeight;
    return (boundsHeight - height) / 2;
  }
};
_element = new WeakMap();
_height = new WeakMap();
_lock = new WeakMap();
_width = new WeakMap();
__name(_Centered, "Centered");
let Centered = _Centered;
const browserCentered = new Centered();
const positionInitial = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  Centered,
  browserCentered
}, Symbol.toStringTag, { value: "Module" }));
const _PositionChangeSet = class _PositionChangeSet {
  constructor() {
    this.left = false;
    this.top = false;
    this.width = false;
    this.height = false;
    this.maxHeight = false;
    this.maxWidth = false;
    this.minHeight = false;
    this.minWidth = false;
    this.zIndex = false;
    this.transform = false;
    this.transformOrigin = false;
  }
  hasChange() {
    return this.left || this.top || this.width || this.height || this.maxHeight || this.maxWidth || this.minHeight || this.minWidth || this.zIndex || this.transform || this.transformOrigin;
  }
  set(value) {
    this.left = value;
    this.top = value;
    this.width = value;
    this.height = value;
    this.maxHeight = value;
    this.maxWidth = value;
    this.minHeight = value;
    this.minWidth = value;
    this.zIndex = value;
    this.transform = value;
    this.transformOrigin = value;
  }
};
__name(_PositionChangeSet, "PositionChangeSet");
let PositionChangeSet = _PositionChangeSet;
const _PositionData = class _PositionData {
  constructor({
    height = null,
    left = null,
    maxHeight = null,
    maxWidth = null,
    minHeight = null,
    minWidth = null,
    rotateX = null,
    rotateY = null,
    rotateZ = null,
    scale = null,
    translateX = null,
    translateY = null,
    translateZ = null,
    top = null,
    transformOrigin = null,
    width = null,
    zIndex = null
  } = {}) {
    this.height = height;
    this.left = left;
    this.maxHeight = maxHeight;
    this.maxWidth = maxWidth;
    this.minHeight = minHeight;
    this.minWidth = minWidth;
    this.rotateX = rotateX;
    this.rotateY = rotateY;
    this.rotateZ = rotateZ;
    this.scale = scale;
    this.top = top;
    this.transformOrigin = transformOrigin;
    this.translateX = translateX;
    this.translateY = translateY;
    this.translateZ = translateZ;
    this.width = width;
    this.zIndex = zIndex;
    Object.seal(this);
  }
  /**
   * Copies given data to this instance.
   *
   * @param {PositionData}   data - Copy from this instance.
   *
   * @returns {PositionData} This instance.
   */
  copy(data2) {
    this.height = data2.height;
    this.left = data2.left;
    this.maxHeight = data2.maxHeight;
    this.maxWidth = data2.maxWidth;
    this.minHeight = data2.minHeight;
    this.minWidth = data2.minWidth;
    this.rotateX = data2.rotateX;
    this.rotateY = data2.rotateY;
    this.rotateZ = data2.rotateZ;
    this.scale = data2.scale;
    this.top = data2.top;
    this.transformOrigin = data2.transformOrigin;
    this.translateX = data2.translateX;
    this.translateY = data2.translateY;
    this.translateZ = data2.translateZ;
    this.width = data2.width;
    this.zIndex = data2.zIndex;
    return this;
  }
};
__name(_PositionData, "PositionData");
let PositionData = _PositionData;
const _PositionStateAPI = class _PositionStateAPI {
  constructor(position, data2, transforms) {
    /** @type {PositionData} */
    __privateAdd(this, _data2, void 0);
    /**
     * @type {Map<string, PositionDataExtended>}
     */
    __privateAdd(this, _dataSaved, /* @__PURE__ */ new Map());
    /** @type {Position} */
    __privateAdd(this, _position2, void 0);
    /** @type {Transforms} */
    __privateAdd(this, _transforms, void 0);
    __privateSet(this, _position2, position);
    __privateSet(this, _data2, data2);
    __privateSet(this, _transforms, transforms);
  }
  /**
   * Returns any stored save state by name.
   *
   * @param {string}   name - Saved data set name.
   *
   * @returns {PositionDataExtended} The saved data set.
   */
  get({ name }) {
    if (typeof name !== "string") {
      throw new TypeError(`Position - getSave error: 'name' is not a string.`);
    }
    return __privateGet(this, _dataSaved).get(name);
  }
  /**
   * Returns any associated default data.
   *
   * @returns {PositionDataExtended} Associated default data.
   */
  getDefault() {
    return __privateGet(this, _dataSaved).get("#defaultData");
  }
  /**
   * Removes and returns any position state by name.
   *
   * @param {object}   options - Options.
   *
   * @param {string}   options.name - Name to remove and retrieve.
   *
   * @returns {PositionDataExtended} Saved position data.
   */
  remove({ name }) {
    if (typeof name !== "string") {
      throw new TypeError(`Position - remove: 'name' is not a string.`);
    }
    const data2 = __privateGet(this, _dataSaved).get(name);
    __privateGet(this, _dataSaved).delete(name);
    return data2;
  }
  /**
   * Resets data to default values and invokes set.
   *
   * @param {object}   [opts] - Optional parameters.
   *
   * @param {boolean}  [opts.keepZIndex=false] - When true keeps current z-index.
   *
   * @param {boolean}  [opts.invokeSet=true] - When true invokes set method.
   *
   * @returns {boolean} Operation successful.
   */
  reset({ keepZIndex = false, invokeSet = true } = {}) {
    const defaultData = __privateGet(this, _dataSaved).get("#defaultData");
    if (typeof defaultData !== "object") {
      return false;
    }
    if (__privateGet(this, _position2).animate.isScheduled) {
      __privateGet(this, _position2).animate.cancel();
    }
    const zIndex = __privateGet(this, _position2).zIndex;
    const data2 = Object.assign({}, defaultData);
    if (keepZIndex) {
      data2.zIndex = zIndex;
    }
    __privateGet(this, _transforms).reset(data2);
    if (__privateGet(this, _position2).parent?.reactive?.minimized) {
      __privateGet(this, _position2).parent?.maximize?.({ animate: false, duration: 0 });
    }
    if (invokeSet) {
      setTimeout(() => __privateGet(this, _position2).set(data2), 0);
    }
    return true;
  }
  /**
   * Restores a saved positional state returning the data. Several optional parameters are available
   * to control whether the restore action occurs silently (no store / inline styles updates), animates
   * to the stored data, or simply sets the stored data. Restoring via {@link AnimationAPI.to} allows
   * specification of the duration, easing, and interpolate functions along with configuring a Promise to be
   * returned if awaiting the end of the animation.
   *
   * @param {object}            params - Parameters
   *
   * @param {string}            params.name - Saved data set name.
   *
   * @param {boolean}           [params.remove=false] - Remove data set.
   *
   * @param {Iterable<string>}  [params.properties] - Specific properties to set / animate.
   *
   * @param {boolean}           [params.silent] - Set position data directly; no store or style updates.
   *
   * @param {boolean}           [params.async=false] - If animating return a Promise that resolves with any saved data.
   *
   * @param {boolean}           [params.animateTo=false] - Animate to restore data.
   *
   * @param {number}            [params.duration=0.1] - Duration in seconds.
   *
   * @param {Function}          [params.ease=linear] - Easing function.
   *
   * @param {Function}          [params.interpolate=lerp] - Interpolation function.
   *
   * @returns {PositionDataExtended|Promise<PositionDataExtended>} Saved position data.
   */
  restore({
    name,
    remove = false,
    properties,
    silent = false,
    async = false,
    animateTo = false,
    duration = 0.1,
    ease = identity,
    interpolate = lerp$5
  }) {
    if (typeof name !== "string") {
      throw new TypeError(`Position - restore error: 'name' is not a string.`);
    }
    const dataSaved = __privateGet(this, _dataSaved).get(name);
    if (dataSaved) {
      if (remove) {
        __privateGet(this, _dataSaved).delete(name);
      }
      let data2 = dataSaved;
      if (isIterable(properties)) {
        data2 = {};
        for (const property of properties) {
          data2[property] = dataSaved[property];
        }
      }
      if (silent) {
        for (const property in data2) {
          __privateGet(this, _data2)[property] = data2[property];
        }
        return dataSaved;
      } else if (animateTo) {
        if (data2.transformOrigin !== __privateGet(this, _position2).transformOrigin) {
          __privateGet(this, _position2).transformOrigin = data2.transformOrigin;
        }
        if (async) {
          return __privateGet(this, _position2).animate.to(data2, { duration, ease, interpolate }).finished.then(() => dataSaved);
        } else {
          __privateGet(this, _position2).animate.to(data2, { duration, ease, interpolate });
        }
      } else {
        __privateGet(this, _position2).set(data2);
      }
    }
    return dataSaved;
  }
  /**
   * Saves current position state with the opportunity to add extra data to the saved state.
   *
   * @param {object}   opts - Options.
   *
   * @param {string}   opts.name - name to index this saved data.
   *
   * @param {...*}     [opts.extra] - Extra data to add to saved data.
   *
   * @returns {PositionData} Current position data
   */
  save({ name, ...extra }) {
    if (typeof name !== "string") {
      throw new TypeError(`Position - save error: 'name' is not a string.`);
    }
    const data2 = __privateGet(this, _position2).get(extra);
    __privateGet(this, _dataSaved).set(name, data2);
    return data2;
  }
  /**
   * Directly sets a position state.
   *
   * @param {object}   opts - Options.
   *
   * @param {string}   opts.name - name to index this saved data.
   *
   * @param {...*}     [opts.data] - Position data to set.
   */
  set({ name, ...data2 }) {
    if (typeof name !== "string") {
      throw new TypeError(`Position - set error: 'name' is not a string.`);
    }
    __privateGet(this, _dataSaved).set(name, data2);
  }
};
_data2 = new WeakMap();
_dataSaved = new WeakMap();
_position2 = new WeakMap();
_transforms = new WeakMap();
__name(_PositionStateAPI, "PositionStateAPI");
let PositionStateAPI = _PositionStateAPI;
const _StyleCache = class _StyleCache {
  constructor() {
    this.el = void 0;
    this.computed = void 0;
    this.marginLeft = void 0;
    this.marginTop = void 0;
    this.maxHeight = void 0;
    this.maxWidth = void 0;
    this.minHeight = void 0;
    this.minWidth = void 0;
    this.hasWillChange = false;
    this.resizeObserved = {
      contentHeight: void 0,
      contentWidth: void 0,
      offsetHeight: void 0,
      offsetWidth: void 0
    };
    const storeResizeObserved = writable$1(this.resizeObserved);
    this.stores = {
      element: writable$1(this.el),
      resizeContentHeight: propertyStore(storeResizeObserved, "contentHeight"),
      resizeContentWidth: propertyStore(storeResizeObserved, "contentWidth"),
      resizeObserved: storeResizeObserved,
      resizeOffsetHeight: propertyStore(storeResizeObserved, "offsetHeight"),
      resizeOffsetWidth: propertyStore(storeResizeObserved, "offsetWidth")
    };
  }
  /**
   * Returns the cached offsetHeight from any attached `resizeObserver` action otherwise gets the offsetHeight from
   * the element directly. The more optimized path is using `resizeObserver` as getting it from the element
   * directly is more expensive and alters the execution order of an animation frame.
   *
   * @returns {number} The element offsetHeight.
   */
  get offsetHeight() {
    if (this.el instanceof HTMLElement) {
      return this.resizeObserved.offsetHeight !== void 0 ? this.resizeObserved.offsetHeight : this.el.offsetHeight;
    }
    throw new Error(`StyleCache - get offsetHeight error: no element assigned.`);
  }
  /**
   * Returns the cached offsetWidth from any attached `resizeObserver` action otherwise gets the offsetWidth from
   * the element directly. The more optimized path is using `resizeObserver` as getting it from the element
   * directly is more expensive and alters the execution order of an animation frame.
   *
   * @returns {number} The element offsetHeight.
   */
  get offsetWidth() {
    if (this.el instanceof HTMLElement) {
      return this.resizeObserved.offsetWidth !== void 0 ? this.resizeObserved.offsetWidth : this.el.offsetWidth;
    }
    throw new Error(`StyleCache - get offsetWidth error: no element assigned.`);
  }
  /**
   * @param {HTMLElement} el -
   *
   * @returns {boolean} Does element match cached element.
   */
  hasData(el) {
    return this.el === el;
  }
  /**
   * Resets the style cache.
   */
  reset() {
    if (this.el instanceof HTMLElement && this.el.isConnected && !this.hasWillChange) {
      this.el.style.willChange = null;
    }
    this.el = void 0;
    this.computed = void 0;
    this.marginLeft = void 0;
    this.marginTop = void 0;
    this.maxHeight = void 0;
    this.maxWidth = void 0;
    this.minHeight = void 0;
    this.minWidth = void 0;
    this.hasWillChange = false;
    this.resizeObserved.contentHeight = void 0;
    this.resizeObserved.contentWidth = void 0;
    this.resizeObserved.offsetHeight = void 0;
    this.resizeObserved.offsetWidth = void 0;
    this.stores.element.set(void 0);
  }
  /**
   * Updates the style cache with new data from the given element.
   *
   * @param {HTMLElement} el - An HTML element.
   */
  update(el) {
    this.el = el;
    this.computed = globalThis.getComputedStyle(el);
    this.marginLeft = styleParsePixels(el.style.marginLeft) ?? styleParsePixels(this.computed.marginLeft);
    this.marginTop = styleParsePixels(el.style.marginTop) ?? styleParsePixels(this.computed.marginTop);
    this.maxHeight = styleParsePixels(el.style.maxHeight) ?? styleParsePixels(this.computed.maxHeight);
    this.maxWidth = styleParsePixels(el.style.maxWidth) ?? styleParsePixels(this.computed.maxWidth);
    this.minHeight = styleParsePixels(el.style.minHeight) ?? styleParsePixels(this.computed.minHeight);
    this.minWidth = styleParsePixels(el.style.minWidth) ?? styleParsePixels(this.computed.minWidth);
    const willChange = el.style.willChange !== "" ? el.style.willChange : this.computed.willChange;
    this.hasWillChange = willChange !== "" && willChange !== "auto";
    this.stores.element.set(el);
  }
};
__name(_StyleCache, "StyleCache");
let StyleCache = _StyleCache;
const _TransformData = class _TransformData {
  constructor() {
    /**
     * Stores the calculated bounding rectangle.
     *
     * @type {DOMRect}
     */
    __privateAdd(this, _boundingRect, new DOMRect());
    /**
     * Stores the individual transformed corner points of the window in screenspace clockwise from:
     * top left -> top right -> bottom right -> bottom left.
     *
     * @type {Vector3[]}
     */
    __privateAdd(this, _corners, [vec3.create(), vec3.create(), vec3.create(), vec3.create()]);
    /**
     * Stores the current gl-matrix mat4 data.
     *
     * @type {Matrix4}
     */
    __privateAdd(this, _mat4, mat4.create());
    /**
     * Stores the pre & post origin translations to apply to matrix transforms.
     *
     * @type {Matrix4[]}
     */
    __privateAdd(this, _originTranslations, [mat4.create(), mat4.create()]);
    Object.seal(this);
  }
  /**
   * @returns {DOMRect} The bounding rectangle.
   */
  get boundingRect() {
    return __privateGet(this, _boundingRect);
  }
  /**
   * @returns {Vector3[]} The transformed corner points as vec3 in screen space.
   */
  get corners() {
    return __privateGet(this, _corners);
  }
  /**
   * @returns {string} Returns the CSS style string for the transform matrix.
   */
  get css() {
    return `matrix3d(${this.mat4.join(",")})`;
  }
  /**
   * @returns {Matrix4} The transform matrix.
   */
  get mat4() {
    return __privateGet(this, _mat4);
  }
  /**
   * @returns {Matrix4[]} The pre / post translation matrices for origin translation.
   */
  get originTranslations() {
    return __privateGet(this, _originTranslations);
  }
};
_boundingRect = new WeakMap();
_corners = new WeakMap();
_mat4 = new WeakMap();
_originTranslations = new WeakMap();
__name(_TransformData, "TransformData");
let TransformData = _TransformData;
const _AdapterValidators = class _AdapterValidators {
  /**
   * @returns {[AdapterValidators, ValidatorData[]]} Returns this and internal storage for validator adapter.
   */
  constructor() {
    /** @type {boolean} */
    __privateAdd(this, _enabled, true);
    /**
     * @type {ValidatorData[]}
     */
    __privateAdd(this, _validatorData, void 0);
    __privateAdd(this, _mapUnsubscribe2, /* @__PURE__ */ new Map());
    __privateSet(this, _validatorData, []);
    Object.seal(this);
    return [this, __privateGet(this, _validatorData)];
  }
  /**
   * @returns {boolean} Returns the enabled state.s
   */
  get enabled() {
    return __privateGet(this, _enabled);
  }
  /**
   * @returns {number} Returns the length of the validators array.
   */
  get length() {
    return __privateGet(this, _validatorData).length;
  }
  /**
   * @param {boolean}  enabled - Sets enabled state.
   */
  set enabled(enabled) {
    if (typeof enabled !== "boolean") {
      throw new TypeError(`'enabled' is not a boolean.`);
    }
    __privateSet(this, _enabled, enabled);
  }
  /**
   * Provides an iterator for validators.
   *
   * @returns {Generator<ValidatorData|undefined>} Generator / iterator of validators.
   * @yields {ValidatorData}
   */
  *[Symbol.iterator]() {
    if (__privateGet(this, _validatorData).length === 0) {
      return;
    }
    for (const entry of __privateGet(this, _validatorData)) {
      yield { ...entry };
    }
  }
  /**
   * @param {...(ValidatorFn|ValidatorData)}   validators -
   */
  add(...validators) {
    for (const validator of validators) {
      const validatorType = typeof validator;
      if (validatorType !== "function" && validatorType !== "object" || validator === null) {
        throw new TypeError(`AdapterValidator error: 'validator' is not a function or object.`);
      }
      let data2 = void 0;
      let subscribeFn = void 0;
      switch (validatorType) {
        case "function":
          data2 = {
            id: void 0,
            validator,
            weight: 1
          };
          subscribeFn = validator.subscribe;
          break;
        case "object":
          if (typeof validator.validator !== "function") {
            throw new TypeError(`AdapterValidator error: 'validator' attribute is not a function.`);
          }
          if (validator.weight !== void 0 && typeof validator.weight !== "number" || (validator.weight < 0 || validator.weight > 1)) {
            throw new TypeError(
              `AdapterValidator error: 'weight' attribute is not a number between '0 - 1' inclusive.`
            );
          }
          data2 = {
            id: validator.id !== void 0 ? validator.id : void 0,
            validator: validator.validator.bind(validator),
            weight: validator.weight || 1,
            instance: validator
          };
          subscribeFn = validator.validator.subscribe ?? validator.subscribe;
          break;
      }
      const index2 = __privateGet(this, _validatorData).findIndex((value) => {
        return data2.weight < value.weight;
      });
      if (index2 >= 0) {
        __privateGet(this, _validatorData).splice(index2, 0, data2);
      } else {
        __privateGet(this, _validatorData).push(data2);
      }
      if (typeof subscribeFn === "function") {
        const unsubscribe = subscribeFn();
        if (typeof unsubscribe !== "function") {
          throw new TypeError(
            "AdapterValidator error: Filter has subscribe function, but no unsubscribe function is returned."
          );
        }
        if (__privateGet(this, _mapUnsubscribe2).has(data2.validator)) {
          throw new Error(
            "AdapterValidator error: Filter added already has an unsubscribe function registered."
          );
        }
        __privateGet(this, _mapUnsubscribe2).set(data2.validator, unsubscribe);
      }
    }
  }
  clear() {
    __privateGet(this, _validatorData).length = 0;
    for (const unsubscribe of __privateGet(this, _mapUnsubscribe2).values()) {
      unsubscribe();
    }
    __privateGet(this, _mapUnsubscribe2).clear();
  }
  /**
   * @param {...(ValidatorFn|ValidatorData)}   validators -
   */
  remove(...validators) {
    const length = __privateGet(this, _validatorData).length;
    if (length === 0) {
      return;
    }
    for (const data2 of validators) {
      const actualValidator = typeof data2 === "function" ? data2 : isObject(data2) ? data2.validator : void 0;
      if (!actualValidator) {
        continue;
      }
      for (let cntr = __privateGet(this, _validatorData).length; --cntr >= 0; ) {
        if (__privateGet(this, _validatorData)[cntr].validator === actualValidator) {
          __privateGet(this, _validatorData).splice(cntr, 1);
          let unsubscribe = void 0;
          if (typeof (unsubscribe = __privateGet(this, _mapUnsubscribe2).get(actualValidator)) === "function") {
            unsubscribe();
            __privateGet(this, _mapUnsubscribe2).delete(actualValidator);
          }
        }
      }
    }
  }
  /**
   * Remove validators by the provided callback. The callback takes 3 parameters: `id`, `validator`, and `weight`.
   * Any truthy value returned will remove that validator.
   *
   * @param {function(*, ValidatorFn, number): boolean} callback - Callback function to evaluate each validator
   *                                                                  entry.
   */
  removeBy(callback) {
    const length = __privateGet(this, _validatorData).length;
    if (length === 0) {
      return;
    }
    if (typeof callback !== "function") {
      throw new TypeError(`AdapterValidator error: 'callback' is not a function.`);
    }
    __privateSet(this, _validatorData, __privateGet(this, _validatorData).filter((data2) => {
      const remove = callback.call(callback, { ...data2 });
      if (remove) {
        let unsubscribe;
        if (typeof (unsubscribe = __privateGet(this, _mapUnsubscribe2).get(data2.validator)) === "function") {
          unsubscribe();
          __privateGet(this, _mapUnsubscribe2).delete(data2.validator);
        }
      }
      return !remove;
    }));
  }
  removeById(...ids) {
    const length = __privateGet(this, _validatorData).length;
    if (length === 0) {
      return;
    }
    __privateSet(this, _validatorData, __privateGet(this, _validatorData).filter((data2) => {
      let remove = false;
      for (const id of ids) {
        remove |= data2.id === id;
      }
      if (remove) {
        let unsubscribe;
        if (typeof (unsubscribe = __privateGet(this, _mapUnsubscribe2).get(data2.validator)) === "function") {
          unsubscribe();
          __privateGet(this, _mapUnsubscribe2).delete(data2.validator);
        }
      }
      return !remove;
    }));
  }
};
_enabled = new WeakMap();
_validatorData = new WeakMap();
_mapUnsubscribe2 = new WeakMap();
__name(_AdapterValidators, "AdapterValidators");
let AdapterValidators = _AdapterValidators;
const _BasicBounds = class _BasicBounds {
  constructor({ constrain = true, element: element2, enabled = true, lock = false, width, height } = {}) {
    /**
     * When true constrains the min / max width or height to element.
     *
     * @type {boolean}
     */
    __privateAdd(this, _constrain, void 0);
    /**
     * @type {HTMLElement}
     */
    __privateAdd(this, _element2, void 0);
    /**
     * When true the validator is active.
     *
     * @type {boolean}
     */
    __privateAdd(this, _enabled2, void 0);
    /**
     * Provides a manual setting of the element height. As things go `offsetHeight` causes a browser layout and is not
     * performance oriented. If manually set this height is used instead of `offsetHeight`.
     *
     * @type {number}
     */
    __privateAdd(this, _height2, void 0);
    /**
     * Set from an optional value in the constructor to lock accessors preventing modification.
     */
    __privateAdd(this, _lock2, void 0);
    /**
     * Provides a manual setting of the element width. As things go `offsetWidth` causes a browser layout and is not
     * performance oriented. If manually set this width is used instead of `offsetWidth`.
     *
     * @type {number}
     */
    __privateAdd(this, _width2, void 0);
    this.element = element2;
    this.constrain = constrain;
    this.enabled = enabled;
    this.width = width;
    this.height = height;
    __privateSet(this, _lock2, typeof lock === "boolean" ? lock : false);
  }
  get constrain() {
    return __privateGet(this, _constrain);
  }
  get element() {
    return __privateGet(this, _element2);
  }
  get enabled() {
    return __privateGet(this, _enabled2);
  }
  get height() {
    return __privateGet(this, _height2);
  }
  get width() {
    return __privateGet(this, _width2);
  }
  set constrain(constrain) {
    if (__privateGet(this, _lock2)) {
      return;
    }
    if (typeof constrain !== "boolean") {
      throw new TypeError(`'constrain' is not a boolean.`);
    }
    __privateSet(this, _constrain, constrain);
  }
  set element(element2) {
    if (__privateGet(this, _lock2)) {
      return;
    }
    if (element2 === void 0 || element2 === null || element2 instanceof HTMLElement) {
      __privateSet(this, _element2, element2);
    } else {
      throw new TypeError(`'element' is not a HTMLElement, undefined, or null.`);
    }
  }
  set enabled(enabled) {
    if (__privateGet(this, _lock2)) {
      return;
    }
    if (typeof enabled !== "boolean") {
      throw new TypeError(`'enabled' is not a boolean.`);
    }
    __privateSet(this, _enabled2, enabled);
  }
  set height(height) {
    if (__privateGet(this, _lock2)) {
      return;
    }
    if (height === void 0 || Number.isFinite(height)) {
      __privateSet(this, _height2, height);
    } else {
      throw new TypeError(`'height' is not a finite number or undefined.`);
    }
  }
  set width(width) {
    if (__privateGet(this, _lock2)) {
      return;
    }
    if (width === void 0 || Number.isFinite(width)) {
      __privateSet(this, _width2, width);
    } else {
      throw new TypeError(`'width' is not a finite number or undefined.`);
    }
  }
  setDimension(width, height) {
    if (__privateGet(this, _lock2)) {
      return;
    }
    if (width === void 0 || Number.isFinite(width)) {
      __privateSet(this, _width2, width);
    } else {
      throw new TypeError(`'width' is not a finite number or undefined.`);
    }
    if (height === void 0 || Number.isFinite(height)) {
      __privateSet(this, _height2, height);
    } else {
      throw new TypeError(`'height' is not a finite number or undefined.`);
    }
  }
  /**
   * Provides a validator that respects transforms in positional data constraining the position to within the target
   * elements bounds.
   *
   * @param {ValidationData}   valData - The associated validation data for position updates.
   *
   * @returns {PositionData} Potentially adjusted position data.
   */
  validator(valData) {
    if (!__privateGet(this, _enabled2)) {
      return valData.position;
    }
    const boundsWidth = __privateGet(this, _width2) ?? __privateGet(this, _element2)?.offsetWidth ?? globalThis.innerWidth;
    const boundsHeight = __privateGet(this, _height2) ?? __privateGet(this, _element2)?.offsetHeight ?? globalThis.innerHeight;
    if (typeof valData.position.width === "number") {
      const maxW = valData.maxWidth ?? (__privateGet(this, _constrain) ? boundsWidth : Number.MAX_SAFE_INTEGER);
      valData.position.width = valData.width = Math.clamped(valData.position.width, valData.minWidth, maxW);
      if (valData.width + valData.position.left + valData.marginLeft > boundsWidth) {
        valData.position.left = boundsWidth - valData.width - valData.marginLeft;
      }
    }
    if (typeof valData.position.height === "number") {
      const maxH = valData.maxHeight ?? (__privateGet(this, _constrain) ? boundsHeight : Number.MAX_SAFE_INTEGER);
      valData.position.height = valData.height = Math.clamped(valData.position.height, valData.minHeight, maxH);
      if (valData.height + valData.position.top + valData.marginTop > boundsHeight) {
        valData.position.top = boundsHeight - valData.height - valData.marginTop;
      }
    }
    const maxL = Math.max(boundsWidth - valData.width - valData.marginLeft, 0);
    valData.position.left = Math.round(Math.clamped(valData.position.left, 0, maxL));
    const maxT = Math.max(boundsHeight - valData.height - valData.marginTop, 0);
    valData.position.top = Math.round(Math.clamped(valData.position.top, 0, maxT));
    return valData.position;
  }
};
_constrain = new WeakMap();
_element2 = new WeakMap();
_enabled2 = new WeakMap();
_height2 = new WeakMap();
_lock2 = new WeakMap();
_width2 = new WeakMap();
__name(_BasicBounds, "BasicBounds");
let BasicBounds = _BasicBounds;
const s_TRANSFORM_DATA = new TransformData();
const _TransformBounds = class _TransformBounds {
  constructor({ constrain = true, element: element2, enabled = true, lock = false, width, height } = {}) {
    /**
     * When true constrains the min / max width or height to element.
     *
     * @type {boolean}
     */
    __privateAdd(this, _constrain2, void 0);
    /**
     * @type {HTMLElement}
     */
    __privateAdd(this, _element3, void 0);
    /**
     * When true the validator is active.
     *
     * @type {boolean}
     */
    __privateAdd(this, _enabled3, void 0);
    /**
     * Provides a manual setting of the element height. As things go `offsetHeight` causes a browser layout and is not
     * performance oriented. If manually set this height is used instead of `offsetHeight`.
     *
     * @type {number}
     */
    __privateAdd(this, _height3, void 0);
    /**
     * Set from an optional value in the constructor to lock accessors preventing modification.
     */
    __privateAdd(this, _lock3, void 0);
    /**
     * Provides a manual setting of the element width. As things go `offsetWidth` causes a browser layout and is not
     * performance oriented. If manually set this width is used instead of `offsetWidth`.
     *
     * @type {number}
     */
    __privateAdd(this, _width3, void 0);
    this.element = element2;
    this.constrain = constrain;
    this.enabled = enabled;
    this.width = width;
    this.height = height;
    __privateSet(this, _lock3, typeof lock === "boolean" ? lock : false);
  }
  get constrain() {
    return __privateGet(this, _constrain2);
  }
  get element() {
    return __privateGet(this, _element3);
  }
  get enabled() {
    return __privateGet(this, _enabled3);
  }
  get height() {
    return __privateGet(this, _height3);
  }
  get width() {
    return __privateGet(this, _width3);
  }
  set constrain(constrain) {
    if (__privateGet(this, _lock3)) {
      return;
    }
    if (typeof constrain !== "boolean") {
      throw new TypeError(`'constrain' is not a boolean.`);
    }
    __privateSet(this, _constrain2, constrain);
  }
  set element(element2) {
    if (__privateGet(this, _lock3)) {
      return;
    }
    if (element2 === void 0 || element2 === null || element2 instanceof HTMLElement) {
      __privateSet(this, _element3, element2);
    } else {
      throw new TypeError(`'element' is not a HTMLElement, undefined, or null.`);
    }
  }
  set enabled(enabled) {
    if (__privateGet(this, _lock3)) {
      return;
    }
    if (typeof enabled !== "boolean") {
      throw new TypeError(`'enabled' is not a boolean.`);
    }
    __privateSet(this, _enabled3, enabled);
  }
  set height(height) {
    if (__privateGet(this, _lock3)) {
      return;
    }
    if (height === void 0 || Number.isFinite(height)) {
      __privateSet(this, _height3, height);
    } else {
      throw new TypeError(`'height' is not a finite number or undefined.`);
    }
  }
  set width(width) {
    if (__privateGet(this, _lock3)) {
      return;
    }
    if (width === void 0 || Number.isFinite(width)) {
      __privateSet(this, _width3, width);
    } else {
      throw new TypeError(`'width' is not a finite number or undefined.`);
    }
  }
  setDimension(width, height) {
    if (__privateGet(this, _lock3)) {
      return;
    }
    if (width === void 0 || Number.isFinite(width)) {
      __privateSet(this, _width3, width);
    } else {
      throw new TypeError(`'width' is not a finite number or undefined.`);
    }
    if (height === void 0 || Number.isFinite(height)) {
      __privateSet(this, _height3, height);
    } else {
      throw new TypeError(`'height' is not a finite number or undefined.`);
    }
  }
  /**
   * Provides a validator that respects transforms in positional data constraining the position to within the target
   * elements bounds.
   *
   * @param {ValidationData}   valData - The associated validation data for position updates.
   *
   * @returns {PositionData} Potentially adjusted position data.
   */
  validator(valData) {
    if (!__privateGet(this, _enabled3)) {
      return valData.position;
    }
    const boundsWidth = __privateGet(this, _width3) ?? __privateGet(this, _element3)?.offsetWidth ?? globalThis.innerWidth;
    const boundsHeight = __privateGet(this, _height3) ?? __privateGet(this, _element3)?.offsetHeight ?? globalThis.innerHeight;
    if (typeof valData.position.width === "number") {
      const maxW = valData.maxWidth ?? (__privateGet(this, _constrain2) ? boundsWidth : Number.MAX_SAFE_INTEGER);
      valData.position.width = Math.clamped(valData.width, valData.minWidth, maxW);
    }
    if (typeof valData.position.height === "number") {
      const maxH = valData.maxHeight ?? (__privateGet(this, _constrain2) ? boundsHeight : Number.MAX_SAFE_INTEGER);
      valData.position.height = Math.clamped(valData.height, valData.minHeight, maxH);
    }
    const data2 = valData.transforms.getData(valData.position, s_TRANSFORM_DATA, valData);
    const initialX = data2.boundingRect.x;
    const initialY = data2.boundingRect.y;
    if (data2.boundingRect.bottom + valData.marginTop > boundsHeight) {
      data2.boundingRect.y += boundsHeight - data2.boundingRect.bottom - valData.marginTop;
    }
    if (data2.boundingRect.right + valData.marginLeft > boundsWidth) {
      data2.boundingRect.x += boundsWidth - data2.boundingRect.right - valData.marginLeft;
    }
    if (data2.boundingRect.top - valData.marginTop < 0) {
      data2.boundingRect.y += Math.abs(data2.boundingRect.top - valData.marginTop);
    }
    if (data2.boundingRect.left - valData.marginLeft < 0) {
      data2.boundingRect.x += Math.abs(data2.boundingRect.left - valData.marginLeft);
    }
    valData.position.left -= initialX - data2.boundingRect.x;
    valData.position.top -= initialY - data2.boundingRect.y;
    return valData.position;
  }
};
_constrain2 = new WeakMap();
_element3 = new WeakMap();
_enabled3 = new WeakMap();
_height3 = new WeakMap();
_lock3 = new WeakMap();
_width3 = new WeakMap();
__name(_TransformBounds, "TransformBounds");
let TransformBounds = _TransformBounds;
const basicWindow = new BasicBounds({ lock: true });
const transformWindow = new TransformBounds({ lock: true });
const positionValidators = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  BasicBounds,
  TransformBounds,
  basicWindow,
  transformWindow
}, Symbol.toStringTag, { value: "Module" }));
const s_SCALE_VECTOR = [1, 1, 1];
const s_TRANSLATE_VECTOR = [0, 0, 0];
const s_MAT4_RESULT = mat4.create();
const s_MAT4_TEMP = mat4.create();
const s_VEC3_TEMP = vec3.create();
const _Transforms = class _Transforms {
  constructor() {
    /**
     * Stores the transform keys in the order added.
     *
     * @type {string[]}
     */
    __privateAdd(this, _orderList, []);
    this._data = {};
  }
  /**
   * @returns {boolean} Whether there are active transforms in local data.
   */
  get isActive() {
    return __privateGet(this, _orderList).length > 0;
  }
  /**
   * @returns {number|undefined} Any local rotateX data.
   */
  get rotateX() {
    return this._data.rotateX;
  }
  /**
   * @returns {number|undefined} Any local rotateY data.
   */
  get rotateY() {
    return this._data.rotateY;
  }
  /**
   * @returns {number|undefined} Any local rotateZ data.
   */
  get rotateZ() {
    return this._data.rotateZ;
  }
  /**
   * @returns {number|undefined} Any local rotateZ scale.
   */
  get scale() {
    return this._data.scale;
  }
  /**
   * @returns {number|undefined} Any local translateZ data.
   */
  get translateX() {
    return this._data.translateX;
  }
  /**
   * @returns {number|undefined} Any local translateZ data.
   */
  get translateY() {
    return this._data.translateY;
  }
  /**
   * @returns {number|undefined} Any local translateZ data.
   */
  get translateZ() {
    return this._data.translateZ;
  }
  /**
   * Sets the local rotateX data if the value is a finite number otherwise removes the local data.
   *
   * @param {number|null|undefined}   value - A value to set.
   */
  set rotateX(value) {
    if (Number.isFinite(value)) {
      if (this._data.rotateX === void 0) {
        __privateGet(this, _orderList).push("rotateX");
      }
      this._data.rotateX = value;
    } else {
      if (this._data.rotateX !== void 0) {
        const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === "rotateX");
        if (index2 >= 0) {
          __privateGet(this, _orderList).splice(index2, 1);
        }
      }
      delete this._data.rotateX;
    }
  }
  /**
   * Sets the local rotateY data if the value is a finite number otherwise removes the local data.
   *
   * @param {number|null|undefined}   value - A value to set.
   */
  set rotateY(value) {
    if (Number.isFinite(value)) {
      if (this._data.rotateY === void 0) {
        __privateGet(this, _orderList).push("rotateY");
      }
      this._data.rotateY = value;
    } else {
      if (this._data.rotateY !== void 0) {
        const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === "rotateY");
        if (index2 >= 0) {
          __privateGet(this, _orderList).splice(index2, 1);
        }
      }
      delete this._data.rotateY;
    }
  }
  /**
   * Sets the local rotateZ data if the value is a finite number otherwise removes the local data.
   *
   * @param {number|null|undefined}   value - A value to set.
   */
  set rotateZ(value) {
    if (Number.isFinite(value)) {
      if (this._data.rotateZ === void 0) {
        __privateGet(this, _orderList).push("rotateZ");
      }
      this._data.rotateZ = value;
    } else {
      if (this._data.rotateZ !== void 0) {
        const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === "rotateZ");
        if (index2 >= 0) {
          __privateGet(this, _orderList).splice(index2, 1);
        }
      }
      delete this._data.rotateZ;
    }
  }
  /**
   * Sets the local scale data if the value is a finite number otherwise removes the local data.
   *
   * @param {number|null|undefined}   value - A value to set.
   */
  set scale(value) {
    if (Number.isFinite(value)) {
      if (this._data.scale === void 0) {
        __privateGet(this, _orderList).push("scale");
      }
      this._data.scale = value;
    } else {
      if (this._data.scale !== void 0) {
        const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === "scale");
        if (index2 >= 0) {
          __privateGet(this, _orderList).splice(index2, 1);
        }
      }
      delete this._data.scale;
    }
  }
  /**
   * Sets the local translateX data if the value is a finite number otherwise removes the local data.
   *
   * @param {number|null|undefined}   value - A value to set.
   */
  set translateX(value) {
    if (Number.isFinite(value)) {
      if (this._data.translateX === void 0) {
        __privateGet(this, _orderList).push("translateX");
      }
      this._data.translateX = value;
    } else {
      if (this._data.translateX !== void 0) {
        const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === "translateX");
        if (index2 >= 0) {
          __privateGet(this, _orderList).splice(index2, 1);
        }
      }
      delete this._data.translateX;
    }
  }
  /**
   * Sets the local translateY data if the value is a finite number otherwise removes the local data.
   *
   * @param {number|null|undefined}   value - A value to set.
   */
  set translateY(value) {
    if (Number.isFinite(value)) {
      if (this._data.translateY === void 0) {
        __privateGet(this, _orderList).push("translateY");
      }
      this._data.translateY = value;
    } else {
      if (this._data.translateY !== void 0) {
        const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === "translateY");
        if (index2 >= 0) {
          __privateGet(this, _orderList).splice(index2, 1);
        }
      }
      delete this._data.translateY;
    }
  }
  /**
   * Sets the local translateZ data if the value is a finite number otherwise removes the local data.
   *
   * @param {number|null|undefined}   value - A value to set.
   */
  set translateZ(value) {
    if (Number.isFinite(value)) {
      if (this._data.translateZ === void 0) {
        __privateGet(this, _orderList).push("translateZ");
      }
      this._data.translateZ = value;
    } else {
      if (this._data.translateZ !== void 0) {
        const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === "translateZ");
        if (index2 >= 0) {
          __privateGet(this, _orderList).splice(index2, 1);
        }
      }
      delete this._data.translateZ;
    }
  }
  /**
   * Returns the matrix3d CSS transform for the given position / transform data.
   *
   * @param {object} [data] - Optional position data otherwise use local stored transform data.
   *
   * @returns {string} The CSS matrix3d string.
   */
  getCSS(data2 = this._data) {
    return `matrix3d(${this.getMat4(data2, s_MAT4_RESULT).join(",")})`;
  }
  /**
   * Returns the matrix3d CSS transform for the given position / transform data.
   *
   * @param {object} [data] - Optional position data otherwise use local stored transform data.
   *
   * @returns {string} The CSS matrix3d string.
   */
  getCSSOrtho(data2 = this._data) {
    return `matrix3d(${this.getMat4Ortho(data2, s_MAT4_RESULT).join(",")})`;
  }
  /**
   * Collects all data including a bounding rect, transform matrix, and points array of the given {@link PositionData}
   * instance with the applied local transform data.
   *
   * @param {PositionData} position - The position data to process.
   *
   * @param {TransformData} [output] - Optional TransformData output instance.
   *
   * @param {object} [validationData] - Optional validation data for adjustment parameters.
   *
   * @returns {TransformData} The output TransformData instance.
   */
  getData(position, output = new TransformData(), validationData = {}) {
    const valWidth = validationData.width ?? 0;
    const valHeight = validationData.height ?? 0;
    const valOffsetTop = validationData.offsetTop ?? validationData.marginTop ?? 0;
    const valOffsetLeft = validationData.offsetLeft ?? validationData.offsetLeft ?? 0;
    position.top += valOffsetTop;
    position.left += valOffsetLeft;
    const width = Number.isFinite(position.width) ? position.width : valWidth;
    const height = Number.isFinite(position.height) ? position.height : valHeight;
    const rect = output.corners;
    if (this.hasTransform(position)) {
      rect[0][0] = rect[0][1] = rect[0][2] = 0;
      rect[1][0] = width;
      rect[1][1] = rect[1][2] = 0;
      rect[2][0] = width;
      rect[2][1] = height;
      rect[2][2] = 0;
      rect[3][0] = 0;
      rect[3][1] = height;
      rect[3][2] = 0;
      const matrix = this.getMat4(position, output.mat4);
      const translate = s_GET_ORIGIN_TRANSLATION(position.transformOrigin, width, height, output.originTranslations);
      if (transformOriginDefault === position.transformOrigin) {
        vec3.transformMat4(rect[0], rect[0], matrix);
        vec3.transformMat4(rect[1], rect[1], matrix);
        vec3.transformMat4(rect[2], rect[2], matrix);
        vec3.transformMat4(rect[3], rect[3], matrix);
      } else {
        vec3.transformMat4(rect[0], rect[0], translate[0]);
        vec3.transformMat4(rect[0], rect[0], matrix);
        vec3.transformMat4(rect[0], rect[0], translate[1]);
        vec3.transformMat4(rect[1], rect[1], translate[0]);
        vec3.transformMat4(rect[1], rect[1], matrix);
        vec3.transformMat4(rect[1], rect[1], translate[1]);
        vec3.transformMat4(rect[2], rect[2], translate[0]);
        vec3.transformMat4(rect[2], rect[2], matrix);
        vec3.transformMat4(rect[2], rect[2], translate[1]);
        vec3.transformMat4(rect[3], rect[3], translate[0]);
        vec3.transformMat4(rect[3], rect[3], matrix);
        vec3.transformMat4(rect[3], rect[3], translate[1]);
      }
      rect[0][0] = position.left + rect[0][0];
      rect[0][1] = position.top + rect[0][1];
      rect[1][0] = position.left + rect[1][0];
      rect[1][1] = position.top + rect[1][1];
      rect[2][0] = position.left + rect[2][0];
      rect[2][1] = position.top + rect[2][1];
      rect[3][0] = position.left + rect[3][0];
      rect[3][1] = position.top + rect[3][1];
    } else {
      rect[0][0] = position.left;
      rect[0][1] = position.top;
      rect[1][0] = position.left + width;
      rect[1][1] = position.top;
      rect[2][0] = position.left + width;
      rect[2][1] = position.top + height;
      rect[3][0] = position.left;
      rect[3][1] = position.top + height;
      mat4.identity(output.mat4);
    }
    let maxX = Number.MIN_SAFE_INTEGER;
    let maxY = Number.MIN_SAFE_INTEGER;
    let minX = Number.MAX_SAFE_INTEGER;
    let minY = Number.MAX_SAFE_INTEGER;
    for (let cntr = 4; --cntr >= 0; ) {
      if (rect[cntr][0] > maxX) {
        maxX = rect[cntr][0];
      }
      if (rect[cntr][0] < minX) {
        minX = rect[cntr][0];
      }
      if (rect[cntr][1] > maxY) {
        maxY = rect[cntr][1];
      }
      if (rect[cntr][1] < minY) {
        minY = rect[cntr][1];
      }
    }
    const boundingRect = output.boundingRect;
    boundingRect.x = minX;
    boundingRect.y = minY;
    boundingRect.width = maxX - minX;
    boundingRect.height = maxY - minY;
    position.top -= valOffsetTop;
    position.left -= valOffsetLeft;
    return output;
  }
  /**
   * Creates a transform matrix based on local data applied in order it was added.
   *
   * If no data object is provided then the source is the local transform data. If another data object is supplied
   * then the stored local transform order is applied then all remaining transform keys are applied. This allows the
   * construction of a transform matrix in advance of setting local data and is useful in collision detection.
   *
   * @param {object}   [data] - PositionData instance or local transform data.
   *
   * @param {Matrix4}  [output] - The output mat4 instance.
   *
   * @returns {Matrix4} Transform matrix.
   */
  getMat4(data2 = this._data, output = mat4.create()) {
    const matrix = mat4.identity(output);
    let seenKeys = 0;
    const orderList = __privateGet(this, _orderList);
    for (let cntr = 0; cntr < orderList.length; cntr++) {
      const key = orderList[cntr];
      switch (key) {
        case "rotateX":
          seenKeys |= transformKeysBitwise.rotateX;
          mat4.multiply(matrix, matrix, mat4.fromXRotation(s_MAT4_TEMP, degToRad(data2[key])));
          break;
        case "rotateY":
          seenKeys |= transformKeysBitwise.rotateY;
          mat4.multiply(matrix, matrix, mat4.fromYRotation(s_MAT4_TEMP, degToRad(data2[key])));
          break;
        case "rotateZ":
          seenKeys |= transformKeysBitwise.rotateZ;
          mat4.multiply(matrix, matrix, mat4.fromZRotation(s_MAT4_TEMP, degToRad(data2[key])));
          break;
        case "scale":
          seenKeys |= transformKeysBitwise.scale;
          s_SCALE_VECTOR[0] = s_SCALE_VECTOR[1] = data2[key];
          mat4.multiply(matrix, matrix, mat4.fromScaling(s_MAT4_TEMP, s_SCALE_VECTOR));
          break;
        case "translateX":
          seenKeys |= transformKeysBitwise.translateX;
          s_TRANSLATE_VECTOR[0] = data2.translateX;
          s_TRANSLATE_VECTOR[1] = 0;
          s_TRANSLATE_VECTOR[2] = 0;
          mat4.multiply(matrix, matrix, mat4.fromTranslation(s_MAT4_TEMP, s_TRANSLATE_VECTOR));
          break;
        case "translateY":
          seenKeys |= transformKeysBitwise.translateY;
          s_TRANSLATE_VECTOR[0] = 0;
          s_TRANSLATE_VECTOR[1] = data2.translateY;
          s_TRANSLATE_VECTOR[2] = 0;
          mat4.multiply(matrix, matrix, mat4.fromTranslation(s_MAT4_TEMP, s_TRANSLATE_VECTOR));
          break;
        case "translateZ":
          seenKeys |= transformKeysBitwise.translateZ;
          s_TRANSLATE_VECTOR[0] = 0;
          s_TRANSLATE_VECTOR[1] = 0;
          s_TRANSLATE_VECTOR[2] = data2.translateZ;
          mat4.multiply(matrix, matrix, mat4.fromTranslation(s_MAT4_TEMP, s_TRANSLATE_VECTOR));
          break;
      }
    }
    if (data2 !== this._data) {
      for (let cntr = 0; cntr < transformKeys.length; cntr++) {
        const key = transformKeys[cntr];
        if (data2[key] === null || (seenKeys & transformKeysBitwise[key]) > 0) {
          continue;
        }
        switch (key) {
          case "rotateX":
            mat4.multiply(matrix, matrix, mat4.fromXRotation(s_MAT4_TEMP, degToRad(data2[key])));
            break;
          case "rotateY":
            mat4.multiply(matrix, matrix, mat4.fromYRotation(s_MAT4_TEMP, degToRad(data2[key])));
            break;
          case "rotateZ":
            mat4.multiply(matrix, matrix, mat4.fromZRotation(s_MAT4_TEMP, degToRad(data2[key])));
            break;
          case "scale":
            s_SCALE_VECTOR[0] = s_SCALE_VECTOR[1] = data2[key];
            mat4.multiply(matrix, matrix, mat4.fromScaling(s_MAT4_TEMP, s_SCALE_VECTOR));
            break;
          case "translateX":
            s_TRANSLATE_VECTOR[0] = data2[key];
            s_TRANSLATE_VECTOR[1] = 0;
            s_TRANSLATE_VECTOR[2] = 0;
            mat4.multiply(matrix, matrix, mat4.fromTranslation(s_MAT4_TEMP, s_TRANSLATE_VECTOR));
            break;
          case "translateY":
            s_TRANSLATE_VECTOR[0] = 0;
            s_TRANSLATE_VECTOR[1] = data2[key];
            s_TRANSLATE_VECTOR[2] = 0;
            mat4.multiply(matrix, matrix, mat4.fromTranslation(s_MAT4_TEMP, s_TRANSLATE_VECTOR));
            break;
          case "translateZ":
            s_TRANSLATE_VECTOR[0] = 0;
            s_TRANSLATE_VECTOR[1] = 0;
            s_TRANSLATE_VECTOR[2] = data2[key];
            mat4.multiply(matrix, matrix, mat4.fromTranslation(s_MAT4_TEMP, s_TRANSLATE_VECTOR));
            break;
        }
      }
    }
    return matrix;
  }
  /**
   * Provides an orthographic enhancement to convert left / top positional data to a translate operation.
   *
   * This transform matrix takes into account that the remaining operations are , but adds any left / top attributes from passed in data to
   * translate X / Y.
   *
   * If no data object is provided then the source is the local transform data. If another data object is supplied
   * then the stored local transform order is applied then all remaining transform keys are applied. This allows the
   * construction of a transform matrix in advance of setting local data and is useful in collision detection.
   *
   * @param {object}   [data] - PositionData instance or local transform data.
   *
   * @param {Matrix4}  [output] - The output mat4 instance.
   *
   * @returns {Matrix4} Transform matrix.
   */
  getMat4Ortho(data2 = this._data, output = mat4.create()) {
    const matrix = mat4.identity(output);
    s_TRANSLATE_VECTOR[0] = (data2.left ?? 0) + (data2.translateX ?? 0);
    s_TRANSLATE_VECTOR[1] = (data2.top ?? 0) + (data2.translateY ?? 0);
    s_TRANSLATE_VECTOR[2] = data2.translateZ ?? 0;
    mat4.multiply(matrix, matrix, mat4.fromTranslation(s_MAT4_TEMP, s_TRANSLATE_VECTOR));
    if (data2.scale !== null) {
      s_SCALE_VECTOR[0] = s_SCALE_VECTOR[1] = data2.scale;
      mat4.multiply(matrix, matrix, mat4.fromScaling(s_MAT4_TEMP, s_SCALE_VECTOR));
    }
    if (data2.rotateX === null && data2.rotateY === null && data2.rotateZ === null) {
      return matrix;
    }
    let seenKeys = 0;
    const orderList = __privateGet(this, _orderList);
    for (let cntr = 0; cntr < orderList.length; cntr++) {
      const key = orderList[cntr];
      switch (key) {
        case "rotateX":
          seenKeys |= transformKeysBitwise.rotateX;
          mat4.multiply(matrix, matrix, mat4.fromXRotation(s_MAT4_TEMP, degToRad(data2[key])));
          break;
        case "rotateY":
          seenKeys |= transformKeysBitwise.rotateY;
          mat4.multiply(matrix, matrix, mat4.fromYRotation(s_MAT4_TEMP, degToRad(data2[key])));
          break;
        case "rotateZ":
          seenKeys |= transformKeysBitwise.rotateZ;
          mat4.multiply(matrix, matrix, mat4.fromZRotation(s_MAT4_TEMP, degToRad(data2[key])));
          break;
      }
    }
    if (data2 !== this._data) {
      for (let cntr = 0; cntr < transformKeys.length; cntr++) {
        const key = transformKeys[cntr];
        if (data2[key] === null || (seenKeys & transformKeysBitwise[key]) > 0) {
          continue;
        }
        switch (key) {
          case "rotateX":
            mat4.multiply(matrix, matrix, mat4.fromXRotation(s_MAT4_TEMP, degToRad(data2[key])));
            break;
          case "rotateY":
            mat4.multiply(matrix, matrix, mat4.fromYRotation(s_MAT4_TEMP, degToRad(data2[key])));
            break;
          case "rotateZ":
            mat4.multiply(matrix, matrix, mat4.fromZRotation(s_MAT4_TEMP, degToRad(data2[key])));
            break;
        }
      }
    }
    return matrix;
  }
  /**
   * Tests an object if it contains transform keys and the values are finite numbers.
   *
   * @param {object} data - An object to test for transform data.
   *
   * @returns {boolean} Whether the given PositionData has transforms.
   */
  hasTransform(data2) {
    for (const key of transformKeys) {
      if (Number.isFinite(data2[key])) {
        return true;
      }
    }
    return false;
  }
  /**
   * Resets internal data from the given object containing valid transform keys.
   *
   * @param {object}   data - An object with transform data.
   */
  reset(data2) {
    for (const key in data2) {
      if (transformKeys.includes(key)) {
        if (Number.isFinite(data2[key])) {
          this._data[key] = data2[key];
        } else {
          const index2 = __privateGet(this, _orderList).findIndex((entry) => entry === key);
          if (index2 >= 0) {
            __privateGet(this, _orderList).splice(index2, 1);
          }
          delete this._data[key];
        }
      }
    }
  }
};
_orderList = new WeakMap();
__name(_Transforms, "Transforms");
let Transforms = _Transforms;
function s_GET_ORIGIN_TRANSLATION(transformOrigin, width, height, output) {
  const vector = s_VEC3_TEMP;
  switch (transformOrigin) {
    case "top left":
      vector[0] = vector[1] = 0;
      mat4.fromTranslation(output[0], vector);
      mat4.fromTranslation(output[1], vector);
      break;
    case "top center":
      vector[0] = -width * 0.5;
      vector[1] = 0;
      mat4.fromTranslation(output[0], vector);
      vector[0] = width * 0.5;
      mat4.fromTranslation(output[1], vector);
      break;
    case "top right":
      vector[0] = -width;
      vector[1] = 0;
      mat4.fromTranslation(output[0], vector);
      vector[0] = width;
      mat4.fromTranslation(output[1], vector);
      break;
    case "center left":
      vector[0] = 0;
      vector[1] = -height * 0.5;
      mat4.fromTranslation(output[0], vector);
      vector[1] = height * 0.5;
      mat4.fromTranslation(output[1], vector);
      break;
    case null:
    case "center":
      vector[0] = -width * 0.5;
      vector[1] = -height * 0.5;
      mat4.fromTranslation(output[0], vector);
      vector[0] = width * 0.5;
      vector[1] = height * 0.5;
      mat4.fromTranslation(output[1], vector);
      break;
    case "center right":
      vector[0] = -width;
      vector[1] = -height * 0.5;
      mat4.fromTranslation(output[0], vector);
      vector[0] = width;
      vector[1] = height * 0.5;
      mat4.fromTranslation(output[1], vector);
      break;
    case "bottom left":
      vector[0] = 0;
      vector[1] = -height;
      mat4.fromTranslation(output[0], vector);
      vector[1] = height;
      mat4.fromTranslation(output[1], vector);
      break;
    case "bottom center":
      vector[0] = -width * 0.5;
      vector[1] = -height;
      mat4.fromTranslation(output[0], vector);
      vector[0] = width * 0.5;
      vector[1] = height;
      mat4.fromTranslation(output[1], vector);
      break;
    case "bottom right":
      vector[0] = -width;
      vector[1] = -height;
      mat4.fromTranslation(output[0], vector);
      vector[0] = width;
      vector[1] = height;
      mat4.fromTranslation(output[1], vector);
      break;
    default:
      mat4.identity(output[0]);
      mat4.identity(output[1]);
      break;
  }
  return output;
}
__name(s_GET_ORIGIN_TRANSLATION, "s_GET_ORIGIN_TRANSLATION");
const _UpdateElementData = class _UpdateElementData {
  constructor() {
    this.data = void 0;
    this.dataSubscribers = new PositionData();
    this.dimensionData = { width: 0, height: 0 };
    this.changeSet = void 0;
    this.options = void 0;
    this.queued = false;
    this.styleCache = void 0;
    this.transforms = void 0;
    this.transformData = new TransformData();
    this.subscriptions = void 0;
    this.storeDimension = writable$1(this.dimensionData);
    this.storeTransform = writable$1(this.transformData, () => {
      this.options.transformSubscribed = true;
      return () => this.options.transformSubscribed = false;
    });
    this.queued = false;
    Object.seal(this.dimensionData);
  }
};
__name(_UpdateElementData, "UpdateElementData");
let UpdateElementData = _UpdateElementData;
async function nextAnimationFrame(cntr = 1) {
  if (!Number.isInteger(cntr) || cntr < 1) {
    throw new TypeError(`nextAnimationFrame error: 'cntr' must be a positive integer greater than 0.`);
  }
  let currentTime = performance.now();
  for (; --cntr >= 0; ) {
    currentTime = await new Promise((resolve) => requestAnimationFrame(resolve));
  }
  return currentTime;
}
__name(nextAnimationFrame, "nextAnimationFrame");
const _UpdateElementManager = class _UpdateElementManager {
  static get promise() {
    return this.updatePromise;
  }
  /**
   * Potentially adds the given element and internal updateData instance to the list.
   *
   * @param {HTMLElement}       el - An HTMLElement instance.
   *
   * @param {UpdateElementData} updateData - An UpdateElementData instance.
   *
   * @returns {Promise<number>} The unified next frame update promise. Returns `currentTime`.
   */
  static add(el, updateData) {
    if (this.listCntr < this.list.length) {
      const entry = this.list[this.listCntr];
      entry[0] = el;
      entry[1] = updateData;
    } else {
      this.list.push([el, updateData]);
    }
    this.listCntr++;
    updateData.queued = true;
    if (!this.updatePromise) {
      this.updatePromise = this.wait();
    }
    return this.updatePromise;
  }
  /**
   * Await on `nextAnimationFrame` and iterate over list map invoking callback functions.
   *
   * @returns {Promise<number>} The next frame Promise / currentTime from nextAnimationFrame.
   */
  static async wait() {
    const currentTime = await nextAnimationFrame();
    this.updatePromise = void 0;
    for (let cntr = this.listCntr; --cntr >= 0; ) {
      const entry = this.list[cntr];
      const el = entry[0];
      const updateData = entry[1];
      entry[0] = void 0;
      entry[1] = void 0;
      updateData.queued = false;
      if (!el.isConnected) {
        continue;
      }
      if (updateData.options.ortho) {
        s_UPDATE_ELEMENT_ORTHO(el, updateData);
      } else {
        s_UPDATE_ELEMENT(el, updateData);
      }
      if (updateData.options.calculateTransform || updateData.options.transformSubscribed) {
        s_UPDATE_TRANSFORM(el, updateData);
      }
      this.updateSubscribers(updateData);
    }
    this.listCntr = 0;
    return currentTime;
  }
  /**
   * Potentially immediately updates the given element.
   *
   * @param {HTMLElement}       el - An HTMLElement instance.
   *
   * @param {UpdateElementData} updateData - An UpdateElementData instance.
   */
  static immediate(el, updateData) {
    if (!el.isConnected) {
      return;
    }
    if (updateData.options.ortho) {
      s_UPDATE_ELEMENT_ORTHO(el, updateData);
    } else {
      s_UPDATE_ELEMENT(el, updateData);
    }
    if (updateData.options.calculateTransform || updateData.options.transformSubscribed) {
      s_UPDATE_TRANSFORM(el, updateData);
    }
    this.updateSubscribers(updateData);
  }
  /**
   * @param {UpdateElementData} updateData - Data change set.
   */
  static updateSubscribers(updateData) {
    const data2 = updateData.data;
    const changeSet = updateData.changeSet;
    if (!changeSet.hasChange()) {
      return;
    }
    const output = updateData.dataSubscribers.copy(data2);
    const subscriptions = updateData.subscriptions;
    if (subscriptions.length > 0) {
      for (let cntr = 0; cntr < subscriptions.length; cntr++) {
        subscriptions[cntr](output);
      }
    }
    if (changeSet.width || changeSet.height) {
      updateData.dimensionData.width = data2.width;
      updateData.dimensionData.height = data2.height;
      updateData.storeDimension.set(updateData.dimensionData);
    }
    changeSet.set(false);
  }
};
__name(_UpdateElementManager, "UpdateElementManager");
__publicField(_UpdateElementManager, "list", []);
__publicField(_UpdateElementManager, "listCntr", 0);
__publicField(_UpdateElementManager, "updatePromise");
let UpdateElementManager = _UpdateElementManager;
function s_UPDATE_ELEMENT(el, updateData) {
  const changeSet = updateData.changeSet;
  const data2 = updateData.data;
  if (changeSet.left) {
    el.style.left = `${data2.left}px`;
  }
  if (changeSet.top) {
    el.style.top = `${data2.top}px`;
  }
  if (changeSet.zIndex) {
    el.style.zIndex = typeof data2.zIndex === "number" ? `${data2.zIndex}` : null;
  }
  if (changeSet.width) {
    el.style.width = typeof data2.width === "number" ? `${data2.width}px` : data2.width;
  }
  if (changeSet.height) {
    el.style.height = typeof data2.height === "number" ? `${data2.height}px` : data2.height;
  }
  if (changeSet.transformOrigin) {
    el.style.transformOrigin = data2.transformOrigin === "center" ? null : data2.transformOrigin;
  }
  if (changeSet.transform) {
    el.style.transform = updateData.transforms.isActive ? updateData.transforms.getCSS() : null;
  }
}
__name(s_UPDATE_ELEMENT, "s_UPDATE_ELEMENT");
function s_UPDATE_ELEMENT_ORTHO(el, updateData) {
  const changeSet = updateData.changeSet;
  const data2 = updateData.data;
  if (changeSet.zIndex) {
    el.style.zIndex = typeof data2.zIndex === "number" ? `${data2.zIndex}` : null;
  }
  if (changeSet.width) {
    el.style.width = typeof data2.width === "number" ? `${data2.width}px` : data2.width;
  }
  if (changeSet.height) {
    el.style.height = typeof data2.height === "number" ? `${data2.height}px` : data2.height;
  }
  if (changeSet.transformOrigin) {
    el.style.transformOrigin = data2.transformOrigin === "center" ? null : data2.transformOrigin;
  }
  if (changeSet.left || changeSet.top || changeSet.transform) {
    el.style.transform = updateData.transforms.getCSSOrtho(data2);
  }
}
__name(s_UPDATE_ELEMENT_ORTHO, "s_UPDATE_ELEMENT_ORTHO");
function s_UPDATE_TRANSFORM(el, updateData) {
  s_VALIDATION_DATA$1.height = updateData.data.height !== "auto" ? updateData.data.height : updateData.styleCache.offsetHeight;
  s_VALIDATION_DATA$1.width = updateData.data.width !== "auto" ? updateData.data.width : updateData.styleCache.offsetWidth;
  s_VALIDATION_DATA$1.marginLeft = updateData.styleCache.marginLeft;
  s_VALIDATION_DATA$1.marginTop = updateData.styleCache.marginTop;
  updateData.transforms.getData(updateData.data, updateData.transformData, s_VALIDATION_DATA$1);
  updateData.storeTransform.set(updateData.transformData);
}
__name(s_UPDATE_TRANSFORM, "s_UPDATE_TRANSFORM");
const s_VALIDATION_DATA$1 = {
  height: void 0,
  width: void 0,
  marginLeft: void 0,
  marginTop: void 0
};
const _Position = class _Position {
  /**
   * @param {PositionParent|PositionOptionsAll}   [parent] - A potential parent element or object w/ `elementTarget`
   *                                                      getter. May also be the PositionOptions object w/ 1 argument.
   *
   * @param {PositionOptionsAll}   [options] - Default values.
   */
  constructor(parent, options) {
    /**
     * @param {PositionDataExtended} opts -
     *
     * @param {number|null} opts.left -
     *
     * @param {number|null} opts.top -
     *
     * @param {number|null} opts.maxHeight -
     *
     * @param {number|null} opts.maxWidth -
     *
     * @param {number|null} opts.minHeight -
     *
     * @param {number|null} opts.minWidth -
     *
     * @param {number|'auto'|null} opts.width -
     *
     * @param {number|'auto'|null} opts.height -
     *
     * @param {number|null} opts.rotateX -
     *
     * @param {number|null} opts.rotateY -
     *
     * @param {number|null} opts.rotateZ -
     *
     * @param {number|null} opts.scale -
     *
     * @param {string} opts.transformOrigin -
     *
     * @param {number|null} opts.translateX -
     *
     * @param {number|null} opts.translateY -
     *
     * @param {number|null} opts.translateZ -
     *
     * @param {number|null} opts.zIndex -
     *
     * @param {number|null} opts.rotation - alias for rotateZ
     *
     * @param {*} opts.rest -
     *
     * @param {object} parent -
     *
     * @param {HTMLElement} el -
     *
     * @param {StyleCache} styleCache -
     *
     * @returns {null|PositionData} Updated position data or null if validation fails.
     */
    __privateAdd(this, _updatePosition);
    /**
     * @type {PositionData}
     */
    __privateAdd(this, _data3, new PositionData());
    /**
     * Provides the animation API.
     *
     * @type {AnimationAPI}
     */
    __privateAdd(this, _animate, new AnimationAPI(this, __privateGet(this, _data3)));
    /**
     * Provides a way to turn on / off the position handling.
     *
     * @type {boolean}
     */
    __privateAdd(this, _enabled4, true);
    /**
     * Stores the style attributes that changed on update.
     *
     * @type {PositionChangeSet}
     */
    __privateAdd(this, _positionChangeSet, new PositionChangeSet());
    /**
     * Stores ongoing options that are set in the constructor or by transform store subscription.
     *
     * @type {PositionOptions}
     */
    __privateAdd(this, _options2, {
      calculateTransform: false,
      initialHelper: void 0,
      ortho: true,
      transformSubscribed: false
    });
    /**
     * The associated parent for positional data tracking. Used in validators.
     *
     * @type {PositionParent}
     */
    __privateAdd(this, _parent, void 0);
    /**
     * @type {StorePosition}
     */
    __privateAdd(this, _stores3, void 0);
    /**
     * Stores an instance of the computer styles for the target element.
     *
     * @type {StyleCache}
     */
    __privateAdd(this, _styleCache, void 0);
    /**
     * Stores the subscribers.
     *
     * @type {(function(PositionData): void)[]}
     */
    __privateAdd(this, _subscriptions5, []);
    /**
     * @type {Transforms}
     */
    __privateAdd(this, _transforms2, new Transforms());
    /**
     * @type {UpdateElementData}
     */
    __privateAdd(this, _updateElementData, void 0);
    /**
     * Stores the UpdateElementManager wait promise.
     *
     * @type {Promise}
     */
    __privateAdd(this, _updateElementPromise, void 0);
    /**
     * @type {AdapterValidators}
     */
    __privateAdd(this, _validators, void 0);
    /**
     * @type {ValidatorData[]}
     */
    __privateAdd(this, _validatorData2, void 0);
    /**
     * @type {PositionStateAPI}
     */
    __privateAdd(this, _state, new PositionStateAPI(this, __privateGet(this, _data3), __privateGet(this, _transforms2)));
    if (isPlainObject(parent)) {
      options = parent;
    } else {
      __privateSet(this, _parent, parent);
    }
    const data2 = __privateGet(this, _data3);
    const transforms = __privateGet(this, _transforms2);
    __privateSet(this, _styleCache, new StyleCache());
    const updateData = new UpdateElementData();
    updateData.changeSet = __privateGet(this, _positionChangeSet);
    updateData.data = __privateGet(this, _data3);
    updateData.options = __privateGet(this, _options2);
    updateData.styleCache = __privateGet(this, _styleCache);
    updateData.subscriptions = __privateGet(this, _subscriptions5);
    updateData.transforms = __privateGet(this, _transforms2);
    __privateSet(this, _updateElementData, updateData);
    if (isObject(options)) {
      if (typeof options.calculateTransform === "boolean") {
        __privateGet(this, _options2).calculateTransform = options.calculateTransform;
      }
      if (typeof options.ortho === "boolean") {
        __privateGet(this, _options2).ortho = options.ortho;
      }
      if (Number.isFinite(options.height) || options.height === "auto" || options.height === "inherit" || options.height === null) {
        data2.height = updateData.dimensionData.height = typeof options.height === "number" ? Math.round(options.height) : options.height;
      }
      if (Number.isFinite(options.left) || options.left === null) {
        data2.left = typeof options.left === "number" ? Math.round(options.left) : options.left;
      }
      if (Number.isFinite(options.maxHeight) || options.maxHeight === null) {
        data2.maxHeight = typeof options.maxHeight === "number" ? Math.round(options.maxHeight) : options.maxHeight;
      }
      if (Number.isFinite(options.maxWidth) || options.maxWidth === null) {
        data2.maxWidth = typeof options.maxWidth === "number" ? Math.round(options.maxWidth) : options.maxWidth;
      }
      if (Number.isFinite(options.minHeight) || options.minHeight === null) {
        data2.minHeight = typeof options.minHeight === "number" ? Math.round(options.minHeight) : options.minHeight;
      }
      if (Number.isFinite(options.minWidth) || options.minWidth === null) {
        data2.minWidth = typeof options.minWidth === "number" ? Math.round(options.minWidth) : options.minWidth;
      }
      if (Number.isFinite(options.rotateX) || options.rotateX === null) {
        transforms.rotateX = data2.rotateX = options.rotateX;
      }
      if (Number.isFinite(options.rotateY) || options.rotateY === null) {
        transforms.rotateY = data2.rotateY = options.rotateY;
      }
      if (Number.isFinite(options.rotateZ) || options.rotateZ === null) {
        transforms.rotateZ = data2.rotateZ = options.rotateZ;
      }
      if (Number.isFinite(options.scale) || options.scale === null) {
        transforms.scale = data2.scale = options.scale;
      }
      if (Number.isFinite(options.top) || options.top === null) {
        data2.top = typeof options.top === "number" ? Math.round(options.top) : options.top;
      }
      if (typeof options.transformOrigin === "string" || options.transformOrigin === null) {
        data2.transformOrigin = transformOrigins.includes(options.transformOrigin) ? options.transformOrigin : null;
      }
      if (Number.isFinite(options.translateX) || options.translateX === null) {
        transforms.translateX = data2.translateX = options.translateX;
      }
      if (Number.isFinite(options.translateY) || options.translateY === null) {
        transforms.translateY = data2.translateY = options.translateY;
      }
      if (Number.isFinite(options.translateZ) || options.translateZ === null) {
        transforms.translateZ = data2.translateZ = options.translateZ;
      }
      if (Number.isFinite(options.width) || options.width === "auto" || options.width === "inherit" || options.width === null) {
        data2.width = updateData.dimensionData.width = typeof options.width === "number" ? Math.round(options.width) : options.width;
      }
      if (Number.isFinite(options.zIndex) || options.zIndex === null) {
        data2.zIndex = typeof options.zIndex === "number" ? Math.round(options.zIndex) : options.zIndex;
      }
    }
    __privateSet(this, _stores3, {
      // The main properties for manipulating Position.
      height: propertyStore(this, "height"),
      left: propertyStore(this, "left"),
      rotateX: propertyStore(this, "rotateX"),
      rotateY: propertyStore(this, "rotateY"),
      rotateZ: propertyStore(this, "rotateZ"),
      scale: propertyStore(this, "scale"),
      top: propertyStore(this, "top"),
      transformOrigin: propertyStore(this, "transformOrigin"),
      translateX: propertyStore(this, "translateX"),
      translateY: propertyStore(this, "translateY"),
      translateZ: propertyStore(this, "translateZ"),
      width: propertyStore(this, "width"),
      zIndex: propertyStore(this, "zIndex"),
      // Stores that control validation when width / height is not `auto`.
      maxHeight: propertyStore(this, "maxHeight"),
      maxWidth: propertyStore(this, "maxWidth"),
      minHeight: propertyStore(this, "minHeight"),
      minWidth: propertyStore(this, "minWidth"),
      // Readable stores based on updates or from resize observer changes.
      dimension: { subscribe: updateData.storeDimension.subscribe },
      element: { subscribe: __privateGet(this, _styleCache).stores.element.subscribe },
      resizeContentHeight: { subscribe: __privateGet(this, _styleCache).stores.resizeContentHeight.subscribe },
      resizeContentWidth: { subscribe: __privateGet(this, _styleCache).stores.resizeContentWidth.subscribe },
      resizeOffsetHeight: { subscribe: __privateGet(this, _styleCache).stores.resizeOffsetHeight.subscribe },
      resizeOffsetWidth: { subscribe: __privateGet(this, _styleCache).stores.resizeOffsetWidth.subscribe },
      transform: { subscribe: updateData.storeTransform.subscribe },
      // Protected store that should only be set by resizeObserver action.
      resizeObserved: __privateGet(this, _styleCache).stores.resizeObserved
    });
    subscribeIgnoreFirst(__privateGet(this, _stores3).resizeObserved, (resizeData) => {
      const parent2 = __privateGet(this, _parent);
      const el = parent2 instanceof HTMLElement ? parent2 : parent2?.elementTarget;
      if (el instanceof HTMLElement && Number.isFinite(resizeData?.offsetWidth) && Number.isFinite(resizeData?.offsetHeight)) {
        this.set(data2);
      }
    });
    __privateGet(this, _stores3).transformOrigin.values = transformOrigins;
    [__privateWrapper(this, _validators)._, __privateWrapper(this, _validatorData2)._] = new AdapterValidators();
    if (options?.initial || options?.positionInitial) {
      const initialHelper = options.initial ?? options.positionInitial;
      if (typeof initialHelper?.getLeft !== "function" || typeof initialHelper?.getTop !== "function") {
        throw new Error(
          `'options.initial' position helper does not contain 'getLeft' and / or 'getTop' functions.`
        );
      }
      __privateGet(this, _options2).initialHelper = options.initial;
    }
    if (options?.validator) {
      if (isIterable(options?.validator)) {
        this.validators.add(...options.validator);
      } else {
        this.validators.add(options.validator);
      }
    }
  }
  /**
   * @returns {AnimationGroupAPI} Public Animation API.
   */
  static get Animate() {
    return AnimationGroupAPI;
  }
  /**
   * @returns {{browserCentered?: Centered, Centered?: *}} Initial position helpers.
   */
  static get Initial() {
    return positionInitial;
  }
  /**
   * Returns TransformData class / constructor.
   *
   * @returns {TransformData} TransformData class / constructor.
   */
  static get TransformData() {
    return TransformData;
  }
  /**
   * Returns default validators.
   *
   * Note: `basicWindow` and `BasicBounds` will eventually be removed.
   *
   * @returns {{basicWindow?: BasicBounds, transformWindow?: TransformBounds, TransformBounds?: *, BasicBounds?: *}}
   *  Available validators.
   */
  static get Validators() {
    return positionValidators;
  }
  /**
   * Returns a duplicate of a given position instance copying any options and validators.
   *
   * // TODO: Consider more safety over options processing.
   *
   * @param {Position}          position - A position instance.
   *
   * @param {PositionOptions}   options - Position options.
   *
   * @returns {Position} A duplicate position instance.
   */
  static duplicate(position, options) {
    if (!(position instanceof _Position)) {
      throw new TypeError(`'position' is not an instance of Position.`);
    }
    const newPosition = new _Position(options);
    __privateSet(newPosition, _options2, Object.assign({}, __privateGet(position, _options2), options));
    __privateGet(newPosition, _validators).add(...__privateGet(position, _validators));
    newPosition.set(__privateGet(position, _data3));
    return newPosition;
  }
  /**
   * Returns the animation API.
   *
   * @returns {AnimationAPI} Animation API.
   */
  get animate() {
    return __privateGet(this, _animate);
  }
  /**
   * Returns the dimension data for the readable store.
   *
   * @returns {{width: number | 'auto', height: number | 'auto'}} Dimension data.
   */
  get dimension() {
    return __privateGet(this, _updateElementData).dimensionData;
  }
  /**
   * Returns the enabled state.
   *
   * @returns {boolean} Enabled state.
   */
  get enabled() {
    return __privateGet(this, _enabled4);
  }
  /**
   * Returns the current HTMLElement being positioned.
   *
   * @returns {HTMLElement|undefined} Current HTMLElement being positioned.
   */
  get element() {
    return __privateGet(this, _styleCache).el;
  }
  /**
   * Returns a promise that is resolved on the next element update with the time of the update.
   *
   * @returns {Promise<number>} Promise resolved on element update.
   */
  get elementUpdated() {
    return __privateGet(this, _updateElementPromise);
  }
  /**
   * Returns the associated {@link PositionParent} instance.
   *
   * @returns {PositionParent} The PositionParent instance.
   */
  get parent() {
    return __privateGet(this, _parent);
  }
  /**
   * Returns the state API.
   *
   * @returns {PositionStateAPI} Position state API.
   */
  get state() {
    return __privateGet(this, _state);
  }
  /**
   * Returns the derived writable stores for individual data variables.
   *
   * @returns {StorePosition} Derived / writable stores.
   */
  get stores() {
    return __privateGet(this, _stores3);
  }
  /**
   * Returns the transform data for the readable store.
   *
   * @returns {TransformData} Transform Data.
   */
  get transform() {
    return __privateGet(this, _updateElementData).transformData;
  }
  /**
   * Returns the validators.
   *
   * @returns {AdapterValidators} validators.
   */
  get validators() {
    return __privateGet(this, _validators);
  }
  /**
   * Sets the enabled state.
   *
   * @param {boolean}  enabled - New enabled state.
   */
  set enabled(enabled) {
    if (typeof enabled !== "boolean") {
      throw new TypeError(`'enabled' is not a boolean.`);
    }
    __privateSet(this, _enabled4, enabled);
  }
  /**
   * Sets the associated {@link PositionParent} instance. Resets the style cache and default data.
   *
   * @param {PositionParent|void} parent - A PositionParent instance.
   */
  set parent(parent) {
    if (parent !== void 0 && !(parent instanceof HTMLElement) && !isObject(parent)) {
      throw new TypeError(`'parent' is not an HTMLElement, object, or undefined.`);
    }
    __privateSet(this, _parent, parent);
    __privateGet(this, _state).remove({ name: "#defaultData" });
    __privateGet(this, _styleCache).reset();
    if (parent) {
      this.set(__privateGet(this, _data3));
    }
  }
  // Data accessors ----------------------------------------------------------------------------------------------------
  /**
   * @returns {number|'auto'|'inherit'|null} height
   */
  get height() {
    return __privateGet(this, _data3).height;
  }
  /**
   * @returns {number|null} left
   */
  get left() {
    return __privateGet(this, _data3).left;
  }
  /**
   * @returns {number|null} maxHeight
   */
  get maxHeight() {
    return __privateGet(this, _data3).maxHeight;
  }
  /**
   * @returns {number|null} maxWidth
   */
  get maxWidth() {
    return __privateGet(this, _data3).maxWidth;
  }
  /**
   * @returns {number|null} minHeight
   */
  get minHeight() {
    return __privateGet(this, _data3).minHeight;
  }
  /**
   * @returns {number|null} minWidth
   */
  get minWidth() {
    return __privateGet(this, _data3).minWidth;
  }
  /**
   * @returns {number|null} rotateX
   */
  get rotateX() {
    return __privateGet(this, _data3).rotateX;
  }
  /**
   * @returns {number|null} rotateY
   */
  get rotateY() {
    return __privateGet(this, _data3).rotateY;
  }
  /**
   * @returns {number|null} rotateZ
   */
  get rotateZ() {
    return __privateGet(this, _data3).rotateZ;
  }
  /**
   * @returns {number|null} alias for rotateZ
   */
  get rotation() {
    return __privateGet(this, _data3).rotateZ;
  }
  /**
   * @returns {number|null} scale
   */
  get scale() {
    return __privateGet(this, _data3).scale;
  }
  /**
   * @returns {number|null} top
   */
  get top() {
    return __privateGet(this, _data3).top;
  }
  /**
   * @returns {string} transformOrigin
   */
  get transformOrigin() {
    return __privateGet(this, _data3).transformOrigin;
  }
  /**
   * @returns {number|null} translateX
   */
  get translateX() {
    return __privateGet(this, _data3).translateX;
  }
  /**
   * @returns {number|null} translateY
   */
  get translateY() {
    return __privateGet(this, _data3).translateY;
  }
  /**
   * @returns {number|null} translateZ
   */
  get translateZ() {
    return __privateGet(this, _data3).translateZ;
  }
  /**
   * @returns {number|'auto'|'inherit'|null} width
   */
  get width() {
    return __privateGet(this, _data3).width;
  }
  /**
   * @returns {number|null} z-index
   */
  get zIndex() {
    return __privateGet(this, _data3).zIndex;
  }
  /**
   * @param {number|string|null} height -
   */
  set height(height) {
    __privateGet(this, _stores3).height.set(height);
  }
  /**
   * @param {number|string|null} left -
   */
  set left(left) {
    __privateGet(this, _stores3).left.set(left);
  }
  /**
   * @param {number|string|null} maxHeight -
   */
  set maxHeight(maxHeight) {
    __privateGet(this, _stores3).maxHeight.set(maxHeight);
  }
  /**
   * @param {number|string|null} maxWidth -
   */
  set maxWidth(maxWidth) {
    __privateGet(this, _stores3).maxWidth.set(maxWidth);
  }
  /**
   * @param {number|string|null} minHeight -
   */
  set minHeight(minHeight) {
    __privateGet(this, _stores3).minHeight.set(minHeight);
  }
  /**
   * @param {number|string|null} minWidth -
   */
  set minWidth(minWidth) {
    __privateGet(this, _stores3).minWidth.set(minWidth);
  }
  /**
   * @param {number|string|null} rotateX -
   */
  set rotateX(rotateX) {
    __privateGet(this, _stores3).rotateX.set(rotateX);
  }
  /**
   * @param {number|string|null} rotateY -
   */
  set rotateY(rotateY) {
    __privateGet(this, _stores3).rotateY.set(rotateY);
  }
  /**
   * @param {number|string|null} rotateZ -
   */
  set rotateZ(rotateZ) {
    __privateGet(this, _stores3).rotateZ.set(rotateZ);
  }
  /**
   * @param {number|string|null} rotateZ - alias for rotateZ
   */
  set rotation(rotateZ) {
    __privateGet(this, _stores3).rotateZ.set(rotateZ);
  }
  /**
   * @param {number|string|null} scale -
   */
  set scale(scale) {
    __privateGet(this, _stores3).scale.set(scale);
  }
  /**
   * @param {number|string|null} top -
   */
  set top(top) {
    __privateGet(this, _stores3).top.set(top);
  }
  /**
   * @param {string} transformOrigin -
   */
  set transformOrigin(transformOrigin) {
    if (transformOrigins.includes(transformOrigin)) {
      __privateGet(this, _stores3).transformOrigin.set(transformOrigin);
    }
  }
  /**
   * @param {number|string|null} translateX -
   */
  set translateX(translateX) {
    __privateGet(this, _stores3).translateX.set(translateX);
  }
  /**
   * @param {number|string|null} translateY -
   */
  set translateY(translateY) {
    __privateGet(this, _stores3).translateY.set(translateY);
  }
  /**
   * @param {number|string|null} translateZ -
   */
  set translateZ(translateZ) {
    __privateGet(this, _stores3).translateZ.set(translateZ);
  }
  /**
   * @param {number|string|null} width -
   */
  set width(width) {
    __privateGet(this, _stores3).width.set(width);
  }
  /**
   * @param {number|string|null} zIndex -
   */
  set zIndex(zIndex) {
    __privateGet(this, _stores3).zIndex.set(zIndex);
  }
  /**
   * Assigns current position to object passed into method.
   *
   * @param {object|PositionData}  [position] - Target to assign current position data.
   *
   * @param {PositionGetOptions}   [options] - Defines options for specific keys and substituting null for numeric
   *                                           default values.
   *
   * @returns {PositionData} Passed in object with current position data.
   */
  get(position = {}, options) {
    const keys = options?.keys;
    const excludeKeys = options?.exclude;
    const numeric = options?.numeric ?? false;
    if (isIterable(keys)) {
      if (numeric) {
        for (const key of keys) {
          position[key] = this[key] ?? numericDefaults[key];
        }
      } else {
        for (const key of keys) {
          position[key] = this[key];
        }
      }
      if (isIterable(excludeKeys)) {
        for (const key of excludeKeys) {
          delete position[key];
        }
      }
      return position;
    } else {
      const data2 = Object.assign(position, __privateGet(this, _data3));
      if (isIterable(excludeKeys)) {
        for (const key of excludeKeys) {
          delete data2[key];
        }
      }
      if (numeric) {
        setNumericDefaults(data2);
      }
      return data2;
    }
  }
  /**
   * @returns {PositionData} Current position data.
   */
  toJSON() {
    return Object.assign({}, __privateGet(this, _data3));
  }
  /**
   * All calculation and updates of position are implemented in {@link Position}. This allows position to be fully
   * reactive and in control of updating inline styles for the application.
   *
   * Note: the logic for updating position is improved and changes a few aspects from the default
   * {@link Application.setPosition}. The gate on `popOut` is removed, so to ensure no positional application occurs
   * popOut applications can set `this.options.positionable` to false ensuring no positional inline styles are
   * applied.
   *
   * The initial set call on an application with a target element will always set width / height as this is
   * necessary for correct calculations.
   *
   * When a target element is present updated styles are applied after validation. To modify the behavior of set
   * implement one or more validator functions and add them from the application via
   * `this.position.validators.add(<Function>)`.
   *
   * Updates to any target element are decoupled from the underlying Position data. This method returns this instance
   * that you can then await on the target element inline style update by using {@link Position.elementUpdated}.
   *
   * @param {PositionDataExtended} [position] - Position data to set.
   *
   * @returns {Position} This Position instance.
   */
  set(position = {}) {
    if (typeof position !== "object") {
      throw new TypeError(`Position - set error: 'position' is not an object.`);
    }
    const parent = __privateGet(this, _parent);
    if (!__privateGet(this, _enabled4)) {
      return this;
    }
    if (parent !== void 0 && typeof parent?.options?.positionable === "boolean" && !parent?.options?.positionable) {
      return this;
    }
    const immediateElementUpdate = position.immediateElementUpdate === true;
    const data2 = __privateGet(this, _data3);
    const transforms = __privateGet(this, _transforms2);
    const targetEl = parent instanceof HTMLElement ? parent : parent?.elementTarget;
    const el = targetEl instanceof HTMLElement && targetEl.isConnected ? targetEl : void 0;
    const changeSet = __privateGet(this, _positionChangeSet);
    const styleCache = __privateGet(this, _styleCache);
    if (el) {
      if (!styleCache.hasData(el)) {
        styleCache.update(el);
        if (!styleCache.hasWillChange)
          ;
        changeSet.set(true);
        __privateGet(this, _updateElementData).queued = false;
      }
      convertRelative(position, this);
      position = __privateMethod(this, _updatePosition, updatePosition_fn).call(this, position, parent, el, styleCache);
      if (position === null) {
        return this;
      }
    }
    if (Number.isFinite(position.left)) {
      position.left = Math.round(position.left);
      if (data2.left !== position.left) {
        data2.left = position.left;
        changeSet.left = true;
      }
    }
    if (Number.isFinite(position.top)) {
      position.top = Math.round(position.top);
      if (data2.top !== position.top) {
        data2.top = position.top;
        changeSet.top = true;
      }
    }
    if (Number.isFinite(position.maxHeight) || position.maxHeight === null) {
      position.maxHeight = typeof position.maxHeight === "number" ? Math.round(position.maxHeight) : null;
      if (data2.maxHeight !== position.maxHeight) {
        data2.maxHeight = position.maxHeight;
        changeSet.maxHeight = true;
      }
    }
    if (Number.isFinite(position.maxWidth) || position.maxWidth === null) {
      position.maxWidth = typeof position.maxWidth === "number" ? Math.round(position.maxWidth) : null;
      if (data2.maxWidth !== position.maxWidth) {
        data2.maxWidth = position.maxWidth;
        changeSet.maxWidth = true;
      }
    }
    if (Number.isFinite(position.minHeight) || position.minHeight === null) {
      position.minHeight = typeof position.minHeight === "number" ? Math.round(position.minHeight) : null;
      if (data2.minHeight !== position.minHeight) {
        data2.minHeight = position.minHeight;
        changeSet.minHeight = true;
      }
    }
    if (Number.isFinite(position.minWidth) || position.minWidth === null) {
      position.minWidth = typeof position.minWidth === "number" ? Math.round(position.minWidth) : null;
      if (data2.minWidth !== position.minWidth) {
        data2.minWidth = position.minWidth;
        changeSet.minWidth = true;
      }
    }
    if (Number.isFinite(position.rotateX) || position.rotateX === null) {
      if (data2.rotateX !== position.rotateX) {
        data2.rotateX = transforms.rotateX = position.rotateX;
        changeSet.transform = true;
      }
    }
    if (Number.isFinite(position.rotateY) || position.rotateY === null) {
      if (data2.rotateY !== position.rotateY) {
        data2.rotateY = transforms.rotateY = position.rotateY;
        changeSet.transform = true;
      }
    }
    if (Number.isFinite(position.rotateZ) || position.rotateZ === null) {
      if (data2.rotateZ !== position.rotateZ) {
        data2.rotateZ = transforms.rotateZ = position.rotateZ;
        changeSet.transform = true;
      }
    }
    if (Number.isFinite(position.scale) || position.scale === null) {
      position.scale = typeof position.scale === "number" ? Math.max(0, Math.min(position.scale, 1e3)) : null;
      if (data2.scale !== position.scale) {
        data2.scale = transforms.scale = position.scale;
        changeSet.transform = true;
      }
    }
    if (typeof position.transformOrigin === "string" && transformOrigins.includes(
      position.transformOrigin
    ) || position.transformOrigin === null) {
      if (data2.transformOrigin !== position.transformOrigin) {
        data2.transformOrigin = position.transformOrigin;
        changeSet.transformOrigin = true;
      }
    }
    if (Number.isFinite(position.translateX) || position.translateX === null) {
      if (data2.translateX !== position.translateX) {
        data2.translateX = transforms.translateX = position.translateX;
        changeSet.transform = true;
      }
    }
    if (Number.isFinite(position.translateY) || position.translateY === null) {
      if (data2.translateY !== position.translateY) {
        data2.translateY = transforms.translateY = position.translateY;
        changeSet.transform = true;
      }
    }
    if (Number.isFinite(position.translateZ) || position.translateZ === null) {
      if (data2.translateZ !== position.translateZ) {
        data2.translateZ = transforms.translateZ = position.translateZ;
        changeSet.transform = true;
      }
    }
    if (Number.isFinite(position.zIndex)) {
      position.zIndex = Math.round(position.zIndex);
      if (data2.zIndex !== position.zIndex) {
        data2.zIndex = position.zIndex;
        changeSet.zIndex = true;
      }
    }
    if (Number.isFinite(position.width) || position.width === "auto" || position.width === "inherit" || position.width === null) {
      position.width = typeof position.width === "number" ? Math.round(position.width) : position.width;
      if (data2.width !== position.width) {
        data2.width = position.width;
        changeSet.width = true;
      }
    }
    if (Number.isFinite(position.height) || position.height === "auto" || position.height === "inherit" || position.height === null) {
      position.height = typeof position.height === "number" ? Math.round(position.height) : position.height;
      if (data2.height !== position.height) {
        data2.height = position.height;
        changeSet.height = true;
      }
    }
    if (el) {
      const defaultData = __privateGet(this, _state).getDefault();
      if (typeof defaultData !== "object") {
        __privateGet(this, _state).save({ name: "#defaultData", ...Object.assign({}, data2) });
      }
      if (immediateElementUpdate) {
        UpdateElementManager.immediate(el, __privateGet(this, _updateElementData));
        __privateSet(this, _updateElementPromise, Promise.resolve(performance.now()));
      } else if (!__privateGet(this, _updateElementData).queued) {
        __privateSet(this, _updateElementPromise, UpdateElementManager.add(el, __privateGet(this, _updateElementData)));
      }
    } else {
      UpdateElementManager.updateSubscribers(__privateGet(this, _updateElementData));
    }
    return this;
  }
  /**
   *
   * @param {function(PositionData): void} handler - Callback function that is invoked on update / changes. Receives
   *                                                 a copy of the PositionData.
   *
   * @returns {(function(): void)} Unsubscribe function.
   */
  subscribe(handler) {
    __privateGet(this, _subscriptions5).push(handler);
    handler(Object.assign({}, __privateGet(this, _data3)));
    return () => {
      const index2 = __privateGet(this, _subscriptions5).findIndex((sub) => sub === handler);
      if (index2 >= 0) {
        __privateGet(this, _subscriptions5).splice(index2, 1);
      }
    };
  }
};
_data3 = new WeakMap();
_animate = new WeakMap();
_enabled4 = new WeakMap();
_positionChangeSet = new WeakMap();
_options2 = new WeakMap();
_parent = new WeakMap();
_stores3 = new WeakMap();
_styleCache = new WeakMap();
_subscriptions5 = new WeakMap();
_transforms2 = new WeakMap();
_updateElementData = new WeakMap();
_updateElementPromise = new WeakMap();
_validators = new WeakMap();
_validatorData2 = new WeakMap();
_state = new WeakMap();
_updatePosition = new WeakSet();
updatePosition_fn = /* @__PURE__ */ __name(function({
  // Directly supported parameters
  left,
  top,
  maxWidth,
  maxHeight,
  minWidth,
  minHeight,
  width,
  height,
  rotateX,
  rotateY,
  rotateZ,
  scale,
  transformOrigin,
  translateX,
  translateY,
  translateZ,
  zIndex,
  // Aliased parameters
  rotation,
  ...rest
} = {}, parent, el, styleCache) {
  let currentPosition = s_DATA_UPDATE.copy(__privateGet(this, _data3));
  if (el.style.width === "" || width !== void 0) {
    if (width === "auto" || currentPosition.width === "auto" && width !== null) {
      currentPosition.width = "auto";
      width = styleCache.offsetWidth;
    } else if (width === "inherit" || currentPosition.width === "inherit" && width !== null) {
      currentPosition.width = "inherit";
      width = styleCache.offsetWidth;
    } else {
      const newWidth = Number.isFinite(width) ? width : currentPosition.width;
      currentPosition.width = width = Number.isFinite(newWidth) ? Math.round(newWidth) : styleCache.offsetWidth;
    }
  } else {
    width = Number.isFinite(currentPosition.width) ? currentPosition.width : styleCache.offsetWidth;
  }
  if (el.style.height === "" || height !== void 0) {
    if (height === "auto" || currentPosition.height === "auto" && height !== null) {
      currentPosition.height = "auto";
      height = styleCache.offsetHeight;
    } else if (height === "inherit" || currentPosition.height === "inherit" && height !== null) {
      currentPosition.height = "inherit";
      height = styleCache.offsetHeight;
    } else {
      const newHeight = Number.isFinite(height) ? height : currentPosition.height;
      currentPosition.height = height = Number.isFinite(newHeight) ? Math.round(newHeight) : styleCache.offsetHeight;
    }
  } else {
    height = Number.isFinite(currentPosition.height) ? currentPosition.height : styleCache.offsetHeight;
  }
  if (Number.isFinite(left)) {
    currentPosition.left = left;
  } else if (!Number.isFinite(currentPosition.left)) {
    currentPosition.left = typeof __privateGet(this, _options2).initialHelper?.getLeft === "function" ? __privateGet(this, _options2).initialHelper.getLeft(width) : 0;
  }
  if (Number.isFinite(top)) {
    currentPosition.top = top;
  } else if (!Number.isFinite(currentPosition.top)) {
    currentPosition.top = typeof __privateGet(this, _options2).initialHelper?.getTop === "function" ? __privateGet(this, _options2).initialHelper.getTop(height) : 0;
  }
  if (Number.isFinite(maxHeight) || maxHeight === null) {
    currentPosition.maxHeight = Number.isFinite(maxHeight) ? Math.round(maxHeight) : null;
  }
  if (Number.isFinite(maxWidth) || maxWidth === null) {
    currentPosition.maxWidth = Number.isFinite(maxWidth) ? Math.round(maxWidth) : null;
  }
  if (Number.isFinite(minHeight) || minHeight === null) {
    currentPosition.minHeight = Number.isFinite(minHeight) ? Math.round(minHeight) : null;
  }
  if (Number.isFinite(minWidth) || minWidth === null) {
    currentPosition.minWidth = Number.isFinite(minWidth) ? Math.round(minWidth) : null;
  }
  if (Number.isFinite(rotateX) || rotateX === null) {
    currentPosition.rotateX = rotateX;
  }
  if (Number.isFinite(rotateY) || rotateY === null) {
    currentPosition.rotateY = rotateY;
  }
  if (rotateZ !== currentPosition.rotateZ && (Number.isFinite(rotateZ) || rotateZ === null)) {
    currentPosition.rotateZ = rotateZ;
  } else if (rotation !== currentPosition.rotateZ && (Number.isFinite(rotation) || rotation === null)) {
    currentPosition.rotateZ = rotation;
  }
  if (Number.isFinite(translateX) || translateX === null) {
    currentPosition.translateX = translateX;
  }
  if (Number.isFinite(translateY) || translateY === null) {
    currentPosition.translateY = translateY;
  }
  if (Number.isFinite(translateZ) || translateZ === null) {
    currentPosition.translateZ = translateZ;
  }
  if (Number.isFinite(scale) || scale === null) {
    currentPosition.scale = typeof scale === "number" ? Math.max(0, Math.min(scale, 1e3)) : null;
  }
  if (typeof transformOrigin === "string" || transformOrigin === null) {
    currentPosition.transformOrigin = transformOrigins.includes(transformOrigin) ? transformOrigin : null;
  }
  if (Number.isFinite(zIndex) || zIndex === null) {
    currentPosition.zIndex = typeof zIndex === "number" ? Math.round(zIndex) : zIndex;
  }
  const validatorData = __privateGet(this, _validatorData2);
  if (__privateGet(this, _validators).enabled && validatorData.length) {
    s_VALIDATION_DATA.parent = parent;
    s_VALIDATION_DATA.el = el;
    s_VALIDATION_DATA.computed = styleCache.computed;
    s_VALIDATION_DATA.transforms = __privateGet(this, _transforms2);
    s_VALIDATION_DATA.height = height;
    s_VALIDATION_DATA.width = width;
    s_VALIDATION_DATA.marginLeft = styleCache.marginLeft;
    s_VALIDATION_DATA.marginTop = styleCache.marginTop;
    s_VALIDATION_DATA.maxHeight = styleCache.maxHeight ?? currentPosition.maxHeight;
    s_VALIDATION_DATA.maxWidth = styleCache.maxWidth ?? currentPosition.maxWidth;
    const isMinimized = parent?.reactive?.minimized ?? false;
    s_VALIDATION_DATA.minHeight = isMinimized ? currentPosition.minHeight ?? 0 : styleCache.minHeight || (currentPosition.minHeight ?? 0);
    s_VALIDATION_DATA.minWidth = isMinimized ? currentPosition.minWidth ?? 0 : styleCache.minWidth || (currentPosition.minWidth ?? 0);
    for (let cntr = 0; cntr < validatorData.length; cntr++) {
      s_VALIDATION_DATA.position = currentPosition;
      s_VALIDATION_DATA.rest = rest;
      currentPosition = validatorData[cntr].validator(s_VALIDATION_DATA);
      if (currentPosition === null) {
        return null;
      }
    }
  }
  return currentPosition;
}, "#updatePosition");
__name(_Position, "Position");
let Position = _Position;
const s_DATA_UPDATE = new PositionData();
const s_VALIDATION_DATA = {
  position: void 0,
  parent: void 0,
  el: void 0,
  computed: void 0,
  transforms: void 0,
  height: void 0,
  width: void 0,
  marginLeft: void 0,
  marginTop: void 0,
  maxHeight: void 0,
  maxWidth: void 0,
  minHeight: void 0,
  minWidth: void 0,
  rest: void 0
};
Object.seal(s_VALIDATION_DATA);
const _ApplicationState = class _ApplicationState {
  /**
   * @param {ApplicationShellExt}   application - The application.
   */
  constructor(application) {
    /** @type {ApplicationShellExt} */
    __privateAdd(this, _application, void 0);
    /** @type {Map<string, ApplicationStateData>} */
    __privateAdd(this, _dataSaved2, /* @__PURE__ */ new Map());
    __privateSet(this, _application, application);
    Object.seal(this);
  }
  /**
   * Returns current application state along with any extra data passed into method.
   *
   * @param {object} [extra] - Extra data to add to application state.
   *
   * @returns {ApplicationStateData} Passed in object with current application state.
   */
  get(extra = {}) {
    return Object.assign(extra, {
      position: __privateGet(this, _application)?.position?.get(),
      beforeMinimized: __privateGet(this, _application)?.position?.state.get({ name: "#beforeMinimized" }),
      options: Object.assign({}, __privateGet(this, _application)?.options),
      ui: { minimized: __privateGet(this, _application)?.reactive?.minimized }
    });
  }
  /**
   * Returns any stored save state by name.
   *
   * @param {string}   name - Saved data set name.
   *
   * @returns {ApplicationStateData} The saved data set.
   */
  getSave({ name }) {
    if (typeof name !== "string") {
      throw new TypeError(`ApplicationState - getSave error: 'name' is not a string.`);
    }
    return __privateGet(this, _dataSaved2).get(name);
  }
  /**
   * Removes and returns any application state by name.
   *
   * @param {object}   options - Options.
   *
   * @param {string}   options.name - Name to remove and retrieve.
   *
   * @returns {ApplicationStateData} Saved application data.
   */
  remove({ name }) {
    if (typeof name !== "string") {
      throw new TypeError(`ApplicationState - remove: 'name' is not a string.`);
    }
    const data2 = __privateGet(this, _dataSaved2).get(name);
    __privateGet(this, _dataSaved2).delete(name);
    return data2;
  }
  /**
   * Restores a saved application state returning the data. Several optional parameters are available
   * to control whether the restore action occurs silently (no store / inline styles updates), animates
   * to the stored data, or simply sets the stored data. Restoring via {@link AnimationAPI.to} allows
   * specification of the duration, easing, and interpolate functions along with configuring a Promise to be
   * returned if awaiting the end of the animation.
   *
   * @param {object}            params - Parameters
   *
   * @param {string}            params.name - Saved data set name.
   *
   * @param {boolean}           [params.remove=false] - Remove data set.
   *
   * @param {boolean}           [params.async=false] - If animating return a Promise that resolves with any saved data.
   *
   * @param {boolean}           [params.animateTo=false] - Animate to restore data.
   *
   * @param {number}            [params.duration=0.1] - Duration in seconds.
   *
   * @param {Function}          [params.ease=linear] - Easing function.
   *
   * @param {Function}          [params.interpolate=lerp] - Interpolation function.
   *
   * @returns {ApplicationStateData|Promise<ApplicationStateData>} Saved application data.
   */
  restore({
    name,
    remove = false,
    async = false,
    animateTo = false,
    duration = 0.1,
    ease = identity,
    interpolate = lerp$5
  }) {
    if (typeof name !== "string") {
      throw new TypeError(`ApplicationState - restore error: 'name' is not a string.`);
    }
    const dataSaved = __privateGet(this, _dataSaved2).get(name);
    if (dataSaved) {
      if (remove) {
        __privateGet(this, _dataSaved2).delete(name);
      }
      if (async) {
        return this.set(dataSaved, { async, animateTo, duration, ease, interpolate }).then(() => dataSaved);
      } else {
        this.set(dataSaved, { async, animateTo, duration, ease, interpolate });
      }
    }
    return dataSaved;
  }
  /**
   * Saves current application state with the opportunity to add extra data to the saved state.
   *
   * @param {object}   options - Options.
   *
   * @param {string}   options.name - name to index this saved data.
   *
   * @param {...*}     [options.extra] - Extra data to add to saved data.
   *
   * @returns {ApplicationStateData} Current application data
   */
  save({ name, ...extra }) {
    if (typeof name !== "string") {
      throw new TypeError(`ApplicationState - save error: 'name' is not a string.`);
    }
    const data2 = this.get(extra);
    __privateGet(this, _dataSaved2).set(name, data2);
    return data2;
  }
  /**
   * Restores a saved application state returning the data. Several optional parameters are available
   * to control whether the restore action occurs silently (no store / inline styles updates), animates
   * to the stored data, or simply sets the stored data. Restoring via {@link AnimationAPI.to} allows
   * specification of the duration, easing, and interpolate functions along with configuring a Promise to be
   * returned if awaiting the end of the animation.
   *
   * Note: If serializing application state any minimized apps will use the before minimized state on initial render
   * of the app as it is currently not possible to render apps with Foundry VTT core API in the minimized state.
   *
   * TODO: THIS METHOD NEEDS TO BE REFACTORED WHEN TRL IS MADE INTO A STANDALONE FRAMEWORK.
   *
   * @param {ApplicationStateData}   data - Saved data set name.
   *
   * @param {object}            [opts] - Optional parameters
   *
   * @param {boolean}           [opts.async=false] - If animating return a Promise that resolves with any saved data.
   *
   * @param {boolean}           [opts.animateTo=false] - Animate to restore data.
   *
   * @param {number}            [opts.duration=0.1] - Duration in seconds.
   *
   * @param {Function}          [opts.ease=linear] - Easing function.
   *
   * @param {Function}          [opts.interpolate=lerp] - Interpolation function.
   *
   * @returns {ApplicationShellExt|Promise<ApplicationShellExt>} When synchronous the application or Promise when
   *                                                             animating resolving with application.
   */
  set(data2, { async = false, animateTo = false, duration = 0.1, ease = identity, interpolate = lerp$5 } = {}) {
    if (!isObject(data2)) {
      throw new TypeError(`ApplicationState - restore error: 'data' is not an object.`);
    }
    const application = __privateGet(this, _application);
    if (!isObject(data2?.position)) {
      console.warn(`ApplicationState.set warning: 'data.position' is not an object.`);
      return application;
    }
    const rendered = application.rendered;
    if (animateTo && !rendered) {
      console.warn(`ApplicationState.set warning: Application is not rendered and 'animateTo' is true.`);
      return application;
    }
    if (animateTo) {
      if (data2.position.transformOrigin !== application.position.transformOrigin) {
        application.position.transformOrigin = data2.position.transformOrigin;
      }
      if (isObject(data2?.ui)) {
        const minimized = typeof data2.ui?.minimized === "boolean" ? data2.ui.minimized : false;
        if (application?.reactive?.minimized && !minimized) {
          application.maximize({ animate: false, duration: 0 });
        }
      }
      const promise2 = application.position.animate.to(
        data2.position,
        { duration, ease, interpolate }
      ).finished.then((cancelled) => {
        if (cancelled) {
          return application;
        }
        if (isObject(data2?.options)) {
          application?.reactive.mergeOptions(data2.options);
        }
        if (isObject(data2?.ui)) {
          const minimized = typeof data2.ui?.minimized === "boolean" ? data2.ui.minimized : false;
          if (!application?.reactive?.minimized && minimized) {
            application.minimize({ animate: false, duration: 0 });
          }
        }
        if (isObject(data2?.beforeMinimized)) {
          application.position.state.set({ name: "#beforeMinimized", ...data2.beforeMinimized });
        }
        return application;
      });
      if (async) {
        return promise2;
      }
    } else {
      if (rendered) {
        if (isObject(data2?.options)) {
          application?.reactive.mergeOptions(data2.options);
        }
        if (isObject(data2?.ui)) {
          const minimized = typeof data2.ui?.minimized === "boolean" ? data2.ui.minimized : false;
          if (application?.reactive?.minimized && !minimized) {
            application.maximize({ animate: false, duration: 0 });
          } else if (!application?.reactive?.minimized && minimized) {
            application.minimize({ animate: false, duration });
          }
        }
        if (isObject(data2?.beforeMinimized)) {
          application.position.state.set({ name: "#beforeMinimized", ...data2.beforeMinimized });
        }
        application.position.set(data2.position);
      } else {
        let positionData = data2.position;
        if (isObject(data2.beforeMinimized)) {
          positionData = data2.beforeMinimized;
          positionData.left = data2.position.left;
          positionData.top = data2.position.top;
        }
        application.position.set(positionData);
      }
    }
    return application;
  }
};
_application = new WeakMap();
_dataSaved2 = new WeakMap();
__name(_ApplicationState, "ApplicationState");
let ApplicationState = _ApplicationState;
const _GetSvelteData = class _GetSvelteData {
  /**
   * Keep a direct reference to the SvelteData array in an associated {@link SvelteApplication}.
   *
   * @param {MountedAppShell[]|null[]}  applicationShellHolder - A reference to the MountedAppShell array.
   *
   * @param {SvelteData[]}  svelteData - A reference to the SvelteData array of mounted components.
   */
  constructor(applicationShellHolder, svelteData) {
    /**
     * @type {MountedAppShell[]|null[]}
     */
    __privateAdd(this, _applicationShellHolder, void 0);
    /**
     * @type {SvelteData[]}
     */
    __privateAdd(this, _svelteData, void 0);
    __privateSet(this, _applicationShellHolder, applicationShellHolder);
    __privateSet(this, _svelteData, svelteData);
  }
  /**
   * Returns any mounted {@link MountedAppShell}.
   *
   * @returns {MountedAppShell|null} Any mounted application shell.
   */
  get applicationShell() {
    return __privateGet(this, _applicationShellHolder)[0];
  }
  /**
   * Returns the indexed Svelte component.
   *
   * @param {number}   index -
   *
   * @returns {object} The loaded Svelte component.
   */
  component(index2) {
    const data2 = __privateGet(this, _svelteData)[index2];
    return isObject(data2) ? data2?.component : void 0;
  }
  /**
   * Returns the Svelte component entries iterator.
   *
   * @returns {Generator<Array<number|SvelteComponent>>} Svelte component entries iterator.
   * @yields
   */
  *componentEntries() {
    for (let cntr = 0; cntr < __privateGet(this, _svelteData).length; cntr++) {
      yield [cntr, __privateGet(this, _svelteData)[cntr].component];
    }
  }
  /**
   * Returns the Svelte component values iterator.
   *
   * @returns {Generator<SvelteComponent>} Svelte component values iterator.
   * @yields
   */
  *componentValues() {
    for (let cntr = 0; cntr < __privateGet(this, _svelteData).length; cntr++) {
      yield __privateGet(this, _svelteData)[cntr].component;
    }
  }
  /**
   * Returns the indexed SvelteData entry.
   *
   * @param {number}   index -
   *
   * @returns {SvelteData} The loaded Svelte config + component.
   */
  data(index2) {
    return __privateGet(this, _svelteData)[index2];
  }
  /**
   * Returns the {@link SvelteData} instance for a given component.
   *
   * @param {object} component - Svelte component.
   *
   * @returns {SvelteData} -  The loaded Svelte config + component.
   */
  dataByComponent(component) {
    for (const data2 of __privateGet(this, _svelteData)) {
      if (data2.component === component) {
        return data2;
      }
    }
    return void 0;
  }
  /**
   * Returns the SvelteData entries iterator.
   *
   * @returns {IterableIterator<[number, SvelteData]>} SvelteData entries iterator.
   */
  dataEntries() {
    return __privateGet(this, _svelteData).entries();
  }
  /**
   * Returns the SvelteData values iterator.
   *
   * @returns {IterableIterator<SvelteData>} SvelteData values iterator.
   */
  dataValues() {
    return __privateGet(this, _svelteData).values();
  }
  /**
   * Returns the length of the mounted Svelte component list.
   *
   * @returns {number} Length of mounted Svelte component list.
   */
  get length() {
    return __privateGet(this, _svelteData).length;
  }
};
_applicationShellHolder = new WeakMap();
_svelteData = new WeakMap();
__name(_GetSvelteData, "GetSvelteData");
let GetSvelteData = _GetSvelteData;
function loadSvelteConfig({ app, template, config, elementRootUpdate } = {}) {
  const svelteOptions = isObject(config.options) ? config.options : {};
  let target;
  if (config.target instanceof HTMLElement) {
    target = config.target;
  } else if (template instanceof HTMLElement && typeof config.target === "string") {
    target = template.querySelector(config.target);
  } else {
    target = document.createDocumentFragment();
  }
  if (target === void 0) {
    console.log(
      `%c[TRL] loadSvelteConfig error - could not find target selector, '${config.target}', for config:
`,
      "background: rgb(57,34,34)",
      config
    );
    throw new Error();
  }
  const NewSvelteComponent = config.class;
  const svelteConfig = parseSvelteConfig({ ...config, target }, app);
  const externalContext = svelteConfig.context.get("#external");
  externalContext.application = app;
  externalContext.elementRootUpdate = elementRootUpdate;
  externalContext.sessionStorage = app.reactive.sessionStorage;
  let eventbus;
  if (isObject(app._eventbus) && typeof app._eventbus.createProxy === "function") {
    eventbus = app._eventbus.createProxy();
    externalContext.eventbus = eventbus;
  }
  Object.seal(externalContext);
  svelteConfig.context.set("external", new Proxy({}, {
    get(targetUnused, prop) {
      console.warn(`[TRL] Deprecation warning: Please change getContext('external') to getContext('#external').`);
      return externalContext[prop];
    }
  }));
  const component = new NewSvelteComponent(svelteConfig);
  svelteConfig.eventbus = eventbus;
  let element2;
  if (isApplicationShell(component)) {
    element2 = component.elementRoot;
  }
  if (target instanceof DocumentFragment && target.firstElementChild) {
    if (element2 === void 0) {
      element2 = target.firstElementChild;
    }
    template.append(target);
  } else if (config.target instanceof HTMLElement && element2 === void 0) {
    if (config.target instanceof HTMLElement && typeof svelteOptions.selectorElement !== "string") {
      console.log(
        `%c[TRL] loadSvelteConfig error - HTMLElement target with no 'selectorElement' defined.

Note: If configuring an application shell and directly targeting a HTMLElement did you bind an'elementRoot' and include '<svelte:options accessors={true}/>'?

Offending config:
`,
        "background: rgb(57,34,34)",
        config
      );
      throw new Error();
    }
    element2 = target.querySelector(svelteOptions.selectorElement);
    if (element2 === null || element2 === void 0) {
      console.log(
        `%c[TRL] loadSvelteConfig error - HTMLElement target with 'selectorElement', '${svelteOptions.selectorElement}', not found for config:
`,
        "background: rgb(57,34,34)",
        config
      );
      throw new Error();
    }
  }
  const injectHTML = !(config.target instanceof HTMLElement);
  return { config: svelteConfig, component, element: element2, injectHTML };
}
__name(loadSvelteConfig, "loadSvelteConfig");
const _SvelteReactive = class _SvelteReactive {
  /**
   * @param {SvelteApplication} application - The host Foundry application.
   */
  constructor(application) {
    /**
     * Initializes the Svelte stores and derived stores for the application options and UI state.
     *
     * While writable stores are created the update method is stored in private variables locally and derived Readable
     * stores are provided for essential options which are commonly used.
     *
     * These stores are injected into all Svelte components mounted under the `external` context: `storeAppOptions` and
     * ` storeUIState`.
     */
    __privateAdd(this, _storesInitialize);
    /**
     * Registers local store subscriptions for app options. `popOut` controls registering this app with `ui.windows`.
     *
     * @see SvelteApplication._injectHTML
     */
    __privateAdd(this, _storesSubscribe);
    /**
     * Unsubscribes from any locally monitored stores.
     *
     * @see SvelteApplication.close
     */
    __privateAdd(this, _storesUnsubscribe);
    /**
     * @type {SvelteApplication}
     */
    __privateAdd(this, _application2, void 0);
    /**
     * @type {boolean}
     */
    __privateAdd(this, _initialized, false);
    /** @type {TJSSessionStorage} */
    __privateAdd(this, _sessionStorage, void 0);
    /**
     * The Application option store which is injected into mounted Svelte component context under the `external` key.
     *
     * @type {StoreAppOptions}
     */
    __privateAdd(this, _storeAppOptions, void 0);
    /**
     * Stores the update function for `#storeAppOptions`.
     *
     * @type {import('svelte/store').Writable.update}
     */
    __privateAdd(this, _storeAppOptionsUpdate, void 0);
    /**
     * Stores the UI state data to make it accessible via getters.
     *
     * @type {object}
     */
    __privateAdd(this, _dataUIState, void 0);
    /**
     * The UI option store which is injected into mounted Svelte component context under the `external` key.
     *
     * @type {StoreUIOptions}
     */
    __privateAdd(this, _storeUIState, void 0);
    /**
     * Stores the update function for `#storeUIState`.
     *
     * @type {import('svelte/store').Writable.update}
     */
    __privateAdd(this, _storeUIStateUpdate, void 0);
    /**
     * Stores the unsubscribe functions from local store subscriptions.
     *
     * @type {import('svelte/store').Unsubscriber[]}
     */
    __privateAdd(this, _storeUnsubscribe, []);
    __privateSet(this, _application2, application);
    const optionsSessionStorage = application?.options?.sessionStorage;
    if (optionsSessionStorage !== void 0 && !(optionsSessionStorage instanceof TJSSessionStorage)) {
      throw new TypeError(`'options.sessionStorage' is not an instance of TJSSessionStorage.`);
    }
    __privateSet(this, _sessionStorage, optionsSessionStorage !== void 0 ? optionsSessionStorage : new TJSSessionStorage());
  }
  /**
   * Initializes reactive support. Package private for internal use.
   *
   * @returns {SvelteStores|void} Internal methods to interact with Svelte stores.
   * @package
   */
  initialize() {
    if (__privateGet(this, _initialized)) {
      return;
    }
    __privateSet(this, _initialized, true);
    __privateMethod(this, _storesInitialize, storesInitialize_fn).call(this);
    return {
      appOptionsUpdate: __privateGet(this, _storeAppOptionsUpdate),
      uiOptionsUpdate: __privateGet(this, _storeUIStateUpdate),
      subscribe: __privateMethod(this, _storesSubscribe, storesSubscribe_fn).bind(this),
      unsubscribe: __privateMethod(this, _storesUnsubscribe, storesUnsubscribe_fn).bind(this)
    };
  }
  // Store getters -----------------------------------------------------------------------------------------------------
  /**
   * @returns {TJSSessionStorage} Returns TJSSessionStorage instance.
   */
  get sessionStorage() {
    return __privateGet(this, _sessionStorage);
  }
  /**
   * Returns the store for app options.
   *
   * @returns {StoreAppOptions} App options store.
   */
  get storeAppOptions() {
    return __privateGet(this, _storeAppOptions);
  }
  /**
   * Returns the store for UI options.
   *
   * @returns {StoreUIOptions} UI options store.
   */
  get storeUIState() {
    return __privateGet(this, _storeUIState);
  }
  // Only reactive getters ---------------------------------------------------------------------------------------------
  /**
   * Returns the current dragging UI state.
   *
   * @returns {boolean} Dragging UI state.
   */
  get dragging() {
    return __privateGet(this, _dataUIState).dragging;
  }
  /**
   * Returns the current minimized UI state.
   *
   * @returns {boolean} Minimized UI state.
   */
  get minimized() {
    return __privateGet(this, _dataUIState).minimized;
  }
  /**
   * Returns the current resizing UI state.
   *
   * @returns {boolean} Resizing UI state.
   */
  get resizing() {
    return __privateGet(this, _dataUIState).resizing;
  }
  // Reactive getter / setters -----------------------------------------------------------------------------------------
  /**
   * Returns the draggable app option.
   *
   * @returns {boolean} Draggable app option.
   */
  get draggable() {
    return __privateGet(this, _application2)?.options?.draggable;
  }
  /**
   * Returns the focusAuto app option.
   *
   * @returns {boolean} When true auto-management of app focus is enabled.
   */
  get focusAuto() {
    return __privateGet(this, _application2)?.options?.focusAuto;
  }
  /**
   * Returns the focusKeep app option.
   *
   * @returns {boolean} When `focusAuto` and `focusKeep` is true; keeps internal focus.
   */
  get focusKeep() {
    return __privateGet(this, _application2)?.options?.focusKeep;
  }
  /**
   * Returns the focusTrap app option.
   *
   * @returns {boolean} When true focus trapping / wrapping is enabled keeping focus inside app.
   */
  get focusTrap() {
    return __privateGet(this, _application2)?.options?.focusTrap;
  }
  /**
   * Returns the headerButtonNoClose app option.
   *
   * @returns {boolean} Remove the close the button in header app option.
   */
  get headerButtonNoClose() {
    return __privateGet(this, _application2)?.options?.headerButtonNoClose;
  }
  /**
   * Returns the headerButtonNoLabel app option.
   *
   * @returns {boolean} Remove the labels from buttons in header app option.
   */
  get headerButtonNoLabel() {
    return __privateGet(this, _application2)?.options?.headerButtonNoLabel;
  }
  /**
   * Returns the headerIcon app option.
   *
   * @returns {string|void} URL for header app icon.
   */
  get headerIcon() {
    return __privateGet(this, _application2)?.options?.headerIcon;
  }
  /**
   * Returns the headerNoTitleMinimized app option.
   *
   * @returns {boolean} When true removes the header title when minimized.
   */
  get headerNoTitleMinimized() {
    return __privateGet(this, _application2)?.options?.headerNoTitleMinimized;
  }
  /**
   * Returns the minimizable app option.
   *
   * @returns {boolean} Minimizable app option.
   */
  get minimizable() {
    return __privateGet(this, _application2)?.options?.minimizable;
  }
  /**
   * Returns the Foundry popOut state; {@link Application.popOut}
   *
   * @returns {boolean} Positionable app option.
   */
  get popOut() {
    return __privateGet(this, _application2).popOut;
  }
  /**
   * Returns the positionable app option; {@link SvelteApplicationOptions.positionable}
   *
   * @returns {boolean} Positionable app option.
   */
  get positionable() {
    return __privateGet(this, _application2)?.options?.positionable;
  }
  /**
   * Returns the resizable option.
   *
   * @returns {boolean} Resizable app option.
   */
  get resizable() {
    return __privateGet(this, _application2)?.options?.resizable;
  }
  /**
   * Returns the title accessor from the parent Application class; {@link Application.title}
   * TODO: Application v2; note that super.title localizes `this.options.title`; IMHO it shouldn't.
   *
   * @returns {string} Title.
   */
  get title() {
    return __privateGet(this, _application2).title;
  }
  /**
   * Sets `this.options.draggable` which is reactive for application shells.
   *
   * @param {boolean}  draggable - Sets the draggable option.
   */
  set draggable(draggable2) {
    if (typeof draggable2 === "boolean") {
      this.setOptions("draggable", draggable2);
    }
  }
  /**
   * Sets `this.options.focusAuto` which is reactive for application shells.
   *
   * @param {boolean}  focusAuto - Sets the focusAuto option.
   */
  set focusAuto(focusAuto) {
    if (typeof focusAuto === "boolean") {
      this.setOptions("focusAuto", focusAuto);
    }
  }
  /**
   * Sets `this.options.focusKeep` which is reactive for application shells.
   *
   * @param {boolean}  focusKeep - Sets the focusKeep option.
   */
  set focusKeep(focusKeep) {
    if (typeof focusKeep === "boolean") {
      this.setOptions("focusKeep", focusKeep);
    }
  }
  /**
   * Sets `this.options.focusTrap` which is reactive for application shells.
   *
   * @param {boolean}  focusTrap - Sets the focusTrap option.
   */
  set focusTrap(focusTrap) {
    if (typeof focusTrap === "boolean") {
      this.setOptions("focusTrap", focusTrap);
    }
  }
  /**
   * Sets `this.options.headerButtonNoClose` which is reactive for application shells.
   *
   * @param {boolean}  headerButtonNoClose - Sets the headerButtonNoClose option.
   */
  set headerButtonNoClose(headerButtonNoClose) {
    if (typeof headerButtonNoClose === "boolean") {
      this.setOptions("headerButtonNoClose", headerButtonNoClose);
    }
  }
  /**
   * Sets `this.options.headerButtonNoLabel` which is reactive for application shells.
   *
   * @param {boolean}  headerButtonNoLabel - Sets the headerButtonNoLabel option.
   */
  set headerButtonNoLabel(headerButtonNoLabel) {
    if (typeof headerButtonNoLabel === "boolean") {
      this.setOptions("headerButtonNoLabel", headerButtonNoLabel);
    }
  }
  /**
   * Sets `this.options.headerIcon` which is reactive for application shells.
   *
   * @param {string|void}  headerIcon - Sets the headerButtonNoLabel option.
   */
  set headerIcon(headerIcon) {
    if (headerIcon === void 0 || typeof headerIcon === "string") {
      this.setOptions("headerIcon", headerIcon);
    }
  }
  /**
   * Sets `this.options.headerNoTitleMinimized` which is reactive for application shells.
   *
   * @param {boolean}  headerNoTitleMinimized - Sets the headerNoTitleMinimized option.
   */
  set headerNoTitleMinimized(headerNoTitleMinimized) {
    if (typeof headerNoTitleMinimized === "boolean") {
      this.setOptions("headerNoTitleMinimized", headerNoTitleMinimized);
    }
  }
  /**
   * Sets `this.options.minimizable` which is reactive for application shells that are also pop out.
   *
   * @param {boolean}  minimizable - Sets the minimizable option.
   */
  set minimizable(minimizable) {
    if (typeof minimizable === "boolean") {
      this.setOptions("minimizable", minimizable);
    }
  }
  /**
   * Sets `this.options.popOut` which is reactive for application shells. This will add / remove this application
   * from `ui.windows`.
   *
   * @param {boolean}  popOut - Sets the popOut option.
   */
  set popOut(popOut) {
    if (typeof popOut === "boolean") {
      this.setOptions("popOut", popOut);
    }
  }
  /**
   * Sets `this.options.positionable` enabling / disabling {@link SvelteApplication.position.set}.
   *
   * @param {boolean}  positionable - Sets the positionable option.
   */
  set positionable(positionable) {
    if (typeof positionable === "boolean") {
      this.setOptions("positionable", positionable);
    }
  }
  /**
   * Sets `this.options.resizable` which is reactive for application shells.
   *
   * @param {boolean}  resizable - Sets the resizable option.
   */
  set resizable(resizable) {
    if (typeof resizable === "boolean") {
      this.setOptions("resizable", resizable);
    }
  }
  /**
   * Sets `this.options.title` which is reactive for application shells.
   *
   * Note: Will set empty string if title is undefined or null.
   *
   * @param {string|undefined|null}   title - Application title; will be localized, so a translation key is fine.
   */
  set title(title) {
    if (typeof title === "string") {
      this.setOptions("title", title);
    } else if (title === void 0 || title === null) {
      this.setOptions("title", "");
    }
  }
  // Reactive Options API -------------------------------------------------------------------------------------------
  /**
   * Provides a way to safely get this applications options given an accessor string which describes the
   * entries to walk. To access deeper entries into the object format the accessor string with `.` between entries
   * to walk.
   *
   * // TODO DOCUMENT the accessor in more detail.
   *
   * @param {string}   accessor - The path / key to set. You can set multiple levels.
   *
   * @param {*}        [defaultValue] - A default value returned if the accessor is not found.
   *
   * @returns {*} Value at the accessor.
   */
  getOptions(accessor, defaultValue) {
    return safeAccess(__privateGet(this, _application2).options, accessor, defaultValue);
  }
  /**
   * Provides a way to merge `options` into this applications options and update the appOptions store.
   *
   * @param {object}   options - The options object to merge with `this.options`.
   */
  mergeOptions(options) {
    __privateGet(this, _storeAppOptionsUpdate).call(this, (instanceOptions) => deepMerge(instanceOptions, options));
  }
  /**
   * Provides a way to safely set this applications options given an accessor string which describes the
   * entries to walk. To access deeper entries into the object format the accessor string with `.` between entries
   * to walk.
   *
   * Additionally if an application shell Svelte component is mounted and exports the `appOptions` property then
   * the application options is set to `appOptions` potentially updating the application shell / Svelte component.
   *
   * // TODO DOCUMENT the accessor in more detail.
   *
   * @param {string}   accessor - The path / key to set. You can set multiple levels.
   *
   * @param {*}        value - Value to set.
   */
  setOptions(accessor, value) {
    const success = safeSet(__privateGet(this, _application2).options, accessor, value);
    if (success) {
      __privateGet(this, _storeAppOptionsUpdate).call(this, () => __privateGet(this, _application2).options);
    }
  }
  /**
   * Updates the UI Options store with the current header buttons. You may dynamically add / remove header buttons
   * if using an application shell Svelte component. In either overriding `_getHeaderButtons` or responding to the
   * Hooks fired return a new button array and the uiOptions store is updated and the application shell will render
   * the new buttons.
   *
   * Optionally you can set in the SvelteApplication app options {@link SvelteApplicationOptions.headerButtonNoClose}
   * to remove the close button and {@link SvelteApplicationOptions.headerButtonNoLabel} to true and labels will be
   * removed from the header buttons.
   *
   * @param {object} opts - Optional parameters (for internal use)
   *
   * @param {boolean} opts.headerButtonNoClose - The value for `headerButtonNoClose`.
   *
   * @param {boolean} opts.headerButtonNoLabel - The value for `headerButtonNoLabel`.
   */
  updateHeaderButtons({
    headerButtonNoClose = __privateGet(this, _application2).options.headerButtonNoClose,
    headerButtonNoLabel = __privateGet(this, _application2).options.headerButtonNoLabel
  } = {}) {
    let buttons = __privateGet(this, _application2)._getHeaderButtons();
    if (typeof headerButtonNoClose === "boolean" && headerButtonNoClose) {
      buttons = buttons.filter((button) => button.class !== "close");
    }
    if (typeof headerButtonNoLabel === "boolean" && headerButtonNoLabel) {
      for (const button of buttons) {
        button.label = void 0;
      }
    }
    __privateGet(this, _storeUIStateUpdate).call(this, (options) => {
      options.headerButtons = buttons;
      return options;
    });
  }
};
_application2 = new WeakMap();
_initialized = new WeakMap();
_sessionStorage = new WeakMap();
_storeAppOptions = new WeakMap();
_storeAppOptionsUpdate = new WeakMap();
_dataUIState = new WeakMap();
_storeUIState = new WeakMap();
_storeUIStateUpdate = new WeakMap();
_storeUnsubscribe = new WeakMap();
_storesInitialize = new WeakSet();
storesInitialize_fn = /* @__PURE__ */ __name(function() {
  const writableAppOptions = writable$1(__privateGet(this, _application2).options);
  __privateSet(this, _storeAppOptionsUpdate, writableAppOptions.update);
  const storeAppOptions = {
    subscribe: writableAppOptions.subscribe,
    draggable: propertyStore(writableAppOptions, "draggable"),
    focusAuto: propertyStore(writableAppOptions, "focusAuto"),
    focusKeep: propertyStore(writableAppOptions, "focusKeep"),
    focusTrap: propertyStore(writableAppOptions, "focusTrap"),
    headerButtonNoClose: propertyStore(writableAppOptions, "headerButtonNoClose"),
    headerButtonNoLabel: propertyStore(writableAppOptions, "headerButtonNoLabel"),
    headerIcon: propertyStore(writableAppOptions, "headerIcon"),
    headerNoTitleMinimized: propertyStore(writableAppOptions, "headerNoTitleMinimized"),
    minimizable: propertyStore(writableAppOptions, "minimizable"),
    popOut: propertyStore(writableAppOptions, "popOut"),
    positionable: propertyStore(writableAppOptions, "positionable"),
    resizable: propertyStore(writableAppOptions, "resizable"),
    title: propertyStore(writableAppOptions, "title")
  };
  Object.freeze(storeAppOptions);
  __privateSet(this, _storeAppOptions, storeAppOptions);
  __privateSet(this, _dataUIState, {
    dragging: false,
    headerButtons: [],
    minimized: __privateGet(this, _application2)._minimized,
    resizing: false
  });
  const writableUIOptions = writable$1(__privateGet(this, _dataUIState));
  __privateSet(this, _storeUIStateUpdate, writableUIOptions.update);
  const storeUIState = {
    subscribe: writableUIOptions.subscribe,
    dragging: propertyStore(writableUIOptions, "dragging"),
    headerButtons: derived(writableUIOptions, ($options, set) => set($options.headerButtons)),
    minimized: derived(writableUIOptions, ($options, set) => set($options.minimized)),
    resizing: propertyStore(writableUIOptions, "resizing")
  };
  Object.freeze(storeUIState);
  __privateSet(this, _storeUIState, storeUIState);
}, "#storesInitialize");
_storesSubscribe = new WeakSet();
storesSubscribe_fn = /* @__PURE__ */ __name(function() {
  __privateGet(this, _storeUnsubscribe).push(subscribeIgnoreFirst(__privateGet(this, _storeAppOptions).headerButtonNoClose, (value) => {
    this.updateHeaderButtons({ headerButtonNoClose: value });
  }));
  __privateGet(this, _storeUnsubscribe).push(subscribeIgnoreFirst(__privateGet(this, _storeAppOptions).headerButtonNoLabel, (value) => {
    this.updateHeaderButtons({ headerButtonNoLabel: value });
  }));
  __privateGet(this, _storeUnsubscribe).push(subscribeIgnoreFirst(__privateGet(this, _storeAppOptions).popOut, (value) => {
    if (value && __privateGet(this, _application2).rendered) {
      globalThis.ui.windows[__privateGet(this, _application2).appId] = __privateGet(this, _application2);
    } else {
      delete globalThis.ui.windows[__privateGet(this, _application2).appId];
    }
  }));
}, "#storesSubscribe");
_storesUnsubscribe = new WeakSet();
storesUnsubscribe_fn = /* @__PURE__ */ __name(function() {
  __privateGet(this, _storeUnsubscribe).forEach((unsubscribe) => unsubscribe());
  __privateSet(this, _storeUnsubscribe, []);
}, "#storesUnsubscribe");
__name(_SvelteReactive, "SvelteReactive");
let SvelteReactive = _SvelteReactive;
const _SvelteApplication = class _SvelteApplication extends Application {
  /**
   * @param {SvelteApplicationOptions} options - The options for the application.
   *
   * @inheritDoc
   */
  constructor(options = {}) {
    super(options);
    /**
     * This method is invoked by the `elementRootUpdate` callback that is added to the external context passed to
     * Svelte components. When invoked it updates the local element roots tracked by SvelteApplication.
     *
     * This method may also be invoked by HMR / hot module replacement via `svelte-hmr`.
     */
    __privateAdd(this, _updateApplicationShell);
    /**
     * Stores the first mounted component which follows the application shell contract.
     *
     * @type {MountedAppShell[]|null[]} Application shell.
     */
    __privateAdd(this, _applicationShellHolder2, [null]);
    /**
     * Stores and manages application state for saving / restoring / serializing.
     *
     * @type {ApplicationState}
     */
    __privateAdd(this, _applicationState, void 0);
    /**
     * Stores the target element which may not necessarily be the main element.
     *
     * @type {HTMLElement}
     */
    __privateAdd(this, _elementTarget, null);
    /**
     * Stores the content element which is set for application shells.
     *
     * @type {HTMLElement}
     */
    __privateAdd(this, _elementContent, null);
    /**
     * Stores initial z-index from `_renderOuter` to set to target element / Svelte component.
     *
     * @type {number}
     */
    __privateAdd(this, _initialZIndex, 95);
    /**
     * Stores on mount state which is checked in _render to trigger onSvelteMount callback.
     *
     * @type {boolean}
     */
    __privateAdd(this, _onMount, false);
    /**
     * The position store.
     *
     * @type {Position}
     */
    __privateAdd(this, _position3, void 0);
    /**
     * Contains the Svelte stores and reactive accessors.
     *
     * @type {SvelteReactive}
     */
    __privateAdd(this, _reactive, void 0);
    /**
     * Stores SvelteData entries with instantiated Svelte components.
     *
     * @type {SvelteData[]}
     */
    __privateAdd(this, _svelteData2, []);
    /**
     * Provides a helper class that combines multiple methods for interacting with the mounted components tracked in
     * {@link SvelteData}.
     *
     * @type {GetSvelteData}
     */
    __privateAdd(this, _getSvelteData, new GetSvelteData(__privateGet(this, _applicationShellHolder2), __privateGet(this, _svelteData2)));
    /**
     * Contains methods to interact with the Svelte stores.
     *
     * @type {SvelteStores}
     */
    __privateAdd(this, _stores4, void 0);
    __privateSet(this, _applicationState, new ApplicationState(this));
    __privateSet(this, _position3, new Position(this, {
      ...this.position,
      ...this.options,
      initial: this.options.positionInitial,
      ortho: this.options.positionOrtho,
      validator: this.options.positionValidator
    }));
    delete this.position;
    Object.defineProperty(this, "position", {
      get: () => __privateGet(this, _position3),
      set: (position) => {
        if (isObject(position)) {
          __privateGet(this, _position3).set(position);
        }
      }
    });
    __privateSet(this, _reactive, new SvelteReactive(this));
    __privateSet(this, _stores4, __privateGet(this, _reactive).initialize());
  }
  /**
   * Specifies the default options that SvelteApplication supports.
   *
   * @returns {SvelteApplicationOptions} options - Application options.
   * @see https://foundryvtt.com/api/interfaces/client.ApplicationOptions.html
   */
  static get defaultOptions() {
    return deepMerge(super.defaultOptions, {
      defaultCloseAnimation: true,
      // If false the default slide close animation is not run.
      draggable: true,
      // If true then application shells are draggable.
      focusAuto: true,
      // When true auto-management of app focus is enabled.
      focusKeep: false,
      // When `focusAuto` and `focusKeep` is true; keeps internal focus.
      focusSource: void 0,
      // Stores any A11yFocusSource data that is applied when app is closed.
      focusTrap: true,
      // When true focus trapping / wrapping is enabled keeping focus inside app.
      headerButtonNoClose: false,
      // If true then the close header button is removed.
      headerButtonNoLabel: false,
      // If true then header button labels are removed for application shells.
      headerIcon: void 0,
      // Sets a header icon given an image URL.
      headerNoTitleMinimized: false,
      // If true then header title is hidden when application is minimized.
      minHeight: MIN_WINDOW_HEIGHT,
      // Assigned to position. Number specifying minimum window height.
      minWidth: MIN_WINDOW_WIDTH,
      // Assigned to position. Number specifying minimum window width.
      positionable: true,
      // If false then `position.set` does not take effect.
      positionInitial: Position.Initial.browserCentered,
      // A helper for initial position placement.
      positionOrtho: true,
      // When true Position is optimized for orthographic use.
      positionValidator: Position.Validators.transformWindow,
      // A function providing the default validator.
      sessionStorage: void 0,
      // An instance of SessionStorage to share across SvelteApplications.
      svelte: void 0,
      // A Svelte configuration object.
      transformOrigin: "top left"
      // By default, 'top / left' respects rotation when minimizing.
    });
  }
  /**
   * Returns the content element if an application shell is mounted.
   *
   * @returns {HTMLElement} Content element.
   */
  get elementContent() {
    return __privateGet(this, _elementContent);
  }
  /**
   * Returns the target element or main element if no target defined.
   *
   * @returns {HTMLElement} Target element.
   */
  get elementTarget() {
    return __privateGet(this, _elementTarget);
  }
  /**
   * Returns the reactive accessors & Svelte stores for SvelteApplication.
   *
   * @returns {SvelteReactive} The reactive accessors & Svelte stores.
   */
  get reactive() {
    return __privateGet(this, _reactive);
  }
  /**
   * Returns the application state manager.
   *
   * @returns {ApplicationState} The application state manager.
   */
  get state() {
    return __privateGet(this, _applicationState);
  }
  /**
   * Returns the Svelte helper class w/ various methods to access mounted Svelte components.
   *
   * @returns {GetSvelteData} GetSvelteData
   */
  get svelte() {
    return __privateGet(this, _getSvelteData);
  }
  /**
   * In this case of when a template is defined in app options `html` references the inner HTML / template. However,
   * to activate classic v1 tabs for a Svelte component the element target is passed as an array simulating JQuery as
   * the element is retrieved immediately and the core listeners use standard DOM queries.
   *
   * @inheritDoc
   * @protected
   * @ignore
   */
  _activateCoreListeners(html) {
    super._activateCoreListeners(typeof this.options.template === "string" ? html : [__privateGet(this, _elementTarget)]);
  }
  /**
   * Provide an override to set this application as the active window regardless of z-index. Changes behaviour from
   * Foundry core. This is important / used for instance in dialog key handling for left / right button selection.
   *
   * @param {object} [opts] - Optional parameters.
   *
   * @param {boolean} [opts.force=false] - Force bring to top; will increment z-index by popOut order.
   *
   */
  bringToTop({ force = false } = {}) {
    if (force || this.popOut) {
      super.bringToTop();
    }
    if (document.activeElement !== document.body && !this.elementTarget.contains(document.activeElement)) {
      if (document.activeElement instanceof HTMLElement) {
        document.activeElement.blur();
      }
      document.body.focus();
    }
    globalThis.ui.activeWindow = this;
  }
  /**
   * Note: This method is fully overridden and duplicated as Svelte components need to be destroyed manually and the
   * best visual result is to destroy them after the default slide up animation occurs, but before the element
   * is removed from the DOM.
   *
   * If you destroy the Svelte components before the slide up animation the Svelte elements are removed immediately
   * from the DOM. The purpose of overriding ensures the slide up animation is always completed before
   * the Svelte components are destroyed and then the element is removed from the DOM.
   *
   * Close the application and un-register references to it within UI mappings.
   * This function returns a Promise which resolves once the window closing animation concludes
   *
   * @param {object}   [options] - Optional parameters.
   *
   * @param {boolean}  [options.force] - Force close regardless of render state.
   *
   * @returns {Promise<void>}    A Promise which resolves once the application is closed.
   * @ignore
   */
  async close(options = {}) {
    const states = Application.RENDER_STATES;
    if (!options.force && ![states.RENDERED, states.ERROR].includes(this._state)) {
      return;
    }
    __privateGet(this, _stores4).unsubscribe();
    this._state = states.CLOSING;
    const el = __privateGet(this, _elementTarget);
    if (!el) {
      return this._state = states.CLOSED;
    }
    const content = el.querySelector(".window-content");
    if (content) {
      content.style.overflow = "hidden";
      for (let cntr = content.children.length; --cntr >= 0; ) {
        content.children[cntr].style.overflow = "hidden";
      }
    }
    for (const cls of this.constructor._getInheritanceChain()) {
      Hooks.call(`close${cls.name}`, this, el);
    }
    const animate = typeof this.options.defaultCloseAnimation === "boolean" ? this.options.defaultCloseAnimation : true;
    if (animate) {
      el.style.minHeight = "0";
      const { paddingBottom, paddingTop } = globalThis.getComputedStyle(el);
      await el.animate([
        { maxHeight: `${el.clientHeight}px`, paddingTop, paddingBottom },
        { maxHeight: 0, paddingTop: 0, paddingBottom: 0 }
      ], { duration: 250, easing: "ease-in", fill: "forwards" }).finished;
    }
    const svelteDestroyPromises = [];
    for (const entry of __privateGet(this, _svelteData2)) {
      svelteDestroyPromises.push(outroAndDestroy(entry.component));
      const eventbus = entry.config.eventbus;
      if (isObject(eventbus) && typeof eventbus.off === "function") {
        eventbus.off();
        entry.config.eventbus = void 0;
      }
    }
    await Promise.all(svelteDestroyPromises);
    __privateGet(this, _svelteData2).length = 0;
    el.remove();
    this.position.state.restore({
      name: "#beforeMinimized",
      properties: ["width", "height"],
      silent: true,
      remove: true
    });
    __privateGet(this, _applicationShellHolder2)[0] = null;
    this._element = null;
    __privateSet(this, _elementContent, null);
    __privateSet(this, _elementTarget, null);
    delete globalThis.ui.windows[this.appId];
    this._minimized = false;
    this._scrollPositions = null;
    this._state = states.CLOSED;
    __privateSet(this, _onMount, false);
    __privateGet(this, _stores4).uiOptionsUpdate((storeOptions) => deepMerge(storeOptions, { minimized: this._minimized }));
    A11yHelper.applyFocusSource(this.options.focusSource);
    delete this.options.focusSource;
  }
  /**
   * Inject the Svelte components defined in `this.options.svelte`. The Svelte component can attach to the existing
   * pop-out of Application or provide no template and render into a document fragment which is then attached to the
   * DOM.
   *
   * @param {JQuery} html -
   *
   * @inheritDoc
   * @ignore
   */
  _injectHTML(html) {
    if (this.popOut && html.length === 0 && Array.isArray(this.options.svelte)) {
      throw new Error(
        "SvelteApplication - _injectHTML - A popout app with no template can only support one Svelte component."
      );
    }
    this.reactive.updateHeaderButtons();
    const elementRootUpdate = /* @__PURE__ */ __name(() => {
      let cntr = 0;
      return (elementRoot) => {
        if (elementRoot !== null && elementRoot !== void 0 && cntr++ > 0) {
          __privateMethod(this, _updateApplicationShell, updateApplicationShell_fn).call(this);
          return true;
        }
        return false;
      };
    }, "elementRootUpdate");
    if (Array.isArray(this.options.svelte)) {
      for (const svelteConfig of this.options.svelte) {
        const svelteData = loadSvelteConfig({
          app: this,
          template: html[0],
          config: svelteConfig,
          elementRootUpdate
        });
        if (isApplicationShell(svelteData.component)) {
          if (this.svelte.applicationShell !== null) {
            throw new Error(
              `SvelteApplication - _injectHTML - An application shell is already mounted; offending config:
                    ${JSON.stringify(svelteConfig)}`
            );
          }
          __privateGet(this, _applicationShellHolder2)[0] = svelteData.component;
          if (isHMRProxy(svelteData.component) && Array.isArray(svelteData.component?.$$?.on_hmr)) {
            svelteData.component.$$.on_hmr.push(() => () => __privateMethod(this, _updateApplicationShell, updateApplicationShell_fn).call(this));
          }
        }
        __privateGet(this, _svelteData2).push(svelteData);
      }
    } else if (isObject(this.options.svelte)) {
      const svelteData = loadSvelteConfig({
        app: this,
        template: html[0],
        config: this.options.svelte,
        elementRootUpdate
      });
      if (isApplicationShell(svelteData.component)) {
        if (this.svelte.applicationShell !== null) {
          throw new Error(
            `SvelteApplication - _injectHTML - An application shell is already mounted; offending config:
                 ${JSON.stringify(this.options.svelte)}`
          );
        }
        __privateGet(this, _applicationShellHolder2)[0] = svelteData.component;
        if (isHMRProxy(svelteData.component) && Array.isArray(svelteData.component?.$$?.on_hmr)) {
          svelteData.component.$$.on_hmr.push(() => () => __privateMethod(this, _updateApplicationShell, updateApplicationShell_fn).call(this));
        }
      }
      __privateGet(this, _svelteData2).push(svelteData);
    }
    const isDocumentFragment = html.length && html[0] instanceof DocumentFragment;
    let injectHTML = true;
    for (const svelteData of __privateGet(this, _svelteData2)) {
      if (!svelteData.injectHTML) {
        injectHTML = false;
        break;
      }
    }
    if (injectHTML) {
      super._injectHTML(html);
    }
    if (this.svelte.applicationShell !== null) {
      this._element = $(this.svelte.applicationShell.elementRoot);
      __privateSet(this, _elementContent, hasGetter(this.svelte.applicationShell, "elementContent") ? this.svelte.applicationShell.elementContent : null);
      __privateSet(this, _elementTarget, hasGetter(this.svelte.applicationShell, "elementTarget") ? this.svelte.applicationShell.elementTarget : null);
    } else if (isDocumentFragment) {
      for (const svelteData of __privateGet(this, _svelteData2)) {
        if (svelteData.element instanceof HTMLElement) {
          this._element = $(svelteData.element);
          break;
        }
      }
    }
    if (__privateGet(this, _elementTarget) === null) {
      __privateSet(this, _elementTarget, typeof this.options.selectorTarget === "string" ? this._element[0].querySelector(this.options.selectorTarget) : this._element[0]);
    }
    if (__privateGet(this, _elementTarget) === null || __privateGet(this, _elementTarget) === void 0) {
      throw new Error(`SvelteApplication - _injectHTML: Target element '${this.options.selectorTarget}' not found.`);
    }
    if (typeof this.options.positionable === "boolean" && this.options.positionable) {
      __privateGet(this, _elementTarget).style.zIndex = typeof this.options.zIndex === "number" ? this.options.zIndex : __privateGet(this, _initialZIndex) ?? 95;
    }
    __privateGet(this, _stores4).subscribe();
  }
  /**
   * Provides a mechanism to update the UI options store for maximized.
   *
   * Note: the sanity check is duplicated from {@link Application.maximize} the store is updated _before_
   * performing the rest of animations. This allows application shells to remove / show any resize handlers
   * correctly. Extra constraint data is stored in a saved position state in {@link SvelteApplication.minimize}
   * to animate the content area.
   *
   * @param {object}   [opts] - Optional parameters.
   *
   * @param {boolean}  [opts.animate=true] - When true perform default maximizing animation.
   *
   * @param {number}   [opts.duration=0.1] - Controls content area animation duration in seconds.
   */
  async maximize({ animate = true, duration = 0.1 } = {}) {
    if (!this.popOut || [false, null].includes(this._minimized)) {
      return;
    }
    this._minimized = null;
    const durationMS = duration * 1e3;
    const element2 = this.elementTarget;
    const header = element2.querySelector(".window-header");
    const content = element2.querySelector(".window-content");
    const positionBefore = this.position.state.get({ name: "#beforeMinimized" });
    if (animate) {
      await this.position.state.restore({
        name: "#beforeMinimized",
        async: true,
        animateTo: true,
        properties: ["width"],
        duration: 0.1
      });
    }
    element2.classList.remove("minimized");
    for (let cntr = header.children.length; --cntr >= 0; ) {
      header.children[cntr].style.display = null;
    }
    content.style.display = null;
    let constraints;
    if (animate) {
      ({ constraints } = this.position.state.restore({
        name: "#beforeMinimized",
        animateTo: true,
        properties: ["height"],
        remove: true,
        duration
      }));
    } else {
      ({ constraints } = this.position.state.remove({ name: "#beforeMinimized" }));
    }
    await content.animate([
      { maxHeight: 0, paddingTop: 0, paddingBottom: 0, offset: 0 },
      { ...constraints, offset: 1 },
      { maxHeight: "100%", offset: 1 }
    ], { duration: durationMS, fill: "forwards" }).finished;
    this.position.set({
      minHeight: positionBefore.minHeight ?? this.options?.minHeight ?? MIN_WINDOW_HEIGHT,
      minWidth: positionBefore.minWidth ?? this.options?.minWidth ?? MIN_WINDOW_WIDTH
    });
    element2.style.minWidth = null;
    element2.style.minHeight = null;
    this._minimized = false;
    setTimeout(() => {
      content.style.overflow = null;
      for (let cntr = content.children.length; --cntr >= 0; ) {
        content.children[cntr].style.overflow = null;
      }
    }, 50);
    __privateGet(this, _stores4).uiOptionsUpdate((options) => deepMerge(options, { minimized: false }));
  }
  /**
   * Provides a mechanism to update the UI options store for minimized.
   *
   * Note: the sanity check is duplicated from {@link Application.minimize} the store is updated _before_
   * performing the rest of animations. This allows application shells to remove / show any resize handlers
   * correctly. Extra constraint data is stored in a saved position state in {@link SvelteApplication.minimize}
   * to animate the content area.
   *
   * @param {object}   [opts] - Optional parameters
   *
   * @param {boolean}  [opts.animate=true] - When true perform default minimizing animation.
   *
   * @param {number}   [opts.duration=0.1] - Controls content area animation duration in seconds.
   */
  async minimize({ animate = true, duration = 0.1 } = {}) {
    if (!this.rendered || !this.popOut || [true, null].includes(this._minimized)) {
      return;
    }
    __privateGet(this, _stores4).uiOptionsUpdate((options) => deepMerge(options, { minimized: true }));
    this._minimized = null;
    const durationMS = duration * 1e3;
    const element2 = this.elementTarget;
    const header = element2.querySelector(".window-header");
    const content = element2.querySelector(".window-content");
    const beforeMinWidth = this.position.minWidth;
    const beforeMinHeight = this.position.minHeight;
    this.position.set({ minWidth: 100, minHeight: 30 });
    element2.style.minWidth = "100px";
    element2.style.minHeight = "30px";
    if (content) {
      content.style.overflow = "hidden";
      for (let cntr = content.children.length; --cntr >= 0; ) {
        content.children[cntr].style.overflow = "hidden";
      }
    }
    const { paddingBottom, paddingTop } = globalThis.getComputedStyle(content);
    const constraints = {
      maxHeight: `${content.clientHeight}px`,
      paddingTop,
      paddingBottom
    };
    if (animate) {
      const animation = content.animate([
        constraints,
        { maxHeight: 0, paddingTop: 0, paddingBottom: 0 }
      ], { duration: durationMS, fill: "forwards" });
      animation.finished.then(() => content.style.display = "none");
    } else {
      setTimeout(() => content.style.display = "none", durationMS);
    }
    const saved = this.position.state.save({ name: "#beforeMinimized", constraints });
    saved.minWidth = beforeMinWidth;
    saved.minHeight = beforeMinHeight;
    const headerOffsetHeight = header.offsetHeight;
    this.position.minHeight = headerOffsetHeight;
    if (animate) {
      await this.position.animate.to({ height: headerOffsetHeight }, { duration }).finished;
    }
    for (let cntr = header.children.length; --cntr >= 0; ) {
      const className = header.children[cntr].className;
      if (className.includes("window-title") || className.includes("close")) {
        continue;
      }
      if (className.includes("keep-minimized")) {
        header.children[cntr].style.display = "block";
        continue;
      }
      header.children[cntr].style.display = "none";
    }
    if (animate) {
      await this.position.animate.to({ width: MIN_WINDOW_WIDTH }, { duration: 0.1 }).finished;
    }
    element2.classList.add("minimized");
    this._minimized = true;
  }
  /**
   * Provides a callback after all Svelte components are initialized.
   *
   * @param {object}      [opts] - Optional parameters.
   *
   * @param {HTMLElement} [opts.element] - HTMLElement container for main application element.
   *
   * @param {HTMLElement} [opts.elementContent] - HTMLElement container for content area of application shells.
   *
   * @param {HTMLElement} [opts.elementTarget] - HTMLElement container for main application target element.
   */
  onSvelteMount({ element: element2, elementContent, elementTarget } = {}) {
  }
  // eslint-disable-line no-unused-vars
  /**
   * Provides a callback after the main application shell is remounted. This may occur during HMR / hot module
   * replacement or directly invoked from the `elementRootUpdate` callback passed to the application shell component
   * context.
   *
   * @param {object}      [opts] - Optional parameters.
   *
   * @param {HTMLElement} [opts.element] - HTMLElement container for main application element.
   *
   * @param {HTMLElement} [opts.elementContent] - HTMLElement container for content area of application shells.
   *
   * @param {HTMLElement} [opts.elementTarget] - HTMLElement container for main application target element.
   */
  onSvelteRemount({ element: element2, elementContent, elementTarget } = {}) {
  }
  // eslint-disable-line no-unused-vars
  /**
   * Override replacing HTML as Svelte components control the rendering process. Only potentially change the outer
   * application frame / title for pop-out applications.
   *
   * @inheritDoc
   * @ignore
   */
  _replaceHTML(element2, html) {
    if (!element2.length) {
      return;
    }
    this.reactive.updateHeaderButtons();
  }
  /**
   * Provides an override verifying that a new Application being rendered for the first time doesn't have a
   * corresponding DOM element already loaded. This is a check that only occurs when `this._state` is
   * `Application.RENDER_STATES.NONE`. It is useful in particular when SvelteApplication has a static ID
   * explicitly set in `this.options.id` and long intro / outro transitions are assigned. If a new application
   * sharing this static ID attempts to open / render for the first time while an existing DOM element sharing
   * this static ID exists then the initial render is cancelled below rather than crashing later in the render
   * cycle {@link Position.set}.
   *
   * @inheritDoc
   * @protected
   * @ignore
   */
  async _render(force = false, options = {}) {
    if (isObject(options?.focusSource)) {
      this.options.focusSource = options.focusSource;
    }
    if (this._state === Application.RENDER_STATES.NONE && document.querySelector(`#${this.id}`) instanceof HTMLElement) {
      console.warn(`SvelteApplication - _render: A DOM element already exists for CSS ID '${this.id}'. Cancelling initial render for new application with appId '${this.appId}'.`);
      return;
    }
    await super._render(force, options);
    if (!__privateGet(this, _onMount)) {
      this.onSvelteMount({ element: this._element[0], elementContent: __privateGet(this, _elementContent), elementTarget: __privateGet(this, _elementTarget) });
      __privateSet(this, _onMount, true);
    }
  }
  /**
   * Render the inner application content. Only render a template if one is defined otherwise provide an empty
   * JQuery element per the core Foundry API.
   *
   * @param {object} data         The data used to render the inner template
   *
   * @returns {Promise.<JQuery>}   A promise resolving to the constructed jQuery object
   *
   * @protected
   * @ignore
   */
  async _renderInner(data2) {
    const html = typeof this.template === "string" ? await renderTemplate(this.template, data2) : document.createDocumentFragment();
    return $(html);
  }
  /**
   * Stores the initial z-index set in `_renderOuter` which is used in `_injectHTML` to set the target element
   * z-index after the Svelte component is mounted.
   *
   * @returns {Promise<JQuery>} Outer frame / unused.
   * @protected
   * @ignore
   */
  async _renderOuter() {
    const html = await super._renderOuter();
    __privateSet(this, _initialZIndex, html[0].style.zIndex);
    return html;
  }
  /**
   * All calculation and updates of position are implemented in {@link Position.set}. This allows position to be fully
   * reactive and in control of updating inline styles for the application.
   *
   * This method remains for backward compatibility with Foundry. If you have a custom override quite likely you need
   * to update to using the {@link Position.validators} functionality.
   *
   * @param {PositionDataExtended}   [position] - Position data.
   *
   * @returns {Position} The updated position object for the application containing the new values
   */
  setPosition(position) {
    return this.position.set(position);
  }
};
_applicationShellHolder2 = new WeakMap();
_applicationState = new WeakMap();
_elementTarget = new WeakMap();
_elementContent = new WeakMap();
_initialZIndex = new WeakMap();
_onMount = new WeakMap();
_position3 = new WeakMap();
_reactive = new WeakMap();
_svelteData2 = new WeakMap();
_getSvelteData = new WeakMap();
_stores4 = new WeakMap();
_updateApplicationShell = new WeakSet();
updateApplicationShell_fn = /* @__PURE__ */ __name(function() {
  const applicationShell = this.svelte.applicationShell;
  if (applicationShell !== null) {
    this._element = $(applicationShell.elementRoot);
    __privateSet(this, _elementContent, hasGetter(applicationShell, "elementContent") ? applicationShell.elementContent : null);
    __privateSet(this, _elementTarget, hasGetter(applicationShell, "elementTarget") ? applicationShell.elementTarget : null);
    if (__privateGet(this, _elementTarget) === null) {
      __privateSet(this, _elementTarget, typeof this.options.selectorTarget === "string" ? this._element[0].querySelector(this.options.selectorTarget) : this._element[0]);
    }
    if (typeof this.options.positionable === "boolean" && this.options.positionable) {
      __privateGet(this, _elementTarget).style.zIndex = typeof this.options.zIndex === "number" ? this.options.zIndex : __privateGet(this, _initialZIndex) ?? 95;
      __superGet(_SvelteApplication.prototype, this, "bringToTop").call(this);
      this.position.set(this.position.get());
    }
    __superGet(_SvelteApplication.prototype, this, "_activateCoreListeners").call(this, [__privateGet(this, _elementTarget)]);
    this.onSvelteRemount({ element: this._element[0], elementContent: __privateGet(this, _elementContent), elementTarget: __privateGet(this, _elementTarget) });
  }
}, "#updateApplicationShell");
__name(_SvelteApplication, "SvelteApplication");
let SvelteApplication = _SvelteApplication;
const _TJSDialogData = class _TJSDialogData {
  /**
   * @param {SvelteApplication} application - The host Foundry application.
   */
  constructor(application) {
    /**
     * @type {SvelteApplication}
     */
    __privateAdd(this, _application3, void 0);
    /**
     * Provides configuration of the dialog button bar.
     *
     * @type {Record<string, TJSDialogButtonData>}
     */
    __publicField(this, "buttons");
    /**
     * A Svelte configuration object or HTML string content.
     *
     * @type {object|string}
     */
    __publicField(this, "content");
    /**
     * The default button ID to focus initially.
     *
     * @type {string}
     */
    __publicField(this, "default");
    /**
     * The dialog is draggable when true.
     *
     * @type {boolean}
     */
    __publicField(this, "draggable");
    /**
     * When true auto-management of app focus is enabled.
     *
     * @type {boolean}
     */
    __publicField(this, "focusAuto");
    /**
     * When true the first focusable element that isn't a button is focused.
     *
     * @type {boolean}
     */
    __publicField(this, "focusFirst");
    /**
     * When `focusAuto` and `focusKeep` is true; keeps internal focus.
     *
     * @type {boolean}
     */
    __publicField(this, "focusKeep");
    /**
     * When true the dialog is minimizable.
     *
     * @type {boolean}
     */
    __publicField(this, "minimizable");
    /**
     * When true a modal dialog is displayed.
     *
     * @type {boolean}
     */
    __publicField(this, "modal");
    /**
     * Additional options for modal dialog display.
     *
     * @type {object}
     * TODO: Better specify type / options.
     */
    __publicField(this, "modalOptions");
    /**
     * When true and an error is raised in dialog callback functions post a UI error notification.
     *
     * @type {boolean}
     */
    __publicField(this, "notifyError");
    /**
     * Callback invoked when dialog is closed; no button option selected. When defined as a string any matching function
     * by name exported from content Svelte component is invoked.
     *
     * @type {string|((application: TJSDialog) => any)}
     */
    __publicField(this, "onClose");
    /**
     * When true and a Promise has been created by {@link TJSDialog.wait} and the Promise is not in the process of being
     * resolved or rejected on close of the dialog any `onClose` function is invoked and any result that is undefined
     * will cause the Promise to then be rejected.
     *
     * @type {boolean}
     */
    __publicField(this, "rejectClose");
    /**
     * When true the dialog is resizable.
     *
     * @type {boolean}
     */
    __publicField(this, "resizable");
    /**
     * When true and resolving any Promises and there are undefined results from any button callbacks the button ID is
     * resolved.
     *
     * @type {boolean}
     */
    __publicField(this, "resolveId");
    /**
     * The dialog window title.
     *
     * @type {string}
     */
    __publicField(this, "title");
    /**
     * Transition options for the dialog.
     *
     * @type {object}
     * TODO: Better specify type / options.
     */
    __publicField(this, "transition");
    /**
     * A specific z-index for the dialog. Pass null for the dialog to act like other applications in regard bringing to
     * top when activated.
     *
     * @type {number|null}
     */
    __publicField(this, "zIndex");
    __privateSet(this, _application3, application);
  }
  /**
   * Provides a way to safely get this dialogs data given an accessor string which describes the
   * entries to walk. To access deeper entries into the object format the accessor string with `.` between entries
   * to walk.
   *
   * // TODO DOCUMENT the accessor in more detail.
   *
   * @param {string}   accessor - The path / key to set. You can set multiple levels.
   *
   * @param {*}        [defaultValue] - A default value returned if the accessor is not found.
   *
   * @returns {*} Value at the accessor.
   */
  get(accessor, defaultValue) {
    return safeAccess(this, accessor, defaultValue);
  }
  /**
   * @param {object} data - Merge provided data object into Dialog data.
   */
  merge(data2) {
    deepMerge(this, data2);
    const component = __privateGet(this, _application3).svelte.component(0);
    if (component?.data) {
      component.data = this;
    }
  }
  /**
   * Provides a way to safely set this dialogs data given an accessor string which describes the
   * entries to walk. To access deeper entries into the object format the accessor string with `.` between entries
   * to walk.
   *
   * Automatically the dialog data will be updated in the associated DialogShell Svelte component.
   *
   * // TODO DOCUMENT the accessor in more detail.
   *
   * @param {string}   accessor - The path / key to set. You can set multiple levels.
   *
   * @param {*}        value - Value to set.
   *
   * @returns {boolean} True if successful.
   */
  set(accessor, value) {
    const success = safeSet(this, accessor, value);
    if (success) {
      const component = __privateGet(this, _application3).svelte.component(0);
      if (component?.data) {
        component.data = this;
      }
    }
    return success;
  }
};
_application3 = new WeakMap();
__name(_TJSDialogData, "TJSDialogData");
let TJSDialogData = _TJSDialogData;
const _TJSDialog = class _TJSDialog extends SvelteApplication {
  /**
   * @param {TJSDialogOptions}           data - Dialog options.
   *
   * @param {SvelteApplicationOptions}   [options] - SvelteApplication options.
   */
  constructor(data2, options = {}) {
    super(options);
    /** @type {TJSDialogData} */
    __privateAdd(this, _data4, void 0);
    /** @type {ManagedPromise} */
    __privateAdd(this, _managedPromise, void 0);
    __privateSet(this, _managedPromise, new ManagedPromise());
    __privateSet(this, _data4, new TJSDialogData(this));
    this.data = data2;
    Object.defineProperty(this.svelte, "dialogComponent", {
      get: () => this.svelte?.applicationShell?.dialogComponent
    });
  }
  /**
   * Default options for TJSDialog. Provides a default width and setting `height` to `auto` to always display dialog
   * content even if it changes. The default `DialogShell` / `svelte` options should not be changed and instead mount
   * the dialog content component by supplying a Svelte configuration object to dialog data `content` field.
   *
   * @returns {SvelteApplicationOptions} Default options
   */
  static get defaultOptions() {
    return deepMerge(super.defaultOptions, {
      classes: ["dialog"],
      width: 400,
      height: "auto",
      svelte: {
        class: DialogShell,
        intro: true,
        target: document.body,
        props: function() {
          return {
            data: __privateGet(this, _data4),
            managedPromise: __privateGet(this, _managedPromise)
          };
        }
      }
    });
  }
  /**
   * Returns the dialog data.
   *
   * @returns {TJSDialogData} Dialog data.
   */
  get data() {
    return __privateGet(this, _data4);
  }
  /**
   * @returns {ManagedPromise} Returns the managed promise.
   */
  get managedPromise() {
    return __privateGet(this, _managedPromise);
  }
  /**
   * Sets the dialog data; this is reactive.
   *
   * @param {object}   data - Dialog data.
   */
  set data(data2) {
    if (!isObject(data2)) {
      throw new TypeError(`TJSDialog set data error: 'data' is not an object'.`);
    }
    const descriptors = Object.getOwnPropertyDescriptors(__privateGet(this, _data4));
    for (const descriptor in descriptors) {
      if (descriptors[descriptor].configurable) {
        delete __privateGet(this, _data4)[descriptor];
      }
    }
    __privateGet(this, _data4).merge(data2);
  }
  /**
   * Close the dialog and un-register references to it within UI mappings.
   * This function returns a Promise which resolves once the window closing animation concludes.
   *
   * @param {object}   [options] - Optional parameters.
   *
   * @param {boolean}  [options.force] - Force close regardless of render state.
   *
   * @returns {Promise<void>} A Promise which resolves once the application is closed with the callback value or
   *                          `true`.
   */
  async close(options) {
    var _a2;
    try {
      if (__privateGet(this, _managedPromise).isActive && !__privateGet(this, _managedPromise).isProcessing) {
        const result = __privateMethod(_a2 = _TJSDialog, _invokeFn, invokeFn_fn).call(_a2, __privateGet(this, _data4).onClose, this, null);
        const rejectClose = typeof __privateGet(this, _data4).rejectClose === "boolean" ? __privateGet(this, _data4).rejectClose : false;
        if (rejectClose && result === null) {
          __privateGet(this, _managedPromise).reject(new Error("TJSDialog was closed without a choice being made."));
        } else {
          __privateGet(this, _managedPromise).resolve(result);
        }
      }
    } catch (err) {
      const notifyError = typeof __privateGet(this, _data4).notifyError === "boolean" ? __privateGet(this, _data4).notifyError : true;
      if (notifyError) {
        globalThis.ui.notifications.error(err, { console: false });
      }
      if (!__privateGet(this, _managedPromise).reject(err)) {
        throw err;
      }
    } finally {
      await super.close(options);
    }
  }
  /**
   * Brings to top or renders this dialog returning a Promise that is resolved any button pressed or when the dialog
   * is closed.
   *
   * Creates an anonymous data defined TJSDialog returning a Promise that can be awaited upon for the user to make a
   * choice.
   *
   * Note: `null` is returned if the dialog is closed without a user making a choice.
   *
   * @template T
   *
   * @param {object}   [options] - Options.
   *
   * @param {boolean}  [options.reuse=false] - When true if there is an existing managed Promise this allows multiple
   *        sources to await on the same result.
   *
   * @returns {Promise<T>} A promise for dialog resolution.
   */
  async wait(options) {
    if (this.rendered) {
      this.bringToTop();
    } else {
      this.render(true, { focus: true });
    }
    return __privateGet(this, _managedPromise).create(options);
  }
  // ---------------------------------------------------------------------------------------------------------------
  /**
   * A helper factory method to create simple confirmation dialog windows which consist of simple yes / no prompts.
   * If you require more flexibility, a custom TJSDialog instance is preferred. The default focused button is 'yes'.
   * You can change the default focused button by setting `default` to `yes` or `no`.
   *
   * @template T
   *
   * @param {TJSDialogOptions} data - Confirm dialog options.
   *
   * @param {string|((application: TJSDialog) => any)} [data.onYes] - Callback function upon `yes`; may be an async
   *        function. When defined as a string any matching function by name exported from content Svelte component is
   *        invoked.
   *
   * @param {string|((application: TJSDialog) => any)} [data.onNo] - Callback function upon `no`; may be an async
   *        function. When defined as a string any matching function by name exported from content Svelte component is
   *        invoked.
   *
   * @param {SvelteApplicationOptions}  [options]  SvelteApplication options passed to the TJSDialog constructor.
   *
   * @returns {Promise<T>} A promise which resolves with result of yes / no callbacks or true / false.
   *
   * @example
   * const result = await TJSDialog.confirm({
   *  title: 'A Yes or No Question',
   *  content: '<p>Choose wisely.</p>',
   *  onYes: () => 'YES Result'
   *  onNo: () => 'NO Result'
   * });
   *
   * // Logs 'YES result', 'NO Result', or null if the user closed the dialog without making a selection.
   * console.log(result);
   */
  static async confirm({ onYes, onNo, ...data2 } = {}, options = {}) {
    const mergedButtons = deepMerge({
      yes: {
        icon: "fas fa-check",
        label: "Yes"
      },
      no: {
        icon: "fas fa-times",
        label: "No"
      }
    }, data2.buttons ?? {});
    return this.wait({
      ...data2,
      buttons: deepMerge(mergedButtons, {
        yes: {
          onPress: (application) => __privateMethod(this, _invokeFn, invokeFn_fn).call(this, onYes, application, true)
        },
        no: {
          onPress: (application) => __privateMethod(this, _invokeFn, invokeFn_fn).call(this, onNo, application, false)
        }
      }),
      default: data2.default ?? "yes"
    }, options);
  }
  /**
   * A helper factory method to display a basic "prompt" style TJSDialog with a single button.
   *
   * @template T
   *
   * @param {TJSDialogOptions} [data] - Prompt dialog options.
   *
   * @param {string|((application: TJSDialog) => any)} [data.onOk] - Callback function upon `ok`; may be an async
   *        function. When defined as a string any matching function by name exported from content Svelte component is
   *        invoked.
   *
   * @param {string}   [data.label] - The OK prompt button text.
   *
   * @param {string}   [data.icon="fas fa-check"] - Set another icon besides `fas fa-check` for button.
   *
   * @param {SvelteApplicationOptions}  [options]  SvelteApplication options passed to the TJSDialog constructor.
   *
   * @returns {Promise<T>} The returned value from the provided callback function or `true` if the button
   *          is pressed.
   *
   * @example
   * const result = await TJSDialog.prompt({
   *  title: 'Are you OK?',
   *  content: '<p>Are you OK?.</p>',
   *  label: 'Feeling Fine!'
   *  onOk: () => 'OK'
   * });
   *
   * // Logs 'OK' or null if the user closed the dialog without making a selection.
   * console.log(result);
   */
  static async prompt({ onOk, label, icon = "fas fa-check", ...data2 } = {}, options = {}) {
    return this.wait({
      ...data2,
      buttons: {
        ok: {
          icon,
          label,
          onPress: (application) => __privateMethod(this, _invokeFn, invokeFn_fn).call(this, onOk, application, true)
        }
      },
      default: "ok"
    }, options);
  }
  /**
   * Creates an anonymous data defined TJSDialog returning a Promise that can be awaited upon for the user to make a
   * choice.
   *
   * Note: By default `null` is returned if the dialog is closed without a user making a choice.
   *
   * @template T
   *
   * @param {TJSDialogOptions}  data - Dialog data passed to the TJSDialog constructor.
   *
   * @param {SvelteApplicationOptions}  [options]  SvelteApplication options passed to the TJSDialog constructor.
   *
   * @returns {Promise<T>} A Promise that resolves to the chosen result.
   */
  static async wait(data2, options = {}) {
    if (!isObject(data2)) {
      throw new TypeError(`TJSDialog.wait error: 'data' is not an object'.`);
    }
    return new this({ ...data2 }, options).wait();
  }
};
_data4 = new WeakMap();
_managedPromise = new WeakMap();
_invokeFn = new WeakSet();
invokeFn_fn = /* @__PURE__ */ __name(function(callback, application, defaultResult = void 0) {
  let result = defaultResult;
  switch (typeof callback) {
    case "function":
      result = callback(application);
      break;
    case "string": {
      const dialogComponent = application?.svelte?.dialogComponent;
      if (dialogComponent !== void 0 && typeof dialogComponent?.[callback] === "function") {
        result = dialogComponent?.[callback](application);
      } else {
        if (dialogComponent === void 0) {
          console.warn(`[TRL] TJSDialog warning: 'onPress' defined as a string with no associated content Svelte component.`);
        } else if (typeof dialogComponent?.[callback] !== "function") {
          console.warn(`[TRL] TJSDialog warning: The content Svelte component does not contain an associated function '${callback}'. Did you remember to add '<svelte:options accessors={true} />' and export the function?`);
        }
      }
      break;
    }
  }
  return result;
}, "#invokeFn");
/**
 * A helper method to invoke a callback function directly or lookup an exported function with the same name from any
 * content Svelte component to invoke. This is used internally to apply default values for `confirm` and `prompt`.
 *
 * @param {string|((application: TJSDialog) => any)} callback - Callback function to invoke; may be an async
 *        function. When defined as a string any matching function by name exported from content Svelte component is
 *        invoked.
 *
 * @param {TJSDialog} application - TJSDialog instance passed to callback.
 *
 * @param {*} [defaultResult] - An optional default result to return; undefined if not specified.
 *
 * @returns {*} Result.
 */
__privateAdd(_TJSDialog, _invokeFn);
__name(_TJSDialog, "TJSDialog");
let TJSDialog = _TJSDialog;
Hooks.on("PopOut:loading", (app) => {
  if (app instanceof SvelteApplication) {
    app.position.enabled = false;
  }
});
Hooks.on("PopOut:popin", (app) => {
  if (app instanceof SvelteApplication) {
    app.position.enabled = true;
  }
});
Hooks.on("PopOut:close", (app) => {
  if (app instanceof SvelteApplication) {
    app.position.enabled = true;
  }
});
const _DropItemDialog = class _DropItemDialog extends SvelteApplication {
  /**
   *
   * @param item
   * @param target
   * @param options
   */
  constructor(item, target, options = {
    localizationTitle: "DropItem"
  }) {
    super({
      title: game.i18n.localize(`ITEM-PILES.Applications.${options.localizationTitle}.Title`),
      id: `item-pile-drop-item-${item.id}${target ? "-" + target.id : ""}-${randomID()}`,
      svelte: {
        class: Drop_item_dialog_shell,
        target: document.body,
        props: {
          item,
          target
        }
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
    this.item = item;
    this.target = target;
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 430,
      height: "auto",
      classes: ["item-piles-app"]
    });
  }
  static getActiveApps(id) {
    return getActiveApps(`item-pile-drop-item-${id}`);
  }
  static async show(item, target, options = {}) {
    if (!options?.localizationTitle) {
      options.localizationTitle = "DropItem";
    }
    const apps = this.getActiveApps(item.uuid + (target ? "-" + target.uuid : ""));
    if (apps.length) {
      for (let app of apps) {
        app.render(false, { focus: true });
      }
      return;
    }
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(item, target, options).render(true, { focus: true });
    });
  }
};
__name(_DropItemDialog, "DropItemDialog");
let DropItemDialog = _DropItemDialog;
function create_if_block_5$e(ctx) {
  let span;
  let t0;
  let t1;
  let t2;
  return {
    c() {
      span = element("span");
      t0 = text("(x");
      t1 = text(
        /*$quantity*/
        ctx[6]
      );
      t2 = text(")");
      attr(span, "class", "item-piles-small-text");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t0);
      append(span, t1);
      append(span, t2);
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantity*/
      64)
        set_data(
          t1,
          /*$quantity*/
          ctx2[6]
        );
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_if_block_5$e, "create_if_block_5$e");
function create_if_block_2$u(ctx) {
  let div;
  function select_block_type(ctx2, dirty) {
    if (
      /*$editQuantities*/
      ctx2[4]
    )
      return create_if_block_3$o;
    if (
      /*$quantityLeft*/
      ctx2[5] && /*$quantity*/
      ctx2[6]
    )
      return create_if_block_4$i;
    return create_else_block$o;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      if_block.c();
      attr(div, "class", "item-piles-quantity-container");
      set_style(div, "flex", "2.5");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if_block.m(div, null);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(div, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if_block.d();
    }
  };
}
__name(create_if_block_2$u, "create_if_block_2$u");
function create_else_block$o(ctx) {
  let span;
  let t_value = localize(`ITEM-PILES.Inspect.${/*entry*/
  ctx[1].toShare && /*$quantity*/
  ctx[6] ? "NoShareLeft" : "NoneLeft"}`) + "";
  let t;
  return {
    c() {
      span = element("span");
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*entry, $quantity*/
      66 && t_value !== (t_value = localize(`ITEM-PILES.Inspect.${/*entry*/
      ctx2[1].toShare && /*$quantity*/
      ctx2[6] ? "NoShareLeft" : "NoneLeft"}`) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_else_block$o, "create_else_block$o");
function create_if_block_4$i(ctx) {
  let div;
  let input;
  let input_disabled_value;
  let t0;
  let span;
  let t1;
  let t2;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      input = element("input");
      t0 = space();
      span = element("span");
      t1 = text("/ ");
      t2 = text(
        /*$quantityLeft*/
        ctx[5]
      );
      attr(input, "class", "item-piles-quantity");
      attr(input, "type", "number");
      attr(input, "min", "1");
      attr(
        input,
        "max",
        /*$quantity*/
        ctx[6]
      );
      input.disabled = input_disabled_value = !/*$quantity*/
      ctx[6];
      attr(span, "class", "item-piles-input-divider");
      toggle_class(span, "item-piles-text-right", !/*store*/
      ctx[0].recipient);
      attr(div, "class", "item-piles-quantity-input-container");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*$currentQuantity*/
        ctx[10]
      );
      append(div, t0);
      append(div, span);
      append(span, t1);
      append(span, t2);
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler_1*/
          ctx[24]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantity*/
      64) {
        attr(
          input,
          "max",
          /*$quantity*/
          ctx2[6]
        );
      }
      if (dirty & /*$quantity*/
      64 && input_disabled_value !== (input_disabled_value = !/*$quantity*/
      ctx2[6])) {
        input.disabled = input_disabled_value;
      }
      if (dirty & /*$currentQuantity*/
      1024 && to_number(input.value) !== /*$currentQuantity*/
      ctx2[10]) {
        set_input_value(
          input,
          /*$currentQuantity*/
          ctx2[10]
        );
      }
      if (dirty & /*$quantityLeft*/
      32)
        set_data(
          t2,
          /*$quantityLeft*/
          ctx2[5]
        );
      if (dirty & /*store*/
      1) {
        toggle_class(span, "item-piles-text-right", !/*store*/
        ctx2[0].recipient);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$i, "create_if_block_4$i");
function create_if_block_3$o(ctx) {
  let div;
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      input = element("input");
      attr(input, "class", "item-piles-quantity");
      attr(input, "type", "number");
      attr(input, "min", "0");
      attr(input, "draggable", "true");
      attr(div, "class", "item-piles-quantity-input-container");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*$quantity*/
        ctx[6]
      );
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[23]
          ),
          listen(input, "dragstart", stop_propagation(prevent_default(
            /*dragstart_handler*/
            ctx[21]
          )))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantity*/
      64 && to_number(input.value) !== /*$quantity*/
      ctx2[6]) {
        set_input_value(
          input,
          /*$quantity*/
          ctx2[6]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_3$o, "create_if_block_3$o");
function create_if_block_1$G(ctx) {
  let button;
  let t_value = localize("Remove") + "";
  let t;
  let button_disabled_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t = text(t_value);
      attr(button, "class", "item-piles-item-take-button");
      attr(button, "type", "button");
      button.disabled = button_disabled_value = !/*$quantityLeft*/
      ctx[5];
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_2*/
          ctx[26]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantityLeft*/
      32 && button_disabled_value !== (button_disabled_value = !/*$quantityLeft*/
      ctx2[5])) {
        button.disabled = button_disabled_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$G, "create_if_block_1$G");
function create_if_block$W(ctx) {
  let button;
  let t_value = localize("ITEM-PILES.Inspect.Take") + "";
  let t;
  let button_disabled_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t = text(t_value);
      attr(button, "class", "item-piles-item-take-button");
      attr(button, "type", "button");
      button.disabled = button_disabled_value = !/*$quantityLeft*/
      ctx[5] || !/*$quantity*/
      ctx[6];
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[25]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantityLeft, $quantity*/
      96 && button_disabled_value !== (button_disabled_value = !/*$quantityLeft*/
      ctx2[5] || !/*$quantity*/
      ctx2[6])) {
        button.disabled = button_disabled_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$W, "create_if_block$W");
function create_fragment$1h(ctx) {
  let div3;
  let div0;
  let img_1;
  let img_1_src_value;
  let t0;
  let div2;
  let div1;
  let p;
  let t1;
  let t2;
  let t3;
  let t4;
  let div3_draggable_value;
  let div3_transition;
  let current;
  let mounted;
  let dispose;
  let if_block0 = !/*$editQuantities*/
  ctx[4] && /*entry*/
  ctx[1].canStack && !/*currency*/
  ctx[2] && create_if_block_5$e(ctx);
  let if_block1 = (
    /*entry*/
    (ctx[1].canStack || !/*entry*/
    ctx[1].id) && create_if_block_2$u(ctx)
  );
  function select_block_type_1(ctx2, dirty) {
    if (!/*$editQuantities*/
    ctx2[4])
      return create_if_block$W;
    if (!/*entry*/
    ctx2[1].canStack && !/*entry*/
    ctx2[1].isCurrency)
      return create_if_block_1$G;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block2 = current_block_type && current_block_type(ctx);
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      img_1 = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      p = element("p");
      t1 = text(
        /*$name*/
        ctx[9]
      );
      t2 = space();
      if (if_block0)
        if_block0.c();
      t3 = space();
      if (if_block1)
        if_block1.c();
      t4 = space();
      if (if_block2)
        if_block2.c();
      attr(img_1, "class", "item-piles-img");
      if (!src_url_equal(img_1.src, img_1_src_value = /*$img*/
      ctx[7]))
        attr(img_1, "src", img_1_src_value);
      attr(div0, "class", "item-piles-img-container");
      set_style(
        p,
        "color",
        /*$rarityColor*/
        ctx[8] || "inherit"
      );
      toggle_class(
        p,
        "item-piles-clickable-link",
        /*canInspectItems*/
        ctx[3]
      );
      attr(div1, "class", "item-piles-name-container");
      attr(div2, "class", "item-piles-name");
      attr(div3, "class", "item-piles-flexrow item-piles-item-row item-piles-even-color");
      attr(div3, "draggable", div3_draggable_value = !!/*entry*/
      ctx[1].id);
      toggle_class(div3, "item-piles-disabled", !/*$editQuantities*/
      ctx[4] && (!/*$quantityLeft*/
      ctx[5] || !/*$quantity*/
      ctx[6]));
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img_1);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, p);
      append(p, t1);
      append(div1, t2);
      if (if_block0)
        if_block0.m(div1, null);
      append(div3, t3);
      if (if_block1)
        if_block1.m(div3, null);
      append(div3, t4);
      if (if_block2)
        if_block2.m(div3, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            p,
            "click",
            /*click_handler*/
            ctx[22]
          ),
          listen(
            div3,
            "dragstart",
            /*dragstart_handler_1*/
            ctx[27]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (!current || dirty & /*$img*/
      128 && !src_url_equal(img_1.src, img_1_src_value = /*$img*/
      ctx2[7])) {
        attr(img_1, "src", img_1_src_value);
      }
      if (!current || dirty & /*$name*/
      512)
        set_data(
          t1,
          /*$name*/
          ctx2[9]
        );
      if (!current || dirty & /*$rarityColor*/
      256) {
        set_style(
          p,
          "color",
          /*$rarityColor*/
          ctx2[8] || "inherit"
        );
      }
      if (!current || dirty & /*canInspectItems*/
      8) {
        toggle_class(
          p,
          "item-piles-clickable-link",
          /*canInspectItems*/
          ctx2[3]
        );
      }
      if (!/*$editQuantities*/
      ctx2[4] && /*entry*/
      ctx2[1].canStack && !/*currency*/
      ctx2[2]) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_5$e(ctx2);
          if_block0.c();
          if_block0.m(div1, null);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*entry*/
        ctx2[1].canStack || !/*entry*/
        ctx2[1].id
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_2$u(ctx2);
          if_block1.c();
          if_block1.m(div3, t4);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block2) {
        if_block2.p(ctx2, dirty);
      } else {
        if (if_block2)
          if_block2.d(1);
        if_block2 = current_block_type && current_block_type(ctx2);
        if (if_block2) {
          if_block2.c();
          if_block2.m(div3, null);
        }
      }
      if (!current || dirty & /*entry*/
      2 && div3_draggable_value !== (div3_draggable_value = !!/*entry*/
      ctx2[1].id)) {
        attr(div3, "draggable", div3_draggable_value);
      }
      if (!current || dirty & /*$editQuantities, $quantityLeft, $quantity*/
      112) {
        toggle_class(div3, "item-piles-disabled", !/*$editQuantities*/
        ctx2[4] && (!/*$quantityLeft*/
        ctx2[5] || !/*$quantity*/
        ctx2[6]));
      }
    },
    i(local) {
      if (current)
        return;
      add_render_callback(() => {
        if (!current)
          return;
        if (!div3_transition)
          div3_transition = create_bidirectional_transition(div3, fade, { duration: 250 }, true);
        div3_transition.run(1);
      });
      current = true;
    },
    o(local) {
      if (!div3_transition)
        div3_transition = create_bidirectional_transition(div3, fade, { duration: 250 }, false);
      div3_transition.run(0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (if_block2) {
        if_block2.d();
      }
      if (detaching && div3_transition)
        div3_transition.end();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$1h, "create_fragment$1h");
function instance$1e($$self, $$props, $$invalidate) {
  let canInspectItems;
  let $pileData;
  let $editQuantities;
  let $quantityLeft;
  let $quantity;
  let $img;
  let $rarityColor;
  let $name;
  let $currentQuantity;
  let { store } = $$props;
  let { entry } = $$props;
  let { currency = false } = $$props;
  const name = entry.name;
  component_subscribe($$self, name, (value) => $$invalidate(9, $name = value));
  const img = entry.img;
  component_subscribe($$self, img, (value) => $$invalidate(7, $img = value));
  const rarityColor = entry.rarityColor;
  component_subscribe($$self, rarityColor, (value) => $$invalidate(8, $rarityColor = value));
  const quantityLeft = entry.quantityLeft;
  component_subscribe($$self, quantityLeft, (value) => $$invalidate(5, $quantityLeft = value));
  const quantity = entry.quantity;
  component_subscribe($$self, quantity, (value) => $$invalidate(6, $quantity = value));
  const currentQuantity = entry.currentQuantity;
  component_subscribe($$self, currentQuantity, (value) => $$invalidate(10, $currentQuantity = value));
  const pileData = store.pileData;
  component_subscribe($$self, pileData, (value) => $$invalidate(20, $pileData = value));
  const editQuantities = store.editQuantities;
  component_subscribe($$self, editQuantities, (value) => $$invalidate(4, $editQuantities = value));
  function dragStart(event) {
    const data2 = { type: "Item", uuid: entry.item.uuid };
    Hooks.callAll(CONSTANTS.HOOKS.DRAG_DOCUMENT, data2);
    event.dataTransfer.setData("text/plain", JSON.stringify(data2));
  }
  __name(dragStart, "dragStart");
  function dragstart_handler(event) {
    bubble.call(this, $$self, event);
  }
  __name(dragstart_handler, "dragstart_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    entry.preview();
  }, "click_handler");
  function input_input_handler() {
    $quantity = to_number(this.value);
    quantity.set($quantity);
  }
  __name(input_input_handler, "input_input_handler");
  function input_input_handler_1() {
    $currentQuantity = to_number(this.value);
    currentQuantity.set($currentQuantity);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    entry.take();
  }, "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    entry.remove();
  }, "click_handler_2");
  const dragstart_handler_1 = /* @__PURE__ */ __name((event) => {
    dragStart(event);
  }, "dragstart_handler_1");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
    if ("entry" in $$props2)
      $$invalidate(1, entry = $$props2.entry);
    if ("currency" in $$props2)
      $$invalidate(2, currency = $$props2.currency);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*entry, $pileData*/
    1048578) {
      $$invalidate(3, canInspectItems = entry.id && $pileData.canInspectItems);
    }
  };
  return [
    store,
    entry,
    currency,
    canInspectItems,
    $editQuantities,
    $quantityLeft,
    $quantity,
    $img,
    $rarityColor,
    $name,
    $currentQuantity,
    name,
    img,
    rarityColor,
    quantityLeft,
    quantity,
    currentQuantity,
    pileData,
    editQuantities,
    dragStart,
    $pileData,
    dragstart_handler,
    click_handler,
    input_input_handler,
    input_input_handler_1,
    click_handler_1,
    click_handler_2,
    dragstart_handler_1
  ];
}
__name(instance$1e, "instance$1e");
const _ListEntry = class _ListEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1e, create_fragment$1h, safe_not_equal, { store: 0, entry: 1, currency: 2 });
  }
};
__name(_ListEntry, "ListEntry");
let ListEntry = _ListEntry;
function get_each_context$F(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[6] = list[i];
  child_ctx[7] = list;
  child_ctx[8] = i;
  return child_ctx;
}
__name(get_each_context$F, "get_each_context$F");
function create_if_block$V(ctx) {
  let div1;
  let div0;
  let h3;
  let t1;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let div1_intro;
  let current;
  let each_value = (
    /*$items*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[6].identifier
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$F(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$F(key, child_ctx));
  }
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      h3 = element("h3");
      h3.textContent = `${localize("ITEM-PILES.Items")}`;
      t1 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div0, "class", "item-piles-flexrow");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, h3);
      append(div1, t1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div1, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*store, $items*/
      5) {
        each_value = /*$items*/
        ctx2[2];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div1, outro_and_destroy_block, create_each_block$F, null, get_each_context$F);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      if (local) {
        if (!div1_intro) {
          add_render_callback(() => {
            div1_intro = create_in_transition(div1, fade, { duration: 150 });
            div1_intro.start();
          });
        }
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_if_block$V, "create_if_block$V");
function create_each_block$F(key_1, ctx) {
  let first;
  let listentry;
  let updating_entry;
  let current;
  function listentry_entry_binding(value) {
    ctx[5](
      value,
      /*item*/
      ctx[6],
      /*each_value*/
      ctx[7],
      /*item_index*/
      ctx[8]
    );
  }
  __name(listentry_entry_binding, "listentry_entry_binding");
  let listentry_props = { store: (
    /*store*/
    ctx[0]
  ) };
  if (
    /*item*/
    ctx[6] !== void 0
  ) {
    listentry_props.entry = /*item*/
    ctx[6];
  }
  listentry = new ListEntry({ props: listentry_props });
  binding_callbacks.push(() => bind(listentry, "entry", listentry_entry_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(listentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(listentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const listentry_changes = {};
      if (dirty & /*store*/
      1)
        listentry_changes.store = /*store*/
        ctx[0];
      if (!updating_entry && dirty & /*$items*/
      4) {
        updating_entry = true;
        listentry_changes.entry = /*item*/
        ctx[6];
        add_flush_callback(() => updating_entry = false);
      }
      listentry.$set(listentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(listentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(listentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(listentry, detaching);
    }
  };
}
__name(create_each_block$F, "create_each_block$F");
function create_fragment$1g(ctx) {
  let if_block_anchor;
  let current;
  let if_block = (
    /*$numItems*/
    ctx[1] > 0 && create_if_block$V(ctx)
  );
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (
        /*$numItems*/
        ctx2[1] > 0
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*$numItems*/
          2) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$V(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_fragment$1g, "create_fragment$1g");
function instance$1d($$self, $$props, $$invalidate) {
  let $numItems;
  let $items;
  let { store } = $$props;
  const items = store.items;
  component_subscribe($$self, items, (value) => $$invalidate(2, $items = value));
  const numItems = store.numItems;
  component_subscribe($$self, numItems, (value) => $$invalidate(1, $numItems = value));
  function listentry_entry_binding(value, item, each_value, item_index) {
    each_value[item_index] = value;
    items.set($items);
  }
  __name(listentry_entry_binding, "listentry_entry_binding");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
  };
  return [store, $numItems, $items, items, numItems, listentry_entry_binding];
}
__name(instance$1d, "instance$1d");
const _ItemList = class _ItemList extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1d, create_fragment$1g, safe_not_equal, { store: 0 });
  }
};
__name(_ItemList, "ItemList");
let ItemList = _ItemList;
function get_each_context$E(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[9] = list[i];
  child_ctx[10] = list;
  child_ctx[11] = i;
  return child_ctx;
}
__name(get_each_context$E, "get_each_context$E");
function create_if_block_1$F(ctx) {
  let h3;
  return {
    c() {
      h3 = element("h3");
      h3.textContent = `${localize("ITEM-PILES.Currencies")}:`;
    },
    m(target, anchor) {
      insert(target, h3, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(h3);
    }
  };
}
__name(create_if_block_1$F, "create_if_block_1$F");
function create_if_block$U(ctx) {
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let current;
  let each_value = (
    /*$currencies*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*currency*/
    ctx2[9].identifier
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$E(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$E(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*store, $currencies*/
      5) {
        each_value = /*$currencies*/
        ctx2[2];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, outro_and_destroy_block, create_each_block$E, null, get_each_context$E);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_if_block$U, "create_if_block$U");
function create_each_block$E(key_1, ctx) {
  let first;
  let listentry;
  let updating_entry;
  let current;
  function listentry_entry_binding(value) {
    ctx[6](
      value,
      /*currency*/
      ctx[9],
      /*each_value*/
      ctx[10],
      /*index*/
      ctx[11]
    );
  }
  __name(listentry_entry_binding, "listentry_entry_binding");
  let listentry_props = { store: (
    /*store*/
    ctx[0]
  ), currency: true };
  if (
    /*currency*/
    ctx[9] !== void 0
  ) {
    listentry_props.entry = /*currency*/
    ctx[9];
  }
  listentry = new ListEntry({ props: listentry_props });
  binding_callbacks.push(() => bind(listentry, "entry", listentry_entry_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(listentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(listentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const listentry_changes = {};
      if (dirty & /*store*/
      1)
        listentry_changes.store = /*store*/
        ctx[0];
      if (!updating_entry && dirty & /*$currencies*/
      4) {
        updating_entry = true;
        listentry_changes.entry = /*currency*/
        ctx[9];
        add_flush_callback(() => updating_entry = false);
      }
      listentry.$set(listentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(listentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(listentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(listentry, detaching);
    }
  };
}
__name(create_each_block$E, "create_each_block$E");
function create_fragment$1f(ctx) {
  let div1;
  let div0;
  let t0;
  let a;
  let i;
  let t1;
  let t2_value = localize("ITEM-PILES.Inspect.AddCurrency") + "";
  let t2;
  let t3;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*$numCurrencies*/
    ctx[1] > 0 && create_if_block_1$F()
  );
  let if_block1 = (
    /*$numCurrencies*/
    ctx[1] > 0 && create_if_block$U(ctx)
  );
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      a = element("a");
      i = element("i");
      t1 = space();
      t2 = text(t2_value);
      t3 = space();
      if (if_block1)
        if_block1.c();
      attr(i, "class", "fas fa-plus");
      attr(a, "class", "item-piles-clickable item-piles-text-right item-piles-small-text item-piles-middle");
      attr(div0, "class", "item-piles-flexrow");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      if (if_block0)
        if_block0.m(div0, null);
      append(div0, t0);
      append(div0, a);
      append(a, i);
      append(a, t1);
      append(a, t2);
      append(div1, t3);
      if (if_block1)
        if_block1.m(div1, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[5]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (
        /*$numCurrencies*/
        ctx2[1] > 0
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_1$F();
          if_block0.c();
          if_block0.m(div0, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*$numCurrencies*/
        ctx2[1] > 0
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*$numCurrencies*/
          2) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block$U(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div1, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$1f, "create_fragment$1f");
function instance$1c($$self, $$props, $$invalidate) {
  let $numCurrencies;
  let $currencies;
  let { store } = $$props;
  const currencies = store.currencies;
  component_subscribe($$self, currencies, (value) => $$invalidate(2, $currencies = value));
  store.numItems;
  const numCurrencies = store.numCurrencies;
  component_subscribe($$self, numCurrencies, (value) => $$invalidate(1, $numCurrencies = value));
  store.editQuantities;
  const click_handler = /* @__PURE__ */ __name(() => store.addCurrency(store.recipient), "click_handler");
  function listentry_entry_binding(value, currency, each_value, index2) {
    each_value[index2] = value;
    currencies.set($currencies);
  }
  __name(listentry_entry_binding, "listentry_entry_binding");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
  };
  return [
    store,
    $numCurrencies,
    $currencies,
    currencies,
    numCurrencies,
    click_handler,
    listentry_entry_binding
  ];
}
__name(instance$1c, "instance$1c");
let CurrencyList$2 = (_a = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1c, create_fragment$1f, safe_not_equal, { store: 0 });
  }
}, __name(_a, "CurrencyList"), _a);
function get_each_context$D(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[13] = list[i];
  child_ctx[15] = i;
  return child_ctx;
}
__name(get_each_context$D, "get_each_context$D");
function create_else_block$n(ctx) {
  let div;
  let t;
  let if_block0 = !/*changingActor*/
  ctx[3] && create_if_block_3$n(ctx);
  let if_block1 = (
    /*playerActors*/
    ctx[7].length > 1 && create_if_block_1$E(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t = space();
      if (if_block1)
        if_block1.c();
      attr(
        div,
        "style",
        /*style*/
        ctx[1]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t);
      if (if_block1)
        if_block1.m(div, null);
    },
    p(ctx2, dirty) {
      if (!/*changingActor*/
      ctx2[3]) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_3$n(ctx2);
          if_block0.c();
          if_block0.m(div, t);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*playerActors*/
        ctx2[7].length > 1
      )
        if_block1.p(ctx2, dirty);
      if (dirty & /*style*/
      2) {
        attr(
          div,
          "style",
          /*style*/
          ctx2[1]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
    }
  };
}
__name(create_else_block$n, "create_else_block$n");
function create_if_block$T(ctx) {
  let div;
  let t_value = localize("ITEM-PILES.Inspect.Owner") + "";
  let t;
  return {
    c() {
      div = element("div");
      t = text(t_value);
      attr(
        div,
        "style",
        /*style*/
        ctx[1]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*style*/
      2) {
        attr(
          div,
          "style",
          /*style*/
          ctx2[1]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block$T, "create_if_block$T");
function create_if_block_3$n(ctx) {
  let t_value = localize(
    /*localization*/
    ctx[0],
    { actorName: (
      /*$recipientDoc*/
      ctx[2].name
    ) }
  ) + "";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*localization, $recipientDoc*/
      5 && t_value !== (t_value = localize(
        /*localization*/
        ctx2[0],
        { actorName: (
          /*$recipientDoc*/
          ctx2[2].name
        ) }
      ) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(create_if_block_3$n, "create_if_block_3$n");
function create_if_block_1$E(ctx) {
  let if_block_anchor;
  function select_block_type_1(ctx2, dirty) {
    if (!/*changingActor*/
    ctx2[3])
      return create_if_block_2$t;
    return create_else_block_1$8;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    d(detaching) {
      if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block_1$E, "create_if_block_1$E");
function create_else_block_1$8(ctx) {
  let select;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let mounted;
  let dispose;
  let each_value = (
    /*playerActors*/
    ctx[7]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[15]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$D(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$D(key, child_ctx));
  }
  return {
    c() {
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(select, "class", "item-piles-change-actor-select");
      set_style(select, "height", "auto");
      if (
        /*recipientUuid*/
        ctx[4] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[12].call(select)
        ));
      toggle_class(
        select,
        "active",
        /*changingActor*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, select, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*recipientUuid*/
        ctx[4],
        true
      );
      if (!mounted) {
        dispose = [
          listen(
            select,
            "change",
            /*select_change_handler*/
            ctx[12]
          ),
          listen(
            select,
            "change",
            /*changeRecipientActor*/
            ctx[9]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*Utilities, playerActors*/
      128) {
        each_value = /*playerActors*/
        ctx2[7];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, select, destroy_block, create_each_block$D, null, get_each_context$D);
      }
      if (dirty & /*recipientUuid, Utilities, playerActors*/
      144) {
        select_option(
          select,
          /*recipientUuid*/
          ctx2[4]
        );
      }
      if (dirty & /*changingActor*/
      8) {
        toggle_class(
          select,
          "active",
          /*changingActor*/
          ctx2[3]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_else_block_1$8, "create_else_block_1$8");
function create_if_block_2$t(ctx) {
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.textContent = "Change.";
      attr(a, "class", "item-piles-highlight");
      toggle_class(a, "active", !/*changingActor*/
      ctx[3]);
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[11]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*changingActor*/
      8) {
        toggle_class(a, "active", !/*changingActor*/
        ctx2[3]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_2$t, "create_if_block_2$t");
function create_each_block$D(key_1, ctx) {
  let option;
  let t_value = (
    /*actor*/
    ctx[13].name + ""
  );
  let t;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = getUuid(
        /*actor*/
        ctx[13].uuid
      );
      option.value = option.__value;
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$D, "create_each_block$D");
function create_fragment$1e(ctx) {
  let if_block_anchor;
  function select_block_type(ctx2, dirty) {
    if (
      /*$editQuantities*/
      ctx2[5]
    )
      return create_if_block$T;
    return create_else_block$n;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, [dirty]) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_fragment$1e, "create_fragment$1e");
function instance$1b($$self, $$props, $$invalidate) {
  let $recipientDoc;
  let $editQuantities;
  let { store } = $$props;
  let { localization = "ITEM-PILES.Inspect.AsActor" } = $$props;
  let { style = "text-align: center; flex: 0 1 auto; height: 27px;" } = $$props;
  let editQuantities = store.editQuantities;
  component_subscribe($$self, editQuantities, (value) => $$invalidate(5, $editQuantities = value));
  let changingActor = false;
  let playerActors = game.actors.filter((actor) => actor.isOwner && actor !== store.pileActor && actor.prototypeToken.actorLink);
  let recipientUuid = getUuid(store.recipient);
  const recipientDoc = store.recipientDocument;
  component_subscribe($$self, recipientDoc, (value) => $$invalidate(2, $recipientDoc = value));
  function changeRecipientActor() {
    $$invalidate(10, store.recipient = playerActors.find((actor) => getUuid(actor) === recipientUuid), store);
    store.update();
    $$invalidate(3, changingActor = false);
  }
  __name(changeRecipientActor, "changeRecipientActor");
  const click_handler = /* @__PURE__ */ __name(() => {
    $$invalidate(3, changingActor = true);
  }, "click_handler");
  function select_change_handler() {
    recipientUuid = select_value(this);
    $$invalidate(4, recipientUuid), $$invalidate(2, $recipientDoc), $$invalidate(10, store);
    $$invalidate(7, playerActors);
  }
  __name(select_change_handler, "select_change_handler");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(10, store = $$props2.store);
    if ("localization" in $$props2)
      $$invalidate(0, localization = $$props2.localization);
    if ("style" in $$props2)
      $$invalidate(1, style = $$props2.style);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$recipientDoc, store*/
    1028) {
      {
        $$invalidate(4, recipientUuid = store.recipient ? getUuid(store.recipient) : false);
      }
    }
  };
  return [
    localization,
    style,
    $recipientDoc,
    changingActor,
    recipientUuid,
    $editQuantities,
    editQuantities,
    playerActors,
    recipientDoc,
    changeRecipientActor,
    store,
    click_handler,
    select_change_handler
  ];
}
__name(instance$1b, "instance$1b");
const _ActorPicker = class _ActorPicker extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1b, create_fragment$1e, safe_not_equal, { store: 10, localization: 0, style: 1 });
  }
};
__name(_ActorPicker, "ActorPicker");
let ActorPicker = _ActorPicker;
const _BasePlugin = class _BasePlugin {
  invalidVersionError = "";
  minVersionError = "";
  constructor(pluginName, minVersion, invalidVersion) {
    this.pluginName = pluginName;
    this.minVersion = minVersion;
    this.invalidVersion = invalidVersion;
    this.initialized = false;
    this.initialize();
  }
  initialize() {
    if (!game.modules.get(this.pluginName)?.active) {
      return;
    }
    if (game.modules.get(this.pluginName).version === this.invalidVersion) {
      if (this.invalidVersionError) {
        throw custom_error(this.invalidVersionError);
      }
      return;
    }
    if (isNewerVersion(this.minVersion, game.modules.get(this.pluginName).version)) {
      if (this.minVersionError) {
        throw custom_error(this.minVersionError);
      }
      return;
    }
    this.registerHooks();
    this.initialized = true;
  }
  registerHooks() {
  }
};
__name(_BasePlugin, "BasePlugin");
let BasePlugin = _BasePlugin;
const _Transaction = class _Transaction {
  constructor(actor) {
    this.actor = actor;
    this.actorFlags = getActorFlagData(this.actor);
    this.itemsToCreate = [];
    this.itemsToUpdate = [];
    this.itemsToDelete = [];
    this.itemsToForceDelete = /* @__PURE__ */ new Set();
    this.itemsToNotDelete = /* @__PURE__ */ new Set();
    this.actorUpdates = {};
    this.attributeDeltas = /* @__PURE__ */ new Map();
    this.attributeTypeMap = /* @__PURE__ */ new Map();
    this.itemDeltas = /* @__PURE__ */ new Map();
    this.itemTypeMap = /* @__PURE__ */ new Map();
    this.itemFlagMap = /* @__PURE__ */ new Map();
    this.preCommitted = false;
  }
  async appendItemChanges(items, {
    remove = false,
    type = "item",
    keepIfZero = false,
    onlyDelta = false
  } = {}) {
    for (let data2 of items) {
      let item = data2.item ?? data2;
      type = isItemCurrency(item) ? "currency" : type;
      let flags = data2.flags ?? false;
      let itemData = item instanceof Item ? item.toObject() : foundry.utils.deepClone(item);
      if (SYSTEMS.DATA.ITEM_TRANSFORMER && !remove) {
        itemData = await SYSTEMS.DATA.ITEM_TRANSFORMER(itemData);
      }
      const incomingQuantity = Math.abs(data2.quantity ?? getItemQuantity(itemData)) * (remove ? -1 : 1);
      let itemId = itemData._id ?? itemData.id;
      let actorHasItem = false;
      let actorExistingItem = false;
      if (this.actorFlags.type === CONSTANTS.PILE_TYPES.VAULT && type !== "currency" && !remove) {
        const actorExistingItems = findSimilarItem(this.actor.items, itemData, {
          returnOne: false
        });
        actorExistingItem = actorExistingItems.find((item2) => {
          return canItemStack(item2, this.actor) && (foundry.utils.getProperty(itemData, CONSTANTS.FLAGS.ITEM + ".x") === void 0 && foundry.utils.getProperty(itemData, CONSTANTS.FLAGS.ITEM + ".y") === void 0 || areItemsColliding(item2, itemData));
        });
      } else {
        actorHasItem = this.actor.items.get(itemId);
        actorExistingItem = actorHasItem || findSimilarItem(this.actor.items, itemData);
      }
      const canItemStack$1 = canItemStack(actorExistingItem || itemData, this.actor);
      if (remove && (keepIfZero || type === "currency")) {
        this.itemsToNotDelete.add(item.id);
      }
      if (flags) {
        this.itemFlagMap.set(itemId, flags);
      }
      if (actorExistingItem) {
        const itemQuantity = getItemQuantity(actorExistingItem);
        if (itemQuantity > 1 || canItemStack$1) {
          const newQuantity = itemQuantity + incomingQuantity;
          const existingItemUpdate = remove ? this.itemsToUpdate.find((item2) => item2._id === itemId) : findSimilarItem(this.itemsToUpdate, itemData);
          if (existingItemUpdate) {
            setItemQuantity(existingItemUpdate, newQuantity);
            if (keepIfZero && type !== "currency") {
              setProperty(existingItemUpdate, CONSTANTS.FLAGS.ITEM + ".notForSale", newQuantity === 0);
            }
          } else {
            const update2 = setItemQuantity(actorExistingItem.toObject(), newQuantity);
            if (keepIfZero && type !== "currency") {
              setProperty(update2, CONSTANTS.FLAGS.ITEM + ".notForSale", newQuantity === 0);
            }
            this.itemTypeMap.set(actorExistingItem.id, type);
            this.itemsToUpdate.push(update2);
          }
          this.itemDeltas.set(actorExistingItem.id, (this.itemDeltas.has(actorExistingItem.id) ? this.itemDeltas.get(actorExistingItem.id) : 0) + incomingQuantity);
        } else if (remove) {
          this.itemsToForceDelete.add(actorExistingItem.id);
          this.itemDeltas.set(actorExistingItem.id, (this.itemDeltas.has(actorExistingItem.id) ? this.itemDeltas.get(actorExistingItem.id) : 0) + incomingQuantity);
        } else {
          if (!itemData._id) {
            itemData._id = randomID();
          }
          setItemQuantity(itemData, incomingQuantity);
          this.itemsToCreate.push(itemData);
          this.itemTypeMap.set(itemData._id, type);
        }
      } else {
        const existingItemCreation = findSimilarItem(this.itemsToCreate, itemData);
        if (existingItemCreation && canItemStack$1) {
          const newQuantity = getItemQuantity(existingItemCreation) + incomingQuantity;
          setItemQuantity(existingItemCreation, newQuantity);
        } else {
          if (!itemData._id) {
            itemData._id = randomID();
          }
          setItemQuantity(itemData, incomingQuantity);
          this.itemsToCreate.push(itemData);
          this.itemTypeMap.set(itemData._id, type);
        }
      }
    }
  }
  async appendActorChanges(attributes, { set = false, remove = false, type = "attribute", onlyDelta = false } = {}) {
    if (!Array.isArray(attributes)) {
      attributes = Object.entries(attributes).map((entry) => ({ path: entry[0], quantity: entry[1] }));
    }
    this.actorUpdates = attributes.reduce((acc, attribute) => {
      const incomingQuantity = Math.abs(attribute.quantity) * (remove ? -1 : 1);
      acc[attribute.path] = acc[attribute.path] ?? Number(foundry.utils.getProperty(this.actor, attribute.path) ?? 0);
      if (set) {
        if (!onlyDelta) {
          acc[attribute.path] = incomingQuantity;
        }
        this.attributeDeltas.set(attribute.path, (this.attributeDeltas.has(attribute.path) ? this.attributeDeltas.get(attribute.path) : acc[attribute.path]) + incomingQuantity);
      } else {
        if (!onlyDelta) {
          acc[attribute.path] += incomingQuantity;
        }
        this.attributeDeltas.set(attribute.path, (this.attributeDeltas.has(attribute.path) ? this.attributeDeltas.get(attribute.path) : 0) + incomingQuantity);
      }
      this.attributeTypeMap.set(attribute.path, type);
      return acc;
    }, this.actorUpdates);
  }
  prepare() {
    this.actorUpdates = Object.fromEntries(Object.entries(this.actorUpdates).filter((entry) => {
      if (this.attributeDeltas.get(entry[0]) === 0) {
        this.attributeDeltas.delete(entry[0]);
      }
      return Number(foundry.utils.getProperty(this.actor, entry[0])) !== entry[1];
    }));
    this.itemsToCreate = this.itemsToCreate.filter((item) => {
      return !canItemStack(item, this.actor) || getItemQuantity(item) > 0 || this.itemTypeMap.get(item._id) === "currency";
    });
    this.itemsToDelete = this.itemsToUpdate.filter((item) => {
      return getItemQuantity(item) <= 0 && this.itemTypeMap.get(item._id) !== "currency";
    }).map((item) => item._id).concat(Array.from(this.itemsToForceDelete));
    for (const itemId of this.itemsToDelete) {
      if (this.itemsToNotDelete.has(itemId)) {
        this.itemsToDelete.splice(this.itemsToDelete.indexOf(itemId), 1);
      }
    }
    this.itemDeltas = Array.from(this.itemDeltas).map(([id, quantity]) => {
      const item = this.actor.items.get(id).toObject();
      const existingFlagData = getItemFlagData(item);
      const newFlagData = this.itemFlagMap.get(id) ?? {};
      setProperty(item, CONSTANTS.FLAGS.ITEM, foundry.utils.mergeObject(existingFlagData, newFlagData));
      const type = this.itemTypeMap.get(id);
      setItemQuantity(item, quantity, true);
      return { item, quantity, type };
    }).filter((delta) => delta.quantity);
    this.itemsToUpdate = this.itemsToUpdate.filter((item) => getItemQuantity(item) > 0 || this.itemsToNotDelete.has(item._id) || this.itemTypeMap.get(item._id) === "currency").filter((itemData) => {
      const item = this.actor.items.get(itemData._id);
      return getItemQuantity(item) !== getItemQuantity(itemData);
    });
    this.attributeDeltas = Object.fromEntries(this.attributeDeltas);
    this.preCommitted = true;
    return {
      actorUpdates: this.actorUpdates,
      itemsToCreate: this.itemsToCreate,
      itemsToDelete: this.itemsToDelete,
      itemsToUpdate: this.itemsToUpdate,
      attributeDeltas: this.attributeDeltas,
      itemDeltas: this.itemDeltas
    };
  }
  async commit() {
    if (!this.preCommitted) {
      this.prepare();
    }
    let itemsCreated;
    const actorUuid = getUuid(this.actor);
    if (this.actor.isOwner) {
      itemsCreated = await PrivateAPI._commitActorChanges(actorUuid, {
        actorUpdates: this.actorUpdates,
        itemsToUpdate: this.itemsToUpdate,
        itemsToDelete: this.itemsToDelete,
        itemsToCreate: this.itemsToCreate
      });
    } else {
      itemsCreated = await ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.COMMIT_ACTOR_CHANGES, actorUuid, {
        actorUpdates: this.actorUpdates,
        itemsToUpdate: this.itemsToUpdate,
        itemsToDelete: this.itemsToDelete,
        itemsToCreate: this.itemsToCreate
      });
    }
    return {
      attributeDeltas: this.attributeDeltas,
      itemDeltas: this.itemDeltas.concat(itemsCreated.map((item) => {
        return {
          item,
          quantity: canItemStack(item) ? getItemQuantity(item) : 1
        };
      }))
    };
  }
};
__name(_Transaction, "Transaction");
let Transaction = _Transaction;
let previousState;
const _SimpleCalendarPlugin = class _SimpleCalendarPlugin extends BasePlugin {
  invalidVersionError = "Simple Calendar version 1.3.75 is installed, but Item Piles requires version 2.0.0 or above. The author made a mistake, and you will need to reinstall the Simple Calendar module.";
  minVersionError = "Simple Calendar is out of date to be compatible with Item Piles, please update as soon as possible.";
  registerHooks() {
    previousState = {
      dateTime: window.SimpleCalendar.api.currentDateTime(),
      weekday: window.SimpleCalendar.api.getCurrentWeekday(),
      timestamp: window.SimpleCalendar.api.dateToTimestamp({})
    };
    previousState.time = Number(previousState.dateTime.hour.toString() + "." + previousState.dateTime.minute.toString());
    Hooks.on("updateWorldTime", async () => {
      ItemPileStore.notifyAllOfChanges("updateOpenCloseStatus");
      if (!isResponsibleGM())
        return;
      this.handleTimePassed();
    });
    const debounceCollectAllMerchants = foundry.utils.debounce(() => {
      this.collectAllMerchants();
    }, 1e3);
    Hooks.on("updateActor", () => {
      debounceCollectAllMerchants();
    });
    Hooks.on("updateToken", () => {
      debounceCollectAllMerchants();
    });
    this.collectAllMerchants();
  }
  collectAllMerchants() {
    this.actors = getItemPileActors((actor) => {
      return isItemPileMerchant(actor);
    });
    const { validTokensOnScenes } = getItemPileTokens((token) => {
      return isItemPileMerchant(token);
    });
    this.validTokensOnScenes = validTokensOnScenes;
  }
  handleTimePassed() {
    const newState = {
      dateTime: window.SimpleCalendar.api.currentDateTime(),
      weekday: window.SimpleCalendar.api.getCurrentWeekday(),
      timestamp: window.SimpleCalendar.api.dateToTimestamp({})
    };
    newState.time = Number(newState.dateTime.hour.toString() + "." + newState.dateTime.minute.toString());
    const prevMinute = Math.floor(previousState.timestamp / 60);
    const newMinute = Math.floor(newState.timestamp / 60);
    if (prevMinute === newMinute) {
      previousState = newState;
      return;
    }
    debug("Running handleTimePassed");
    const currentCalendar = window.SimpleCalendar.api.getCurrentCalendar();
    const numWeekdays = currentCalendar.weekdays.length;
    const notes = window.SimpleCalendar.api.getNotes().filter((note) => getProperty(note, "flags.foundryvtt-simple-calendar.noteData.categories")?.length).map((note) => {
      const flags = getProperty(note, "flags.foundryvtt-simple-calendar.noteData");
      let timestampData = {
        year: flags.startDate.year,
        month: flags.startDate.month,
        day: flags.startDate.day,
        hour: flags.allDay ? 0 : flags.startDate.hour,
        minute: flags.allDay ? 0 : flags.startDate.minute,
        seconds: flags.allDay ? 0 : flags.startDate.seconds
      };
      switch (flags?.repeats) {
        case window.SimpleCalendar.api.NoteRepeat.Weekly:
          const noteWeekDay = window.SimpleCalendar.api.timestampToDate(window.SimpleCalendar.api.dateToTimestamp(timestampData)).dayOfTheWeek - 1;
          const currentWeekDay = window.SimpleCalendar.api.timestampToDate(newState.timestamp).dayOfTheWeek - 1;
          let weekdayCountDifference = currentWeekDay - noteWeekDay;
          if (weekdayCountDifference < 0) {
            weekdayCountDifference += numWeekdays;
          }
          timestampData.year = newState.dateTime.year;
          timestampData.month = newState.dateTime.month;
          timestampData.day = newState.dateTime.day;
          const weekInSeconds = SimpleCalendar.api.timestampPlusInterval(0, { day: 1 }) * weekdayCountDifference;
          const timestamp = window.SimpleCalendar.api.dateToTimestamp(timestampData) - weekInSeconds;
          timestampData.day = window.SimpleCalendar.api.timestampToDate(timestamp).day;
          break;
        case window.SimpleCalendar.api.NoteRepeat.Monthly:
          timestampData.year = newState.dateTime.year;
          timestampData.month = newState.dateTime.month;
          break;
        case window.SimpleCalendar.api.NoteRepeat.Yearly:
          timestampData.year = newState.dateTime.year;
          break;
      }
      return {
        document: note,
        flags,
        dateTime: timestampData,
        timestamp: window.SimpleCalendar.api.dateToTimestamp(timestampData)
      };
    }).filter((note) => {
      return note.timestamp > previousState.timestamp && note.timestamp <= newState.timestamp;
    });
    const categories = new Set(notes.map((note) => note.flags?.categories ?? []).deepFlatten());
    this.hideMerchantTokens();
    this.refreshMerchantInventories(newState, previousState, categories, notes);
    previousState = newState;
  }
  async hideMerchantTokens() {
    const actors = this.actors.filter((actor) => {
      const pileData = getActorFlagData(actor);
      return pileData.hideTokenWhenClosed && isMerchantClosed(actor, { pileData });
    });
    const actorTokens = actors.map((actor) => actor.getActiveTokens()).deepFlatten().reduce((acc, token) => {
      if (!acc[token.parent.id])
        acc[token.parent.id] = [];
      acc[token.parent.id].push(token);
      return acc;
    }, {});
    const validTokensOnScenes = this.validTokensOnScenes.filter((token) => {
      const pileData = getActorFlagData(token);
      return pileData.hideTokenWhenClosed && isMerchantClosed(token, { pileData });
    });
    for (const [sceneId, tokens] of validTokensOnScenes) {
      const scene = game.scenes.get(sceneId);
      const updates = Object.values(tokens.concat(actorTokens).reduce((acc, token) => {
        if (!acc[token.id]) {
          acc[token.id] = {
            _id: token.id,
            hidden: isMerchantClosed(token)
          };
        }
        return acc;
      }, {}));
      if (updates.length) {
        debug(`Hid ${updates.length} merchant tokens on ${scene.name}`);
        await scene.updateEmbeddedDocuments("Token", updates);
      }
    }
  }
  async refreshMerchantInventories(newState, previousState2, categories, notes) {
    const actors = this.actors.filter((actor) => {
      const flags = getActorFlagData(actor);
      return merchantRefreshFilter(flags, newState, previousState2, categories);
    });
    const validTokensOnScenes = this.validTokensOnScenes.map(([scene, tokens]) => {
      return [scene, tokens.filter((token) => {
        const flags = getActorFlagData(token);
        return merchantRefreshFilter(flags, newState, previousState2, categories);
      })];
    }).filter(([_, tokens]) => tokens.length);
    if (actors.length)
      debug(`Refreshing ${actors.length} merchant inventories`);
    for (const actor of actors) {
      await this.refreshActorItems(actor, notes);
    }
    for (const [sceneId, tokens] of validTokensOnScenes) {
      const scene = game.scenes.get(sceneId);
      if (tokens.length)
        debug(`Refreshing ${tokens.length} merchant inventories on scene ${scene.name}`);
      for (const token of tokens) {
        await this.refreshActorItems(token.actor, notes);
      }
    }
  }
  async refreshActorItems(actor, notes) {
    const actorTransaction = new Transaction(actor);
    const actorItems = game.itempiles.API.getActorItems(actor);
    const newActorItems = await rollMerchantTables({ actor });
    await actorTransaction.appendItemChanges(actorItems.filter((item) => {
      const itemFlags = getItemFlagData(item);
      return !itemFlags.keepOnMerchant && !itemFlags.keepIfZero;
    }), { remove: true });
    await actorTransaction.appendItemChanges(actorItems.filter((item) => {
      const itemFlags = getItemFlagData(item);
      return !itemFlags.keepOnMerchant && itemFlags.keepIfZero;
    }), { remove: true, keepIfZero: true });
    await actorTransaction.appendItemChanges(newActorItems.map((entry) => ({
      item: entry.item,
      quantity: entry.quantity,
      flags: entry.flags
    })));
    const commit = actorTransaction.prepare();
    const result = Hooks.call(CONSTANTS.HOOKS.PILE.PRE_REFRESH_INVENTORY, actor, commit, notes);
    if (result === false)
      return;
    await actorTransaction.commit();
  }
};
__name(_SimpleCalendarPlugin, "SimpleCalendarPlugin");
let SimpleCalendarPlugin = _SimpleCalendarPlugin;
function merchantRefreshFilter(flags, newState, previousState2, categories) {
  const openTimesEnabled = flags.openTimes.enabled;
  if (!openTimesEnabled)
    return false;
  const openTimes = flags.openTimes.open;
  const closeTimes = flags.openTimes.close;
  const openHour = openTimesEnabled ? openTimes.hour : 0;
  const openMinute = openTimesEnabled ? openTimes.minute : 0;
  const closeHour = openTimesEnabled ? closeTimes.hour : 0;
  const closeMinute = openTimesEnabled ? closeTimes.minute : 0;
  const openingTime = Number(openHour.toString() + "." + openMinute.toString());
  const closingTime = Number(closeHour.toString() + "." + closeMinute.toString());
  const wasOpen = openingTime > closingTime ? previousState2.time >= openingTime || previousState2.time <= closingTime : previousState2.time >= openingTime && previousState2.time <= closingTime;
  const isOpen = openingTime > closingTime ? newState.time >= openingTime || newState.time <= closingTime : newState.time >= openingTime && newState.time <= closingTime;
  const allWeekdays = window.SimpleCalendar.api.getAllWeekdays();
  const dayLength = SimpleCalendar.api.timestampPlusInterval(0, { day: 1 });
  const daysPassed = Math.floor((newState.timestamp - previousState2.timestamp) / dayLength);
  const currentWeekday = newState.weekday;
  const shouldRefreshOnCurrentWeekday = flags.refreshItemsDays.includes(currentWeekday.name);
  const shouldRefreshPastWeekday = flags.refreshItemsDays.length > 0 && daysPassed >= allWeekdays.length;
  const shouldRefresh = flags.refreshItemsOnOpen || shouldRefreshOnCurrentWeekday || shouldRefreshPastWeekday || categories.intersection(new Set(flags.refreshItemsHolidays)).size > 0;
  return !wasOpen && isOpen && shouldRefresh;
}
__name(merchantRefreshFilter, "merchantRefreshFilter");
const _Levels3dPreview = class _Levels3dPreview extends BasePlugin {
  registerHooks() {
    Hooks.on("3DCanvasConfig", (config) => {
      config.INTERACTIONS.dropFunctions.Item = async function(event, data2) {
        canvas.tokens.activate();
        return PrivateAPI._dropData(canvas, data2);
      };
    });
  }
};
__name(_Levels3dPreview, "Levels3dPreview");
let Levels3dPreview = _Levels3dPreview;
const _RarityColors = class _RarityColors extends BasePlugin {
  minVersionError = "Rarity Colors is out of date to be compatible with Item Piles, please update to 0.3.6 soon as possible.";
  getItemColor(item) {
    if (game.system.id !== "dnd5e")
      return false;
    if (!game.modules.get(this.pluginName)?.api?.getColorFromItem)
      return false;
    try {
      return game.modules.get(this.pluginName)?.api?.getColorFromItem(item);
    } catch (err) {
      return false;
    }
  }
};
__name(_RarityColors, "RarityColors");
let RarityColors = _RarityColors;
const Plugins = {
  "foundryvtt-simple-calendar": {
    on: "ready",
    data: null,
    class: SimpleCalendarPlugin,
    minVersion: "2.0.0",
    invalidVersion: "v1.3.75"
  },
  "levels-3d-preview": {
    on: "init",
    data: null,
    class: Levels3dPreview,
    minVersion: "4.9.6"
  },
  "rarity-colors": {
    on: "init",
    data: null,
    class: RarityColors,
    minVersion: "0.3.6"
  }
};
function setupPlugins(hook) {
  for (const [plugin, pluginData] of Object.entries(Plugins).filter((e) => e[1].on === hook)) {
    if (!game.modules.get(plugin)?.active) {
      continue;
    }
    pluginData.data = new pluginData.class(plugin, pluginData.minVersion, pluginData?.invalidVersion);
  }
}
__name(setupPlugins, "setupPlugins");
const PACK_ID = `world.item-piles-item-backup-do-not-delete`;
const COMPENDIUM_CACHE = {};
async function initializeCompendiumCache() {
  Hooks.on("updateItem", async (item) => {
    if (!item?.pack || !item?.pack.startsWith(PACK_ID))
      return;
    COMPENDIUM_CACHE[item.uuid] = item.toObject();
  });
  const pack = game.packs.get(PACK_ID);
  if (pack) {
    for (const index2 of pack.index) {
      const item = await pack.getDocument(index2._id);
      COMPENDIUM_CACHE[item.uuid] = item.toObject();
    }
  }
  setTimeout(async () => {
    await updateCache();
    Hooks.on("updateCompendium", updateCache);
  }, 250);
}
__name(initializeCompendiumCache, "initializeCompendiumCache");
async function updateCache() {
  const currencies = getSetting(SETTINGS$1.CURRENCIES);
  const secondaryCurrencies = getSetting(SETTINGS$1.SECONDARY_CURRENCIES);
  for (const currency of currencies.concat(secondaryCurrencies)) {
    if (currency.type !== "item")
      continue;
    if (currency.data.uuid) {
      COMPENDIUM_CACHE[currency.data?.uuid] = (await fromUuid(currency.data.uuid)).toObject();
    } else if (currency.data.item) {
      const item = await findOrCreateItemInCompendium(currency.data.item);
      COMPENDIUM_CACHE[item.uuid] = item.toObject();
    }
  }
}
__name(updateCache, "updateCache");
async function getItemCompendium() {
  return game.packs.get(PACK_ID) || await CompendiumCollection.createCompendium({
    label: `Item Piles: Item Backup (DO NOT DELETE)`,
    id: PACK_ID,
    private: true,
    type: "Item"
  });
}
__name(getItemCompendium, "getItemCompendium");
async function addItemsToCompendium(items) {
  return Item.createDocuments(items, { pack: PACK_ID });
}
__name(addItemsToCompendium, "addItemsToCompendium");
async function findSimilarItemInCompendium(itemToFind) {
  const pack = await getItemCompendium();
  const item = game.packs.get(PACK_ID).index.find((compendiumItem) => {
    return compendiumItem.name === itemToFind.name && compendiumItem.type === itemToFind.type;
  });
  return item?._id ? pack.getDocument(item._id) : false;
}
__name(findSimilarItemInCompendium, "findSimilarItemInCompendium");
function getItemFromCache(uuid) {
  return COMPENDIUM_CACHE[uuid] ?? false;
}
__name(getItemFromCache, "getItemFromCache");
async function findOrCreateItemInCompendium(itemData) {
  let compendiumItem = await findSimilarItemInCompendium(itemData);
  if (!compendiumItem) {
    compendiumItem = (await addItemsToCompendium([itemData]))[0];
  }
  COMPENDIUM_CACHE[compendiumItem.uuid] = itemData;
  return compendiumItem;
}
__name(findOrCreateItemInCompendium, "findOrCreateItemInCompendium");
function findSimilarItemInCompendiumSync(itemToFind) {
  return Object.values(COMPENDIUM_CACHE).find((compendiumItem) => {
    return compendiumItem.name === itemToFind.name && compendiumItem.type === itemToFind.type;
  }) ?? false;
}
__name(findSimilarItemInCompendiumSync, "findSimilarItemInCompendiumSync");
const _PileBaseItem = class _PileBaseItem {
  constructor(store, data2, isCurrency = false, isSecondaryCurrency = false) {
    this.store = store;
    this.subscriptions = [];
    this.isCurrency = isCurrency;
    this.isSecondaryCurrency = isSecondaryCurrency;
    this.setup(data2);
  }
  setupStores() {
    this.category = writable$1({ service: false, type: "", label: "" });
    this.quantity = writable$1(1);
    this.currentQuantity = writable$1(1);
    this.quantityLeft = writable$1(1);
    this.filtered = writable$1(true);
    this.presentFromTheStart = writable$1(false);
    this.rarityColor = writable$1(false);
  }
  setupSubscriptions() {
  }
  setup(data2) {
    this.unsubscribe();
    this.setupStores(data2);
    this.setupSubscriptions(data2);
  }
  subscribeTo(target, callback) {
    this.subscriptions.push(target.subscribe(callback));
  }
  unsubscribe() {
    this.subscriptions.forEach((unsubscribe) => unsubscribe());
    this.subscriptions = [];
  }
  preview() {
  }
};
__name(_PileBaseItem, "PileBaseItem");
let PileBaseItem = _PileBaseItem;
const _PileItem = class _PileItem extends PileBaseItem {
  setupStores(item) {
    super.setupStores();
    this.item = item;
    this.itemDocument = new TJSDocument(this.item);
    this.canStack = canItemStack(this.item, this.actor);
    this.presentFromTheStart.set(getItemQuantity(this.item) > 0 || !this.canStack);
    this.quantity.set(this.canStack ? getItemQuantity(this.item) : 1);
    this.currentQuantity.set(Math.min(get_store_value(this.currentQuantity), get_store_value(this.quantityLeft), get_store_value(this.quantity)));
    this.id = this.item.id;
    this.type = this.item.type;
    const itemData = findSimilarItemInCompendiumSync(this.item);
    this.name = writable$1(itemData?.name ?? this.item.name);
    this.img = writable$1(itemData?.img ?? this.item.img);
    this.abbreviation = writable$1("");
    this.identifier = randomID();
    this.itemFlagData = writable$1(getItemFlagData(this.item));
  }
  setupSubscriptions() {
    super.setupSubscriptions();
    this.subscribeTo(this.store.pileData, () => {
      this.setupProperties();
    });
    this.subscribeTo(this.store.pileCurrencies, () => {
      this.setupProperties();
    });
    this.subscribeTo(this.store.shareData, () => {
      if (!this.toShare) {
        this.quantityLeft.set(get_store_value(this.quantity));
        return;
      }
      const quantityLeft = getItemSharesLeftForActor(this.store.actor, this.item, this.store.recipient);
      this.quantityLeft.set(quantityLeft);
    });
    this.subscribeTo(this.itemDocument, () => {
      const { data: data2 } = this.itemDocument.updateOptions;
      const itemData = findSimilarItemInCompendiumSync(this.item);
      this.name.set(itemData?.name ?? this.item.name);
      this.img.set(itemData?.img ?? this.item.img);
      this.similarities = setSimilarityProperties({}, this.item);
      if (canItemStack(this.item, this.store.actor) && hasItemQuantity(data2)) {
        this.quantity.set(getItemQuantity(data2));
        const quantity = Math.min(get_store_value(this.currentQuantity), get_store_value(this.quantityLeft), get_store_value(this.quantity));
        this.currentQuantity.set(quantity);
      }
      if (hasProperty(data2, CONSTANTS.FLAGS.ITEM)) {
        this.itemFlagData.set(getItemFlagData(this.item));
        this.updateCategory();
        this.store.refreshItems();
      }
    });
    this.updateCategory();
    this.subscribeTo(this.quantity, this.filter.bind(this));
    this.subscribeTo(this.store.search, this.filter.bind(this));
    this.subscribeTo(this.category, this.filter.bind(this));
  }
  setupProperties() {
    const actorIsItemPile = isValidItemPile(this.store.actor, get_store_value(this.store.pileData));
    const pileActor = actorIsItemPile ? this.store.actor : this.store.recipient;
    const pileActorData = actorIsItemPile ? this.store.pileData : this.store.recipientPileData;
    const pileCurrencies = actorIsItemPile ? get_store_value(this.store.pileCurrencies) : get_store_value(this.store.recipientCurrencies);
    this.isCurrency = isItemCurrency(this.item, {
      target: pileActor,
      actorCurrencies: pileCurrencies
    });
    const currency = this.isCurrency ? getItemCurrencyData(this.item, {
      target: pileActor,
      actorCurrencies: pileCurrencies
    }) : {};
    this.isSecondaryCurrency = !!currency?.secondary;
    this.abbreviation.set(currency?.abbreviation ?? "");
    this.similarities = setSimilarityProperties({}, this.item);
    this.name.set(this.isCurrency ? currency.name : this.item.name);
    this.img.set(this.isCurrency ? currency.img : this.item.img);
    this.toShare = this.isCurrency ? get_store_value(pileActorData).shareCurrenciesEnabled && !!this.store.recipient : get_store_value(pileActorData).shareItemsEnabled && !!this.store.recipient;
  }
  updateCategory() {
    const pileData = get_store_value(this.store.pileData);
    const itemFlagData = get_store_value(this.itemFlagData);
    this.category.update((cat) => {
      cat.service = itemFlagData?.isService;
      if (itemFlagData.customCategory) {
        cat.type = itemFlagData.customCategory.toLowerCase();
        cat.label = itemFlagData.customCategory;
      } else if (cat.service && pileData.enabled && pileData.type === CONSTANTS.PILE_TYPES.MERCHANT) {
        cat.type = "item-piles-service";
        cat.label = "ITEM-PILES.Merchant.Service";
      } else {
        cat.type = this.type;
        cat.label = CONFIG.Item.typeLabels[this.type];
      }
      return cat;
    });
  }
  filter() {
    const name = get_store_value(this.name).trim();
    const search = get_store_value(this.store.search).trim();
    const presentFromTheStart = get_store_value(this.presentFromTheStart);
    const quantity = get_store_value(this.quantity);
    if (quantity === 0 && !presentFromTheStart) {
      this.filtered.set(true);
    } else if (search) {
      this.filtered.set(!name.toLowerCase().includes(search.toLowerCase()));
    } else {
      this.filtered.set(!presentFromTheStart && quantity === 0);
    }
  }
  take() {
    const quantity = Math.min(get_store_value(this.currentQuantity), get_store_value(this.quantityLeft));
    if (!quantity)
      return;
    return game.itempiles.API.transferItems(
      this.store.actor,
      this.store.recipient,
      [{ _id: this.id, quantity }],
      { interactionId: this.store.interactionId }
    );
  }
  async remove() {
    return game.itempiles.API.removeItems(this.store.actor, [this.id]);
  }
  updateQuantity(quantity, add = false) {
    let total = typeof quantity === "string" ? new Roll(quantity).evaluate({ async: false }).total : quantity;
    if (add) {
      total += get_store_value(this.quantity);
    }
    this.quantity.set(total);
    return this.item.update(setItemQuantity({}, total));
  }
  async updateFlags() {
    await updateItemData(this.item, {
      flags: get_store_value(this.itemFlagData)
    });
  }
  preview() {
    const pileData = get_store_value(this.store.pileData);
    if (!pileData.canInspectItems && !game.user.isGM)
      return;
    if (SYSTEMS.DATA?.PREVIEW_ITEM_TRANSFORMER) {
      if (!SYSTEMS.DATA?.PREVIEW_ITEM_TRANSFORMER(this.item)) {
        return;
      }
    }
    if (game.user.isGM || this.item.permission[game.user.id] === 3) {
      return this.item.sheet.render(true);
    }
    const cls = this.item._getSheetClass();
    const sheet = new cls(this.item, { editable: false });
    return sheet._render(true);
  }
};
__name(_PileItem, "PileItem");
let PileItem = _PileItem;
const _PileAttribute = class _PileAttribute extends PileBaseItem {
  setupStores(attribute) {
    super.setupStores();
    this.attribute = attribute;
    this.path = this.attribute.path;
    this.name = writable$1(this.attribute.name);
    this.img = writable$1(this.attribute.img);
    this.abbreviation = writable$1(this.attribute.abbreviation);
    this.identifier = randomID();
    const startingQuantity = Number(getProperty(this.store.actor, this.path) ?? 0);
    this.presentFromTheStart.set(startingQuantity > 0);
    this.quantity.set(startingQuantity);
    this.currentQuantity.set(Math.min(get_store_value(this.currentQuantity), get_store_value(this.quantityLeft), get_store_value(this.quantity)));
    this.category.set({ type: "currency", label: "ITEM-PILES.Currency" });
  }
  setupSubscriptions() {
    super.setupSubscriptions();
    this.subscribeTo(this.store.pileData, this.setupProperties.bind(this));
    this.subscribeTo(this.store.shareData, (val) => {
      if (!this.toShare) {
        this.quantityLeft.set(get_store_value(this.quantity));
        return;
      }
      const quantityLeft = getAttributeSharesLeftForActor(this.store.actor, this.path, this.store.recipient);
      this.quantityLeft.set(quantityLeft);
    });
    this.subscribeTo(this.store.document, () => {
      const { data: data2 } = this.store.document.updateOptions;
      this.path = this.attribute.path;
      this.name.set(this.attribute.name);
      this.img.set(this.attribute.img);
      if (hasProperty(data2, this.path)) {
        this.quantity.set(Number(getProperty(data2, this.path) ?? 0));
        this.currentQuantity.set(Math.min(get_store_value(this.currentQuantity), get_store_value(this.quantityLeft), get_store_value(this.quantity)));
        this.store.refreshItems();
      }
    });
    this.subscribeTo(this.quantity, this.filter.bind(this));
    this.subscribeTo(this.store.search, this.filter.bind(this));
  }
  setupProperties() {
    this.toShare = get_store_value(this.store.pileData).shareCurrenciesEnabled && !!this.store.recipient;
  }
  filter() {
    const name = get_store_value(this.name);
    const search = get_store_value(this.store.search);
    const presentFromTheStart = get_store_value(this.presentFromTheStart);
    const quantity = get_store_value(this.quantity);
    if (quantity === 0 && !presentFromTheStart) {
      this.filtered.set(true);
    } else if (search) {
      this.filtered.set(!name.toLowerCase().includes(search.toLowerCase()));
    } else {
      this.filtered.set(!presentFromTheStart && quantity === 0);
    }
  }
  take() {
    const quantity = Math.min(get_store_value(this.currentQuantity), get_store_value(this.quantityLeft));
    return game.itempiles.API.transferAttributes(
      this.store.actor,
      this.store.recipient,
      { [this.path]: quantity },
      { interactionId: this.store.interactionId }
    );
  }
  updateQuantity() {
    return this.store.actor.update({
      [this.path]: get_store_value(this.quantity)
    });
  }
};
__name(_PileAttribute, "PileAttribute");
let PileAttribute = _PileAttribute;
function get_each_context$C(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[34] = list;
  child_ctx[35] = i;
  return child_ctx;
}
__name(get_each_context$C, "get_each_context$C");
function get_each_context_1$i(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[36] = list[i];
  child_ctx[37] = list;
  child_ctx[35] = i;
  return child_ctx;
}
__name(get_each_context_1$i, "get_each_context_1$i");
function get_each_context_2$7(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[38] = list;
  child_ctx[35] = i;
  return child_ctx;
}
__name(get_each_context_2$7, "get_each_context_2$7");
function get_each_context_3$4(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[36] = list[i];
  child_ctx[39] = list;
  child_ctx[35] = i;
  return child_ctx;
}
__name(get_each_context_3$4, "get_each_context_3$4");
function create_else_block_4(ctx) {
  let p;
  let t_value = localize(`ITEM-PILES.Applications.${/*localization*/
  ctx[2]}.NoCurrency`, { actor_name: (
    /*sourceActor*/
    ctx[1].name
  ) }) + "";
  let t;
  return {
    c() {
      p = element("p");
      t = text(t_value);
      set_style(p, "text-align", "center");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*localization, sourceActor*/
      6 && t_value !== (t_value = localize(`ITEM-PILES.Applications.${/*localization*/
      ctx2[2]}.NoCurrency`, { actor_name: (
        /*sourceActor*/
        ctx2[1].name
      ) }) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_else_block_4, "create_else_block_4");
function create_if_block_1$D(ctx) {
  let p;
  let t0_value = (
    /*settings*/
    (ctx[3]?.content ?? localize(`ITEM-PILES.Applications.${/*localization*/
    ctx[2]}.Content`)) + ""
  );
  let t0;
  let t1;
  let each_blocks_1 = [];
  let each0_lookup = /* @__PURE__ */ new Map();
  let t2;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let t3;
  let show_if = (
    /*attributes*/
    ctx[4].filter(func$3).length || /*items*/
    ctx[5].filter(func_1).length
  );
  let if_block_anchor;
  let each_value_3 = (
    /*attributes*/
    ctx[4].filter(func_2$1)
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*attribute*/
    ctx2[36].path
  ), "get_key");
  for (let i = 0; i < each_value_3.length; i += 1) {
    let child_ctx = get_each_context_3$4(ctx, each_value_3, i);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_1[i] = create_each_block_3$4(key, child_ctx));
  }
  let each_value_2 = (
    /*items*/
    ctx[5].filter(func_3)
  );
  const get_key_1 = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[33].id
  ), "get_key_1");
  for (let i = 0; i < each_value_2.length; i += 1) {
    let child_ctx = get_each_context_2$7(ctx, each_value_2, i);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block_2$7(key, child_ctx));
  }
  let if_block = show_if && create_if_block_2$s(ctx);
  return {
    c() {
      p = element("p");
      t0 = text(t0_value);
      t1 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t2 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t3 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      set_style(p, "text-align", "center");
      set_style(p, "margin", "0");
      attr(p, "class", "item-piles-bottom-divider");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, t0);
      insert(target, t1, anchor);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(target, anchor);
        }
      }
      insert(target, t2, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, t3, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*settings, localization*/
      12 && t0_value !== (t0_value = /*settings*/
      (ctx2[3]?.content ?? localize(`ITEM-PILES.Applications.${/*localization*/
      ctx2[2]}.Content`)) + ""))
        set_data(t0, t0_value);
      if (dirty[0] & /*attributes, settings*/
      24) {
        each_value_3 = /*attributes*/
        ctx2[4].filter(func_2$1);
        each_blocks_1 = update_keyed_each(each_blocks_1, dirty, get_key, 1, ctx2, each_value_3, each0_lookup, t2.parentNode, destroy_block, create_each_block_3$4, t2, get_each_context_3$4);
      }
      if (dirty[0] & /*items, settings*/
      40) {
        each_value_2 = /*items*/
        ctx2[5].filter(func_3);
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_1, 1, ctx2, each_value_2, each1_lookup, t3.parentNode, destroy_block, create_each_block_2$7, t3, get_each_context_2$7);
      }
      if (dirty[0] & /*attributes, items*/
      48)
        show_if = /*attributes*/
        ctx2[4].filter(func$3).length || /*items*/
        ctx2[5].filter(func_1).length;
      if (show_if) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_2$s(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(p);
      if (detaching)
        detach(t1);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].d(detaching);
      }
      if (detaching)
        detach(t2);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(t3);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block_1$D, "create_if_block_1$D");
function create_else_block_3(ctx) {
  let input0;
  let input0_max_value;
  let t0;
  let input1;
  let t1;
  let div;
  let t2;
  let t3_value = abbreviateNumbers(
    /*attribute*/
    ctx[36].quantity
  ) + "";
  let t3;
  let mounted;
  let dispose;
  function input0_change_input_handler() {
    ctx[12].call(
      input0,
      /*each_value_3*/
      ctx[39],
      /*index*/
      ctx[35]
    );
  }
  __name(input0_change_input_handler, "input0_change_input_handler");
  function input1_input_handler() {
    ctx[13].call(
      input1,
      /*each_value_3*/
      ctx[39],
      /*index*/
      ctx[35]
    );
  }
  __name(input1_input_handler, "input1_input_handler");
  function click_handler() {
    return (
      /*click_handler*/
      ctx[14](
        /*attribute*/
        ctx[36],
        /*each_value_3*/
        ctx[39],
        /*index*/
        ctx[35]
      )
    );
  }
  __name(click_handler, "click_handler");
  return {
    c() {
      input0 = element("input");
      t0 = space();
      input1 = element("input");
      t1 = space();
      div = element("div");
      t2 = text("/ ");
      t3 = text(t3_value);
      attr(input0, "class", "item-piles-range-slider");
      set_style(input0, "flex", "5");
      attr(input0, "type", "range");
      attr(input0, "min", "0");
      attr(input0, "max", input0_max_value = /*attribute*/
      ctx[36].quantity);
      attr(input1, "class", "item-piles-range-input");
      set_style(input1, "flex", "2");
      set_style(input1, "margin-left", "1rem");
      attr(input1, "type", "number");
      set_style(div, "flex", "0 1 50px");
      set_style(div, "margin", "0 5px");
    },
    m(target, anchor) {
      insert(target, input0, anchor);
      set_input_value(
        input0,
        /*attribute*/
        ctx[36].currentQuantity
      );
      insert(target, t0, anchor);
      insert(target, input1, anchor);
      set_input_value(
        input1,
        /*attribute*/
        ctx[36].currentQuantity
      );
      insert(target, t1, anchor);
      insert(target, div, anchor);
      append(div, t2);
      append(div, t3);
      if (!mounted) {
        dispose = [
          listen(input0, "change", input0_change_input_handler),
          listen(input0, "input", input0_change_input_handler),
          listen(input1, "input", input1_input_handler),
          listen(input1, "click", click_handler)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*attributes*/
      16 && input0_max_value !== (input0_max_value = /*attribute*/
      ctx[36].quantity)) {
        attr(input0, "max", input0_max_value);
      }
      if (dirty[0] & /*attributes*/
      16) {
        set_input_value(
          input0,
          /*attribute*/
          ctx[36].currentQuantity
        );
      }
      if (dirty[0] & /*attributes*/
      16 && to_number(input1.value) !== /*attribute*/
      ctx[36].currentQuantity) {
        set_input_value(
          input1,
          /*attribute*/
          ctx[36].currentQuantity
        );
      }
      if (dirty[0] & /*attributes*/
      16 && t3_value !== (t3_value = abbreviateNumbers(
        /*attribute*/
        ctx[36].quantity
      ) + ""))
        set_data(t3, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(input0);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(input1);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_else_block_3, "create_else_block_3");
function create_if_block_6$9(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx[11].call(
      input,
      /*each_value_3*/
      ctx[39],
      /*index*/
      ctx[35]
    );
  }
  __name(input_input_handler, "input_input_handler");
  return {
    c() {
      input = element("input");
      attr(input, "class", "item-piles-range-input");
      set_style(input, "flex", "2");
      set_style(input, "margin-left", "1rem");
      attr(input, "type", "number");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*attribute*/
        ctx[36].currentQuantity
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*attributes*/
      16 && to_number(input.value) !== /*attribute*/
      ctx[36].currentQuantity) {
        set_input_value(
          input,
          /*attribute*/
          ctx[36].currentQuantity
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_6$9, "create_if_block_6$9");
function create_each_block_3$4(key_1, ctx) {
  let div3;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let div2;
  let div1;
  let t1_value = (
    /*attribute*/
    ctx[36].name + ""
  );
  let t1;
  let t2;
  function select_block_type_1(ctx2, dirty) {
    if (
      /*settings*/
      ctx2[3]?.unlimitedCurrencies
    )
      return create_if_block_6$9;
    return create_else_block_3;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block = current_block_type(ctx);
  return {
    key: key_1,
    first: null,
    c() {
      div3 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      t1 = text(t1_value);
      t2 = space();
      if_block.c();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*attribute*/
      ctx[36].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      attr(div2, "class", "item-piles-name item-piles-text");
      attr(div3, "class", "form-group item-piles-slider-group item-piles-odd-color");
      this.first = div3;
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, t1);
      append(div3, t2);
      if_block.m(div3, null);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*attributes*/
      16 && !src_url_equal(img.src, img_src_value = /*attribute*/
      ctx[36].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*attributes*/
      16 && t1_value !== (t1_value = /*attribute*/
      ctx[36].name + ""))
        set_data(t1, t1_value);
      if (current_block_type === (current_block_type = select_block_type_1(ctx)) && if_block) {
        if_block.p(ctx, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx);
        if (if_block) {
          if_block.c();
          if_block.m(div3, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if_block.d();
    }
  };
}
__name(create_each_block_3$4, "create_each_block_3$4");
function create_else_block_2$3(ctx) {
  let input0;
  let input0_max_value;
  let t0;
  let input1;
  let t1;
  let div;
  let t2;
  let t3_value = abbreviateNumbers(
    /*item*/
    ctx[33].quantity
  ) + "";
  let t3;
  let mounted;
  let dispose;
  function input0_change_input_handler_1() {
    ctx[16].call(
      input0,
      /*each_value_2*/
      ctx[38],
      /*index*/
      ctx[35]
    );
  }
  __name(input0_change_input_handler_1, "input0_change_input_handler_1");
  function input1_input_handler_1() {
    ctx[17].call(
      input1,
      /*each_value_2*/
      ctx[38],
      /*index*/
      ctx[35]
    );
  }
  __name(input1_input_handler_1, "input1_input_handler_1");
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[18](
        /*item*/
        ctx[33],
        /*each_value_2*/
        ctx[38],
        /*index*/
        ctx[35]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    c() {
      input0 = element("input");
      t0 = space();
      input1 = element("input");
      t1 = space();
      div = element("div");
      t2 = text("/ ");
      t3 = text(t3_value);
      attr(input0, "class", "item-piles-range-slider");
      set_style(input0, "flex", "5");
      attr(input0, "type", "range");
      attr(input0, "min", "0");
      attr(input0, "max", input0_max_value = /*item*/
      ctx[33].quantity);
      attr(input1, "class", "item-piles-range-input");
      set_style(input1, "flex", "1.5");
      set_style(input1, "margin-left", "1rem");
      attr(input1, "type", "number");
      set_style(div, "flex", "0 1 50px");
      set_style(div, "margin", "0 5px");
    },
    m(target, anchor) {
      insert(target, input0, anchor);
      set_input_value(
        input0,
        /*item*/
        ctx[33].currentQuantity
      );
      insert(target, t0, anchor);
      insert(target, input1, anchor);
      set_input_value(
        input1,
        /*item*/
        ctx[33].currentQuantity
      );
      insert(target, t1, anchor);
      insert(target, div, anchor);
      append(div, t2);
      append(div, t3);
      if (!mounted) {
        dispose = [
          listen(input0, "change", input0_change_input_handler_1),
          listen(input0, "input", input0_change_input_handler_1),
          listen(input1, "input", input1_input_handler_1),
          listen(input1, "click", click_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      32 && input0_max_value !== (input0_max_value = /*item*/
      ctx[33].quantity)) {
        attr(input0, "max", input0_max_value);
      }
      if (dirty[0] & /*items*/
      32) {
        set_input_value(
          input0,
          /*item*/
          ctx[33].currentQuantity
        );
      }
      if (dirty[0] & /*items*/
      32 && to_number(input1.value) !== /*item*/
      ctx[33].currentQuantity) {
        set_input_value(
          input1,
          /*item*/
          ctx[33].currentQuantity
        );
      }
      if (dirty[0] & /*items*/
      32 && t3_value !== (t3_value = abbreviateNumbers(
        /*item*/
        ctx[33].quantity
      ) + ""))
        set_data(t3, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(input0);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(input1);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_else_block_2$3, "create_else_block_2$3");
function create_if_block_5$d(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler_1() {
    ctx[15].call(
      input,
      /*each_value_2*/
      ctx[38],
      /*index*/
      ctx[35]
    );
  }
  __name(input_input_handler_1, "input_input_handler_1");
  return {
    c() {
      input = element("input");
      attr(input, "class", "item-piles-range-input");
      set_style(input, "flex", "2");
      set_style(input, "margin-left", "1rem");
      attr(input, "type", "number");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*item*/
        ctx[33].currentQuantity
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler_1);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      32 && to_number(input.value) !== /*item*/
      ctx[33].currentQuantity) {
        set_input_value(
          input,
          /*item*/
          ctx[33].currentQuantity
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_5$d, "create_if_block_5$d");
function create_each_block_2$7(key_1, ctx) {
  let div3;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let div2;
  let div1;
  let t1_value = (
    /*item*/
    ctx[33].name + ""
  );
  let t1;
  let t2;
  function select_block_type_2(ctx2, dirty) {
    if (
      /*settings*/
      ctx2[3]?.unlimitedCurrencies
    )
      return create_if_block_5$d;
    return create_else_block_2$3;
  }
  __name(select_block_type_2, "select_block_type_2");
  let current_block_type = select_block_type_2(ctx);
  let if_block = current_block_type(ctx);
  return {
    key: key_1,
    first: null,
    c() {
      div3 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      t1 = text(t1_value);
      t2 = space();
      if_block.c();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*item*/
      ctx[33].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      attr(div2, "class", "item-piles-name item-piles-text");
      attr(div3, "class", "form-group item-piles-slider-group item-piles-odd-color");
      this.first = div3;
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, t1);
      append(div3, t2);
      if_block.m(div3, null);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      32 && !src_url_equal(img.src, img_src_value = /*item*/
      ctx[33].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*items*/
      32 && t1_value !== (t1_value = /*item*/
      ctx[33].name + ""))
        set_data(t1, t1_value);
      if (current_block_type === (current_block_type = select_block_type_2(ctx)) && if_block) {
        if_block.p(ctx, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx);
        if (if_block) {
          if_block.c();
          if_block.m(div3, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if_block.d();
    }
  };
}
__name(create_each_block_2$7, "create_each_block_2$7");
function create_if_block_2$s(ctx) {
  let div;
  let t0;
  let each_blocks_1 = [];
  let each0_lookup = /* @__PURE__ */ new Map();
  let t1;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let each1_anchor;
  let each_value_1 = (
    /*attributes*/
    ctx[4].filter(func_4)
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*attribute*/
    ctx2[36].path
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$i(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_1[i] = create_each_block_1$i(key, child_ctx));
  }
  let each_value = (
    /*items*/
    ctx[5].filter(func_5)
  );
  const get_key_1 = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[33].id
  ), "get_key_1");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$C(ctx, each_value, i);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block$C(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      t0 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t1 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each1_anchor = empty();
      attr(div, "class", "item-piles-top-divider");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      insert(target, t0, anchor);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(target, anchor);
        }
      }
      insert(target, t1, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*attributes, settings*/
      24) {
        each_value_1 = /*attributes*/
        ctx2[4].filter(func_4);
        each_blocks_1 = update_keyed_each(each_blocks_1, dirty, get_key, 1, ctx2, each_value_1, each0_lookup, t1.parentNode, destroy_block, create_each_block_1$i, t1, get_each_context_1$i);
      }
      if (dirty[0] & /*items, settings*/
      40) {
        each_value = /*items*/
        ctx2[5].filter(func_5);
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_1, 1, ctx2, each_value, each1_lookup, each1_anchor.parentNode, destroy_block, create_each_block$C, each1_anchor, get_each_context$C);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t0);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].d(detaching);
      }
      if (detaching)
        detach(t1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each1_anchor);
    }
  };
}
__name(create_if_block_2$s, "create_if_block_2$s");
function create_else_block_1$7(ctx) {
  let input0;
  let input0_max_value;
  let t0;
  let input1;
  let t1;
  let div;
  let t2;
  let t3_value = abbreviateNumbers(
    /*attribute*/
    ctx[36].quantity
  ) + "";
  let t3;
  let mounted;
  let dispose;
  function input0_change_input_handler_2() {
    ctx[20].call(
      input0,
      /*each_value_1*/
      ctx[37],
      /*index*/
      ctx[35]
    );
  }
  __name(input0_change_input_handler_2, "input0_change_input_handler_2");
  function input1_input_handler_2() {
    ctx[21].call(
      input1,
      /*each_value_1*/
      ctx[37],
      /*index*/
      ctx[35]
    );
  }
  __name(input1_input_handler_2, "input1_input_handler_2");
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx[22](
        /*attribute*/
        ctx[36],
        /*each_value_1*/
        ctx[37],
        /*index*/
        ctx[35]
      )
    );
  }
  __name(click_handler_2, "click_handler_2");
  return {
    c() {
      input0 = element("input");
      t0 = space();
      input1 = element("input");
      t1 = space();
      div = element("div");
      t2 = text("/ ");
      t3 = text(t3_value);
      attr(input0, "class", "item-piles-range-slider");
      set_style(input0, "flex", "5");
      attr(input0, "type", "range");
      attr(input0, "min", "0");
      attr(input0, "max", input0_max_value = /*attribute*/
      ctx[36].quantity);
      attr(input1, "class", "item-piles-range-input");
      set_style(input1, "flex", "2");
      set_style(input1, "margin-left", "1rem");
      attr(input1, "type", "number");
      set_style(div, "flex", "0 1 50px");
      set_style(div, "margin", "0 5px");
    },
    m(target, anchor) {
      insert(target, input0, anchor);
      set_input_value(
        input0,
        /*attribute*/
        ctx[36].currentQuantity
      );
      insert(target, t0, anchor);
      insert(target, input1, anchor);
      set_input_value(
        input1,
        /*attribute*/
        ctx[36].currentQuantity
      );
      insert(target, t1, anchor);
      insert(target, div, anchor);
      append(div, t2);
      append(div, t3);
      if (!mounted) {
        dispose = [
          listen(input0, "change", input0_change_input_handler_2),
          listen(input0, "input", input0_change_input_handler_2),
          listen(input1, "input", input1_input_handler_2),
          listen(input1, "click", click_handler_2)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*attributes*/
      16 && input0_max_value !== (input0_max_value = /*attribute*/
      ctx[36].quantity)) {
        attr(input0, "max", input0_max_value);
      }
      if (dirty[0] & /*attributes*/
      16) {
        set_input_value(
          input0,
          /*attribute*/
          ctx[36].currentQuantity
        );
      }
      if (dirty[0] & /*attributes*/
      16 && to_number(input1.value) !== /*attribute*/
      ctx[36].currentQuantity) {
        set_input_value(
          input1,
          /*attribute*/
          ctx[36].currentQuantity
        );
      }
      if (dirty[0] & /*attributes*/
      16 && t3_value !== (t3_value = abbreviateNumbers(
        /*attribute*/
        ctx[36].quantity
      ) + ""))
        set_data(t3, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(input0);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(input1);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_else_block_1$7, "create_else_block_1$7");
function create_if_block_4$h(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler_2() {
    ctx[19].call(
      input,
      /*each_value_1*/
      ctx[37],
      /*index*/
      ctx[35]
    );
  }
  __name(input_input_handler_2, "input_input_handler_2");
  return {
    c() {
      input = element("input");
      attr(input, "class", "item-piles-range-input");
      set_style(input, "flex", "2");
      set_style(input, "margin-left", "1rem");
      attr(input, "type", "number");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*attribute*/
        ctx[36].currentQuantity
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler_2);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*attributes*/
      16 && to_number(input.value) !== /*attribute*/
      ctx[36].currentQuantity) {
        set_input_value(
          input,
          /*attribute*/
          ctx[36].currentQuantity
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$h, "create_if_block_4$h");
function create_each_block_1$i(key_1, ctx) {
  let div3;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let div2;
  let div1;
  let t1_value = (
    /*attribute*/
    ctx[36].name + ""
  );
  let t1;
  let t2;
  function select_block_type_3(ctx2, dirty) {
    if (
      /*settings*/
      ctx2[3]?.unlimitedCurrencies
    )
      return create_if_block_4$h;
    return create_else_block_1$7;
  }
  __name(select_block_type_3, "select_block_type_3");
  let current_block_type = select_block_type_3(ctx);
  let if_block = current_block_type(ctx);
  return {
    key: key_1,
    first: null,
    c() {
      div3 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      t1 = text(t1_value);
      t2 = space();
      if_block.c();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*attribute*/
      ctx[36].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      attr(div2, "class", "item-piles-name item-piles-text");
      attr(div3, "class", "form-group item-piles-slider-group item-piles-odd-color");
      this.first = div3;
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, t1);
      append(div3, t2);
      if_block.m(div3, null);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*attributes*/
      16 && !src_url_equal(img.src, img_src_value = /*attribute*/
      ctx[36].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*attributes*/
      16 && t1_value !== (t1_value = /*attribute*/
      ctx[36].name + ""))
        set_data(t1, t1_value);
      if (current_block_type === (current_block_type = select_block_type_3(ctx)) && if_block) {
        if_block.p(ctx, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx);
        if (if_block) {
          if_block.c();
          if_block.m(div3, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if_block.d();
    }
  };
}
__name(create_each_block_1$i, "create_each_block_1$i");
function create_else_block$m(ctx) {
  let input0;
  let input0_max_value;
  let t0;
  let input1;
  let t1;
  let div;
  let t2;
  let t3_value = abbreviateNumbers(
    /*item*/
    ctx[33].quantity
  ) + "";
  let t3;
  let mounted;
  let dispose;
  function input0_change_input_handler_3() {
    ctx[24].call(
      input0,
      /*each_value*/
      ctx[34],
      /*index*/
      ctx[35]
    );
  }
  __name(input0_change_input_handler_3, "input0_change_input_handler_3");
  function input1_input_handler_3() {
    ctx[25].call(
      input1,
      /*each_value*/
      ctx[34],
      /*index*/
      ctx[35]
    );
  }
  __name(input1_input_handler_3, "input1_input_handler_3");
  function click_handler_32() {
    return (
      /*click_handler_3*/
      ctx[26](
        /*item*/
        ctx[33],
        /*each_value*/
        ctx[34],
        /*index*/
        ctx[35]
      )
    );
  }
  __name(click_handler_32, "click_handler_3");
  return {
    c() {
      input0 = element("input");
      t0 = space();
      input1 = element("input");
      t1 = space();
      div = element("div");
      t2 = text("/ ");
      t3 = text(t3_value);
      attr(input0, "class", "item-piles-range-slider");
      set_style(input0, "flex", "5");
      attr(input0, "type", "range");
      attr(input0, "min", "0");
      attr(input0, "max", input0_max_value = /*item*/
      ctx[33].quantity);
      attr(input1, "class", "item-piles-range-input");
      set_style(input1, "flex", "1.5");
      set_style(input1, "margin-left", "1rem");
      attr(input1, "type", "number");
      set_style(div, "flex", "0 1 50px");
      set_style(div, "margin", "0 5px");
    },
    m(target, anchor) {
      insert(target, input0, anchor);
      set_input_value(
        input0,
        /*item*/
        ctx[33].currentQuantity
      );
      insert(target, t0, anchor);
      insert(target, input1, anchor);
      set_input_value(
        input1,
        /*item*/
        ctx[33].currentQuantity
      );
      insert(target, t1, anchor);
      insert(target, div, anchor);
      append(div, t2);
      append(div, t3);
      if (!mounted) {
        dispose = [
          listen(input0, "change", input0_change_input_handler_3),
          listen(input0, "input", input0_change_input_handler_3),
          listen(input1, "input", input1_input_handler_3),
          listen(input1, "click", click_handler_32)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      32 && input0_max_value !== (input0_max_value = /*item*/
      ctx[33].quantity)) {
        attr(input0, "max", input0_max_value);
      }
      if (dirty[0] & /*items*/
      32) {
        set_input_value(
          input0,
          /*item*/
          ctx[33].currentQuantity
        );
      }
      if (dirty[0] & /*items*/
      32 && to_number(input1.value) !== /*item*/
      ctx[33].currentQuantity) {
        set_input_value(
          input1,
          /*item*/
          ctx[33].currentQuantity
        );
      }
      if (dirty[0] & /*items*/
      32 && t3_value !== (t3_value = abbreviateNumbers(
        /*item*/
        ctx[33].quantity
      ) + ""))
        set_data(t3, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(input0);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(input1);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_else_block$m, "create_else_block$m");
function create_if_block_3$m(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler_3() {
    ctx[23].call(
      input,
      /*each_value*/
      ctx[34],
      /*index*/
      ctx[35]
    );
  }
  __name(input_input_handler_3, "input_input_handler_3");
  return {
    c() {
      input = element("input");
      attr(input, "class", "item-piles-range-input");
      set_style(input, "flex", "2");
      set_style(input, "margin-left", "1rem");
      attr(input, "type", "number");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*item*/
        ctx[33].currentQuantity
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler_3);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      32 && to_number(input.value) !== /*item*/
      ctx[33].currentQuantity) {
        set_input_value(
          input,
          /*item*/
          ctx[33].currentQuantity
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$m, "create_if_block_3$m");
function create_each_block$C(key_1, ctx) {
  let div3;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let div2;
  let div1;
  let t1_value = (
    /*item*/
    ctx[33].name + ""
  );
  let t1;
  let t2;
  let t3;
  function select_block_type_4(ctx2, dirty) {
    if (
      /*settings*/
      ctx2[3]?.unlimitedCurrencies
    )
      return create_if_block_3$m;
    return create_else_block$m;
  }
  __name(select_block_type_4, "select_block_type_4");
  let current_block_type = select_block_type_4(ctx);
  let if_block = current_block_type(ctx);
  return {
    key: key_1,
    first: null,
    c() {
      div3 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      t1 = text(t1_value);
      t2 = space();
      if_block.c();
      t3 = space();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*item*/
      ctx[33].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      attr(div2, "class", "item-piles-name item-piles-text");
      attr(div3, "class", "form-group item-piles-slider-group item-piles-odd-color");
      this.first = div3;
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, t1);
      append(div3, t2);
      if_block.m(div3, null);
      append(div3, t3);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      32 && !src_url_equal(img.src, img_src_value = /*item*/
      ctx[33].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*items*/
      32 && t1_value !== (t1_value = /*item*/
      ctx[33].name + ""))
        set_data(t1, t1_value);
      if (current_block_type === (current_block_type = select_block_type_4(ctx)) && if_block) {
        if_block.p(ctx, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx);
        if (if_block) {
          if_block.c();
          if_block.m(div3, t3);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if_block.d();
    }
  };
}
__name(create_each_block$C, "create_each_block$C");
function create_if_block$S(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize(
    /*settings*/
    ctx[3]?.button ?? `ITEM-PILES.Applications.${/*localization*/
    ctx[2]}.Submit`
  ) + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-download");
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*requestSubmit*/
          ctx[8],
          { once: true }
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*settings, localization*/
      12 && t1_value !== (t1_value = localize(
        /*settings*/
        ctx2[3]?.button ?? `ITEM-PILES.Applications.${/*localization*/
        ctx2[2]}.Submit`
      ) + ""))
        set_data(t1, t1_value);
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$S, "create_if_block$S");
function create_default_slot$s(ctx) {
  let form_1;
  let t0;
  let footer;
  let t1;
  let button;
  let i;
  let t2;
  let t3_value = localize("Cancel") + "";
  let t3;
  let mounted;
  let dispose;
  function select_block_type(ctx2, dirty) {
    if (
      /*attributes*/
      ctx2[4].length || /*items*/
      ctx2[5].length
    )
      return create_if_block_1$D;
    return create_else_block_4;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block0 = current_block_type(ctx);
  let if_block1 = (
    /*attributes*/
    (ctx[4].length || /*items*/
    ctx[5].length) && create_if_block$S(ctx)
  );
  return {
    c() {
      form_1 = element("form");
      if_block0.c();
      t0 = space();
      footer = element("footer");
      if (if_block1)
        if_block1.c();
      t1 = space();
      button = element("button");
      i = element("i");
      t2 = space();
      t3 = text(t3_value);
      attr(i, "class", "fas fa-times");
      attr(button, "type", "button");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
      set_style(footer, "margin-top", "1rem");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-flexcol");
      set_style(form_1, "padding", "0.5rem");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      if_block0.m(form_1, null);
      append(form_1, t0);
      append(form_1, footer);
      if (if_block1)
        if_block1.m(footer, null);
      append(footer, t1);
      append(footer, button);
      append(button, i);
      append(button, t2);
      append(button, t3);
      ctx[28](form_1);
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*click_handler_4*/
            ctx[27],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*submit*/
            ctx[9]
          ), { once: true })
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block0) {
        if_block0.p(ctx2, dirty);
      } else {
        if_block0.d(1);
        if_block0 = current_block_type(ctx2);
        if (if_block0) {
          if_block0.c();
          if_block0.m(form_1, t0);
        }
      }
      if (
        /*attributes*/
        ctx2[4].length || /*items*/
        ctx2[5].length
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block$S(ctx2);
          if_block1.c();
          if_block1.m(footer, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      if_block0.d();
      if (if_block1)
        if_block1.d();
      ctx[28](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$s, "create_default_slot$s");
function create_fragment$1d(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[29](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$s] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*form, settings, localization, attributes, items, sourceActor*/
      126 | dirty[1] & /*$$scope*/
      512) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$1d, "create_fragment$1d");
const func$3 = /* @__PURE__ */ __name((currency) => currency.secondary, "func$3");
const func_1 = /* @__PURE__ */ __name((currency) => currency.secondary, "func_1");
const func_2$1 = /* @__PURE__ */ __name((currency) => !currency.secondary, "func_2$1");
const func_3 = /* @__PURE__ */ __name((currency) => !currency.secondary, "func_3");
const func_4 = /* @__PURE__ */ __name((currency) => currency.secondary, "func_4");
const func_5 = /* @__PURE__ */ __name((currency) => currency.secondary, "func_5");
function instance$1a($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { sourceActor } = $$props;
  let { targetActor } = $$props;
  let { localization } = $$props;
  let { settings } = $$props;
  let { elementRoot } = $$props;
  const targetCurrencyData = getCurrencyList(targetActor);
  const currencies = getActorCurrencies(sourceActor, {
    currencyList: targetCurrencyData.currencies,
    getAll: settings?.unlimitedCurrencies
  });
  const existingCurrencies = settings.existingCurrencies ?? getActorCurrencies(sourceActor, {
    currencyList: targetCurrencyData.currencies
  });
  let attributes = currencies.filter((entry) => entry.type === "attribute").map((currency) => {
    currency.currentQuantity = 0;
    return currency;
  });
  if (settings?.unlimitedCurrencies) {
    attributes.forEach((currency) => {
      const existingCurrency = existingCurrencies.find((existingCurrency2) => existingCurrency2.name === currency.name && existingCurrency2.img === currency.img);
      if (existingCurrency) {
        currency.currentQuantity = existingCurrency.quantity;
      }
    });
  }
  let items = currencies.filter((entry) => entry.type !== "attribute").map((currency) => {
    currency.create = !existingCurrencies.some((existingCurrency) => existingCurrency.name === currency.name && existingCurrency.img === currency.img);
    currency.id = currency.id ?? randomID();
    currency.currentQuantity = 0;
    return currency;
  });
  if (settings?.unlimitedCurrencies) {
    items.forEach((currency) => {
      const existingCurrency = existingCurrencies.find((existingCurrency2) => existingCurrency2.name === currency.name && existingCurrency2.img === currency.img);
      if (existingCurrency) {
        currency.currentQuantity = existingCurrency.quantity;
      }
    });
  }
  let form;
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function submit() {
    const itemsToUpdate = items.filter((item) => (settings.unlimitedCurrencies || item.currentQuantity) && !item.create).map((item) => {
      return {
        _id: item.id,
        quantity: settings.getUpdates && item.quantity ? item.currentQuantity - item.quantity : item.currentQuantity
      };
    });
    const itemsToCreate = items.filter((item) => item.currentQuantity && item.create).map((item) => ({
      item: item.data.item,
      quantity: settings.unlimitedCurrencies ? item.currentQuantity : Math.max(0, Math.min(item.quantity, item.currentQuantity))
    }));
    application.options.resolve({
      attributes: Object.fromEntries(attributes.filter((attribute) => settings.unlimitedCurrencies || attribute.currentQuantity).map((attribute) => [
        attribute.path,
        settings.unlimitedCurrencies ? attribute.currentQuantity : Math.max(0, Math.min(attribute.quantity, attribute.currentQuantity))
      ])),
      items: itemsToUpdate.concat(itemsToCreate)
    });
    application.close();
  }
  __name(submit, "submit");
  function input_input_handler(each_value_3, index2) {
    each_value_3[index2].currentQuantity = to_number(this.value);
    $$invalidate(4, attributes);
  }
  __name(input_input_handler, "input_input_handler");
  function input0_change_input_handler(each_value_3, index2) {
    each_value_3[index2].currentQuantity = to_number(this.value);
    $$invalidate(4, attributes);
  }
  __name(input0_change_input_handler, "input0_change_input_handler");
  function input1_input_handler(each_value_3, index2) {
    each_value_3[index2].currentQuantity = to_number(this.value);
    $$invalidate(4, attributes);
  }
  __name(input1_input_handler, "input1_input_handler");
  const click_handler = /* @__PURE__ */ __name((attribute, each_value_3, index2) => {
    $$invalidate(4, each_value_3[index2].currentQuantity = Math.max(0, Math.min(attribute.quantity, attribute.currentQuantity)), attributes);
  }, "click_handler");
  function input_input_handler_1(each_value_2, index2) {
    each_value_2[index2].currentQuantity = to_number(this.value);
    $$invalidate(5, items);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  function input0_change_input_handler_1(each_value_2, index2) {
    each_value_2[index2].currentQuantity = to_number(this.value);
    $$invalidate(5, items);
  }
  __name(input0_change_input_handler_1, "input0_change_input_handler_1");
  function input1_input_handler_1(each_value_2, index2) {
    each_value_2[index2].currentQuantity = to_number(this.value);
    $$invalidate(5, items);
  }
  __name(input1_input_handler_1, "input1_input_handler_1");
  const click_handler_1 = /* @__PURE__ */ __name((item, each_value_2, index2) => {
    $$invalidate(5, each_value_2[index2].currentQuantity = Math.max(0, Math.min(item.quantity, item.currentQuantity)), items);
  }, "click_handler_1");
  function input_input_handler_2(each_value_1, index2) {
    each_value_1[index2].currentQuantity = to_number(this.value);
    $$invalidate(4, attributes);
  }
  __name(input_input_handler_2, "input_input_handler_2");
  function input0_change_input_handler_2(each_value_1, index2) {
    each_value_1[index2].currentQuantity = to_number(this.value);
    $$invalidate(4, attributes);
  }
  __name(input0_change_input_handler_2, "input0_change_input_handler_2");
  function input1_input_handler_2(each_value_1, index2) {
    each_value_1[index2].currentQuantity = to_number(this.value);
    $$invalidate(4, attributes);
  }
  __name(input1_input_handler_2, "input1_input_handler_2");
  const click_handler_2 = /* @__PURE__ */ __name((attribute, each_value_1, index2) => {
    $$invalidate(4, each_value_1[index2].currentQuantity = Math.max(0, Math.min(attribute.quantity, attribute.currentQuantity)), attributes);
  }, "click_handler_2");
  function input_input_handler_3(each_value, index2) {
    each_value[index2].currentQuantity = to_number(this.value);
    $$invalidate(5, items);
  }
  __name(input_input_handler_3, "input_input_handler_3");
  function input0_change_input_handler_3(each_value, index2) {
    each_value[index2].currentQuantity = to_number(this.value);
    $$invalidate(5, items);
  }
  __name(input0_change_input_handler_3, "input0_change_input_handler_3");
  function input1_input_handler_3(each_value, index2) {
    each_value[index2].currentQuantity = to_number(this.value);
    $$invalidate(5, items);
  }
  __name(input1_input_handler_3, "input1_input_handler_3");
  const click_handler_32 = /* @__PURE__ */ __name((item, each_value, index2) => {
    $$invalidate(5, each_value[index2].currentQuantity = Math.max(0, Math.min(item.quantity, item.currentQuantity)), items);
  }, "click_handler_3");
  const click_handler_4 = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler_4");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(6, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("sourceActor" in $$props2)
      $$invalidate(1, sourceActor = $$props2.sourceActor);
    if ("targetActor" in $$props2)
      $$invalidate(10, targetActor = $$props2.targetActor);
    if ("localization" in $$props2)
      $$invalidate(2, localization = $$props2.localization);
    if ("settings" in $$props2)
      $$invalidate(3, settings = $$props2.settings);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  return [
    elementRoot,
    sourceActor,
    localization,
    settings,
    attributes,
    items,
    form,
    application,
    requestSubmit,
    submit,
    targetActor,
    input_input_handler,
    input0_change_input_handler,
    input1_input_handler,
    click_handler,
    input_input_handler_1,
    input0_change_input_handler_1,
    input1_input_handler_1,
    click_handler_1,
    input_input_handler_2,
    input0_change_input_handler_2,
    input1_input_handler_2,
    click_handler_2,
    input_input_handler_3,
    input0_change_input_handler_3,
    input1_input_handler_3,
    click_handler_32,
    click_handler_4,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$1a, "instance$1a");
const _Drop_currency_dialog_shell = class _Drop_currency_dialog_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$1a,
      create_fragment$1d,
      safe_not_equal,
      {
        sourceActor: 1,
        targetActor: 10,
        localization: 2,
        settings: 3,
        elementRoot: 0
      },
      null,
      [-1, -1]
    );
  }
  get sourceActor() {
    return this.$$.ctx[1];
  }
  set sourceActor(sourceActor) {
    this.$$set({ sourceActor });
    flush();
  }
  get targetActor() {
    return this.$$.ctx[10];
  }
  set targetActor(targetActor) {
    this.$$set({ targetActor });
    flush();
  }
  get localization() {
    return this.$$.ctx[2];
  }
  set localization(localization) {
    this.$$set({ localization });
    flush();
  }
  get settings() {
    return this.$$.ctx[3];
  }
  set settings(settings) {
    this.$$set({ settings });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
};
__name(_Drop_currency_dialog_shell, "Drop_currency_dialog_shell");
let Drop_currency_dialog_shell = _Drop_currency_dialog_shell;
const _DropCurrencyDialog = class _DropCurrencyDialog extends SvelteApplication {
  /**
   *
   * @param sourceActor
   * @param targetActor
   * @param settings
   * @param options
   */
  constructor(sourceActor, targetActor, settings = {}, options = {}) {
    const localization = settings.localization || "DropCurrencies";
    super({
      id: `item-pile-drop-currency-${sourceActor ? sourceActor.id + (targetActor ? "-" + targetActor.id : "") : ""}-${randomID()}`,
      title: settings.title ?? game.i18n.localize(`ITEM-PILES.Applications.${localization}.Title`),
      svelte: {
        class: Drop_currency_dialog_shell,
        target: document.body,
        props: {
          sourceActor,
          targetActor,
          localization,
          settings
        }
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 430,
      height: "auto",
      classes: ["item-piles-app"]
    });
  }
  static getActiveApps(id) {
    return getActiveApps(`item-pile-drop-currency-${id}`);
  }
  static async show(sourceActor, targetActor, settings = {}, options = {}) {
    if (sourceActor) {
      const apps = this.getActiveApps(targetActor ? sourceActor.uuid + "-" + targetActor.uuid : sourceActor.uuid);
      if (apps.length) {
        for (let app of apps) {
          app.render(false, { focus: true });
        }
        return;
      }
    }
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(sourceActor, targetActor, settings, options).render(true, { focus: true });
    });
  }
};
__name(_DropCurrencyDialog, "DropCurrencyDialog");
let DropCurrencyDialog = _DropCurrencyDialog;
const __STORES__ = /* @__PURE__ */ new Map();
const _ItemPileStore = class _ItemPileStore {
  constructor(application, source, recipient = false, { recipientPileData = false } = {}) {
    this.subscriptions = [];
    this.interactionId = randomID();
    this.application = application;
    this.uuid = getUuid(source);
    this.actor = getActor(source);
    this.document = new TJSDocument(this.actor);
    this.recipient = recipient ? getActor(recipient) : false;
    this.recipientDocument = recipient ? new TJSDocument(this.recipient) : new TJSDocument();
    this.recipientPileData = writable$1(recipientPileData);
    this.pileData = writable$1({});
    this.shareData = writable$1({});
    this.recipientPileData = writable$1({});
    this.recipientShareData = writable$1({});
    this.deleted = writable$1(false);
    this.search = writable$1("");
    this.editQuantities = writable$1(true);
    this.allItems = writable$1([]);
    this.attributes = writable$1([]);
    this.items = writable$1([]);
    this.visibleItems = writable$1([]);
    this.pileCurrencies = writable$1([]);
    this.recipientCurrencies = writable$1([]);
    this.currencies = writable$1([]);
    this.allCurrencies = writable$1([]);
    this.itemsPerCategory = writable$1({});
    this.categories = writable$1([]);
    this.itemCategories = writable$1([]);
    this.numItems = writable$1(0);
    this.numCurrencies = writable$1(0);
    this.name = writable$1("");
    this.img = writable$1("");
    __STORES__.set(this.uuid, this);
  }
  get ItemClass() {
    return PileItem;
  }
  get AttributeClass() {
    return PileAttribute;
  }
  get searchDelay() {
    return 200;
  }
  static make(...args) {
    const store = new this(...args);
    store.setupStores();
    store.setupSubscriptions();
    return store;
  }
  static getStore(actor) {
    const uuid = getUuid(actor);
    return __STORES__.get(uuid);
  }
  static notifyChanges(event, actor, ...args) {
    const store = this.getStore(actor);
    if (store) {
      store[event](...args);
    }
  }
  static notifyAllOfChanges(event, ...args) {
    for (const store of __STORES__.values()) {
      if (store[event]) {
        store[event](...args);
      }
    }
  }
  setupStores() {
    this.pileData.set(getActorFlagData(this.actor));
    this.shareData.set(getItemPileSharingData(this.actor));
    this.recipientPileData.set(this.recipient ? getActorFlagData(this.recipient) : {});
    this.recipientShareData.set(this.recipient ? getItemPileSharingData(this.recipient) : {});
    this.deleted.set(false);
    this.search.set("");
    this.editQuantities.set(!this.recipient);
    this.allItems.set([]);
    this.attributes.set([]);
    this.items.set([]);
    this.visibleItems.set([]);
    this.pileCurrencies.set(getActorCurrencies(this.actor, { getAll: true }));
    this.recipientCurrencies.set(this.recipient ? getActorCurrencies(this.recipient, { getAll: true }) : []);
    this.currencies.set([]);
    this.allCurrencies.set([]);
    this.itemsPerCategory.set({});
    this.categories.set([]);
    this.itemCategories.set([]);
    this.numItems.set(0);
    this.numCurrencies.set(0);
    this.name.set("");
    this.img.set("");
  }
  getActorImage() {
    return this.actor.img;
  }
  setupSubscriptions() {
    this.subscribeTo(this.document, () => {
      const { data: data2 } = this.document.updateOptions;
      if (hasProperty(data2, CONSTANTS.FLAGS.SHARING)) {
        this.shareData.set(getItemPileSharingData(this.actor));
        this.refreshItems();
      }
      if (hasProperty(data2, CONSTANTS.FLAGS.PILE)) {
        this.pileData.set(getActorFlagData(this.actor));
        this.pileCurrencies.set(getActorCurrencies(this.actor, { getAll: true }));
        this.refreshItems();
      }
      this.name.set(this.actor.name);
      this.img.set(this.getActorImage());
    });
    if (this.recipientDocument) {
      this.subscribeTo(this.recipientDocument, () => {
        const { data: data2 } = this.document.updateOptions;
        if (hasProperty(data2, CONSTANTS.FLAGS.SHARING)) {
          this.recipientShareData.set(getItemPileSharingData(this.recipient));
          this.refreshItems();
        }
        if (hasProperty(data2, CONSTANTS.FLAGS.PILE)) {
          this.recipientPileData.set(getActorFlagData(this.recipient));
          this.recipientCurrencies.set(getActorCurrencies(this.recipient, { getAll: true }));
          this.refreshItems();
        }
      });
    }
    const items = [];
    const attributes = [];
    const pileData = isValidItemPile(this.actor) || !this.recipient ? get_store_value(this.pileData) : get_store_value(this.recipientPileData);
    getActorItems(this.actor, { itemFilters: pileData.overrideItemFilters }).map((item) => {
      items.push(new this.ItemClass(this, item));
    });
    getActorCurrencies(this.actor, { forActor: this.recipient, getAll: true }).forEach((currency) => {
      if (currency.type === "item") {
        if (!currency.item)
          return;
        items.push(new this.ItemClass(this, currency.item, true, !!currency?.secondary));
      } else {
        attributes.push(new this.AttributeClass(this, currency, true, !!currency?.secondary));
      }
    });
    this.allItems.set(items);
    this.attributes.set(attributes);
    this.subscribeTo(this.allItems, () => {
      this.refreshItems();
    });
    this.subscribeTo(this.attributes, () => {
      this.refreshItems();
    });
    const filterDebounce = foundry.utils.debounce(() => {
      this.refreshItems();
    }, this.searchDelay);
    this.subscribeTo(this.search, (val) => {
      filterDebounce();
    });
  }
  updateSource(newSource) {
    this.uuid = getUuid(newSource);
    this.actor = getActor(newSource);
    this.document.set(this.actor);
    __STORES__.set(this.uuid, this);
    this.unsubscribe();
    this.setupStores();
    this.setupSubscriptions();
  }
  updateRecipient(newRecipient) {
    this.recipient = newRecipient;
    this.recipientDocument.set(this.recipient);
    this.unsubscribe();
    this.setupStores();
    this.setupSubscriptions();
  }
  visibleItemFilterFunction(entry, actorIsMerchant, pileData, recipientPileData) {
    const itemFlagData = entry.itemFlagData ? get_store_value(entry.itemFlagData) : {};
    return !entry.isCurrency && (this.actor.isOwner || !actorIsMerchant || !itemFlagData?.hidden);
  }
  itemSortFunction(a, b, inverse) {
    return (b.item.name > a.item.name ? -1 : 1) * (inverse ? -1 : 1);
  }
  refreshItems() {
    const allItems = get_store_value(this.allItems);
    const pileData = get_store_value(this.pileData);
    const recipientPileData = this.recipient ? getActorFlagData(this.recipient) : {};
    const actorIsMerchant = isItemPileMerchant(this.actor, pileData);
    const visibleItems = allItems.filter((entry) => this.visibleItemFilterFunction(entry, actorIsMerchant, pileData, recipientPileData));
    const itemCurrencies = allItems.filter((entry) => entry.isCurrency && !entry.isSecondaryCurrency);
    const secondaryItemCurrencies = allItems.filter((entry) => entry.isSecondaryCurrency);
    this.visibleItems.set(visibleItems);
    const items = visibleItems.filter((entry) => !get_store_value(entry.filtered));
    this.numItems.set(items.filter((entry) => get_store_value(entry.quantity) > 0).length);
    this.items.set(items.sort((a, b) => this.itemSortFunction(a, b)));
    const currencies = get_store_value(this.attributes).filter((entry) => !entry.isSecondaryCurrency).concat(itemCurrencies);
    const secondaryCurrencies = get_store_value(this.attributes).filter((entry) => entry.isSecondaryCurrency).concat(secondaryItemCurrencies);
    this.numCurrencies.set(currencies.concat(secondaryCurrencies).filter((entry) => get_store_value(entry.quantity) > 0).length);
    this.currencies.set(currencies.concat(secondaryCurrencies).filter((entry) => !get_store_value(entry.filtered)));
    this.allCurrencies.set(currencies.concat(secondaryCurrencies));
    this.itemCategories.set(Object.values(visibleItems.reduce((acc, item) => {
      const category = get_store_value(item.category);
      if (!acc[category.type]) {
        acc[category.type] = { ...category };
      }
      return acc;
    }, {})).sort((a, b) => a.label < b.label ? -1 : 1));
    const itemsPerCategory = items.reduce((acc, item) => {
      const category = get_store_value(item.category);
      if (!acc[category.type]) {
        acc[category.type] = {
          service: category.service,
          type: category.type,
          label: category.label,
          items: []
        };
      }
      acc[category.type].items.push(item);
      return acc;
    }, {});
    Object.values(itemsPerCategory).forEach((category) => category.items.sort((a, b) => {
      return a.item.name < b.item.name ? -1 : 1;
    }));
    this.itemsPerCategory.set(itemsPerCategory);
    this.categories.set(Object.values(itemsPerCategory).map((category) => {
      return {
        service: category.service,
        label: category.label,
        type: category.type
      };
    }).sort((a, b) => a.label < b.label ? -1 : 1));
  }
  createItem(item) {
    if (isItemInvalid(this.actor, item))
      return;
    const items = get_store_value(this.allItems);
    const deletedItems = items.filter((item2) => item2.id === null).map((item2) => ({
      pileItem: item2,
      ...item2.similarities
    }));
    const previouslyDeletedItem = findSimilarItem(deletedItems, item);
    if (previouslyDeletedItem) {
      previouslyDeletedItem.pileItem.setup(item);
    } else {
      items.push(new this.ItemClass(this, item));
    }
    this.allItems.set(items);
  }
  deleteItem(item) {
    if (isItemInvalid(this.actor, item))
      return;
    const items = get_store_value(this.allItems);
    const pileItem = items.find((pileItem2) => pileItem2.id === item.id);
    if (!pileItem)
      return;
    if (get_store_value(this.editQuantities) || !InterfaceTracker.isOpened(this.application.id)) {
      items.splice(items.indexOf(pileItem), 1);
      this.allItems.set(items);
    } else {
      pileItem.id = null;
      pileItem.quantity.set(0);
      pileItem.quantityLeft.set(0);
    }
    pileItem.unsubscribe();
  }
  getSimilarItem(item) {
    const items = get_store_value(this.allItems).map((item2) => item2.item);
    return findSimilarItem(items, item, get_store_value(this.pileData));
  }
  delete() {
    this.deleted.set(true);
  }
  async update() {
    const itemsToUpdate = [];
    const itemsToDelete = [];
    const attributesToUpdate = {};
    const items = get_store_value(this.allItems).filter((item) => item.id);
    for (let item of items) {
      const itemQuantity = get_store_value(item.quantity);
      if (itemQuantity === 0) {
        itemsToDelete.push(item.id);
      } else {
        if (canItemStack(item.item, this.actor)) {
          itemsToUpdate.push(setItemQuantity({ _id: item.id }, itemQuantity));
        }
      }
    }
    const attributes = get_store_value(this.attributes);
    for (let attribute of attributes) {
      attributesToUpdate[attribute.path] = get_store_value(attribute.quantity);
    }
    const pileSharingData = getItemPileSharingData(this.actor);
    await this.actor.update(attributesToUpdate);
    if (pileSharingData?.currencies) {
      pileSharingData.currencies = pileSharingData.currencies.map((currency) => {
        if (attributesToUpdate[currency.path] !== void 0) {
          currency.actors = currency.actors.map((actor) => {
            actor.quantity = Math.max(0, Math.min(actor.quantity, attributesToUpdate[currency.path]));
            return actor;
          });
        }
        return currency;
      });
    }
    await this.actor.updateEmbeddedDocuments("Item", itemsToUpdate);
    await this.actor.deleteEmbeddedDocuments("Item", itemsToDelete);
    if (pileSharingData?.items) {
      pileSharingData.items = pileSharingData.items.map((item) => {
        const sharingItem = itemsToUpdate.find((item2) => item2._id === item2.id);
        if (sharingItem) {
          item.actors = item.actors.map((actor) => {
            actor.quantity = Math.max(0, Math.min(actor.quantity, sharingItem.quantity));
            return actor;
          });
        }
        return item;
      });
    }
    await updateItemPileSharingData(this.actor, pileSharingData);
    this.refreshItems();
    custom_notify(game.i18n.localize("ITEM-PILES.Notifications.UpdateItemPileSuccess"));
  }
  async depositCurrency() {
    const result = await DropCurrencyDialog.show(this.recipient, this.actor, { localization: "DepositCurrencies" });
    return this._addCurrency(result, this.recipient, this.actor);
  }
  async withdrawCurrency() {
    const result = await DropCurrencyDialog.show(this.actor, this.recipient, { localization: "WithdrawCurrencies" });
    return this._addCurrency(result, this.actor, this.recipient);
  }
  async addCurrency(recipient = false) {
    const source = recipient || this.actor;
    const target = recipient ? this.actor : false;
    const result = await DropCurrencyDialog.show(source, target, {
      localization: !target ? "EditCurrencies" : false,
      unlimitedCurrencies: !target && game.user.isGM,
      existingCurrencies: getActorCurrencies(source, { combine: true }),
      getUpdates: !target
    });
    return this._addCurrency(result, source, target);
  }
  async _addCurrency(currencies, source, target = false) {
    if (!currencies)
      return;
    if (!target) {
      if (!game.user.isGM)
        return;
      if (!foundry.utils.isEmpty(currencies.attributes)) {
        await game.itempiles.API.setAttributes(source, currencies.attributes, { interactionId: this.interactionId });
      }
      if (currencies.items.length) {
        const itemsToAdd = currencies.items.filter((currency) => currency.quantity > 0);
        const itemsToRemove = currencies.items.filter((currency) => currency.quantity < 0);
        await game.itempiles.API.addItems(source, itemsToAdd, { interactionId: this.interactionId });
        await game.itempiles.API.removeItems(source, itemsToRemove, { interactionId: this.interactionId });
      }
    } else {
      if (!foundry.utils.isEmpty(currencies.attributes)) {
        await game.itempiles.API.transferAttributes(source, target, currencies.attributes, { interactionId: this.interactionId });
      }
      if (currencies.items.length) {
        await game.itempiles.API.transferItems(source, target, currencies.items, { interactionId: this.interactionId });
      }
    }
  }
  takeAll() {
    game.itempiles.API.transferEverything(
      this.actor,
      this.recipient,
      { interactionId: this.interactionId }
    );
  }
  splitAll() {
    return game.itempiles.API.splitItemPileContents(this.actor, { instigator: this.recipient });
  }
  closeContainer() {
    if (!InterfaceTracker.isOpened(this.application.id)) {
      return game.itempiles.API.closeItemPile(this.actor, this.recipient);
    }
  }
  subscribeTo(target, callback) {
    this.subscriptions.push(target.subscribe(callback));
  }
  unsubscribe() {
    this.subscriptions.forEach((unsubscribe) => unsubscribe());
    this.subscriptions = [];
  }
  onDestroy() {
    this.unsubscribe();
    __STORES__.delete(this.uuid);
  }
};
__name(_ItemPileStore, "ItemPileStore");
let ItemPileStore = _ItemPileStore;
const CategorizedItemList_svelte_svelte_type_style_lang = "";
function get_each_context$B(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[8] = list[i];
  child_ctx[10] = i;
  return child_ctx;
}
__name(get_each_context$B, "get_each_context$B");
function get_each_context_1$h(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[11] = list[i];
  child_ctx[12] = list;
  child_ctx[13] = i;
  return child_ctx;
}
__name(get_each_context_1$h, "get_each_context_1$h");
function create_if_block$R(ctx) {
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let div_intro;
  let current;
  let each_value = (
    /*$categories*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*category*/
    ctx2[8].type
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$B(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$B(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*$itemsPerCategory, $categories, store, localize*/
      13) {
        each_value = /*$categories*/
        ctx2[2];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, outro_and_destroy_block, create_each_block$B, null, get_each_context$B);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      if (local) {
        if (!div_intro) {
          add_render_callback(() => {
            div_intro = create_in_transition(div, fade, { duration: 150 });
            div_intro.start();
          });
        }
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_if_block$R, "create_if_block$R");
function create_each_block_1$h(key_1, ctx) {
  let first;
  let listentry;
  let updating_entry;
  let current;
  function listentry_entry_binding(value) {
    ctx[7](
      value,
      /*item*/
      ctx[11],
      /*each_value_1*/
      ctx[12],
      /*item_index*/
      ctx[13]
    );
  }
  __name(listentry_entry_binding, "listentry_entry_binding");
  let listentry_props = { store: (
    /*store*/
    ctx[0]
  ) };
  if (
    /*item*/
    ctx[11] !== void 0
  ) {
    listentry_props.entry = /*item*/
    ctx[11];
  }
  listentry = new ListEntry({ props: listentry_props });
  binding_callbacks.push(() => bind(listentry, "entry", listentry_entry_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(listentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(listentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const listentry_changes = {};
      if (dirty & /*store*/
      1)
        listentry_changes.store = /*store*/
        ctx[0];
      if (!updating_entry && dirty & /*$itemsPerCategory, $categories*/
      12) {
        updating_entry = true;
        listentry_changes.entry = /*item*/
        ctx[11];
        add_flush_callback(() => updating_entry = false);
      }
      listentry.$set(listentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(listentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(listentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(listentry, detaching);
    }
  };
}
__name(create_each_block_1$h, "create_each_block_1$h");
function create_each_block$B(key_1, ctx) {
  let div0;
  let h3;
  let t0_value = localize(
    /*category*/
    ctx[8].label
  ) + "";
  let t0;
  let t1;
  let div1;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t2;
  let current;
  let each_value_1 = (
    /*$itemsPerCategory*/
    ctx[3][
      /*category*/
      ctx[8].type
    ].items
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[11].id
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$h(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$h(key, child_ctx));
  }
  return {
    key: key_1,
    first: null,
    c() {
      div0 = element("div");
      h3 = element("h3");
      t0 = text(t0_value);
      t1 = space();
      div1 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t2 = space();
      attr(div0, "class", "item-group-type item-piles-flexrow svelte-bdb8qc");
      attr(div1, "class", "item-piles-items-list");
      this.first = div0;
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, h3);
      append(h3, t0);
      insert(target, t1, anchor);
      insert(target, div1, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div1, null);
        }
      }
      append(div1, t2);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || dirty & /*$categories*/
      4) && t0_value !== (t0_value = localize(
        /*category*/
        ctx[8].label
      ) + ""))
        set_data(t0, t0_value);
      if (dirty & /*store, $itemsPerCategory, $categories*/
      13) {
        each_value_1 = /*$itemsPerCategory*/
        ctx[3][
          /*category*/
          ctx[8].type
        ].items;
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_1, each_1_lookup, div1, outro_and_destroy_block, create_each_block_1$h, t2, get_each_context_1$h);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(div1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_each_block$B, "create_each_block$B");
function create_fragment$1c(ctx) {
  let if_block_anchor;
  let current;
  let if_block = (
    /*$numItems*/
    ctx[1] > 0 && create_if_block$R(ctx)
  );
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (
        /*$numItems*/
        ctx2[1] > 0
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*$numItems*/
          2) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$R(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_fragment$1c, "create_fragment$1c");
function instance$19($$self, $$props, $$invalidate) {
  let $numItems;
  let $categories;
  let $itemsPerCategory;
  let { store } = $$props;
  const numItems = store.numItems;
  component_subscribe($$self, numItems, (value) => $$invalidate(1, $numItems = value));
  const categories = store.categories;
  component_subscribe($$self, categories, (value) => $$invalidate(2, $categories = value));
  const itemsPerCategory = store.itemsPerCategory;
  component_subscribe($$self, itemsPerCategory, (value) => $$invalidate(3, $itemsPerCategory = value));
  function listentry_entry_binding(value, item, each_value_1, item_index) {
    each_value_1[item_index] = value;
    itemsPerCategory.set($itemsPerCategory);
  }
  __name(listentry_entry_binding, "listentry_entry_binding");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
  };
  return [
    store,
    $numItems,
    $categories,
    $itemsPerCategory,
    numItems,
    categories,
    itemsPerCategory,
    listentry_entry_binding
  ];
}
__name(instance$19, "instance$19");
const _CategorizedItemList = class _CategorizedItemList extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$19, create_fragment$1c, safe_not_equal, { store: 0 });
  }
};
__name(_CategorizedItemList, "CategorizedItemList");
let CategorizedItemList = _CategorizedItemList;
const itemPileInventoryShell_svelte_svelte_type_style_lang = "";
function create_else_block_1$6(ctx) {
  let actorpicker;
  let t0;
  let t1;
  let t2;
  let div;
  let t3;
  let current_block_type_index;
  let if_block3;
  let t4;
  let t5;
  let currencylist;
  let current;
  let mounted;
  let dispose;
  actorpicker = new ActorPicker({ props: { store: (
    /*store*/
    ctx[1]
  ) } });
  let if_block0 = (
    /*showSearchBar*/
    ctx[7] && create_if_block_10$3(ctx)
  );
  let if_block1 = (
    /*isPileEmpty*/
    ctx[9] && create_if_block_9$3()
  );
  let if_block2 = (
    /*scrolled*/
    ctx[5] && create_if_block_8$3()
  );
  const if_block_creators = [create_if_block_7$6, create_else_block_2$2];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (
      /*$pileData*/
      ctx2[2].displayItemTypes
    )
      return 0;
    return 1;
  }
  __name(select_block_type_1, "select_block_type_1");
  current_block_type_index = select_block_type_1(ctx);
  if_block3 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block4 = (
    /*hasItems*/
    ctx[8] && create_if_block_6$8()
  );
  currencylist = new CurrencyList$2({ props: { store: (
    /*store*/
    ctx[1]
  ) } });
  return {
    c() {
      create_component(actorpicker.$$.fragment);
      t0 = space();
      if (if_block0)
        if_block0.c();
      t1 = space();
      if (if_block1)
        if_block1.c();
      t2 = space();
      div = element("div");
      if (if_block2)
        if_block2.c();
      t3 = space();
      if_block3.c();
      t4 = space();
      if (if_block4)
        if_block4.c();
      t5 = space();
      create_component(currencylist.$$.fragment);
      attr(div, "class", "item-piles-items-list svelte-1543648");
    },
    m(target, anchor) {
      mount_component(actorpicker, target, anchor);
      insert(target, t0, anchor);
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t1, anchor);
      if (if_block1)
        if_block1.m(target, anchor);
      insert(target, t2, anchor);
      insert(target, div, anchor);
      if (if_block2)
        if_block2.m(div, null);
      append(div, t3);
      if_blocks[current_block_type_index].m(div, null);
      append(div, t4);
      if (if_block4)
        if_block4.m(div, null);
      append(div, t5);
      mount_component(currencylist, div, null);
      ctx[33](div);
      current = true;
      if (!mounted) {
        dispose = listen(
          div,
          "scroll",
          /*evaluateShadow*/
          ctx[24]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const actorpicker_changes = {};
      if (dirty[0] & /*store*/
      2)
        actorpicker_changes.store = /*store*/
        ctx2[1];
      actorpicker.$set(actorpicker_changes);
      if (
        /*showSearchBar*/
        ctx2[7]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*showSearchBar*/
          128) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_10$3(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(t1.parentNode, t1);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*isPileEmpty*/
        ctx2[9]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_9$3();
          if_block1.c();
          if_block1.m(t2.parentNode, t2);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (
        /*scrolled*/
        ctx2[5]
      ) {
        if (if_block2) {
          if (dirty[0] & /*scrolled*/
          32) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_8$3();
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div, t3);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block3 = if_blocks[current_block_type_index];
        if (!if_block3) {
          if_block3 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block3.c();
        } else {
          if_block3.p(ctx2, dirty);
        }
        transition_in(if_block3, 1);
        if_block3.m(div, t4);
      }
      if (
        /*hasItems*/
        ctx2[8]
      ) {
        if (if_block4)
          ;
        else {
          if_block4 = create_if_block_6$8();
          if_block4.c();
          if_block4.m(div, t5);
        }
      } else if (if_block4) {
        if_block4.d(1);
        if_block4 = null;
      }
      const currencylist_changes = {};
      if (dirty[0] & /*store*/
      2)
        currencylist_changes.store = /*store*/
        ctx2[1];
      currencylist.$set(currencylist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(actorpicker.$$.fragment, local);
      transition_in(if_block0);
      transition_in(if_block2);
      transition_in(if_block3);
      transition_in(currencylist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(actorpicker.$$.fragment, local);
      transition_out(if_block0);
      transition_out(if_block2);
      transition_out(if_block3);
      transition_out(currencylist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(actorpicker, detaching);
      if (detaching)
        detach(t0);
      if (if_block0)
        if_block0.d(detaching);
      if (detaching)
        detach(t1);
      if (if_block1)
        if_block1.d(detaching);
      if (detaching)
        detach(t2);
      if (detaching)
        detach(div);
      if (if_block2)
        if_block2.d();
      if_blocks[current_block_type_index].d();
      if (if_block4)
        if_block4.d();
      destroy_component(currencylist);
      ctx[33](null);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block_1$6, "create_else_block_1$6");
function create_if_block_5$c(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Inspect.Destroyed")}`;
      set_style(p, "text-align", "center");
      set_style(p, "flex", "0 1 auto");
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_5$c, "create_if_block_5$c");
function create_if_block_10$3(ctx) {
  let div;
  let label;
  let t1;
  let input;
  let div_transition;
  let current;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      label = element("label");
      label.textContent = "Search:";
      t1 = space();
      input = element("input");
      set_style(label, "flex", "0 1 auto");
      set_style(label, "margin-right", "5px");
      attr(input, "type", "text");
      attr(div, "class", "form-group item-piles-flexrow item-piles-top-divider item-piles-bottom-divider");
      set_style(div, "margin-bottom", "0.5rem");
      set_style(div, "align-items", "center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(div, t1);
      append(div, input);
      set_input_value(
        input,
        /*$searchStore*/
        ctx[11]
      );
      current = true;
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler*/
          ctx[32]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$searchStore*/
      2048 && input.value !== /*$searchStore*/
      ctx2[11]) {
        set_input_value(
          input,
          /*$searchStore*/
          ctx2[11]
        );
      }
    },
    i(local) {
      if (current)
        return;
      add_render_callback(() => {
        if (!current)
          return;
        if (!div_transition)
          div_transition = create_bidirectional_transition(div, fade, { duration: 250 }, true);
        div_transition.run(1);
      });
      current = true;
    },
    o(local) {
      if (!div_transition)
        div_transition = create_bidirectional_transition(div, fade, { duration: 250 }, false);
      div_transition.run(0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching && div_transition)
        div_transition.end();
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_10$3, "create_if_block_10$3");
function create_if_block_9$3(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Inspect.Empty")}`;
      attr(p, "class", "item-piles-top-divider");
      set_style(p, "text-align", "center");
      set_style(p, "flex", "0 1 auto");
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_9$3, "create_if_block_9$3");
function create_if_block_8$3(ctx) {
  let div0;
  let div0_transition;
  let t;
  let div1;
  let current;
  return {
    c() {
      div0 = element("div");
      t = space();
      div1 = element("div");
      attr(div0, "class", "item-pile-shadow scroll-shadow-top svelte-1543648");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      insert(target, t, anchor);
      insert(target, div1, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      add_render_callback(() => {
        if (!current)
          return;
        if (!div0_transition)
          div0_transition = create_bidirectional_transition(div0, fade, { duration: 300 }, true);
        div0_transition.run(1);
      });
      current = true;
    },
    o(local) {
      if (!div0_transition)
        div0_transition = create_bidirectional_transition(div0, fade, { duration: 300 }, false);
      div0_transition.run(0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching && div0_transition)
        div0_transition.end();
      if (detaching)
        detach(t);
      if (detaching)
        detach(div1);
    }
  };
}
__name(create_if_block_8$3, "create_if_block_8$3");
function create_else_block_2$2(ctx) {
  let itemlist;
  let current;
  itemlist = new ItemList({ props: { store: (
    /*store*/
    ctx[1]
  ) } });
  return {
    c() {
      create_component(itemlist.$$.fragment);
    },
    m(target, anchor) {
      mount_component(itemlist, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const itemlist_changes = {};
      if (dirty[0] & /*store*/
      2)
        itemlist_changes.store = /*store*/
        ctx2[1];
      itemlist.$set(itemlist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(itemlist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(itemlist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(itemlist, detaching);
    }
  };
}
__name(create_else_block_2$2, "create_else_block_2$2");
function create_if_block_7$6(ctx) {
  let categorizeditemlist;
  let current;
  categorizeditemlist = new CategorizedItemList({ props: { store: (
    /*store*/
    ctx[1]
  ) } });
  return {
    c() {
      create_component(categorizeditemlist.$$.fragment);
    },
    m(target, anchor) {
      mount_component(categorizeditemlist, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const categorizeditemlist_changes = {};
      if (dirty[0] & /*store*/
      2)
        categorizeditemlist_changes.store = /*store*/
        ctx2[1];
      categorizeditemlist.$set(categorizeditemlist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(categorizeditemlist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(categorizeditemlist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(categorizeditemlist, detaching);
    }
  };
}
__name(create_if_block_7$6, "create_if_block_7$6");
function create_if_block_6$8(ctx) {
  let hr;
  return {
    c() {
      hr = element("hr");
    },
    m(target, anchor) {
      insert(target, hr, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(hr);
    }
  };
}
__name(create_if_block_6$8, "create_if_block_6$8");
function create_if_block_4$g(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Applications.ItemPileConfig.Update") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-save");
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx[34]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$g, "create_if_block_4$g");
function create_if_block_2$r(ctx) {
  let button;
  let i;
  let t;
  let button_disabled_value;
  let mounted;
  let dispose;
  function select_block_type_2(ctx2, dirty) {
    if (
      /*$pileData*/
      ctx2[2].shareItemsEnabled
    )
      return create_if_block_3$l;
    return create_else_block$l;
  }
  __name(select_block_type_2, "select_block_type_2");
  let current_block_type = select_block_type_2(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      button = element("button");
      i = element("i");
      t = space();
      if_block.c();
      attr(i, "class", "fas fa-handshake");
      attr(button, "type", "button");
      button.disabled = button_disabled_value = /*isPileEmpty*/
      ctx[9] || !/*canBeSplit*/
      ctx[3];
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t);
      if_block.m(button, null);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[35]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_2(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(button, null);
        }
      }
      if (dirty[0] & /*isPileEmpty, canBeSplit*/
      520 && button_disabled_value !== (button_disabled_value = /*isPileEmpty*/
      ctx2[9] || !/*canBeSplit*/
      ctx2[3])) {
        button.disabled = button_disabled_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_2$r, "create_if_block_2$r");
function create_else_block$l(ctx) {
  let t_value = localize("ITEM-PILES.Inspect.SplitCurrencies", { num_players: (
    /*num_players*/
    ctx[22]
  ) }) + "";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(create_else_block$l, "create_else_block$l");
function create_if_block_3$l(ctx) {
  let t_value = localize("ITEM-PILES.Inspect.SplitAll", { num_players: (
    /*num_players*/
    ctx[22]
  ) }) + "";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(create_if_block_3$l, "create_if_block_3$l");
function create_if_block_1$C(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Inspect.TakeAll") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-fist-raised");
      attr(button, "type", "submit");
      button.disabled = /*isPileEmpty*/
      ctx[9];
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_2*/
          ctx[36]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*isPileEmpty*/
      512) {
        button.disabled = /*isPileEmpty*/
        ctx2[9];
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$C, "create_if_block_1$C");
function create_if_block$Q(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Inspect.Close") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-box");
      attr(button, "type", "submit");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_3*/
          ctx[37]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$Q, "create_if_block$Q");
function create_default_slot$r(ctx) {
  let main;
  let div;
  let current_block_type_index;
  let if_block0;
  let t0;
  let footer;
  let t1;
  let t2;
  let t3;
  let t4;
  let button;
  let i;
  let t5;
  let t6_value = localize("ITEM-PILES.Inspect.Leave") + "";
  let t6;
  let main_intro;
  let current;
  let mounted;
  let dispose;
  const if_block_creators = [create_if_block_5$c, create_else_block_1$6];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*$deleted*/
      ctx2[10]
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block1 = (
    /*editQuantities*/
    ctx[14] && create_if_block_4$g(ctx)
  );
  let if_block2 = (
    /*$pileData*/
    ctx[2].splitAllEnabled && create_if_block_2$r(ctx)
  );
  let if_block3 = (
    /*store*/
    ctx[1].recipient && /*$pileData*/
    ctx[2].takeAllEnabled && create_if_block_1$C(ctx)
  );
  let if_block4 = (
    /*isContainer*/
    ctx[6] && !/*application*/
    ctx[12].options.remote && create_if_block$Q(ctx)
  );
  return {
    c() {
      main = element("main");
      div = element("div");
      if_block0.c();
      t0 = space();
      footer = element("footer");
      if (if_block1)
        if_block1.c();
      t1 = space();
      if (if_block2)
        if_block2.c();
      t2 = space();
      if (if_block3)
        if_block3.c();
      t3 = space();
      if (if_block4)
        if_block4.c();
      t4 = space();
      button = element("button");
      i = element("i");
      t5 = space();
      t6 = text(t6_value);
      attr(i, "class", "fas fa-sign-out-alt");
      attr(button, "type", "submit");
      attr(footer, "class", "sheet-footer item-piles-flexrow item-piles-top-divider");
      attr(div, "class", "item-piles-item-drop-container");
    },
    m(target, anchor) {
      insert(target, main, anchor);
      append(main, div);
      if_blocks[current_block_type_index].m(div, null);
      append(div, t0);
      append(div, footer);
      if (if_block1)
        if_block1.m(footer, null);
      append(footer, t1);
      if (if_block2)
        if_block2.m(footer, null);
      append(footer, t2);
      if (if_block3)
        if_block3.m(footer, null);
      append(footer, t3);
      if (if_block4)
        if_block4.m(footer, null);
      append(footer, t4);
      append(footer, button);
      append(button, i);
      append(button, t5);
      append(button, t6);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*click_handler_4*/
            ctx[38]
          ),
          listen(div, "dragover", preventDefault$2),
          listen(div, "dragstart", preventDefaultGM),
          listen(
            div,
            "drop",
            /*dropData*/
            ctx[23]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block0.c();
        } else {
          if_block0.p(ctx2, dirty);
        }
        transition_in(if_block0, 1);
        if_block0.m(div, t0);
      }
      if (
        /*editQuantities*/
        ctx2[14]
      )
        if_block1.p(ctx2, dirty);
      if (
        /*$pileData*/
        ctx2[2].splitAllEnabled
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block_2$r(ctx2);
          if_block2.c();
          if_block2.m(footer, t2);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (
        /*store*/
        ctx2[1].recipient && /*$pileData*/
        ctx2[2].takeAllEnabled
      ) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
        } else {
          if_block3 = create_if_block_1$C(ctx2);
          if_block3.c();
          if_block3.m(footer, t3);
        }
      } else if (if_block3) {
        if_block3.d(1);
        if_block3 = null;
      }
      if (
        /*isContainer*/
        ctx2[6] && !/*application*/
        ctx2[12].options.remote
      ) {
        if (if_block4) {
          if_block4.p(ctx2, dirty);
        } else {
          if_block4 = create_if_block$Q(ctx2);
          if_block4.c();
          if_block4.m(footer, t4);
        }
      } else if (if_block4) {
        if_block4.d(1);
        if_block4 = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      if (!main_intro) {
        add_render_callback(() => {
          main_intro = create_in_transition(main, fade, { duration: 500 });
          main_intro.start();
        });
      }
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(main);
      if_blocks[current_block_type_index].d();
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      if (if_block3)
        if_block3.d();
      if (if_block4)
        if_block4.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$r, "create_default_slot$r");
function create_fragment$1b(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[39](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$r] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*store, isContainer, isPileEmpty, $pileData, canBeSplit, $deleted, itemListElement, hasItems, scrolled, $searchStore, showSearchBar*/
      4094 | dirty[1] & /*$$scope*/
      512) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$1b, "create_fragment$1b");
function preventDefaultGM(event) {
  if (game.user.isGM)
    return;
  event.preventDefault();
}
__name(preventDefaultGM, "preventDefaultGM");
function preventDefault$2(event) {
  event.preventDefault();
}
__name(preventDefault$2, "preventDefault$2");
function instance$18($$self, $$props, $$invalidate) {
  let isPileEmpty;
  let hasItems;
  let showSearchBar;
  let isContainer;
  let $currencies;
  let $items;
  let $shareData;
  let $pileData;
  let $numItems;
  let $numCurrencies;
  let $deleted;
  let $searchStore;
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let { actor } = $$props;
  let { recipient } = $$props;
  let { store = ItemPileStore.make(application, actor, recipient) } = $$props;
  let canBeSplit = false;
  let searchStore = store.search;
  component_subscribe($$self, searchStore, (value) => $$invalidate(11, $searchStore = value));
  let editQuantities = store.editQuantities;
  let pileData = store.pileData;
  component_subscribe($$self, pileData, (value) => $$invalidate(2, $pileData = value));
  let deleted = store.deleted;
  component_subscribe($$self, deleted, (value) => $$invalidate(10, $deleted = value));
  const items = store.allItems;
  component_subscribe($$self, items, (value) => $$invalidate(28, $items = value));
  const currencies = store.currencies;
  component_subscribe($$self, currencies, (value) => $$invalidate(27, $currencies = value));
  const numItems = store.numItems;
  component_subscribe($$self, numItems, (value) => $$invalidate(30, $numItems = value));
  const shareData = store.shareData;
  component_subscribe($$self, shareData, (value) => $$invalidate(29, $shareData = value));
  const numCurrencies = store.numCurrencies;
  component_subscribe($$self, numCurrencies, (value) => $$invalidate(31, $numCurrencies = value));
  let num_players = getPlayersForItemPile(actor).length;
  async function dropData(event) {
    event.preventDefault();
    let data2;
    try {
      data2 = JSON.parse(event.dataTransfer.getData("text/plain"));
    } catch (err) {
      return false;
    }
    if (data2.type === "Actor" && game.user.isGM) {
      const newRecipient = data2.uuid ? await fromUuid(data2.uuid) : game.actors.get(data2.id);
      return store.updateRecipient(newRecipient);
    }
    if (data2.type !== "Item") {
      custom_warning(`You can't drop documents of type "${data2.type}" into this Item Piles vault!`, true);
      return false;
    }
    const item = await Item.implementation.fromDropData(data2);
    const itemData = item.toObject();
    if (!itemData) {
      console.error(data2);
      throw custom_error("Something went wrong when dropping this item!");
    }
    const source = getSourceActorFromDropData(data2);
    return PrivateAPI._dropItem({
      source,
      target: store.actor,
      itemData: { item: itemData, quantity: 1 },
      skipCheck: true
    });
  }
  __name(dropData, "dropData");
  let itemListElement;
  let scrolled = false;
  function evaluateShadow() {
    $$invalidate(5, scrolled = itemListElement.scrollTop > 20);
  }
  __name(evaluateShadow, "evaluateShadow");
  onDestroy(() => {
    store.onDestroy();
  });
  function input_input_handler() {
    $searchStore = this.value;
    searchStore.set($searchStore);
  }
  __name(input_input_handler, "input_input_handler");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      itemListElement = $$value;
      $$invalidate(4, itemListElement);
    });
  }
  __name(div_binding, "div_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    store.update();
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    store.splitAll();
  }, "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    store.takeAll();
  }, "click_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name(() => {
    store.closeContainer();
    application.close();
  }, "click_handler_3");
  const click_handler_4 = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler_4");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("actor" in $$props2)
      $$invalidate(25, actor = $$props2.actor);
    if ("recipient" in $$props2)
      $$invalidate(26, recipient = $$props2.recipient);
    if ("store" in $$props2)
      $$invalidate(1, store = $$props2.store);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*$numItems*/
    1073741824 | $$self.$$.dirty[1] & /*$numCurrencies*/
    1) {
      $$invalidate(9, isPileEmpty = $numItems === 0 && $numCurrencies === 0);
    }
    if ($$self.$$.dirty[0] & /*$numItems*/
    1073741824) {
      $$invalidate(8, hasItems = $numItems > 0);
    }
    if ($$self.$$.dirty[0] & /*$numItems*/
    1073741824) {
      $$invalidate(7, showSearchBar = $numItems >= 8);
    }
    if ($$self.$$.dirty[0] & /*actor, $pileData*/
    33554436) {
      $$invalidate(6, isContainer = isItemPileContainer(actor, $pileData));
    }
    if ($$self.$$.dirty[0] & /*$shareData, $items, $currencies, actor*/
    973078528) {
      {
        $$invalidate(3, canBeSplit = canItemPileBeSplit(actor));
      }
    }
  };
  return [
    elementRoot,
    store,
    $pileData,
    canBeSplit,
    itemListElement,
    scrolled,
    isContainer,
    showSearchBar,
    hasItems,
    isPileEmpty,
    $deleted,
    $searchStore,
    application,
    searchStore,
    editQuantities,
    pileData,
    deleted,
    items,
    currencies,
    numItems,
    shareData,
    numCurrencies,
    num_players,
    dropData,
    evaluateShadow,
    actor,
    recipient,
    $currencies,
    $items,
    $shareData,
    $numItems,
    $numCurrencies,
    input_input_handler,
    div_binding,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_32,
    click_handler_4,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$18, "instance$18");
const _Item_pile_inventory_shell = class _Item_pile_inventory_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$18,
      create_fragment$1b,
      safe_not_equal,
      {
        elementRoot: 0,
        actor: 25,
        recipient: 26,
        store: 1
      },
      null,
      [-1, -1]
    );
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get actor() {
    return this.$$.ctx[25];
  }
  set actor(actor) {
    this.$$set({ actor });
    flush();
  }
  get recipient() {
    return this.$$.ctx[26];
  }
  set recipient(recipient) {
    this.$$set({ recipient });
    flush();
  }
  get store() {
    return this.$$.ctx[1];
  }
  set store(store) {
    this.$$set({ store });
    flush();
  }
};
__name(_Item_pile_inventory_shell, "Item_pile_inventory_shell");
let Item_pile_inventory_shell = _Item_pile_inventory_shell;
const Tabs_svelte_svelte_type_style_lang = "";
function get_each_context$A(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[6] = list[i];
  child_ctx[8] = i;
  return child_ctx;
}
__name(get_each_context$A, "get_each_context$A");
function create_if_block_2$q(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      set_style(div, "border-right", "1px solid rgba(0,0,0,0.5)");
      set_style(div, "margin", "0 10px");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_2$q, "create_if_block_2$q");
function create_if_block_1$B(ctx) {
  let i;
  let i_class_value;
  return {
    c() {
      i = element("i");
      attr(i, "class", i_class_value = "icon " + /*tab*/
      ctx[6].icon + " svelte-14iev2w");
    },
    m(target, anchor) {
      insert(target, i, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*tabs*/
      2 && i_class_value !== (i_class_value = "icon " + /*tab*/
      ctx2[6].icon + " svelte-14iev2w")) {
        attr(i, "class", i_class_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(i);
    }
  };
}
__name(create_if_block_1$B, "create_if_block_1$B");
function create_if_block$P(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.innerHTML = `<i class="fas fa-exclamation"></i>`;
      attr(div, "class", "blob");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block$P, "create_if_block$P");
function create_each_block$A(key_1, ctx) {
  let first;
  let t0;
  let div;
  let t1;
  let t2_value = localize(
    /*tab*/
    ctx[6].label
  ) + "";
  let t2;
  let t3;
  let t4;
  let mounted;
  let dispose;
  let if_block0 = (
    /*separateElements*/
    ctx[3] && /*index*/
    ctx[8] > 0 && create_if_block_2$q()
  );
  let if_block1 = (
    /*tab*/
    ctx[6].icon && create_if_block_1$B(ctx)
  );
  let if_block2 = (
    /*tab*/
    ctx[6].highlight && create_if_block$P()
  );
  function click_handler() {
    return (
      /*click_handler*/
      ctx[5](
        /*tab*/
        ctx[6]
      )
    );
  }
  __name(click_handler, "click_handler");
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      if (if_block0)
        if_block0.c();
      t0 = space();
      div = element("div");
      if (if_block1)
        if_block1.c();
      t1 = space();
      t2 = text(t2_value);
      t3 = space();
      if (if_block2)
        if_block2.c();
      t4 = space();
      attr(div, "class", "item item-piles-flexrow item-piles-clickable-link svelte-14iev2w");
      attr(div, "data-tab", "rest");
      toggle_class(
        div,
        "underscore",
        /*underscore*/
        ctx[2]
      );
      toggle_class(
        div,
        "active",
        /*activeTab*/
        ctx[0] === /*tab*/
        ctx[6].value
      );
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, div, anchor);
      if (if_block1)
        if_block1.m(div, null);
      append(div, t1);
      append(div, t2);
      append(div, t3);
      if (if_block2)
        if_block2.m(div, null);
      append(div, t4);
      if (!mounted) {
        dispose = listen(div, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (
        /*separateElements*/
        ctx[3] && /*index*/
        ctx[8] > 0
      ) {
        if (if_block0)
          ;
        else {
          if_block0 = create_if_block_2$q();
          if_block0.c();
          if_block0.m(t0.parentNode, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*tab*/
        ctx[6].icon
      ) {
        if (if_block1) {
          if_block1.p(ctx, dirty);
        } else {
          if_block1 = create_if_block_1$B(ctx);
          if_block1.c();
          if_block1.m(div, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty & /*tabs*/
      2 && t2_value !== (t2_value = localize(
        /*tab*/
        ctx[6].label
      ) + ""))
        set_data(t2, t2_value);
      if (
        /*tab*/
        ctx[6].highlight
      ) {
        if (if_block2)
          ;
        else {
          if_block2 = create_if_block$P();
          if_block2.c();
          if_block2.m(div, t4);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (dirty & /*underscore*/
      4) {
        toggle_class(
          div,
          "underscore",
          /*underscore*/
          ctx[2]
        );
      }
      if (dirty & /*activeTab, tabs*/
      3) {
        toggle_class(
          div,
          "active",
          /*activeTab*/
          ctx[0] === /*tab*/
          ctx[6].value
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(first);
      if (if_block0)
        if_block0.d(detaching);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(div);
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_each_block$A, "create_each_block$A");
function create_fragment$1a(ctx) {
  let nav;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let nav_style_value;
  let each_value = (
    /*tabs*/
    ctx[1].filter(func$2)
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*tab*/
    ctx2[6].value
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$A(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$A(key, child_ctx));
  }
  return {
    c() {
      nav = element("nav");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(nav, "class", "tabs svelte-14iev2w");
      attr(nav, "data-group", "primary");
      attr(nav, "style", nav_style_value = /*$$props*/
      ctx[4].style);
    },
    m(target, anchor) {
      insert(target, nav, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(nav, null);
        }
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*underscore, activeTab, tabs, localize, separateElements*/
      15) {
        each_value = /*tabs*/
        ctx2[1].filter(func$2);
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, nav, destroy_block, create_each_block$A, null, get_each_context$A);
      }
      if (dirty & /*$$props*/
      16 && nav_style_value !== (nav_style_value = /*$$props*/
      ctx2[4].style)) {
        attr(nav, "style", nav_style_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(nav);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_fragment$1a, "create_fragment$1a");
const func$2 = /* @__PURE__ */ __name((tab) => !tab.hidden, "func$2");
function instance$17($$self, $$props, $$invalidate) {
  let { activeTab } = $$props;
  let { tabs } = $$props;
  let { underscore = false } = $$props;
  let { separateElements = false } = $$props;
  const click_handler = /* @__PURE__ */ __name((tab) => {
    $$invalidate(0, activeTab = tab.value);
  }, "click_handler");
  $$self.$$set = ($$new_props) => {
    $$invalidate(4, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
    if ("activeTab" in $$new_props)
      $$invalidate(0, activeTab = $$new_props.activeTab);
    if ("tabs" in $$new_props)
      $$invalidate(1, tabs = $$new_props.tabs);
    if ("underscore" in $$new_props)
      $$invalidate(2, underscore = $$new_props.underscore);
    if ("separateElements" in $$new_props)
      $$invalidate(3, separateElements = $$new_props.separateElements);
  };
  $$props = exclude_internal_props($$props);
  return [activeTab, tabs, underscore, separateElements, $$props, click_handler];
}
__name(instance$17, "instance$17");
const _Tabs = class _Tabs extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$17, create_fragment$1a, safe_not_equal, {
      activeTab: 0,
      tabs: 1,
      underscore: 2,
      separateElements: 3
    });
  }
};
__name(_Tabs, "Tabs");
let Tabs = _Tabs;
const _FoundryStyles = class _FoundryStyles {
  /**
   * Gets the properties object associated with the selector. Try and use a direct match otherwise all keys
   * are iterated to find a selector string that includes the `selector`.
   *
   * @param {string}   selector - Selector to find.
   *
   * @returns {Object<string, string>} Properties object.
   */
  static getProperties(selector) {
    if (!__privateGet(this, _initialized2)) {
      __privateMethod(this, _initialize, initialize_fn).call(this);
    }
    if (__privateGet(this, _sheetMap).has(selector)) {
      return __privateGet(this, _sheetMap).get(selector);
    }
    for (const key of __privateGet(this, _sheetMap).keys()) {
      if (key.includes(selector)) {
        return __privateGet(this, _sheetMap).get(key);
      }
    }
    return void 0;
  }
  /**
   * Gets a specific property value from the given `selector` and `property` key. Try and use a direct selector
   * match otherwise all keys are iterated to find a selector string that includes `selector`.
   *
   * @param {string}   selector - Selector to find.
   *
   * @param {string}   property - Specific property to locate.
   *
   * @returns {string|undefined} Property value.
   */
  static getProperty(selector, property) {
    if (!__privateGet(this, _initialized2)) {
      __privateMethod(this, _initialize, initialize_fn).call(this);
    }
    if (__privateGet(this, _sheetMap).has(selector)) {
      const data2 = __privateGet(this, _sheetMap).get(selector);
      return typeof data2 === "object" && property in data2 ? data2[property] : void 0;
    }
    for (const key of __privateGet(this, _sheetMap).keys()) {
      if (key.includes(selector)) {
        const data2 = __privateGet(this, _sheetMap).get(key);
        if (typeof data2 === "object" && property in data2) {
          return data2[property];
        }
      }
    }
    return void 0;
  }
};
_sheet = new WeakMap();
_sheetMap = new WeakMap();
_initialized2 = new WeakMap();
_initialize = new WeakSet();
initialize_fn = /* @__PURE__ */ __name(function() {
  __privateSet(this, _initialized2, true);
  const styleSheets = Array.from(document.styleSheets).filter((entry) => entry.href !== null);
  let sheet;
  const foundryStyleSheet = globalThis.foundry.utils.getRoute("/css/style.css");
  for (const styleSheet of styleSheets) {
    let url;
    try {
      url = new URL(styleSheet.href);
    } catch (err) {
      continue;
    }
    if (typeof url.pathname === "string" && url.pathname === foundryStyleSheet) {
      __privateSet(this, _sheet, sheet = styleSheet);
      break;
    }
  }
  if (!sheet) {
    return;
  }
  for (const rule of sheet.cssRules) {
    if (!(rule instanceof CSSStyleRule)) {
      continue;
    }
    const obj = {};
    for (const entry of rule.style.cssText.split(";")) {
      const parts = entry.split(":");
      if (parts.length < 2) {
        continue;
      }
      obj[parts[0].trim()] = parts[1].trim();
    }
    __privateGet(this, _sheetMap).set(rule.selectorText, obj);
  }
}, "#initialize");
/**
 * Called once on initialization / first usage. Parses the core foundry style sheet.
 */
__privateAdd(_FoundryStyles, _initialize);
__name(_FoundryStyles, "FoundryStyles");
__privateAdd(_FoundryStyles, _sheet, void 0);
__privateAdd(_FoundryStyles, _sheetMap, /* @__PURE__ */ new Map());
__privateAdd(_FoundryStyles, _initialized2, false);
let FoundryStyles = _FoundryStyles;
const s_STYLE_KEY = "#__tjs-root-styles";
const cssVariables = new StyleManager({ docKey: s_STYLE_KEY, version: 1 });
const TJSIconButton_svelte_svelte_type_style_lang = "";
const TJSToggleIconButton_svelte_svelte_type_style_lang = "";
const TJSScrollContainer_svelte_svelte_type_style_lang = "";
const TJSContentEdit_svelte_svelte_type_style_lang = "";
const _PMImpl = class _PMImpl {
  /**
   * Handles `options.initialSelection`: Sets the initial cursor / selection range to the start, end, or selects
   * all text.
   *
   * @param {EditorView}  view - PM editor view.
   *
   * @param {object}  options - TJSProseMirror options.
   */
  static setInitialSelection(view, options) {
    const tr = view.state.tr;
    const doc = tr.doc;
    const initialSelection = options.initialSelection;
    const type = initialSelection === "all" || initialSelection === "end" || initialSelection === "start" ? initialSelection : "start";
    const minPos = globalThis.ProseMirror.TextSelection.atStart(doc).from;
    const maxPos = globalThis.ProseMirror.TextSelection.atEnd(doc).to;
    let transaction;
    switch (type) {
      case "all": {
        const resolvedFrom = __privateMethod(this, _clamp, clamp_fn).call(this, 0, minPos, maxPos);
        const resolvedEnd = __privateMethod(this, _clamp, clamp_fn).call(this, doc.content.size, minPos, maxPos);
        transaction = tr.setSelection(globalThis.ProseMirror.TextSelection.create(doc, resolvedFrom, resolvedEnd));
        break;
      }
      case "end": {
        const resolvedFrom = __privateMethod(this, _clamp, clamp_fn).call(this, doc.content.size, minPos, maxPos);
        const resolvedEnd = __privateMethod(this, _clamp, clamp_fn).call(this, doc.content.size, minPos, maxPos);
        transaction = tr.setSelection(globalThis.ProseMirror.TextSelection.create(doc, resolvedFrom, resolvedEnd));
        break;
      }
      case "start": {
        const resolvedFrom = __privateMethod(this, _clamp, clamp_fn).call(this, 0, minPos, maxPos);
        const resolvedEnd = __privateMethod(this, _clamp, clamp_fn).call(this, 0, minPos, maxPos);
        transaction = tr.setSelection(globalThis.ProseMirror.TextSelection.create(doc, resolvedFrom, resolvedEnd));
        break;
      }
    }
    if (transaction) {
      transaction.scrollIntoView();
      view.dispatch(transaction);
    }
  }
};
_clamp = new WeakSet();
clamp_fn = /* @__PURE__ */ __name(function(value = 0, min2 = 0, max2 = 0) {
  return Math.min(Math.max(value, min2), max2);
}, "#clamp");
/**
 * Clamps a value between min / max values.
 *
 * @param {number}   value - Value to clamp.
 *
 * @param {number}   min - Minimum value.
 *
 * @param {number}   max - Maximum value.
 *
 * @returns {number} Clamped value.
 * TODO: Move Math utility function to @typhonjs-svelte/lib
 */
__privateAdd(_PMImpl, _clamp);
__name(_PMImpl, "PMImpl");
let PMImpl = _PMImpl;
const ProseMirrorKeyMaps = globalThis.ProseMirror ? globalThis.ProseMirror.ProseMirrorKeyMaps : class {
};
const _TJSKeyMaps = class _TJSKeyMaps extends ProseMirrorKeyMaps {
  /**
   * @param {Schema}   schema - The ProseMirror schema to build keymaps for.
   *
   * @param {object}   [options] - Additional options to configure the plugin's behaviour.
   *
   * @param {Function} [options.onSave] - A function to call when Ctrl+S is pressed.
   *
   * @param {Function} [options.onQuit] - A function to call when Ctrl+Q is pressed.
   */
  constructor(schema, options) {
    super(schema, options);
    __privateAdd(this, _onQuit, void 0);
    if (typeof options.onQuit === "function") {
      __privateSet(this, _onQuit, options.onQuit);
    }
  }
  /**
   * Swaps the Foundry default `Escape` / selectParentNode to `Mod-p` and enables `onQuit` function for `Escape`.
   *
   * @returns {Object<ProseMirrorCommand>} ProseMirror keymap data.
   */
  buildMapping() {
    const mapping = super.buildMapping();
    if (__privateGet(this, _onQuit)) {
      if (mapping["Escape"]) {
        mapping["Mod-p"] = mapping["Escape"];
      }
      mapping["Escape"] = () => __privateGet(this, _onQuit).call(this);
    }
    return mapping;
  }
};
_onQuit = new WeakMap();
__name(_TJSKeyMaps, "TJSKeyMaps");
let TJSKeyMaps = _TJSKeyMaps;
const Plugin = globalThis.ProseMirror ? globalThis.ProseMirror.Plugin : class {
};
const _TJSPasteUUID = class _TJSPasteUUID {
  constructor() {
    /**
     * Transforms pasted text. Check if pasted test matches the shape of a raw UUID. If so do a lookup and if a
     * document is retrieved transform it to a document link.
     *
     * @param {string}   text - pasted text to transform.
     *
     * @returns {string} Potentially transformed pasted text.
     */
    __privateAdd(this, _transformUUID);
  }
  /**
   * @returns {Plugin<any>} PM Plugin.
   */
  static build() {
    const instance2 = new this();
    return new Plugin({
      // key: new PluginKey('tjsPasteRawUUID'), // TODO: Add back when exported by Foundry / ProseMirror bundle.
      props: {
        transformPastedText: (text2) => {
          var _a2;
          return __privateMethod(_a2 = instance2, _transformUUID, transformUUID_fn).call(_a2, text2);
        }
      }
    });
  }
};
_s_UUID_REGEX = new WeakMap();
_transformUUID = new WeakSet();
transformUUID_fn = /* @__PURE__ */ __name(function(text2) {
  if (typeof text2 === "string") {
    if (__privateGet(_TJSPasteUUID, _s_UUID_REGEX).test(text2)) {
      const uuidDoc = globalThis.fromUuidSync(text2);
      if (uuidDoc) {
        text2 = `@UUID[${text2}]{${typeof uuidDoc.name === "string" ? uuidDoc.name : "Unknown"}}`;
      }
    }
  }
  return text2;
}, "#transformUUID");
__name(_TJSPasteUUID, "TJSPasteUUID");
/**
 * Defines a regex to check for the shape of a raw Foundry document UUID.
 *
 * @type {RegExp}
 */
__privateAdd(_TJSPasteUUID, _s_UUID_REGEX, /(\.).*([a-zA-Z0-9]{16})/);
let TJSPasteUUID = _TJSPasteUUID;
const index = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  TJSKeyMaps,
  TJSPasteUUID
});
const TJSProseMirror_svelte_svelte_type_style_lang = "";
function create_if_block_1$A(ctx) {
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.innerHTML = `<i class="fas fa-edit"></i>`;
      attr(a, "class", "editor-edit svelte-10m2cp0");
      attr(a, "role", "button");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[15]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$A, "create_if_block_1$A");
function create_else_block$k(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "editor-enriched svelte-10m2cp0");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      div.innerHTML = /*enrichedContent*/
      ctx[1];
    },
    p(ctx2, dirty) {
      if (dirty & /*enrichedContent*/
      2)
        div.innerHTML = /*enrichedContent*/
        ctx2[1];
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_else_block$k, "create_else_block$k");
function create_if_block$O(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "editor-content svelte-10m2cp0");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      ctx[16](div);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      ctx[16](null);
    }
  };
}
__name(create_if_block$O, "create_if_block$O");
function create_fragment$19(ctx) {
  let div;
  let t;
  let div_class_value;
  let applyStyles_action;
  let mounted;
  let dispose;
  let if_block0 = (
    /*editorButton*/
    ctx[5] && create_if_block_1$A(ctx)
  );
  function select_block_type(ctx2, dirty) {
    if (
      /*editorActive*/
      ctx2[3]
    )
      return create_if_block$O;
    return create_else_block$k;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block1 = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t = space();
      if_block1.c();
      attr(div, "class", div_class_value = "editor prosemirror tjs-editor " + (Array.isArray(
        /*options*/
        ctx[0].classes
      ) ? (
        /*options*/
        ctx[0].classes.join(" ")
      ) : "") + " svelte-10m2cp0");
      attr(div, "role", "textbox");
      attr(div, "tabindex", "0");
      toggle_class(
        div,
        "click-to-edit",
        /*clickToEdit*/
        ctx[2]
      );
      toggle_class(
        div,
        "editor-active",
        /*editorActive*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t);
      if_block1.m(div, null);
      ctx[17](div);
      if (!mounted) {
        dispose = [
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            div,
            /*options*/
            ctx[0].styles
          )),
          listen(
            div,
            "click",
            /*onClick*/
            ctx[9]
          ),
          listen(
            div,
            "keydown",
            /*onKeydown*/
            ctx[10]
          ),
          listen(
            div,
            "keyup",
            /*onKeyup*/
            ctx[11]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (
        /*editorButton*/
        ctx2[5]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_1$A(ctx2);
          if_block0.c();
          if_block0.m(div, t);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block1) {
        if_block1.p(ctx2, dirty);
      } else {
        if_block1.d(1);
        if_block1 = current_block_type(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div, null);
        }
      }
      if (dirty & /*options*/
      1 && div_class_value !== (div_class_value = "editor prosemirror tjs-editor " + (Array.isArray(
        /*options*/
        ctx2[0].classes
      ) ? (
        /*options*/
        ctx2[0].classes.join(" ")
      ) : "") + " svelte-10m2cp0")) {
        attr(div, "class", div_class_value);
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*options*/
      1)
        applyStyles_action.update.call(
          null,
          /*options*/
          ctx2[0].styles
        );
      if (dirty & /*options, clickToEdit*/
      5) {
        toggle_class(
          div,
          "click-to-edit",
          /*clickToEdit*/
          ctx2[2]
        );
      }
      if (dirty & /*options, editorActive*/
      9) {
        toggle_class(
          div,
          "editor-active",
          /*editorActive*/
          ctx2[3]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if_block1.d();
      ctx[17](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$19, "create_fragment$19");
function instance$16($$self, $$props, $$invalidate) {
  let $doc;
  let { content = "" } = $$props;
  let { enrichedContent = "" } = $$props;
  let { options = {} } = $$props;
  const dispatch2 = createEventDispatcher();
  const doc = new TJSDocument({ delete: onDocumentDeleted });
  component_subscribe($$self, doc, (value) => $$invalidate(14, $doc = value));
  let clickToEdit;
  let editable = true;
  let editorContentEl;
  let editor;
  let editorActive = false;
  let editorButton;
  let editorEl;
  let keyCode;
  let keyFocused = false;
  onDestroy(() => {
    if (editorActive) {
      saveEditor({
        remove: typeof options.button === "boolean" ? options.button : true
      });
    } else {
      destroyEditor();
    }
  });
  onMount(() => {
    if (editable && !editorButton && !clickToEdit) {
      initEditor();
    }
  });
  function destroyEditor(fireCancel = true) {
    if (editor) {
      editor.destroy();
      editor = void 0;
      setTimeout(
        () => {
          $$invalidate(3, editorActive = false);
        },
        0
      );
      if (keyFocused) {
        keyFocused = false;
        setTimeout(
          () => {
            if (editorEl instanceof HTMLElement && editorEl?.isConnected) {
              editorEl.focus();
            }
          },
          100
        );
      }
      if (fireCancel) {
        dispatch2("editor:cancel");
      }
    }
  }
  __name(destroyEditor, "destroyEditor");
  async function initEditor() {
    const remove = typeof options.button === "boolean" ? options.button : true;
    const editorOptions = {
      ...options,
      plugins: {
        ...ProseMirror.defaultPlugins,
        menu: ProseMirror.ProseMirrorMenu.build(ProseMirror.defaultSchema, {
          destroyOnSave: remove,
          onSave: () => saveEditor({ remove })
        }),
        keyMaps: index.TJSKeyMaps.build(ProseMirror.defaultSchema, {
          onSave: () => saveEditor({ remove }),
          onQuit: () => destroyEditor()
        }),
        tjsPasteRawUUID: index.TJSPasteUUID.build(),
        ...typeof options.plugins === "object" ? options.plugins : {}
      }
    };
    $$invalidate(3, editorActive = true);
    await tick();
    editor = await ProseMirrorEditor.create(editorContentEl, content, editorOptions);
    const containerEl = editorEl.querySelector(".editor-container");
    if (containerEl) {
      containerEl.style = "margin: var(--tjs-editor-container-margin, 0)";
    }
    editor.view.focus();
    PMImpl.setInitialSelection(editor.view, options);
    dispatch2("editor:start");
  }
  __name(initEditor, "initEditor");
  function onClick(event) {
    if (!editorActive && clickToEdit) {
      initEditor();
    }
  }
  __name(onClick, "onClick");
  async function onContentChanged(content2, enrichContent) {
    if (typeof content2 === "string") {
      if (enrichContent) {
        $$invalidate(1, enrichedContent = await TextEditor.enrichHTML(content2, {
          async: true,
          secrets: globalThis.game.user.isGM
        }));
      } else {
        $$invalidate(1, enrichedContent = content2);
      }
    } else {
      $$invalidate(1, enrichedContent = "");
    }
    dispatch2("editor:enrichedContent", { enrichedContent });
  }
  __name(onContentChanged, "onContentChanged");
  function onDocumentDeleted(document2) {
    $$invalidate(0, options.document = void 0, options);
    destroyEditor();
    dispatch2("editor:document:deleted", { document: document2 });
    $$invalidate(12, content = "");
    $$invalidate(1, enrichedContent = "");
  }
  __name(onDocumentDeleted, "onDocumentDeleted");
  function onKeydown(event) {
    if (editorActive) {
      if (event.code === "Escape" || event.code === "KeyS" && (event.ctrlKey || event.metaKey)) {
        event.preventDefault();
        event.stopPropagation();
      }
    } else {
      if (event.code === keyCode) {
        event.preventDefault();
        event.stopPropagation();
      }
    }
  }
  __name(onKeydown, "onKeydown");
  function onKeyup(event) {
    if (event.code === keyCode) {
      if (!editorActive) {
        keyFocused = true;
        initEditor();
      }
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onKeyup, "onKeyup");
  function saveEditor({ remove = true } = {}) {
    if (editor) {
      if (editor.isDirty()) {
        let data2 = ProseMirror.dom.serializeString(editor.view.state.doc);
        if (options?.DOMPurify && typeof options?.DOMPurify?.sanitizeWithVideo === "function") {
          data2 = options.DOMPurify.sanitizeWithVideo(data2);
        }
        if ($doc && options.fieldName) {
          $doc.update({ [options.fieldName]: data2 });
        } else {
          $$invalidate(12, content = data2);
        }
        dispatch2("editor:save", { content: data2 });
      }
      if (remove) {
        destroyEditor(false);
      }
    }
  }
  __name(saveEditor, "saveEditor");
  const click_handler = /* @__PURE__ */ __name(() => initEditor(), "click_handler");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      editorContentEl = $$value;
      $$invalidate(4, editorContentEl);
    });
  }
  __name(div_binding, "div_binding");
  function div_binding_1($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      editorEl = $$value;
      $$invalidate(6, editorEl);
    });
  }
  __name(div_binding_1, "div_binding_1");
  $$self.$$set = ($$props2) => {
    if ("content" in $$props2)
      $$invalidate(12, content = $$props2.content);
    if ("enrichedContent" in $$props2)
      $$invalidate(1, enrichedContent = $$props2.enrichedContent);
    if ("options" in $$props2)
      $$invalidate(0, options = $$props2.options);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*options, editable*/
    8193) {
      {
        $$invalidate(13, editable = typeof options.editable === "boolean" ? options.editable : true);
        if (!editable) {
          destroyEditor();
        }
      }
    }
    if ($$self.$$.dirty & /*editorActive, editable, options*/
    8201) {
      $$invalidate(2, clickToEdit = !editorActive && editable && (typeof options.clickToEdit === "boolean" ? options.clickToEdit : false));
    }
    if ($$self.$$.dirty & /*editorActive, editable, options, clickToEdit*/
    8205) {
      $$invalidate(5, editorButton = !editorActive && editable && (typeof options.button === "boolean" ? options.button : true) && !clickToEdit);
    }
    if ($$self.$$.dirty & /*options*/
    1) {
      keyCode = typeof options.keyCode === "string" ? options.keyCode : "Enter";
    }
    if ($$self.$$.dirty & /*options, $doc*/
    16385) {
      if (options.document !== void 0) {
        if (!(options.document instanceof globalThis.foundry.abstract.Document)) {
          throw new TypeError(`TJSProseMirror error: 'options.document' is not a Foundry document.`);
        }
        if (typeof options.fieldName !== "string") {
          throw new TypeError(`TJSProseMirror error: 'options.document' is defined, but 'options.fieldName' is not a string.`);
        }
        if (options.document !== $doc) {
          $$invalidate(1, enrichedContent = "");
          $$invalidate(12, content = "");
          destroyEditor();
        }
        doc.set(options.document);
      } else {
        if ($doc) {
          $$invalidate(1, enrichedContent = "");
          $$invalidate(12, content = "");
          destroyEditor();
          doc.set(void 0);
        }
      }
    }
    if ($$self.$$.dirty & /*$doc, options, content*/
    20481) {
      {
        $$invalidate(12, content = $doc !== void 0 ? globalThis.foundry.utils.getProperty($doc, options.fieldName) : typeof content === "string" ? content : "");
        onContentChanged(content, typeof options.enrichContent === "boolean" ? options.enrichContent : true);
      }
    }
  };
  return [
    options,
    enrichedContent,
    clickToEdit,
    editorActive,
    editorContentEl,
    editorButton,
    editorEl,
    doc,
    initEditor,
    onClick,
    onKeydown,
    onKeyup,
    content,
    editable,
    $doc,
    click_handler,
    div_binding,
    div_binding_1
  ];
}
__name(instance$16, "instance$16");
const _TJSProseMirror = class _TJSProseMirror extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$16, create_fragment$19, safe_not_equal, {
      content: 12,
      enrichedContent: 1,
      options: 0
    });
  }
};
__name(_TJSProseMirror, "TJSProseMirror");
let TJSProseMirror = _TJSProseMirror;
const TJSTinyMCE_svelte_svelte_type_style_lang = "";
const TJSSvgFolder_svelte_svelte_type_style_lang = "";
const TJSIconFolder_svelte_svelte_type_style_lang = "";
const TJSInputNumber_svelte_svelte_type_style_lang = "";
const TJSInputText_svelte_svelte_type_style_lang = "";
const TJSSelect_svelte_svelte_type_style_lang = "";
const TJSToggleLabel_svelte_svelte_type_style_lang = "";
const get_right_slot_changes$1 = /* @__PURE__ */ __name((dirty) => ({}), "get_right_slot_changes$1");
const get_right_slot_context$1 = /* @__PURE__ */ __name((ctx) => ({}), "get_right_slot_context$1");
const get_left_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_left_slot_changes");
const get_left_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_left_slot_context");
const get_outer_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_outer_slot_changes");
const get_outer_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_outer_slot_context");
function create_if_block_2$p(ctx) {
  let a;
  let t_value = localize(
    /*text*/
    ctx[0]
  ) + "";
  let t;
  return {
    c() {
      a = element("a");
      t = text(t_value);
      attr(a, "role", "presentation");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*text*/
      1 && t_value !== (t_value = localize(
        /*text*/
        ctx2[0]
      ) + ""))
        set_data(t, t_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(a);
    }
  };
}
__name(create_if_block_2$p, "create_if_block_2$p");
function create_if_block_1$z(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  var switch_value = (
    /*comp*/
    ctx[1]
  );
  function switch_props(ctx2) {
    return {};
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*comp*/
      2 && switch_value !== (switch_value = /*comp*/
      ctx2[1])) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
__name(create_if_block_1$z, "create_if_block_1$z");
function create_if_block$N(ctx) {
  let current;
  const default_slot_template = (
    /*#slots*/
    ctx[24].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[23],
    null
  );
  return {
    c() {
      if (default_slot)
        default_slot.c();
    },
    m(target, anchor) {
      if (default_slot) {
        default_slot.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        8388608)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[23],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[23]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[23],
              dirty,
              null
            ),
            null
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (default_slot)
        default_slot.d(detaching);
    }
  };
}
__name(create_if_block$N, "create_if_block$N");
function create_fragment$18(ctx) {
  let div;
  let t0;
  let span;
  let t1;
  let current_block_type_index;
  let if_block0;
  let t2;
  let t3;
  let div_title_value;
  let applyStyles_action;
  let current;
  let mounted;
  let dispose;
  const outer_slot_template = (
    /*#slots*/
    ctx[24].outer
  );
  const outer_slot = create_slot(
    outer_slot_template,
    ctx,
    /*$$scope*/
    ctx[23],
    get_outer_slot_context
  );
  const left_slot_template = (
    /*#slots*/
    ctx[24].left
  );
  const left_slot = create_slot(
    left_slot_template,
    ctx,
    /*$$scope*/
    ctx[23],
    get_left_slot_context
  );
  const if_block_creators = [create_if_block_1$z, create_if_block_2$p];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*comp*/
      ctx2[1]
    )
      return 0;
    if (typeof /*text*/
    ctx2[0] === "string")
      return 1;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  const right_slot_template = (
    /*#slots*/
    ctx[24].right
  );
  const right_slot = create_slot(
    right_slot_template,
    ctx,
    /*$$scope*/
    ctx[23],
    get_right_slot_context$1
  );
  let if_block1 = (
    /*selected*/
    ctx[5] && create_if_block$N(ctx)
  );
  return {
    c() {
      div = element("div");
      if (outer_slot)
        outer_slot.c();
      t0 = space();
      span = element("span");
      if (left_slot)
        left_slot.c();
      t1 = space();
      if (if_block0)
        if_block0.c();
      t2 = space();
      if (right_slot)
        right_slot.c();
      t3 = space();
      if (if_block1)
        if_block1.c();
      attr(span, "role", "button");
      attr(span, "tabindex", "0");
      attr(span, "class", "svelte-1qad3f4");
      toggle_class(
        span,
        "selected",
        /*selected*/
        ctx[5]
      );
      attr(div, "class", "tjs-toggle-label svelte-1qad3f4");
      attr(div, "title", div_title_value = localize(
        /*titleCurrent*/
        ctx[7]
      ));
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (outer_slot) {
        outer_slot.m(div, null);
      }
      append(div, t0);
      append(div, span);
      if (left_slot) {
        left_slot.m(span, null);
      }
      append(span, t1);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(span, null);
      }
      append(span, t2);
      if (right_slot) {
        right_slot.m(span, null);
      }
      ctx[27](span);
      append(div, t3);
      if (if_block1)
        if_block1.m(div, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            span,
            "click",
            /*onClick*/
            ctx[8]
          ),
          listen(
            span,
            "contextmenu",
            /*onContextMenuPress*/
            ctx[11]
          ),
          listen(
            span,
            "keydown",
            /*onKeydown*/
            ctx[12]
          ),
          listen(
            span,
            "keyup",
            /*onKeyup*/
            ctx[13]
          ),
          listen(
            span,
            "click",
            /*click_handler*/
            ctx[25]
          ),
          listen(
            span,
            "contextmenu",
            /*contextmenu_handler*/
            ctx[26]
          ),
          action_destroyer(
            /*efx*/
            ctx[4].call(null, span)
          ),
          listen(
            div,
            "click",
            /*onClickDiv*/
            ctx[9]
          ),
          listen(
            div,
            "close:popup",
            /*onClosePopup*/
            ctx[10]
          ),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            div,
            /*styles*/
            ctx[3]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (outer_slot) {
        if (outer_slot.p && (!current || dirty & /*$$scope*/
        8388608)) {
          update_slot_base(
            outer_slot,
            outer_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[23],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[23]
            ) : get_slot_changes(
              outer_slot_template,
              /*$$scope*/
              ctx2[23],
              dirty,
              get_outer_slot_changes
            ),
            get_outer_slot_context
          );
        }
      }
      if (left_slot) {
        if (left_slot.p && (!current || dirty & /*$$scope*/
        8388608)) {
          update_slot_base(
            left_slot,
            left_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[23],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[23]
            ) : get_slot_changes(
              left_slot_template,
              /*$$scope*/
              ctx2[23],
              dirty,
              get_left_slot_changes
            ),
            get_left_slot_context
          );
        }
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block0) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block0 = if_blocks[current_block_type_index];
          if (!if_block0) {
            if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block0.c();
          } else {
            if_block0.p(ctx2, dirty);
          }
          transition_in(if_block0, 1);
          if_block0.m(span, t2);
        } else {
          if_block0 = null;
        }
      }
      if (right_slot) {
        if (right_slot.p && (!current || dirty & /*$$scope*/
        8388608)) {
          update_slot_base(
            right_slot,
            right_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[23],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[23]
            ) : get_slot_changes(
              right_slot_template,
              /*$$scope*/
              ctx2[23],
              dirty,
              get_right_slot_changes$1
            ),
            get_right_slot_context$1
          );
        }
      }
      if (!current || dirty & /*selected*/
      32) {
        toggle_class(
          span,
          "selected",
          /*selected*/
          ctx2[5]
        );
      }
      if (
        /*selected*/
        ctx2[5]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*selected*/
          32) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block$N(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (!current || dirty & /*titleCurrent*/
      128 && div_title_value !== (div_title_value = localize(
        /*titleCurrent*/
        ctx2[7]
      ))) {
        attr(div, "title", div_title_value);
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*styles*/
      8)
        applyStyles_action.update.call(
          null,
          /*styles*/
          ctx2[3]
        );
    },
    i(local) {
      if (current)
        return;
      transition_in(outer_slot, local);
      transition_in(left_slot, local);
      transition_in(if_block0);
      transition_in(right_slot, local);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(outer_slot, local);
      transition_out(left_slot, local);
      transition_out(if_block0);
      transition_out(right_slot, local);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (outer_slot)
        outer_slot.d(detaching);
      if (left_slot)
        left_slot.d(detaching);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
      if (right_slot)
        right_slot.d(detaching);
      ctx[27](null);
      if (if_block1)
        if_block1.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$18, "create_fragment$18");
function instance$15($$self, $$props, $$invalidate) {
  let titleCurrent;
  let $store, $$unsubscribe_store = noop, $$subscribe_store = /* @__PURE__ */ __name(() => ($$unsubscribe_store(), $$unsubscribe_store = subscribe(store, ($$value) => $$invalidate(22, $store = $$value)), store), "$$subscribe_store");
  $$self.$$.on_destroy.push(() => $$unsubscribe_store());
  let { $$slots: slots = {}, $$scope } = $$props;
  let { label = void 0 } = $$props;
  let { text: text2 = void 0 } = $$props;
  let { comp = void 0 } = $$props;
  let { title = void 0 } = $$props;
  let { titleSelected = void 0 } = $$props;
  let { store = void 0 } = $$props;
  $$subscribe_store();
  let { styles: styles2 = void 0 } = $$props;
  let { efx = void 0 } = $$props;
  let { keyCode = void 0 } = $$props;
  let { onPress = void 0 } = $$props;
  let { onClose = void 0 } = $$props;
  let { onContextMenu = void 0 } = $$props;
  let { onClickPropagate = void 0 } = $$props;
  const dispatch2 = createEventDispatcher();
  let spanEl;
  let selected = false;
  function onClick(event) {
    $$invalidate(5, selected = !selected);
    if (store) {
      store.set(selected);
    }
    if (typeof onPress === "function") {
      onPress(selected);
    }
    dispatch2("press", { selected });
    if (!onClickPropagate) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onClick, "onClick");
  function onClickDiv(event) {
    if (!onClickPropagate) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onClickDiv, "onClickDiv");
  function onClosePopup(event) {
    $$invalidate(5, selected = false);
    if (store) {
      store.set(false);
    }
    if (typeof onClose === "function") {
      onClose(selected);
    }
    if (typeof event?.detail?.keyboardFocus === "boolean" && event.detail.keyboardFocus && spanEl?.isConnected) {
      spanEl.focus();
      event.stopPropagation();
      event.preventDefault();
    }
  }
  __name(onClosePopup, "onClosePopup");
  function onContextMenuPress(event) {
    if (typeof onContextMenu === "function") {
      onContextMenu();
    }
    if (!onClickPropagate) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onContextMenuPress, "onContextMenuPress");
  function onKeydown(event) {
    if (event.code === keyCode) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onKeydown, "onKeydown");
  function onKeyup(event) {
    if (event.code === keyCode) {
      $$invalidate(5, selected = !selected);
      if (store) {
        store.set(selected);
      }
      if (typeof onPress === "function") {
        onPress(selected);
      }
      dispatch2("press", { selected });
      event.preventDefault();
      event.stopPropagation();
    }
  }
  __name(onKeyup, "onKeyup");
  function click_handler(event) {
    bubble.call(this, $$self, event);
  }
  __name(click_handler, "click_handler");
  function contextmenu_handler(event) {
    bubble.call(this, $$self, event);
  }
  __name(contextmenu_handler, "contextmenu_handler");
  function span_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      spanEl = $$value;
      $$invalidate(6, spanEl);
    });
  }
  __name(span_binding, "span_binding");
  $$self.$$set = ($$props2) => {
    if ("label" in $$props2)
      $$invalidate(21, label = $$props2.label);
    if ("text" in $$props2)
      $$invalidate(0, text2 = $$props2.text);
    if ("comp" in $$props2)
      $$invalidate(1, comp = $$props2.comp);
    if ("title" in $$props2)
      $$invalidate(14, title = $$props2.title);
    if ("titleSelected" in $$props2)
      $$invalidate(15, titleSelected = $$props2.titleSelected);
    if ("store" in $$props2)
      $$subscribe_store($$invalidate(2, store = $$props2.store));
    if ("styles" in $$props2)
      $$invalidate(3, styles2 = $$props2.styles);
    if ("efx" in $$props2)
      $$invalidate(4, efx = $$props2.efx);
    if ("keyCode" in $$props2)
      $$invalidate(16, keyCode = $$props2.keyCode);
    if ("onPress" in $$props2)
      $$invalidate(17, onPress = $$props2.onPress);
    if ("onClose" in $$props2)
      $$invalidate(18, onClose = $$props2.onClose);
    if ("onContextMenu" in $$props2)
      $$invalidate(19, onContextMenu = $$props2.onContextMenu);
    if ("onClickPropagate" in $$props2)
      $$invalidate(20, onClickPropagate = $$props2.onClickPropagate);
    if ("$$scope" in $$props2)
      $$invalidate(23, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*label, text*/
    2097153) {
      $$invalidate(0, text2 = isObject(label) && typeof label.text === "string" ? label.text : typeof text2 === "string" ? text2 : void 0);
    }
    if ($$self.$$.dirty & /*label, comp*/
    2097154) {
      $$invalidate(1, comp = isObject(label) && isSvelteComponent(label.comp) ? label.comp : isSvelteComponent(comp) ? comp : void 0);
    }
    if ($$self.$$.dirty & /*label, title*/
    2113536) {
      $$invalidate(14, title = isObject(label) && typeof label.title === "string" ? label.title : typeof title === "string" ? title : "");
    }
    if ($$self.$$.dirty & /*label, titleSelected*/
    2129920) {
      $$invalidate(15, titleSelected = isObject(label) && typeof label.titleSelected === "string" ? label.titleSelected : typeof titleSelected === "string" ? titleSelected : "");
    }
    if ($$self.$$.dirty & /*label, store*/
    2097156) {
      $$subscribe_store($$invalidate(2, store = isObject(label) && isWritableStore(label.store) ? label.store : isWritableStore(store) ? store : void 0));
    }
    if ($$self.$$.dirty & /*label, styles*/
    2097160) {
      $$invalidate(3, styles2 = isObject(label) && typeof label.styles === "object" ? label.styles : typeof styles2 === "object" ? styles2 : void 0);
    }
    if ($$self.$$.dirty & /*label, efx*/
    2097168) {
      $$invalidate(4, efx = isObject(label) && typeof label.efx === "function" ? label.efx : typeof efx === "function" ? efx : () => {
      });
    }
    if ($$self.$$.dirty & /*label, keyCode*/
    2162688) {
      $$invalidate(16, keyCode = isObject(label) && typeof label.keyCode === "string" ? label.keyCode : typeof keyCode === "string" ? keyCode : "Enter");
    }
    if ($$self.$$.dirty & /*label, onPress*/
    2228224) {
      $$invalidate(17, onPress = isObject(label) && typeof label.onPress === "function" ? label.onPress : typeof onPress === "function" ? onPress : void 0);
    }
    if ($$self.$$.dirty & /*label, onClose*/
    2359296) {
      $$invalidate(18, onClose = isObject(label) && typeof label.onClose === "function" ? label.onClose : typeof onClose === "function" ? onClose : void 0);
    }
    if ($$self.$$.dirty & /*label, onContextMenu*/
    2621440) {
      $$invalidate(19, onContextMenu = isObject(label) && typeof label.onContextMenu === "function" ? label.onContextMenu : typeof onContextMenu === "function" ? onContextMenu : void 0);
    }
    if ($$self.$$.dirty & /*label, onClickPropagate*/
    3145728) {
      $$invalidate(20, onClickPropagate = isObject(label) && typeof label.onClickPropagate === "boolean" ? label.onClickPropagate : typeof onClickPropagate === "boolean" ? onClickPropagate : false);
    }
    if ($$self.$$.dirty & /*store, $store*/
    4194308) {
      if (store) {
        $$invalidate(5, selected = $store);
      }
    }
    if ($$self.$$.dirty & /*selected, titleSelected, title*/
    49184) {
      $$invalidate(7, titleCurrent = selected && titleSelected !== "" ? titleSelected : title);
    }
  };
  return [
    text2,
    comp,
    store,
    styles2,
    efx,
    selected,
    spanEl,
    titleCurrent,
    onClick,
    onClickDiv,
    onClosePopup,
    onContextMenuPress,
    onKeydown,
    onKeyup,
    title,
    titleSelected,
    keyCode,
    onPress,
    onClose,
    onContextMenu,
    onClickPropagate,
    label,
    $store,
    $$scope,
    slots,
    click_handler,
    contextmenu_handler,
    span_binding
  ];
}
__name(instance$15, "instance$15");
const _TJSToggleLabel = class _TJSToggleLabel extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$15, create_fragment$18, safe_not_equal, {
      label: 21,
      text: 0,
      comp: 1,
      title: 14,
      titleSelected: 15,
      store: 2,
      styles: 3,
      efx: 4,
      keyCode: 16,
      onPress: 17,
      onClose: 18,
      onContextMenu: 19,
      onClickPropagate: 20
    });
  }
};
__name(_TJSToggleLabel, "TJSToggleLabel");
let TJSToggleLabel = _TJSToggleLabel;
const ResizeHitBox_svelte_svelte_type_style_lang = "";
const SelectedBorder_svelte_svelte_type_style_lang = "";
const PositionControl_svelte_svelte_type_style_lang = "";
const TJSPositionControlLayer_svelte_svelte_type_style_lang = "";
const TJSMenu_svelte_svelte_type_style_lang = "";
const { document: document_1$1 } = globals;
const get_after_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_after_slot_changes");
const get_after_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_after_slot_context");
function get_each_context$z(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[36] = list[i];
  return child_ctx;
}
__name(get_each_context$z, "get_each_context$z");
const get_before_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_before_slot_changes");
const get_before_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_before_slot_context");
function create_if_block_6$7(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  const switch_instance_spread_levels = [
    isObject(
      /*menu*/
      ctx[2]?.slotDefault?.props
    ) ? (
      /*menu*/
      ctx[2].slotDefault.props
    ) : {}
  ];
  var switch_value = (
    /*menu*/
    ctx[2].slotDefault.class
  );
  function switch_props(ctx2) {
    let switch_instance_props = {};
    for (let i = 0; i < switch_instance_spread_levels.length; i += 1) {
      switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]);
    }
    return { props: switch_instance_props };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const switch_instance_changes = dirty[0] & /*menu*/
      4 ? get_spread_update(switch_instance_spread_levels, [
        get_spread_object(isObject(
          /*menu*/
          ctx2[2]?.slotDefault?.props
        ) ? (
          /*menu*/
          ctx2[2].slotDefault.props
        ) : {})
      ]) : {};
      if (dirty[0] & /*menu*/
      4 && switch_value !== (switch_value = /*menu*/
      ctx2[2].slotDefault.class)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
__name(create_if_block_6$7, "create_if_block_6$7");
function fallback_block$1(ctx) {
  let show_if = isSvelteComponent(
    /*menu*/
    ctx[2]?.slotDefault?.class
  );
  let if_block_anchor;
  let current;
  let if_block = show_if && create_if_block_6$7(ctx);
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*menu*/
      4)
        show_if = isSvelteComponent(
          /*menu*/
          ctx2[2]?.slotDefault?.class
        );
      if (show_if) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*menu*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_6$7(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(fallback_block$1, "fallback_block$1");
function create_if_block_5$b(ctx) {
  let li;
  let span;
  let t;
  let current;
  let mounted;
  let dispose;
  const before_slot_template = (
    /*#slots*/
    ctx[19].before
  );
  const before_slot = create_slot(
    before_slot_template,
    ctx,
    /*$$scope*/
    ctx[18],
    get_before_slot_context
  );
  return {
    c() {
      li = element("li");
      span = element("span");
      t = space();
      if (before_slot)
        before_slot.c();
      attr(span, "class", "tjs-menu-focus-indicator svelte-7526ak");
      attr(li, "class", "tjs-menu-item svelte-7526ak");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span);
      append(li, t);
      if (before_slot) {
        before_slot.m(li, null);
      }
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            li,
            "click",
            /*click_handler*/
            ctx[20]
          ),
          listen(
            li,
            "keyup",
            /*keyup_handler*/
            ctx[21]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (before_slot) {
        if (before_slot.p && (!current || dirty[0] & /*$$scope*/
        262144)) {
          update_slot_base(
            before_slot,
            before_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[18],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[18]
            ) : get_slot_changes(
              before_slot_template,
              /*$$scope*/
              ctx2[18],
              dirty,
              get_before_slot_changes
            ),
            get_before_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(before_slot, local);
      current = true;
    },
    o(local) {
      transition_out(before_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(li);
      if (before_slot)
        before_slot.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_5$b, "create_if_block_5$b");
function create_if_block_4$f(ctx) {
  let hr;
  return {
    c() {
      hr = element("hr");
      attr(hr, "class", "svelte-7526ak");
    },
    m(target, anchor) {
      insert(target, hr, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(hr);
    }
  };
}
__name(create_if_block_4$f, "create_if_block_4$f");
function create_if_block_3$k(ctx) {
  let li;
  let span0;
  let t0;
  let img;
  let img_src_value;
  let img_alt_value;
  let t1;
  let span1;
  let t2_value = localize(
    /*item*/
    ctx[36].label
  ) + "";
  let t2;
  let mounted;
  let dispose;
  function click_handler_32() {
    return (
      /*click_handler_3*/
      ctx[26](
        /*item*/
        ctx[36]
      )
    );
  }
  __name(click_handler_32, "click_handler_3");
  function keyup_handler_3(...args) {
    return (
      /*keyup_handler_3*/
      ctx[27](
        /*item*/
        ctx[36],
        ...args
      )
    );
  }
  __name(keyup_handler_3, "keyup_handler_3");
  return {
    c() {
      li = element("li");
      span0 = element("span");
      t0 = space();
      img = element("img");
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      attr(span0, "class", "tjs-menu-focus-indicator svelte-7526ak");
      if (!src_url_equal(img.src, img_src_value = /*item*/
      ctx[36].image))
        attr(img, "src", img_src_value);
      attr(img, "alt", img_alt_value = /*item*/
      ctx[36].imageAlt);
      attr(img, "class", "svelte-7526ak");
      attr(span1, "class", "tjs-menu-item-label svelte-7526ak");
      attr(li, "class", "tjs-menu-item tjs-menu-item-button svelte-7526ak");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span0);
      append(li, t0);
      append(li, img);
      append(li, t1);
      append(li, span1);
      append(span1, t2);
      if (!mounted) {
        dispose = [
          listen(li, "click", click_handler_32),
          listen(li, "keyup", keyup_handler_3)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*allItems*/
      8 && !src_url_equal(img.src, img_src_value = /*item*/
      ctx[36].image)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*allItems*/
      8 && img_alt_value !== (img_alt_value = /*item*/
      ctx[36].imageAlt)) {
        attr(img, "alt", img_alt_value);
      }
      if (dirty[0] & /*allItems*/
      8 && t2_value !== (t2_value = localize(
        /*item*/
        ctx[36].label
      ) + ""))
        set_data(t2, t2_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(li);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_3$k, "create_if_block_3$k");
function create_if_block_2$o(ctx) {
  let li;
  let span0;
  let t0;
  let i;
  let i_class_value;
  let t1;
  let span1;
  let t2_value = localize(
    /*item*/
    ctx[36].label
  ) + "";
  let t2;
  let mounted;
  let dispose;
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx[24](
        /*item*/
        ctx[36]
      )
    );
  }
  __name(click_handler_2, "click_handler_2");
  function keyup_handler_2(...args) {
    return (
      /*keyup_handler_2*/
      ctx[25](
        /*item*/
        ctx[36],
        ...args
      )
    );
  }
  __name(keyup_handler_2, "keyup_handler_2");
  return {
    c() {
      li = element("li");
      span0 = element("span");
      t0 = space();
      i = element("i");
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      attr(span0, "class", "tjs-menu-focus-indicator svelte-7526ak");
      attr(i, "class", i_class_value = null_to_empty(
        /*item*/
        ctx[36].icon
      ) + " svelte-7526ak");
      attr(span1, "class", "tjs-menu-item-label svelte-7526ak");
      attr(li, "class", "tjs-menu-item tjs-menu-item-button svelte-7526ak");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span0);
      append(li, t0);
      append(li, i);
      append(li, t1);
      append(li, span1);
      append(span1, t2);
      if (!mounted) {
        dispose = [
          listen(li, "click", click_handler_2),
          listen(li, "keyup", keyup_handler_2)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*allItems*/
      8 && i_class_value !== (i_class_value = null_to_empty(
        /*item*/
        ctx[36].icon
      ) + " svelte-7526ak")) {
        attr(i, "class", i_class_value);
      }
      if (dirty[0] & /*allItems*/
      8 && t2_value !== (t2_value = localize(
        /*item*/
        ctx[36].label
      ) + ""))
        set_data(t2, t2_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(li);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_2$o, "create_if_block_2$o");
function create_if_block_1$y(ctx) {
  let li;
  let span;
  let t;
  let switch_instance;
  let current;
  let mounted;
  let dispose;
  const switch_instance_spread_levels = [
    isObject(
      /*item*/
      ctx[36].props
    ) ? (
      /*item*/
      ctx[36].props
    ) : {}
  ];
  var switch_value = (
    /*item*/
    ctx[36].class
  );
  function switch_props(ctx2) {
    let switch_instance_props = {};
    for (let i = 0; i < switch_instance_spread_levels.length; i += 1) {
      switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]);
    }
    return { props: switch_instance_props };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[22](
        /*item*/
        ctx[36]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  function keyup_handler_1(...args) {
    return (
      /*keyup_handler_1*/
      ctx[23](
        /*item*/
        ctx[36],
        ...args
      )
    );
  }
  __name(keyup_handler_1, "keyup_handler_1");
  return {
    c() {
      li = element("li");
      span = element("span");
      t = space();
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      attr(span, "class", "tjs-menu-focus-indicator svelte-7526ak");
      attr(li, "class", "tjs-menu-item svelte-7526ak");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span);
      append(li, t);
      if (switch_instance)
        mount_component(switch_instance, li, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(li, "click", click_handler_1),
          listen(li, "keyup", keyup_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const switch_instance_changes = dirty[0] & /*allItems*/
      8 ? get_spread_update(switch_instance_spread_levels, [
        get_spread_object(isObject(
          /*item*/
          ctx[36].props
        ) ? (
          /*item*/
          ctx[36].props
        ) : {})
      ]) : {};
      if (dirty[0] & /*allItems*/
      8 && switch_value !== (switch_value = /*item*/
      ctx[36].class)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, li, null);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(li);
      if (switch_instance)
        destroy_component(switch_instance);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_1$y, "create_if_block_1$y");
function create_each_block$z(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block_1$y, create_if_block_2$o, create_if_block_3$k, create_if_block_4$f];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*item*/
      ctx2[36]["#type"] === "class"
    )
      return 0;
    if (
      /*item*/
      ctx2[36]["#type"] === "icon"
    )
      return 1;
    if (
      /*item*/
      ctx2[36]["#type"] === "image"
    )
      return 2;
    if (
      /*item*/
      ctx2[36]["#type"] === "separator-hr"
    )
      return 3;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block$z, "create_each_block$z");
function create_if_block$M(ctx) {
  let li;
  let span;
  let t;
  let current;
  let mounted;
  let dispose;
  const after_slot_template = (
    /*#slots*/
    ctx[19].after
  );
  const after_slot = create_slot(
    after_slot_template,
    ctx,
    /*$$scope*/
    ctx[18],
    get_after_slot_context
  );
  return {
    c() {
      li = element("li");
      span = element("span");
      t = space();
      if (after_slot)
        after_slot.c();
      attr(span, "class", "tjs-menu-focus-indicator svelte-7526ak");
      attr(li, "class", "tjs-menu-item svelte-7526ak");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span);
      append(li, t);
      if (after_slot) {
        after_slot.m(li, null);
      }
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            li,
            "click",
            /*click_handler_4*/
            ctx[28]
          ),
          listen(
            li,
            "keyup",
            /*keyup_handler_4*/
            ctx[29]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (after_slot) {
        if (after_slot.p && (!current || dirty[0] & /*$$scope*/
        262144)) {
          update_slot_base(
            after_slot,
            after_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[18],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[18]
            ) : get_slot_changes(
              after_slot_template,
              /*$$scope*/
              ctx2[18],
              dirty,
              get_after_slot_changes
            ),
            get_after_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(after_slot, local);
      current = true;
    },
    o(local) {
      transition_out(after_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(li);
      if (after_slot)
        after_slot.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block$M, "create_if_block$M");
function create_fragment$17(ctx) {
  let t0;
  let nav;
  let ol;
  let t1;
  let t2;
  let t3;
  let t4;
  let tjsfocuswrap;
  let applyStyles_action;
  let nav_transition;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[19].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[18],
    null
  );
  const default_slot_or_fallback = default_slot || fallback_block$1(ctx);
  let if_block0 = (
    /*$$slots*/
    ctx[12].before && create_if_block_5$b(ctx)
  );
  let each_value = (
    /*allItems*/
    ctx[3]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$z(get_each_context$z(ctx, each_value, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  }), "out");
  let if_block1 = (
    /*$$slots*/
    ctx[12].after && create_if_block$M(ctx)
  );
  tjsfocuswrap = new TJSFocusWrap({
    props: { elementRoot: (
      /*menuEl*/
      ctx[4]
    ) }
  });
  return {
    c() {
      t0 = space();
      nav = element("nav");
      ol = element("ol");
      if (default_slot_or_fallback)
        default_slot_or_fallback.c();
      t1 = space();
      if (if_block0)
        if_block0.c();
      t2 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t3 = space();
      if (if_block1)
        if_block1.c();
      t4 = space();
      create_component(tjsfocuswrap.$$.fragment);
      attr(ol, "class", "tjs-menu-items svelte-7526ak");
      attr(ol, "role", "menu");
      attr(nav, "class", "tjs-menu svelte-7526ak");
      attr(nav, "tabindex", "-1");
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, nav, anchor);
      append(nav, ol);
      if (default_slot_or_fallback) {
        default_slot_or_fallback.m(ol, null);
      }
      append(ol, t1);
      if (if_block0)
        if_block0.m(ol, null);
      append(ol, t2);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ol, null);
        }
      }
      append(ol, t3);
      if (if_block1)
        if_block1.m(ol, null);
      append(nav, t4);
      mount_component(tjsfocuswrap, nav, null);
      ctx[30](nav);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            window,
            "blur",
            /*onWindowBlur*/
            ctx[11]
          ),
          listen(
            document_1$1.body,
            "pointerdown",
            /*onClose*/
            ctx[7]
          ),
          listen(
            document_1$1.body,
            "wheel",
            /*onClose*/
            ctx[7]
          ),
          listen(nav, "click", stop_propagation(prevent_default(click_handler_5))),
          listen(nav, "keydown", stop_propagation(
            /*onKeydownMenu*/
            ctx[8]
          )),
          listen(nav, "keyup", stop_propagation(prevent_default(
            /*onKeyupMenu*/
            ctx[9]
          ))),
          listen(nav, "pointerdown", stop_propagation(pointerdown_handler)),
          listen(nav, "pointerup", stop_propagation(pointerup_handler)),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            nav,
            /*styles*/
            ctx[0]
          )),
          action_destroyer(
            /*efx*/
            ctx[1].call(null, nav)
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty[0] & /*$$scope*/
        262144)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[18],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[18]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[18],
              dirty,
              null
            ),
            null
          );
        }
      } else {
        if (default_slot_or_fallback && default_slot_or_fallback.p && (!current || dirty[0] & /*menu*/
        4)) {
          default_slot_or_fallback.p(ctx2, !current ? [-1, -1] : dirty);
        }
      }
      if (
        /*$$slots*/
        ctx2[12].before
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*$$slots*/
          4096) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_5$b(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(ol, t2);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (dirty[0] & /*onClick, allItems, onKeyupItem*/
      1096) {
        each_value = /*allItems*/
        ctx2[3];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$z(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block$z(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(ol, t3);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
      if (
        /*$$slots*/
        ctx2[12].after
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*$$slots*/
          4096) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block$M(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(ol, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      const tjsfocuswrap_changes = {};
      if (dirty[0] & /*menuEl*/
      16)
        tjsfocuswrap_changes.elementRoot = /*menuEl*/
        ctx2[4];
      tjsfocuswrap.$set(tjsfocuswrap_changes);
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty[0] & /*styles*/
      1)
        applyStyles_action.update.call(
          null,
          /*styles*/
          ctx2[0]
        );
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot_or_fallback, local);
      transition_in(if_block0);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(if_block1);
      transition_in(tjsfocuswrap.$$.fragment, local);
      add_render_callback(() => {
        if (!current)
          return;
        if (!nav_transition)
          nav_transition = create_bidirectional_transition(
            nav,
            /*animate*/
            ctx[5],
            {},
            true
          );
        nav_transition.run(1);
      });
      current = true;
    },
    o(local) {
      transition_out(default_slot_or_fallback, local);
      transition_out(if_block0);
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      transition_out(if_block1);
      transition_out(tjsfocuswrap.$$.fragment, local);
      if (!nav_transition)
        nav_transition = create_bidirectional_transition(
          nav,
          /*animate*/
          ctx[5],
          {},
          false
        );
      nav_transition.run(0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(t0);
      if (detaching)
        detach(nav);
      if (default_slot_or_fallback)
        default_slot_or_fallback.d(detaching);
      if (if_block0)
        if_block0.d();
      destroy_each(each_blocks, detaching);
      if (if_block1)
        if_block1.d();
      destroy_component(tjsfocuswrap);
      ctx[30](null);
      if (detaching && nav_transition)
        nav_transition.end();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$17, "create_fragment$17");
const click_handler_5 = /* @__PURE__ */ __name(() => null, "click_handler_5");
const pointerdown_handler = /* @__PURE__ */ __name(() => null, "pointerdown_handler");
const pointerup_handler = /* @__PURE__ */ __name(() => null, "pointerup_handler");
function instance$14($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  const $$slots = compute_slots(slots);
  let { menu = void 0 } = $$props;
  let { items = void 0 } = $$props;
  let { focusEl = void 0 } = $$props;
  let { offset: offset2 = void 0 } = $$props;
  let { styles: styles2 = void 0 } = $$props;
  let { efx = void 0 } = $$props;
  let { keyCode = void 0 } = $$props;
  let { transitionOptions = void 0 } = $$props;
  const s_DEFAULT_OFFSET = { x: 0, y: 0 };
  const s_IGNORE_CLASSES = { ignoreClasses: ["tjs-focus-wrap"] };
  let allItems;
  let menuEl;
  let closed = false;
  let focusOptions = void 0;
  let hasKeyboardFocus = false;
  onMount(() => {
    const activeEl = document.activeElement;
    const parentEl = menuEl.parentElement;
    if (parentEl instanceof HTMLElement && activeEl instanceof HTMLElement && parentEl.contains(activeEl) && activeEl.matches(":focus-visible")) {
      const firstFocusEl = A11yHelper.getFirstFocusableElement(menuEl);
      if (firstFocusEl instanceof HTMLElement && !firstFocusEl.classList.contains("tjs-focus-wrap")) {
        firstFocusEl.focus();
        hasKeyboardFocus = true;
      } else {
        menuEl.focus();
      }
      focusOptions = { focusSource: { focusEl: [activeEl] } };
      if (focusEl) {
        focusOptions.focusSource.focusEl.push(focusEl);
      }
    } else {
      menuEl.focus();
      if (focusEl) {
        focusOptions = { focusSource: { focusEl: [focusEl] } };
      }
    }
  });
  function animate(node) {
    const result = getStackingContext(node.parentElement);
    if (!(result?.node instanceof HTMLElement)) {
      console.warn(`'TJSMenu.animate warning: Could not locate parent stacking context element.`);
      return;
    }
    const stackingContextRect = result?.node.getBoundingClientRect();
    const stackingContextRight = stackingContextRect.x + stackingContextRect.width;
    const nodeRect = node.getBoundingClientRect();
    const parentRect = node.parentElement.getBoundingClientRect();
    const adjustedOffset = { ...s_DEFAULT_OFFSET, ...offset2 };
    node.style.top = `${adjustedOffset.y + parentRect.height}px`;
    if (parentRect.x + nodeRect.width < stackingContextRight) {
      node.style.left = `${adjustedOffset.x}px`;
      node.style.removeProperty("right");
    } else {
      node.style.right = `${adjustedOffset.x}px`;
      node.style.removeProperty("left");
    }
    return slideFade(node, transitionOptions);
  }
  __name(animate, "animate");
  function onClick(item) {
    const callback = item?.onPress;
    if (typeof callback === "function") {
      callback(item, focusOptions);
    }
    if (!closed) {
      closed = true;
      menuEl.dispatchEvent(new CustomEvent("close:popup", { bubbles: true, cancelable: true }));
    }
  }
  __name(onClick, "onClick");
  async function onClose(event) {
    if (event.target === menuEl || menuEl.contains(event.target)) {
      return;
    }
    if (event.target === menuEl.parentElement || menuEl.parentElement.contains(event.target)) {
      return;
    }
    if (!closed) {
      closed = true;
      menuEl.dispatchEvent(new CustomEvent(
        "close:popup",
        {
          bubbles: true,
          cancelable: true,
          detail: { target: event.target }
        }
      ));
    }
  }
  __name(onClose, "onClose");
  function onKeydownMenu(event) {
    if (event.code === keyCode) {
      event.stopPropagation();
      return;
    }
    switch (event.code) {
      case "Tab":
        event.stopPropagation();
        if (event.shiftKey) {
          const allFocusable = A11yHelper.getFocusableElements(menuEl, s_IGNORE_CLASSES);
          const firstFocusEl = allFocusable.length > 0 ? allFocusable[0] : void 0;
          const lastFocusEl = allFocusable.length > 0 ? allFocusable[allFocusable.length - 1] : void 0;
          if (menuEl === document.activeElement || firstFocusEl === document.activeElement) {
            if (lastFocusEl instanceof HTMLElement && firstFocusEl !== lastFocusEl) {
              lastFocusEl.focus();
            }
            event.preventDefault();
          }
        }
        break;
      default:
        event.stopPropagation();
        break;
    }
  }
  __name(onKeydownMenu, "onKeydownMenu");
  function onKeyupMenu(event) {
    switch (event.code) {
      case "Escape":
        if (!closed) {
          closed = true;
          menuEl.dispatchEvent(new CustomEvent(
            "close:popup",
            {
              bubbles: true,
              cancelable: true,
              detail: { keyboardFocus: hasKeyboardFocus }
            }
          ));
        }
        event.preventDefault();
        event.stopPropagation();
        break;
    }
  }
  __name(onKeyupMenu, "onKeyupMenu");
  function onKeyupItem(event, item) {
    if (event.code === keyCode) {
      const callback = item?.onPress;
      if (typeof callback === "function") {
        callback(item, focusOptions);
      }
      if (!closed) {
        closed = true;
        event.preventDefault();
        event.stopPropagation();
        menuEl.dispatchEvent(new CustomEvent(
          "close:popup",
          {
            bubbles: true,
            cancelable: true,
            detail: { keyboardFocus: hasKeyboardFocus }
          }
        ));
      }
    }
  }
  __name(onKeyupItem, "onKeyupItem");
  function onWindowBlur() {
    if (!closed) {
      closed = true;
      menuEl.dispatchEvent(new CustomEvent("close:popup", { bubbles: true, cancelable: true }));
    }
  }
  __name(onWindowBlur, "onWindowBlur");
  const click_handler = /* @__PURE__ */ __name(() => onClick(), "click_handler");
  const keyup_handler = /* @__PURE__ */ __name((event) => onKeyupItem(event), "keyup_handler");
  const click_handler_1 = /* @__PURE__ */ __name((item) => onClick(item), "click_handler_1");
  const keyup_handler_1 = /* @__PURE__ */ __name((item, event) => onKeyupItem(event, item), "keyup_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name((item) => onClick(item), "click_handler_2");
  const keyup_handler_2 = /* @__PURE__ */ __name((item, event) => onKeyupItem(event, item), "keyup_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name((item) => onClick(item), "click_handler_3");
  const keyup_handler_3 = /* @__PURE__ */ __name((item, event) => onKeyupItem(event, item), "keyup_handler_3");
  const click_handler_4 = /* @__PURE__ */ __name(() => onClick(), "click_handler_4");
  const keyup_handler_4 = /* @__PURE__ */ __name((event) => onKeyupItem(event), "keyup_handler_4");
  function nav_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      menuEl = $$value;
      $$invalidate(4, menuEl);
    });
  }
  __name(nav_binding, "nav_binding");
  $$self.$$set = ($$props2) => {
    if ("menu" in $$props2)
      $$invalidate(2, menu = $$props2.menu);
    if ("items" in $$props2)
      $$invalidate(17, items = $$props2.items);
    if ("focusEl" in $$props2)
      $$invalidate(13, focusEl = $$props2.focusEl);
    if ("offset" in $$props2)
      $$invalidate(14, offset2 = $$props2.offset);
    if ("styles" in $$props2)
      $$invalidate(0, styles2 = $$props2.styles);
    if ("efx" in $$props2)
      $$invalidate(1, efx = $$props2.efx);
    if ("keyCode" in $$props2)
      $$invalidate(15, keyCode = $$props2.keyCode);
    if ("transitionOptions" in $$props2)
      $$invalidate(16, transitionOptions = $$props2.transitionOptions);
    if ("$$scope" in $$props2)
      $$invalidate(18, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*menu, items*/
    131076) {
      {
        const tempList = isObject(menu) && isIterable(menu.items) ? menu.items : isIterable(items) ? items : [];
        const tempItems = [];
        let cntr = -1;
        for (const item of tempList) {
          cntr++;
          if (!isObject(item)) {
            throw new TypeError(`TJSMenu error: 'item[${cntr}]' is not an object.`);
          }
          if (typeof item.condition === "function" && !item.condition()) {
            continue;
          }
          if (typeof item.condition === "boolean" && !item.condition) {
            continue;
          }
          let type;
          if (isSvelteComponent(item.class)) {
            type = "class";
          } else if (typeof item.icon === "string") {
            type = "icon";
          } else if (typeof item.image === "string") {
            type = "image";
          } else if (typeof item.separator === "string") {
            if (item.separator !== "hr") {
              throw new Error(`TJSMenu error: 'item[${cntr}]' has unknown separator type; only 'hr' is currently supported.`);
            }
            type = "separator-hr";
          }
          if (type === void 0) {
            throw new TypeError(`TJSMenu error: Unknown type for 'item[${cntr}]'.`);
          }
          tempItems.push({ ...item, "#type": type });
        }
        $$invalidate(3, allItems = tempItems);
      }
    }
    if ($$self.$$.dirty[0] & /*menu, focusEl*/
    8196) {
      $$invalidate(13, focusEl = isObject(menu) && A11yHelper.isFocusSource(menu.focusEl) ? menu.focusEl : A11yHelper.isFocusSource(focusEl) ? focusEl : void 0);
    }
    if ($$self.$$.dirty[0] & /*menu, offset*/
    16388) {
      $$invalidate(14, offset2 = isObject(menu) && isObject(menu.offset) ? menu.offset : isObject(offset2) ? offset2 : s_DEFAULT_OFFSET);
    }
    if ($$self.$$.dirty[0] & /*menu, styles*/
    5) {
      $$invalidate(0, styles2 = isObject(menu) && isObject(menu.styles) ? menu.styles : isObject(styles2) ? styles2 : void 0);
    }
    if ($$self.$$.dirty[0] & /*menu, efx*/
    6) {
      $$invalidate(1, efx = isObject(menu) && typeof menu.efx === "function" ? menu.efx : typeof efx === "function" ? efx : () => {
      });
    }
    if ($$self.$$.dirty[0] & /*menu, keyCode*/
    32772) {
      $$invalidate(15, keyCode = isObject(menu) && typeof menu.keyCode === "string" ? menu.keyCode : typeof keyCode === "string" ? keyCode : "Enter");
    }
    if ($$self.$$.dirty[0] & /*menu, transitionOptions*/
    65540) {
      $$invalidate(16, transitionOptions = isObject(menu) && isObject(menu.transitionOptions) ? menu.transitionOptions : isObject(transitionOptions) ? transitionOptions : { duration: 200, easing: quintOut });
    }
  };
  return [
    styles2,
    efx,
    menu,
    allItems,
    menuEl,
    animate,
    onClick,
    onClose,
    onKeydownMenu,
    onKeyupMenu,
    onKeyupItem,
    onWindowBlur,
    $$slots,
    focusEl,
    offset2,
    keyCode,
    transitionOptions,
    items,
    $$scope,
    slots,
    click_handler,
    keyup_handler,
    click_handler_1,
    keyup_handler_1,
    click_handler_2,
    keyup_handler_2,
    click_handler_32,
    keyup_handler_3,
    click_handler_4,
    keyup_handler_4,
    nav_binding
  ];
}
__name(instance$14, "instance$14");
const _TJSMenu = class _TJSMenu extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$14,
      create_fragment$17,
      safe_not_equal,
      {
        menu: 2,
        items: 17,
        focusEl: 13,
        offset: 14,
        styles: 0,
        efx: 1,
        keyCode: 15,
        transitionOptions: 16
      },
      null,
      [-1, -1]
    );
  }
};
__name(_TJSMenu, "TJSMenu");
let TJSMenu = _TJSMenu;
const TJSContextMenuImpl_svelte_svelte_type_style_lang = "";
const { document: document_1 } = globals;
function get_each_context$y(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[30] = list[i];
  return child_ctx;
}
__name(get_each_context$y, "get_each_context$y");
function create_if_block_3$j(ctx) {
  let hr;
  return {
    c() {
      hr = element("hr");
      attr(hr, "class", "svelte-1ykv97a");
    },
    m(target, anchor) {
      insert(target, hr, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(hr);
    }
  };
}
__name(create_if_block_3$j, "create_if_block_3$j");
function create_if_block_2$n(ctx) {
  let li;
  let span0;
  let t0;
  let img;
  let img_src_value;
  let img_alt_value;
  let t1;
  let span1;
  let t2_value = localize(
    /*item*/
    ctx[30].label
  ) + "";
  let t2;
  let t3;
  let mounted;
  let dispose;
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx[23](
        /*item*/
        ctx[30]
      )
    );
  }
  __name(click_handler_2, "click_handler_2");
  function keyup_handler_2(...args) {
    return (
      /*keyup_handler_2*/
      ctx[24](
        /*item*/
        ctx[30],
        ...args
      )
    );
  }
  __name(keyup_handler_2, "keyup_handler_2");
  return {
    c() {
      li = element("li");
      span0 = element("span");
      t0 = space();
      img = element("img");
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      t3 = space();
      attr(span0, "class", "tjs-context-menu-focus-indicator svelte-1ykv97a");
      if (!src_url_equal(img.src, img_src_value = /*item*/
      ctx[30].image))
        attr(img, "src", img_src_value);
      attr(img, "alt", img_alt_value = /*item*/
      ctx[30].imageAlt);
      attr(img, "class", "svelte-1ykv97a");
      attr(span1, "class", "tjs-context-menu-item-label svelte-1ykv97a");
      attr(li, "class", "tjs-context-menu-item tjs-context-menu-item-button svelte-1ykv97a");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span0);
      append(li, t0);
      append(li, img);
      append(li, t1);
      append(li, span1);
      append(span1, t2);
      append(li, t3);
      if (!mounted) {
        dispose = [
          listen(li, "click", click_handler_2),
          listen(li, "keyup", keyup_handler_2)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      4 && !src_url_equal(img.src, img_src_value = /*item*/
      ctx[30].image)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*items*/
      4 && img_alt_value !== (img_alt_value = /*item*/
      ctx[30].imageAlt)) {
        attr(img, "alt", img_alt_value);
      }
      if (dirty[0] & /*items*/
      4 && t2_value !== (t2_value = localize(
        /*item*/
        ctx[30].label
      ) + ""))
        set_data(t2, t2_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(li);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_2$n, "create_if_block_2$n");
function create_if_block_1$x(ctx) {
  let li;
  let span0;
  let t0;
  let i;
  let i_class_value;
  let t1;
  let span1;
  let t2_value = localize(
    /*item*/
    ctx[30].label
  ) + "";
  let t2;
  let t3;
  let mounted;
  let dispose;
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[21](
        /*item*/
        ctx[30]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  function keyup_handler_1(...args) {
    return (
      /*keyup_handler_1*/
      ctx[22](
        /*item*/
        ctx[30],
        ...args
      )
    );
  }
  __name(keyup_handler_1, "keyup_handler_1");
  return {
    c() {
      li = element("li");
      span0 = element("span");
      t0 = space();
      i = element("i");
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      t3 = space();
      attr(span0, "class", "tjs-context-menu-focus-indicator svelte-1ykv97a");
      attr(i, "class", i_class_value = null_to_empty(
        /*item*/
        ctx[30].icon
      ) + " svelte-1ykv97a");
      attr(span1, "class", "tjs-context-menu-item-label svelte-1ykv97a");
      attr(li, "class", "tjs-context-menu-item tjs-context-menu-item-button svelte-1ykv97a");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span0);
      append(li, t0);
      append(li, i);
      append(li, t1);
      append(li, span1);
      append(span1, t2);
      append(li, t3);
      if (!mounted) {
        dispose = [
          listen(li, "click", click_handler_1),
          listen(li, "keyup", keyup_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*items*/
      4 && i_class_value !== (i_class_value = null_to_empty(
        /*item*/
        ctx[30].icon
      ) + " svelte-1ykv97a")) {
        attr(i, "class", i_class_value);
      }
      if (dirty[0] & /*items*/
      4 && t2_value !== (t2_value = localize(
        /*item*/
        ctx[30].label
      ) + ""))
        set_data(t2, t2_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(li);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_1$x, "create_if_block_1$x");
function create_if_block$L(ctx) {
  let li;
  let span;
  let t0;
  let switch_instance;
  let t1;
  let current;
  let mounted;
  let dispose;
  const switch_instance_spread_levels = [
    isObject(
      /*item*/
      ctx[30].props
    ) ? (
      /*item*/
      ctx[30].props
    ) : {}
  ];
  var switch_value = (
    /*item*/
    ctx[30].class
  );
  function switch_props(ctx2) {
    let switch_instance_props = {};
    for (let i = 0; i < switch_instance_spread_levels.length; i += 1) {
      switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]);
    }
    return { props: switch_instance_props };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  function click_handler() {
    return (
      /*click_handler*/
      ctx[19](
        /*item*/
        ctx[30]
      )
    );
  }
  __name(click_handler, "click_handler");
  function keyup_handler(...args) {
    return (
      /*keyup_handler*/
      ctx[20](
        /*item*/
        ctx[30],
        ...args
      )
    );
  }
  __name(keyup_handler, "keyup_handler");
  return {
    c() {
      li = element("li");
      span = element("span");
      t0 = space();
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      t1 = space();
      attr(span, "class", "tjs-context-menu-focus-indicator svelte-1ykv97a");
      attr(li, "class", "tjs-context-menu-item svelte-1ykv97a");
      attr(li, "role", "menuitem");
      attr(li, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, span);
      append(li, t0);
      if (switch_instance)
        mount_component(switch_instance, li, null);
      append(li, t1);
      current = true;
      if (!mounted) {
        dispose = [listen(li, "click", click_handler), listen(li, "keyup", keyup_handler)];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const switch_instance_changes = dirty[0] & /*items*/
      4 ? get_spread_update(switch_instance_spread_levels, [
        get_spread_object(isObject(
          /*item*/
          ctx[30].props
        ) ? (
          /*item*/
          ctx[30].props
        ) : {})
      ]) : {};
      if (dirty[0] & /*items*/
      4 && switch_value !== (switch_value = /*item*/
      ctx[30].class)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, li, t1);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(li);
      if (switch_instance)
        destroy_component(switch_instance);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block$L, "create_if_block$L");
function create_each_block$y(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block$L, create_if_block_1$x, create_if_block_2$n, create_if_block_3$j];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*item*/
      ctx2[30]["#type"] === "class"
    )
      return 0;
    if (
      /*item*/
      ctx2[30]["#type"] === "icon"
    )
      return 1;
    if (
      /*item*/
      ctx2[30]["#type"] === "image"
    )
      return 2;
    if (
      /*item*/
      ctx2[30]["#type"] === "separator-hr"
    )
      return 3;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block$y, "create_each_block$y");
function create_fragment$16(ctx) {
  let t0;
  let nav;
  let ol;
  let t1;
  let tjsfocuswrap;
  let applyStyles_action;
  let nav_transition;
  let current;
  let mounted;
  let dispose;
  let each_value = (
    /*items*/
    ctx[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$y(get_each_context$y(ctx, each_value, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  }), "out");
  tjsfocuswrap = new TJSFocusWrap({
    props: { elementRoot: (
      /*menuEl*/
      ctx[4]
    ) }
  });
  return {
    c() {
      t0 = space();
      nav = element("nav");
      ol = element("ol");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t1 = space();
      create_component(tjsfocuswrap.$$.fragment);
      attr(ol, "class", "tjs-context-menu-items svelte-1ykv97a");
      attr(ol, "role", "menu");
      attr(
        nav,
        "id",
        /*id*/
        ctx[1]
      );
      attr(nav, "class", "tjs-context-menu svelte-1ykv97a");
      attr(nav, "tabindex", "-1");
      set_style(
        nav,
        "z-index",
        /*zIndex*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, nav, anchor);
      append(nav, ol);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ol, null);
        }
      }
      append(nav, t1);
      mount_component(tjsfocuswrap, nav, null);
      ctx[25](nav);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            window,
            "blur",
            /*onWindowBlur*/
            ctx[11]
          ),
          listen(
            document_1.body,
            "pointerdown",
            /*onClose*/
            ctx[7]
          ),
          listen(
            document_1.body,
            "wheel",
            /*wheel_handler*/
            ctx[18]
          ),
          listen(nav, "click", stop_propagation(prevent_default(click_handler_3$1))),
          listen(nav, "keydown", stop_propagation(
            /*onKeydownMenu*/
            ctx[8]
          )),
          listen(nav, "keyup", stop_propagation(prevent_default(
            /*onKeyupMenu*/
            ctx[9]
          ))),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            nav,
            /*styles*/
            ctx[0]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*onClick, items, onKeyupItem*/
      1092) {
        each_value = /*items*/
        ctx2[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$y(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block$y(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(ol, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
      const tjsfocuswrap_changes = {};
      if (dirty[0] & /*menuEl*/
      16)
        tjsfocuswrap_changes.elementRoot = /*menuEl*/
        ctx2[4];
      tjsfocuswrap.$set(tjsfocuswrap_changes);
      if (!current || dirty[0] & /*id*/
      2) {
        attr(
          nav,
          "id",
          /*id*/
          ctx2[1]
        );
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty[0] & /*styles*/
      1)
        applyStyles_action.update.call(
          null,
          /*styles*/
          ctx2[0]
        );
      if (dirty[0] & /*zIndex*/
      8) {
        set_style(
          nav,
          "z-index",
          /*zIndex*/
          ctx2[3]
        );
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(tjsfocuswrap.$$.fragment, local);
      add_render_callback(() => {
        if (!current)
          return;
        if (!nav_transition)
          nav_transition = create_bidirectional_transition(
            nav,
            /*animate*/
            ctx[5],
            {},
            true
          );
        nav_transition.run(1);
      });
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      transition_out(tjsfocuswrap.$$.fragment, local);
      if (!nav_transition)
        nav_transition = create_bidirectional_transition(
          nav,
          /*animate*/
          ctx[5],
          {},
          false
        );
      nav_transition.run(0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(t0);
      if (detaching)
        detach(nav);
      destroy_each(each_blocks, detaching);
      destroy_component(tjsfocuswrap);
      ctx[25](null);
      if (detaching && nav_transition)
        nav_transition.end();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$16, "create_fragment$16");
const click_handler_3$1 = /* @__PURE__ */ __name(() => null, "click_handler_3$1");
function instance$13($$self, $$props, $$invalidate) {
  let { menu = void 0 } = $$props;
  let { id = "" } = $$props;
  let { x = 0 } = $$props;
  let { y = 0 } = $$props;
  let { items = [] } = $$props;
  let { zIndex = Number.MAX_SAFE_INTEGER - 100 } = $$props;
  let { styles: styles2 = void 0 } = $$props;
  let { keyCode = void 0 } = $$props;
  let { focusSource = void 0 } = $$props;
  let { transitionOptions = void 0 } = $$props;
  const s_IGNORE_CLASSES = { ignoreClasses: ["tjs-focus-wrap"] };
  const local = current_component;
  const dispatch2 = createEventDispatcher();
  let menuEl;
  let closed = false;
  onMount(() => {
    const keyboardFocus = focusSource?.source === "keyboard";
    if (keyboardFocus) {
      const firstFocusEl = A11yHelper.getFirstFocusableElement(menuEl);
      if (firstFocusEl instanceof HTMLElement && !firstFocusEl.classList.contains("tjs-focus-wrap")) {
        firstFocusEl.focus();
      } else {
        menuEl.focus();
      }
    } else {
      menuEl.focus();
    }
  });
  function animate(node) {
    const expandUp = y + node.clientHeight > document.body.clientHeight;
    const expandLeft = x + node.clientWidth > document.body.clientWidth;
    node.style.top = expandUp ? null : `${y}px`;
    node.style.bottom = expandUp ? `${document.body.clientHeight - y}px` : null;
    node.style.left = expandLeft ? null : `${x}px`;
    node.style.right = expandLeft ? `${document.body.clientWidth - x}px` : null;
    return slideFade(node, transitionOptions);
  }
  __name(animate, "animate");
  function onClick(item) {
    const callback = item?.onPress;
    if (typeof callback === "function") {
      callback(item, { focusSource });
    } else {
      A11yHelper.applyFocusSource(focusSource);
      $$invalidate(13, focusSource = void 0);
    }
    if (!closed) {
      dispatch2("close");
      closed = true;
      outroAndDestroy(local);
    }
  }
  __name(onClick, "onClick");
  function onClose(event, isWheel = false) {
    if (event.target === menuEl || menuEl.contains(event.target)) {
      return;
    }
    if (!isWheel && Math.floor(event.pageX) === x && Math.floor(event.pageY) === y) {
      return;
    }
    if (!closed) {
      dispatch2("close");
      closed = true;
      outroAndDestroy(local);
    }
  }
  __name(onClose, "onClose");
  function onKeydownMenu(event) {
    if (event.code === keyCode) {
      event.stopPropagation();
      return;
    }
    switch (event.code) {
      case "Tab":
        event.stopPropagation();
        if (event.shiftKey) {
          const allFocusable = A11yHelper.getFocusableElements(menuEl, s_IGNORE_CLASSES);
          const firstFocusEl = allFocusable.length > 0 ? allFocusable[0] : void 0;
          const lastFocusEl = allFocusable.length > 0 ? allFocusable[allFocusable.length - 1] : void 0;
          if (menuEl === document.activeElement || firstFocusEl === document.activeElement) {
            if (lastFocusEl instanceof HTMLElement && firstFocusEl !== lastFocusEl) {
              lastFocusEl.focus();
            }
            event.preventDefault();
          }
        }
        break;
      default:
        event.stopPropagation();
        break;
    }
  }
  __name(onKeydownMenu, "onKeydownMenu");
  function onKeyupMenu(event) {
    switch (event.code) {
      case "ContextMenu":
      case "Escape":
        event.preventDefault();
        event.stopPropagation();
        if (!closed) {
          closed = true;
          dispatch2("close");
          outroAndDestroy(local);
          A11yHelper.applyFocusSource(focusSource);
          $$invalidate(13, focusSource = void 0);
        }
        break;
    }
  }
  __name(onKeyupMenu, "onKeyupMenu");
  function onKeyupItem(event, item) {
    if (event.code === keyCode) {
      if (!closed) {
        closed = true;
        dispatch2("close");
        outroAndDestroy(local);
        event.preventDefault();
        event.stopPropagation();
      }
      const callback = item?.onPress;
      if (typeof callback === "function") {
        callback(item, { focusSource });
      } else {
        A11yHelper.applyFocusSource(focusSource);
        $$invalidate(13, focusSource = void 0);
      }
    }
  }
  __name(onKeyupItem, "onKeyupItem");
  function onWindowBlur() {
    if (!closed) {
      dispatch2("close");
      closed = true;
      outroAndDestroy(local);
      A11yHelper.applyFocusSource(focusSource);
      $$invalidate(13, focusSource = void 0);
    }
  }
  __name(onWindowBlur, "onWindowBlur");
  const wheel_handler = /* @__PURE__ */ __name((event) => onClose(event, true), "wheel_handler");
  const click_handler = /* @__PURE__ */ __name((item) => onClick(item), "click_handler");
  const keyup_handler = /* @__PURE__ */ __name((item, event) => onKeyupItem(event, item), "keyup_handler");
  const click_handler_1 = /* @__PURE__ */ __name((item) => onClick(item), "click_handler_1");
  const keyup_handler_1 = /* @__PURE__ */ __name((item, event) => onKeyupItem(event, item), "keyup_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name((item) => onClick(item), "click_handler_2");
  const keyup_handler_2 = /* @__PURE__ */ __name((item, event) => onKeyupItem(event, item), "keyup_handler_2");
  function nav_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      menuEl = $$value;
      $$invalidate(4, menuEl);
    });
  }
  __name(nav_binding, "nav_binding");
  $$self.$$set = ($$props2) => {
    if ("menu" in $$props2)
      $$invalidate(14, menu = $$props2.menu);
    if ("id" in $$props2)
      $$invalidate(1, id = $$props2.id);
    if ("x" in $$props2)
      $$invalidate(15, x = $$props2.x);
    if ("y" in $$props2)
      $$invalidate(16, y = $$props2.y);
    if ("items" in $$props2)
      $$invalidate(2, items = $$props2.items);
    if ("zIndex" in $$props2)
      $$invalidate(3, zIndex = $$props2.zIndex);
    if ("styles" in $$props2)
      $$invalidate(0, styles2 = $$props2.styles);
    if ("keyCode" in $$props2)
      $$invalidate(12, keyCode = $$props2.keyCode);
    if ("focusSource" in $$props2)
      $$invalidate(13, focusSource = $$props2.focusSource);
    if ("transitionOptions" in $$props2)
      $$invalidate(17, transitionOptions = $$props2.transitionOptions);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*menu, styles*/
    16385) {
      $$invalidate(0, styles2 = isObject(menu) && isObject(menu.styles) ? menu.styles : isObject(styles2) ? styles2 : void 0);
    }
    if ($$self.$$.dirty[0] & /*menu, keyCode*/
    20480) {
      $$invalidate(12, keyCode = isObject(menu) && typeof menu.keyCode === "string" ? menu.keyCode : typeof keyCode === "string" ? keyCode : "Enter");
    }
  };
  return [
    styles2,
    id,
    items,
    zIndex,
    menuEl,
    animate,
    onClick,
    onClose,
    onKeydownMenu,
    onKeyupMenu,
    onKeyupItem,
    onWindowBlur,
    keyCode,
    focusSource,
    menu,
    x,
    y,
    transitionOptions,
    wheel_handler,
    click_handler,
    keyup_handler,
    click_handler_1,
    keyup_handler_1,
    click_handler_2,
    keyup_handler_2,
    nav_binding
  ];
}
__name(instance$13, "instance$13");
const _TJSContextMenuImpl = class _TJSContextMenuImpl extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$13,
      create_fragment$16,
      safe_not_equal,
      {
        menu: 14,
        id: 1,
        x: 15,
        y: 16,
        items: 2,
        zIndex: 3,
        styles: 0,
        keyCode: 12,
        focusSource: 13,
        transitionOptions: 17
      },
      null,
      [-1, -1]
    );
  }
};
__name(_TJSContextMenuImpl, "TJSContextMenuImpl");
let TJSContextMenuImpl = _TJSContextMenuImpl;
const SettingEntry_svelte_svelte_type_style_lang = "";
const TJSSettingsEdit_svelte_svelte_type_style_lang = "";
cssVariables.setProperties({
  // For components w/ transparent background checkered pattern.
  "--tjs-checkerboard-background-dark": "rgb(205, 205, 205)",
  "--tjs-checkerboard-background-10": `url('data:image/svg+xml;utf8,<svg preserveAspectRatio="none"  viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"><rect x="0" y="0" width="5" height="5" fill="transparent" /><rect x="5" y="5" width="5" height="5" fill="transparent" /><rect x="5" y="0" width="5" height="5" fill="white" /><rect x="0" y="5" width="5" height="5" fill="white" /></svg>') 0 0 / 10px 10px, var(--tjs-checkerboard-background-dark, rgb(205, 205, 205))`
}, false);
cssVariables.setProperties({
  "--tjs-action-ripple-background": "rgba(0, 0, 0, 0.35)"
}, false);
cssVariables.setProperties({
  "--tjs-icon-button-background-hover": "rgba(0, 0, 0, 0.10)",
  "--tjs-icon-button-background-selected": "rgba(0, 0, 0, 0.20)"
}, false);
{
  const props = FoundryStyles.getProperties('input[type="text"], input[type="number"]');
  if (typeof props === "object") {
    cssVariables.setProperties({
      "--tjs-input-background": "background" in props ? props.background : "rgba(0, 0, 0, 0.05)",
      "--tjs-input-border": "border" in props ? props.border : "1px solid var(--color-border-light-tertiary)",
      "--tjs-input-border-radius": "border-radius" in props ? props["border-radius"] : "3px",
      "--tjs-input-height": "height" in props ? props.height : "var(--form-field-height)",
      "--tjs-input-min-width": "min-width" in props ? props["min-width"] : "20px",
      "--tjs-input-padding": "padding" in props ? props["padding"] : "1px 3px",
      "--tjs-input-width": "width" in props ? props.width : "calc(100% - 2px)",
      // Set default values that are only to be referenced and not set.
      "--_tjs-default-input-height": "height" in props ? props.height : "var(--form-field-height)",
      // Set directly / no lookup:
      "--tjs-input-border-color": "var(--color-border-light-tertiary)"
    }, false);
  }
}
cssVariables.setProperties({
  // `popup` is for components that are slightly elevated, but connected to an application;
  // see: TJSMenu / TJSContextMenu / TJSColordPicker
  "--tjs-default-popup-background": "var(--color-text-dark-header, #23221d)",
  "--tjs-default-popup-border": "1px solid var(--color-border-dark, #000)",
  "--tjs-default-popup-box-shadow": "0 0 2px var(--color-shadow-dark, #000)",
  "--tjs-default-popup-primary-color": "var(--color-text-light-primary, #b5b3a4)",
  "--tjs-default-popup-highlight-color": "var(--color-text-light-highlight, #f0f0e0)",
  // `popover` is for components that are elevated and independent; see: TJSContextMenu
  "--tjs-default-popover-border": "1px solid var(--color-border-dark, #000)",
  "--tjs-default-popover-box-shadow": "0 0 10px var(--color-shadow-dark, #000)"
}, false);
Hooks.on("PopOut:loading", (app, popout) => {
  if (app instanceof SvelteApplication) {
    popout.document.addEventListener("DOMContentLoaded", () => cssVariables.clone(popout.document));
  }
});
const PriceSelector_svelte_svelte_type_style_lang = "";
function get_each_context$x(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[13] = list[i];
  child_ctx[15] = i;
  return child_ctx;
}
__name(get_each_context$x, "get_each_context$x");
function get_each_context_1$g(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[16] = list[i];
  return child_ctx;
}
__name(get_each_context_1$g, "get_each_context_1$g");
function create_else_block$j(ctx) {
  let small;
  return {
    c() {
      small = element("small");
      attr(small, "class", "svelte-m0550s");
      toggle_class(
        small,
        "cant-afford",
        /*cantAfford*/
        ctx[2]
      );
    },
    m(target, anchor) {
      insert(target, small, anchor);
      small.innerHTML = /*labelText*/
      ctx[5];
    },
    p(ctx2, dirty) {
      if (dirty & /*labelText*/
      32)
        small.innerHTML = /*labelText*/
        ctx2[5];
      if (dirty & /*cantAfford*/
      4) {
        toggle_class(
          small,
          "cant-afford",
          /*cantAfford*/
          ctx2[2]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(small);
    }
  };
}
__name(create_else_block$j, "create_else_block$j");
function create_if_block$K(ctx) {
  let tjstogglelabel;
  let current;
  tjstogglelabel = new TJSToggleLabel({
    props: {
      $$slots: {
        left: [create_left_slot],
        default: [create_default_slot$q]
      },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(tjstogglelabel.$$.fragment);
    },
    m(target, anchor) {
      mount_component(tjstogglelabel, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const tjstogglelabel_changes = {};
      if (dirty & /*$$scope, $prices, standalone, cantAfford, cantAffordMultiplePrices, labelText, $selectedPriceGroup, item, $priceSelector*/
      524543) {
        tjstogglelabel_changes.$$scope = { dirty, ctx: ctx2 };
      }
      tjstogglelabel.$set(tjstogglelabel_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tjstogglelabel.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tjstogglelabel.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(tjstogglelabel, detaching);
    }
  };
}
__name(create_if_block$K, "create_if_block$K");
function create_each_block_1$g(key_1, ctx) {
  let div2;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let div1;
  let small;
  let t1_value = (
    /*price*/
    ctx[16].baseCost + /*priceGroup*/
    (ctx[13].prices.length === 0 && /*price*/
    ctx[16].percent ? "%" : "")
  );
  let t1;
  let t2;
  let t3_value = (
    /*price*/
    ctx[16].name + ""
  );
  let t3;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx[11](
        /*index*/
        ctx[15]
      )
    );
  }
  __name(click_handler, "click_handler");
  return {
    key: key_1,
    first: null,
    c() {
      div2 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      div1 = element("div");
      small = element("small");
      t1 = text(t1_value);
      t2 = space();
      t3 = text(t3_value);
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*price*/
      ctx[16].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      toggle_class(div0, "not-for-sale", !/*price*/
      ctx[16].maxQuantity && /*item*/
      ctx[0].store.recipient);
      attr(small, "class", "svelte-m0550s");
      attr(div1, "class", "item-piles-name item-piles-text");
      attr(div2, "class", "price-group-container svelte-m0550s");
      toggle_class(div2, "cant-afford", !/*priceGroup*/
      ctx[13].maxQuantity && /*item*/
      ctx[0].store.recipient);
      this.first = div2;
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div0);
      append(div0, img);
      append(div2, t0);
      append(div2, div1);
      append(div1, small);
      append(small, t1);
      append(small, t2);
      append(small, t3);
      if (!mounted) {
        dispose = listen(div2, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$prices*/
      16 && !src_url_equal(img.src, img_src_value = /*price*/
      ctx[16].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty & /*$prices, item*/
      17) {
        toggle_class(div0, "not-for-sale", !/*price*/
        ctx[16].maxQuantity && /*item*/
        ctx[0].store.recipient);
      }
      if (dirty & /*$prices*/
      16 && t1_value !== (t1_value = /*price*/
      ctx[16].baseCost + /*priceGroup*/
      (ctx[13].prices.length === 0 && /*price*/
      ctx[16].percent ? "%" : "")))
        set_data(t1, t1_value);
      if (dirty & /*$prices*/
      16 && t3_value !== (t3_value = /*price*/
      ctx[16].name + ""))
        set_data(t3, t3_value);
      if (dirty & /*$prices, item*/
      17) {
        toggle_class(div2, "cant-afford", !/*priceGroup*/
        ctx[13].maxQuantity && /*item*/
        ctx[0].store.recipient);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      mounted = false;
      dispose();
    }
  };
}
__name(create_each_block_1$g, "create_each_block_1$g");
function create_each_block$x(key_1, ctx) {
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t;
  let each_value_1 = (
    /*priceGroup*/
    ctx[13].prices.filter(func$1)
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*price*/
    ctx2[16].id
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$g(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$g(key, child_ctx));
  }
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t = space();
      attr(div, "class", "price-group");
      toggle_class(
        div,
        "selected",
        /*$selectedPriceGroup*/
        ctx[3] === /*index*/
        ctx[15]
      );
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      append(div, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$prices, item, $selectedPriceGroup, $priceSelector*/
      153) {
        each_value_1 = /*priceGroup*/
        ctx[13].prices.filter(func$1);
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_1, each_1_lookup, div, destroy_block, create_each_block_1$g, t, get_each_context_1$g);
      }
      if (dirty & /*$selectedPriceGroup, $prices*/
      24) {
        toggle_class(
          div,
          "selected",
          /*$selectedPriceGroup*/
          ctx[3] === /*index*/
          ctx[15]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_each_block$x, "create_each_block$x");
function create_default_slot_1$3(ctx) {
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_value = (
    /*$prices*/
    ctx[4]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[15]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$x(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$x(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "price-list");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$selectedPriceGroup, $prices, item, $priceSelector*/
      153) {
        each_value = /*$prices*/
        ctx2[4];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, destroy_block, create_each_block$x, null, get_each_context$x);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_default_slot_1$3, "create_default_slot_1$3");
function create_default_slot$q(ctx) {
  let tjsmenu;
  let current;
  tjsmenu = new TJSMenu({
    props: {
      offset: { y: 4 },
      $$slots: { default: [create_default_slot_1$3] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(tjsmenu.$$.fragment);
    },
    m(target, anchor) {
      mount_component(tjsmenu, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const tjsmenu_changes = {};
      if (dirty & /*$$scope, $prices, $selectedPriceGroup, item, $priceSelector*/
      524441) {
        tjsmenu_changes.$$scope = { dirty, ctx: ctx2 };
      }
      tjsmenu.$set(tjsmenu_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tjsmenu.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tjsmenu.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(tjsmenu, detaching);
    }
  };
}
__name(create_default_slot$q, "create_default_slot$q");
function create_left_slot(ctx) {
  let div;
  let small;
  return {
    c() {
      div = element("div");
      small = element("small");
      attr(small, "class", "svelte-m0550s");
      attr(div, "slot", "left");
      attr(div, "class", "svelte-m0550s");
      toggle_class(
        div,
        "multiple-prices",
        /*$prices*/
        ctx[4].length > 1 && !/*standalone*/
        ctx[1]
      );
      toggle_class(
        div,
        "cant-afford",
        /*cantAfford*/
        ctx[2]
      );
      toggle_class(
        div,
        "cant-afford-multiple-prices",
        /*cantAffordMultiplePrices*/
        ctx[6]
      );
      toggle_class(
        div,
        "item-piles-clickable-link",
        /*$prices*/
        ctx[4].length > 1
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, small);
      small.innerHTML = /*labelText*/
      ctx[5];
    },
    p(ctx2, dirty) {
      if (dirty & /*labelText*/
      32)
        small.innerHTML = /*labelText*/
        ctx2[5];
      if (dirty & /*$prices, standalone*/
      18) {
        toggle_class(
          div,
          "multiple-prices",
          /*$prices*/
          ctx2[4].length > 1 && !/*standalone*/
          ctx2[1]
        );
      }
      if (dirty & /*cantAfford*/
      4) {
        toggle_class(
          div,
          "cant-afford",
          /*cantAfford*/
          ctx2[2]
        );
      }
      if (dirty & /*cantAffordMultiplePrices*/
      64) {
        toggle_class(
          div,
          "cant-afford-multiple-prices",
          /*cantAffordMultiplePrices*/
          ctx2[6]
        );
      }
      if (dirty & /*$prices*/
      16) {
        toggle_class(
          div,
          "item-piles-clickable-link",
          /*$prices*/
          ctx2[4].length > 1
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_left_slot, "create_left_slot");
function create_fragment$15(ctx) {
  let div;
  let current_block_type_index;
  let if_block;
  let current;
  const if_block_creators = [create_if_block$K, create_else_block$j];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*$prices*/
      ctx2[4].length > 1
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      div = element("div");
      if_block.c();
      attr(div, "class", "price-container svelte-m0550s");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if_blocks[current_block_type_index].m(div, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(div, null);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if_blocks[current_block_type_index].d();
    }
  };
}
__name(create_fragment$15, "create_fragment$15");
const func$1 = /* @__PURE__ */ __name((price) => price.cost, "func$1");
function instance$12($$self, $$props, $$invalidate) {
  let cantAfford;
  let cantAffordMultiplePrices;
  let $selectedPriceGroup;
  let $prices;
  let $priceSelector;
  let { item } = $$props;
  let { standalone = false } = $$props;
  let labelText = "";
  const prices = item.prices;
  component_subscribe($$self, prices, (value) => $$invalidate(4, $prices = value));
  item.itemFlagData;
  const selectedPriceGroup = item.selectedPriceGroup;
  component_subscribe($$self, selectedPriceGroup, (value) => $$invalidate(3, $selectedPriceGroup = value));
  const priceSelector = standalone ? writable$1("") : item.store.priceSelector;
  component_subscribe($$self, priceSelector, (value) => $$invalidate(7, $priceSelector = value));
  const click_handler = /* @__PURE__ */ __name((index2) => {
    set_store_value(selectedPriceGroup, $selectedPriceGroup = index2, $selectedPriceGroup);
    set_store_value(priceSelector, $priceSelector = "", $priceSelector);
  }, "click_handler");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
    if ("standalone" in $$props2)
      $$invalidate(1, standalone = $$props2.standalone);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$prices, $selectedPriceGroup, item, standalone*/
    27) {
      $$invalidate(2, cantAfford = $prices.length > 0 && !$prices[$selectedPriceGroup]?.maxQuantity && item.store.recipient && !standalone);
    }
    if ($$self.$$.dirty & /*cantAfford, $prices*/
    20) {
      $$invalidate(6, cantAffordMultiplePrices = cantAfford && !$prices.filter((group) => group.maxQuantity).length);
    }
    if ($$self.$$.dirty & /*standalone, $prices, $selectedPriceGroup*/
    26) {
      $$invalidate(5, labelText = (standalone && $prices.length > 1 ? '<i class="fas fa-edit"></i> ' : "") + ($prices[$selectedPriceGroup]?.free ? localize("ITEM-PILES.Merchant.ItemFree") : $prices[$selectedPriceGroup]?.basePriceString));
    }
  };
  return [
    item,
    standalone,
    cantAfford,
    $selectedPriceGroup,
    $prices,
    labelText,
    cantAffordMultiplePrices,
    $priceSelector,
    prices,
    selectedPriceGroup,
    priceSelector,
    click_handler
  ];
}
__name(instance$12, "instance$12");
const _PriceSelector = class _PriceSelector extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$12, create_fragment$15, safe_not_equal, { item: 0, standalone: 1 });
  }
};
__name(_PriceSelector, "PriceSelector");
let PriceSelector = _PriceSelector;
function get_each_context$w(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[42] = list[i];
  return child_ctx;
}
__name(get_each_context$w, "get_each_context$w");
function get_each_context_1$f(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[45] = list[i];
  return child_ctx;
}
__name(get_each_context_1$f, "get_each_context_1$f");
function get_each_context_2$6(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[45] = list[i];
  return child_ctx;
}
__name(get_each_context_2$6, "get_each_context_2$6");
function create_else_block_1$5(ctx) {
  let small;
  let t_value = localize(.../*paymentData*/
  ctx[6].reason) + "";
  let t;
  return {
    c() {
      small = element("small");
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, small, anchor);
      append(small, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*paymentData*/
      64 && t_value !== (t_value = localize(.../*paymentData*/
      ctx2[6].reason) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(small);
    }
  };
}
__name(create_else_block_1$5, "create_else_block_1$5");
function create_if_block_5$a(ctx) {
  let div;
  let small0;
  let t1;
  let small1;
  let t2;
  let t3_value = localize("ITEM-PILES.Applications.TradeMerchantItem.MaxQuantity", {
    quantity: (
      /*maxItemPurchaseQuantity*/
      ctx[4]
    )
  }) + "";
  let t3;
  let t4;
  let t5;
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      small0 = element("small");
      small0.textContent = `${localize("ITEM-PILES.Applications.TradeMerchantItem.Quantity")}`;
      t1 = space();
      small1 = element("small");
      t2 = text("(");
      t3 = text(t3_value);
      t4 = text(")");
      t5 = space();
      input = element("input");
      set_style(small1, "font-style", "italic");
      set_style(div, "display", "flex");
      set_style(div, "flex-direction", "column");
      set_style(div, "align-items", "flex-end");
      set_style(div, "margin-right", "0.5rem");
      set_style(input, "max-width", "40px");
      set_style(input, "max-height", "24px");
      attr(input, "type", "number");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, small0);
      append(div, t1);
      append(div, small1);
      append(small1, t2);
      append(small1, t3);
      append(small1, t4);
      insert(target, t5, anchor);
      insert(target, input, anchor);
      set_input_value(
        input,
        /*currentQuantityToBuy*/
        ctx[5]
      );
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[36]
          ),
          listen(
            input,
            "change",
            /*change_handler*/
            ctx[37]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*maxItemPurchaseQuantity*/
      16 && t3_value !== (t3_value = localize("ITEM-PILES.Applications.TradeMerchantItem.MaxQuantity", {
        quantity: (
          /*maxItemPurchaseQuantity*/
          ctx2[4]
        )
      }) + ""))
        set_data(t3, t3_value);
      if (dirty[0] & /*currentQuantityToBuy*/
      32 && to_number(input.value) !== /*currentQuantityToBuy*/
      ctx2[5]) {
        set_input_value(
          input,
          /*currentQuantityToBuy*/
          ctx2[5]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t5);
      if (detaching)
        detach(input);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_5$a, "create_if_block_5$a");
function create_if_block_4$e(ctx) {
  let small;
  let t_value = (
    /*paymentData*/
    ctx[6].basePriceString + ""
  );
  let t;
  return {
    c() {
      small = element("small");
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, small, anchor);
      append(small, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*paymentData*/
      64 && t_value !== (t_value = /*paymentData*/
      ctx2[6].basePriceString + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(small);
    }
  };
}
__name(create_if_block_4$e, "create_if_block_4$e");
function create_if_block_3$i(ctx) {
  let div1;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let span;
  let t1_value = (
    /*price*/
    ctx[45].quantity + ""
  );
  let t1;
  let t2;
  let t3_value = localize(
    /*price*/
    ctx[45].name
  ) + "";
  let t3;
  let t4;
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      span = element("span");
      t1 = text(t1_value);
      t2 = space();
      t3 = text(t3_value);
      t4 = space();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*price*/
      ctx[45].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      set_style(div0, "margin-right", "0.25rem");
      set_style(div1, "display", "flex");
      set_style(div1, "align-items", "center");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, img);
      append(div1, t0);
      append(div1, span);
      append(span, t1);
      append(span, t2);
      append(span, t3);
      append(div1, t4);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*paymentData*/
      64 && !src_url_equal(img.src, img_src_value = /*price*/
      ctx2[45].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*paymentData*/
      64 && t1_value !== (t1_value = /*price*/
      ctx2[45].quantity + ""))
        set_data(t1, t1_value);
      if (dirty[0] & /*paymentData*/
      64 && t3_value !== (t3_value = localize(
        /*price*/
        ctx2[45].name
      ) + ""))
        set_data(t3, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(div1);
    }
  };
}
__name(create_if_block_3$i, "create_if_block_3$i");
function create_each_block_2$6(ctx) {
  let if_block_anchor;
  let if_block = (
    /*price*/
    ctx[45].quantity && create_if_block_3$i(ctx)
  );
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (
        /*price*/
        ctx2[45].quantity
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_3$i(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block_2$6, "create_each_block_2$6");
function create_each_block_1$f(ctx) {
  let div1;
  let span;
  let t0_value = (
    /*price*/
    ctx[45].quantity > 1 ? (
      /*price*/
      ctx[45].quantity + " "
    ) : ""
  );
  let t0;
  let t1_value = (
    /*price*/
    ctx[45].name + ""
  );
  let t1;
  let t2;
  let div0;
  let img;
  let img_src_value;
  return {
    c() {
      div1 = element("div");
      span = element("span");
      t0 = text(t0_value);
      t1 = text(t1_value);
      t2 = space();
      div0 = element("div");
      img = element("img");
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*price*/
      ctx[45].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      set_style(div0, "margin-left", "0.25rem");
      set_style(div1, "display", "flex");
      set_style(div1, "align-items", "center");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, span);
      append(span, t0);
      append(span, t1);
      append(div1, t2);
      append(div1, div0);
      append(div0, img);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*paymentData*/
      64 && t0_value !== (t0_value = /*price*/
      ctx2[45].quantity > 1 ? (
        /*price*/
        ctx2[45].quantity + " "
      ) : ""))
        set_data(t0, t0_value);
      if (dirty[0] & /*paymentData*/
      64 && t1_value !== (t1_value = /*price*/
      ctx2[45].name + ""))
        set_data(t1, t1_value);
      if (dirty[0] & /*paymentData*/
      64 && !src_url_equal(img.src, img_src_value = /*price*/
      ctx2[45].img)) {
        attr(img, "src", img_src_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div1);
    }
  };
}
__name(create_each_block_1$f, "create_each_block_1$f");
function create_if_block_1$w(ctx) {
  let span;
  let t2;
  let each_1_anchor;
  let each_value = (
    /*paymentData*/
    ctx[6].buyerChange
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$w(get_each_context$w(ctx, each_value, i));
  }
  return {
    c() {
      span = element("span");
      span.textContent = `${localize("ITEM-PILES.Applications.TradeMerchantItem.Change")}:`;
      t2 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
      attr(span, "class", "item-piles-small-text item-piles-text-right");
      set_style(span, "margin-right", "0.25rem");
      set_style(span, "margin-top", "0.5rem");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      insert(target, t2, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*paymentData*/
      64) {
        each_value = /*paymentData*/
        ctx2[6].buyerChange;
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$w(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block$w(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching)
        detach(span);
      if (detaching)
        detach(t2);
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block_1$w, "create_if_block_1$w");
function create_if_block_2$m(ctx) {
  let div1;
  let span;
  let t0_value = (
    /*change*/
    ctx[42].quantity + ""
  );
  let t0;
  let t1;
  let t2_value = localize(
    /*change*/
    ctx[42].name
  ) + "";
  let t2;
  let t3;
  let div0;
  let img;
  let img_src_value;
  let t4;
  return {
    c() {
      div1 = element("div");
      span = element("span");
      t0 = text(t0_value);
      t1 = space();
      t2 = text(t2_value);
      t3 = space();
      div0 = element("div");
      img = element("img");
      t4 = space();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*change*/
      ctx[42].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      set_style(div0, "margin-left", "0.25rem");
      set_style(div1, "display", "flex");
      set_style(div1, "align-items", "center");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, span);
      append(span, t0);
      append(span, t1);
      append(span, t2);
      append(div1, t3);
      append(div1, div0);
      append(div0, img);
      append(div1, t4);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*paymentData*/
      64 && t0_value !== (t0_value = /*change*/
      ctx2[42].quantity + ""))
        set_data(t0, t0_value);
      if (dirty[0] & /*paymentData*/
      64 && t2_value !== (t2_value = localize(
        /*change*/
        ctx2[42].name
      ) + ""))
        set_data(t2, t2_value);
      if (dirty[0] & /*paymentData*/
      64 && !src_url_equal(img.src, img_src_value = /*change*/
      ctx2[42].img)) {
        attr(img, "src", img_src_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div1);
    }
  };
}
__name(create_if_block_2$m, "create_if_block_2$m");
function create_each_block$w(ctx) {
  let if_block_anchor;
  let if_block = (
    /*change*/
    ctx[42].quantity && create_if_block_2$m(ctx)
  );
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (
        /*change*/
        ctx2[42].quantity
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_2$m(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block$w, "create_each_block$w");
function create_else_block$i(ctx) {
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Applications.TradeMerchantItem.BuyItem") + "";
  let t1;
  return {
    c() {
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-shopping-cart");
    },
    m(target, anchor) {
      insert(target, i, anchor);
      insert(target, t0, anchor);
      insert(target, t1, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(i);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(t1);
    }
  };
}
__name(create_else_block$i, "create_else_block$i");
function create_if_block$J(ctx) {
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Applications.TradeMerchantItem.SellItem") + "";
  let t1;
  return {
    c() {
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-hand-holding-usd");
    },
    m(target, anchor) {
      insert(target, i, anchor);
      insert(target, t0, anchor);
      insert(target, t1, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(i);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(t1);
    }
  };
}
__name(create_if_block$J, "create_if_block$J");
function create_default_slot$p(ctx) {
  let div9;
  let div5;
  let div1;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let span;
  let t1;
  let t2;
  let div2;
  let t3;
  let div3;
  let priceselector;
  let t4;
  let div4;
  let t5;
  let div8;
  let strong0;
  let t6_value = localize("ITEM-PILES.Applications.TradeMerchantItem." + /*settings*/
  (ctx[2].selling ? "YouReceive" : "YouPay")) + "";
  let t6;
  let t7;
  let t8;
  let strong1;
  let t9_value = localize("ITEM-PILES.Applications.TradeMerchantItem." + /*settings*/
  (ctx[2].selling ? "TheyReceive" : "YouReceive")) + "";
  let t9;
  let t10;
  let t11;
  let div6;
  let t12;
  let div7;
  let t13;
  let t14;
  let footer;
  let button0;
  let button0_disabled_value;
  let t15;
  let button1;
  let i;
  let t16;
  let t17_value = localize("Cancel") + "";
  let t17;
  let current;
  let mounted;
  let dispose;
  function select_block_type(ctx2, dirty) {
    if (
      /*paymentData*/
      ctx2[6].canBuy
    )
      return create_if_block_5$a;
    return create_else_block_1$5;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block0 = current_block_type(ctx);
  priceselector = new PriceSelector({
    props: { item: (
      /*item*/
      ctx[1]
    ), standalone: true }
  });
  let if_block1 = (
    /*paymentData*/
    ctx[6].canBuy && /*$quantityToBuy*/
    ctx[3] > 1 && /*paymentData*/
    ctx[6].primary && create_if_block_4$e(ctx)
  );
  let each_value_2 = (
    /*paymentData*/
    ctx[6].finalPrices
  );
  let each_blocks_1 = [];
  for (let i2 = 0; i2 < each_value_2.length; i2 += 1) {
    each_blocks_1[i2] = create_each_block_2$6(get_each_context_2$6(ctx, each_value_2, i2));
  }
  let each_value_1 = (
    /*paymentData*/
    ctx[6].buyerReceive
  );
  let each_blocks = [];
  for (let i2 = 0; i2 < each_value_1.length; i2 += 1) {
    each_blocks[i2] = create_each_block_1$f(get_each_context_1$f(ctx, each_value_1, i2));
  }
  let if_block2 = (
    /*paymentData*/
    ctx[6].buyerChange.length && create_if_block_1$w(ctx)
  );
  function select_block_type_1(ctx2, dirty) {
    if (
      /*settings*/
      ctx2[2].selling
    )
      return create_if_block$J;
    return create_else_block$i;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type_1 = select_block_type_1(ctx);
  let if_block3 = current_block_type_1(ctx);
  return {
    c() {
      div9 = element("div");
      div5 = element("div");
      div1 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      span = element("span");
      t1 = text(
        /*itemName*/
        ctx[7]
      );
      t2 = space();
      div2 = element("div");
      if_block0.c();
      t3 = space();
      div3 = element("div");
      create_component(priceselector.$$.fragment);
      t4 = space();
      div4 = element("div");
      if (if_block1)
        if_block1.c();
      t5 = space();
      div8 = element("div");
      strong0 = element("strong");
      t6 = text(t6_value);
      t7 = text(":");
      t8 = space();
      strong1 = element("strong");
      t9 = text(t9_value);
      t10 = text(":");
      t11 = space();
      div6 = element("div");
      for (let i2 = 0; i2 < each_blocks_1.length; i2 += 1) {
        each_blocks_1[i2].c();
      }
      t12 = space();
      div7 = element("div");
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        each_blocks[i2].c();
      }
      t13 = space();
      if (if_block2)
        if_block2.c();
      t14 = space();
      footer = element("footer");
      button0 = element("button");
      if_block3.c();
      t15 = space();
      button1 = element("button");
      i = element("i");
      t16 = space();
      t17 = text(t17_value);
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*$itemImg*/
      ctx[8]))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      set_style(div0, "margin-right", "0.25rem");
      set_style(
        span,
        "color",
        /*$itemRarityColor*/
        ctx[9] || "inherit"
      );
      set_style(div1, "display", "flex");
      set_style(div1, "align-items", "center");
      set_style(div1, "font-size", "1rem");
      set_style(div1, "grid-row", "1");
      set_style(div2, "display", "flex");
      set_style(div2, "justify-content", "flex-end");
      set_style(div2, "align-items", "center");
      set_style(div2, "text-align", "right");
      set_style(div3, "margin-top", "0.25rem");
      set_style(div3, "display", "flex");
      set_style(div3, "align-items", "flex-start");
      set_style(div4, "margin-right", "0.25rem");
      set_style(div4, "text-align", "right");
      set_style(div5, "display", "grid");
      set_style(div5, "grid-template-columns", "1fr 0.75fr");
      set_style(div5, "margin-bottom", "0.5rem");
      attr(strong0, "class", "item-piles-bottom-divider");
      set_style(strong0, "margin-bottom", "0.25rem");
      set_style(strong0, "padding-bottom", "0.25rem");
      attr(strong1, "class", "item-piles-bottom-divider item-piles-text-right");
      set_style(strong1, "margin-bottom", "0.25rem");
      set_style(strong1, "padding-bottom", "0.25rem");
      set_style(div7, "display", "flex");
      set_style(div7, "flex-direction", "column");
      set_style(div7, "align-items", "flex-end");
      attr(div8, "class", "item-piles-bottom-divider");
      set_style(div8, "display", "grid");
      set_style(div8, "grid-template-columns", "auto auto");
      button0.disabled = button0_disabled_value = !/*paymentData*/
      ctx[6].canBuy;
      attr(button0, "type", "button");
      attr(i, "class", "fas fa-times");
      attr(button1, "type", "button");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
    },
    m(target, anchor) {
      insert(target, div9, anchor);
      append(div9, div5);
      append(div5, div1);
      append(div1, div0);
      append(div0, img);
      append(div1, t0);
      append(div1, span);
      append(span, t1);
      append(div5, t2);
      append(div5, div2);
      if_block0.m(div2, null);
      append(div5, t3);
      append(div5, div3);
      mount_component(priceselector, div3, null);
      append(div5, t4);
      append(div5, div4);
      if (if_block1)
        if_block1.m(div4, null);
      append(div9, t5);
      append(div9, div8);
      append(div8, strong0);
      append(strong0, t6);
      append(strong0, t7);
      append(div8, t8);
      append(div8, strong1);
      append(strong1, t9);
      append(strong1, t10);
      append(div8, t11);
      append(div8, div6);
      for (let i2 = 0; i2 < each_blocks_1.length; i2 += 1) {
        if (each_blocks_1[i2]) {
          each_blocks_1[i2].m(div6, null);
        }
      }
      append(div8, t12);
      append(div8, div7);
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        if (each_blocks[i2]) {
          each_blocks[i2].m(div7, null);
        }
      }
      append(div7, t13);
      if (if_block2)
        if_block2.m(div7, null);
      append(div9, t14);
      append(div9, footer);
      append(footer, button0);
      if_block3.m(button0, null);
      append(footer, t15);
      append(footer, button1);
      append(button1, i);
      append(button1, t16);
      append(button1, t17);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*click_handler*/
            ctx[38],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler_1*/
            ctx[39],
            { once: true }
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty[0] & /*$itemImg*/
      256 && !src_url_equal(img.src, img_src_value = /*$itemImg*/
      ctx2[8])) {
        attr(img, "src", img_src_value);
      }
      if (!current || dirty[0] & /*itemName*/
      128)
        set_data(
          t1,
          /*itemName*/
          ctx2[7]
        );
      if (!current || dirty[0] & /*$itemRarityColor*/
      512) {
        set_style(
          span,
          "color",
          /*$itemRarityColor*/
          ctx2[9] || "inherit"
        );
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block0) {
        if_block0.p(ctx2, dirty);
      } else {
        if_block0.d(1);
        if_block0 = current_block_type(ctx2);
        if (if_block0) {
          if_block0.c();
          if_block0.m(div2, null);
        }
      }
      const priceselector_changes = {};
      if (dirty[0] & /*item*/
      2)
        priceselector_changes.item = /*item*/
        ctx2[1];
      priceselector.$set(priceselector_changes);
      if (
        /*paymentData*/
        ctx2[6].canBuy && /*$quantityToBuy*/
        ctx2[3] > 1 && /*paymentData*/
        ctx2[6].primary
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_4$e(ctx2);
          if_block1.c();
          if_block1.m(div4, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if ((!current || dirty[0] & /*settings*/
      4) && t6_value !== (t6_value = localize("ITEM-PILES.Applications.TradeMerchantItem." + /*settings*/
      (ctx2[2].selling ? "YouReceive" : "YouPay")) + ""))
        set_data(t6, t6_value);
      if ((!current || dirty[0] & /*settings*/
      4) && t9_value !== (t9_value = localize("ITEM-PILES.Applications.TradeMerchantItem." + /*settings*/
      (ctx2[2].selling ? "TheyReceive" : "YouReceive")) + ""))
        set_data(t9, t9_value);
      if (dirty[0] & /*paymentData*/
      64) {
        each_value_2 = /*paymentData*/
        ctx2[6].finalPrices;
        let i2;
        for (i2 = 0; i2 < each_value_2.length; i2 += 1) {
          const child_ctx = get_each_context_2$6(ctx2, each_value_2, i2);
          if (each_blocks_1[i2]) {
            each_blocks_1[i2].p(child_ctx, dirty);
          } else {
            each_blocks_1[i2] = create_each_block_2$6(child_ctx);
            each_blocks_1[i2].c();
            each_blocks_1[i2].m(div6, null);
          }
        }
        for (; i2 < each_blocks_1.length; i2 += 1) {
          each_blocks_1[i2].d(1);
        }
        each_blocks_1.length = each_value_2.length;
      }
      if (dirty[0] & /*paymentData*/
      64) {
        each_value_1 = /*paymentData*/
        ctx2[6].buyerReceive;
        let i2;
        for (i2 = 0; i2 < each_value_1.length; i2 += 1) {
          const child_ctx = get_each_context_1$f(ctx2, each_value_1, i2);
          if (each_blocks[i2]) {
            each_blocks[i2].p(child_ctx, dirty);
          } else {
            each_blocks[i2] = create_each_block_1$f(child_ctx);
            each_blocks[i2].c();
            each_blocks[i2].m(div7, t13);
          }
        }
        for (; i2 < each_blocks.length; i2 += 1) {
          each_blocks[i2].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
      if (
        /*paymentData*/
        ctx2[6].buyerChange.length
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block_1$w(ctx2);
          if_block2.c();
          if_block2.m(div7, null);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (current_block_type_1 === (current_block_type_1 = select_block_type_1(ctx2)) && if_block3) {
        if_block3.p(ctx2, dirty);
      } else {
        if_block3.d(1);
        if_block3 = current_block_type_1(ctx2);
        if (if_block3) {
          if_block3.c();
          if_block3.m(button0, null);
        }
      }
      if (!current || dirty[0] & /*paymentData*/
      64 && button0_disabled_value !== (button0_disabled_value = !/*paymentData*/
      ctx2[6].canBuy)) {
        button0.disabled = button0_disabled_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(priceselector.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(priceselector.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div9);
      if_block0.d();
      destroy_component(priceselector);
      if (if_block1)
        if_block1.d();
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
      if (if_block2)
        if_block2.d();
      if_block3.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$p, "create_default_slot$p");
function create_fragment$14(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[40](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$p] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*paymentData, settings, $quantityToBuy, item, currentQuantityToBuy, maxItemPurchaseQuantity, $itemRarityColor, itemName, $itemImg*/
      1022 | dirty[1] & /*$$scope*/
      524288) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$14, "create_fragment$14");
function instance$11($$self, $$props, $$invalidate) {
  let maxSellerItemQuantity;
  let maxItemQuantity;
  let itemName;
  let $itemQuantityForPriceStore;
  let $itemNameStore;
  let $selectedPriceGroup;
  let $prices;
  let $itemMaxQuantityStore;
  let $itemInfiniteQuantity;
  let $buyerPileData;
  let $sellerPileData;
  let $quantityToBuy;
  let $itemImg;
  let $itemRarityColor;
  const { application } = getContext("#external");
  let { item } = $$props;
  let { seller } = $$props;
  let { buyer } = $$props;
  let { settings } = $$props;
  let { elementRoot } = $$props;
  let { store = item.store } = $$props;
  const itemNameStore = item.name;
  component_subscribe($$self, itemNameStore, (value) => $$invalidate(29, $itemNameStore = value));
  const itemImg = item.img;
  component_subscribe($$self, itemImg, (value) => $$invalidate(8, $itemImg = value));
  const itemInfiniteQuantity = item.infiniteQuantity;
  component_subscribe($$self, itemInfiniteQuantity, (value) => $$invalidate(33, $itemInfiniteQuantity = value));
  const itemRarityColor = item.rarityColor;
  component_subscribe($$self, itemRarityColor, (value) => $$invalidate(9, $itemRarityColor = value));
  item.itemFlagData;
  const quantityToBuy = item.quantityToBuy;
  component_subscribe($$self, quantityToBuy, (value) => $$invalidate(3, $quantityToBuy = value));
  const itemMaxQuantityStore = item.quantity;
  component_subscribe($$self, itemMaxQuantityStore, (value) => $$invalidate(32, $itemMaxQuantityStore = value));
  const itemQuantityForPriceStore = item.quantityForPrice;
  component_subscribe($$self, itemQuantityForPriceStore, (value) => $$invalidate(28, $itemQuantityForPriceStore = value));
  const prices = item.prices;
  component_subscribe($$self, prices, (value) => $$invalidate(31, $prices = value));
  const sellerPileData = store.pileData;
  component_subscribe($$self, sellerPileData, (value) => $$invalidate(35, $sellerPileData = value));
  const buyerPileData = store.recipientPileData;
  component_subscribe($$self, buyerPileData, (value) => $$invalidate(34, $buyerPileData = value));
  let maxItemPurchaseQuantity;
  let currentQuantityToBuy;
  const selectedPriceGroup = item.selectedPriceGroup;
  component_subscribe($$self, selectedPriceGroup, (value) => $$invalidate(30, $selectedPriceGroup = value));
  let paymentData = {};
  async function submit() {
    const result = await game.itempiles.API.tradeItems(
      seller,
      buyer,
      [
        {
          item: item.item,
          paymentIndex: get_store_value(selectedPriceGroup),
          quantity: get_store_value(quantityToBuy)
        }
      ],
      { interactionId: store.interactionId }
    );
    if (!result)
      return;
    application.options.resolve();
    application.close();
  }
  __name(submit, "submit");
  function input_input_handler() {
    currentQuantityToBuy = to_number(this.value);
    $$invalidate(5, currentQuantityToBuy), $$invalidate(30, $selectedPriceGroup);
  }
  __name(input_input_handler, "input_input_handler");
  const change_handler = /* @__PURE__ */ __name((evt) => {
    set_store_value(quantityToBuy, $quantityToBuy = Math.max(1, Math.min(currentQuantityToBuy, maxItemPurchaseQuantity)), $quantityToBuy);
    $$invalidate(5, currentQuantityToBuy = $quantityToBuy);
  }, "change_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    submit();
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler_1");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(1, item = $$props2.item);
    if ("seller" in $$props2)
      $$invalidate(23, seller = $$props2.seller);
    if ("buyer" in $$props2)
      $$invalidate(24, buyer = $$props2.buyer);
    if ("settings" in $$props2)
      $$invalidate(2, settings = $$props2.settings);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("store" in $$props2)
      $$invalidate(25, store = $$props2.store);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*$selectedPriceGroup*/
    1073741824) {
      {
        $$invalidate(5, currentQuantityToBuy = 1);
        set_store_value(quantityToBuy, $quantityToBuy = 1, $quantityToBuy);
      }
    }
    if ($$self.$$.dirty[0] & /*item, $quantityToBuy, $selectedPriceGroup, seller, buyer*/
    1098907658 | $$self.$$.dirty[1] & /*$sellerPileData, $buyerPileData*/
    24) {
      {
        $$invalidate(6, paymentData = getPaymentData({
          purchaseData: [
            {
              item: item.item,
              quantity: $quantityToBuy,
              paymentIndex: $selectedPriceGroup
            }
          ],
          seller,
          buyer,
          sellerFlagData: $sellerPileData,
          buyerFlagData: $buyerPileData
        }));
      }
    }
    if ($$self.$$.dirty[0] & /*$itemQuantityForPriceStore*/
    268435456 | $$self.$$.dirty[1] & /*$itemInfiniteQuantity, $itemMaxQuantityStore*/
    6) {
      $$invalidate(26, maxSellerItemQuantity = $itemInfiniteQuantity ? Infinity : Math.ceil($itemMaxQuantityStore / $itemQuantityForPriceStore));
    }
    if ($$self.$$.dirty[0] & /*$selectedPriceGroup*/
    1073741824 | $$self.$$.dirty[1] & /*$prices*/
    1) {
      $$invalidate(27, maxItemQuantity = $prices[$selectedPriceGroup]?.maxQuantity ?? Infinity);
    }
    if ($$self.$$.dirty[0] & /*maxItemQuantity, maxSellerItemQuantity*/
    201326592) {
      $$invalidate(4, maxItemPurchaseQuantity = Math.min(maxItemQuantity, maxSellerItemQuantity));
    }
    if ($$self.$$.dirty[0] & /*$itemNameStore, $itemQuantityForPriceStore*/
    805306368) {
      $$invalidate(7, itemName = localize($itemNameStore) + ($itemQuantityForPriceStore > 1 ? ` (${$itemQuantityForPriceStore})` : ""));
    }
  };
  return [
    elementRoot,
    item,
    settings,
    $quantityToBuy,
    maxItemPurchaseQuantity,
    currentQuantityToBuy,
    paymentData,
    itemName,
    $itemImg,
    $itemRarityColor,
    application,
    itemNameStore,
    itemImg,
    itemInfiniteQuantity,
    itemRarityColor,
    quantityToBuy,
    itemMaxQuantityStore,
    itemQuantityForPriceStore,
    prices,
    sellerPileData,
    buyerPileData,
    selectedPriceGroup,
    submit,
    seller,
    buyer,
    store,
    maxSellerItemQuantity,
    maxItemQuantity,
    $itemQuantityForPriceStore,
    $itemNameStore,
    $selectedPriceGroup,
    $prices,
    $itemMaxQuantityStore,
    $itemInfiniteQuantity,
    $buyerPileData,
    $sellerPileData,
    input_input_handler,
    change_handler,
    click_handler,
    click_handler_1,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$11, "instance$11");
const _Trade_merchant_item_dialog_shell = class _Trade_merchant_item_dialog_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$11,
      create_fragment$14,
      safe_not_equal,
      {
        item: 1,
        seller: 23,
        buyer: 24,
        settings: 2,
        elementRoot: 0,
        store: 25
      },
      null,
      [-1, -1]
    );
  }
  get item() {
    return this.$$.ctx[1];
  }
  set item(item) {
    this.$$set({ item });
    flush();
  }
  get seller() {
    return this.$$.ctx[23];
  }
  set seller(seller) {
    this.$$set({ seller });
    flush();
  }
  get buyer() {
    return this.$$.ctx[24];
  }
  set buyer(buyer) {
    this.$$set({ buyer });
    flush();
  }
  get settings() {
    return this.$$.ctx[2];
  }
  set settings(settings) {
    this.$$set({ settings });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get store() {
    return this.$$.ctx[25];
  }
  set store(store) {
    this.$$set({ store });
    flush();
  }
};
__name(_Trade_merchant_item_dialog_shell, "Trade_merchant_item_dialog_shell");
let Trade_merchant_item_dialog_shell = _Trade_merchant_item_dialog_shell;
const _TradeMerchantItemDialog = class _TradeMerchantItemDialog extends SvelteApplication {
  /**
   *
   * @param item
   * @param seller
   * @param buyer
   * @param settings
   * @param options
   */
  constructor(item, seller, buyer, settings = {}, options = {}) {
    super({
      id: `item-pile-buy-item-dialog-${item.id}-${seller.id}-${buyer.id}-${randomID()}`,
      title: game.i18n.format("ITEM-PILES.Applications.TradeMerchantItem.Title", { item_name: get_store_value(item.name) }),
      svelte: {
        class: Trade_merchant_item_dialog_shell,
        target: document.body,
        props: {
          item,
          seller,
          buyer,
          settings
        }
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 330,
      height: "auto",
      classes: ["item-piles-app"]
    });
  }
  static getActiveApps(id) {
    return getActiveApps(`item-pile-buy-item-dialog-${id}`);
  }
  static async show(item, seller, buyer, settings = {}, options = {}) {
    const apps = this.getActiveApps(item.uuid + "-" + seller.uuid + "-" + buyer.uuid);
    if (apps.length) {
      for (let app of apps) {
        app.render(false, { focus: true });
      }
      return;
    }
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(item, seller, buyer, settings, options).render(true, { focus: true });
    });
  }
};
__name(_TradeMerchantItemDialog, "TradeMerchantItemDialog");
let TradeMerchantItemDialog = _TradeMerchantItemDialog;
const CustomColumn_svelte_svelte_type_style_lang = "";
function create_fragment$13(ctx) {
  let div;
  let span;
  return {
    c() {
      div = element("div");
      span = element("span");
      attr(div, "class", "svelte-m19fn7");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      span.innerHTML = /*text*/
      ctx[0];
    },
    p(ctx2, [dirty]) {
      if (dirty & /*text*/
      1)
        span.innerHTML = /*text*/
        ctx2[0];
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_fragment$13, "create_fragment$13");
function instance$10($$self, $$props, $$invalidate) {
  let value;
  let $doc;
  let { item } = $$props;
  let { data: data2 } = $$props;
  const doc = item.itemDocument;
  component_subscribe($$self, doc, (value2) => $$invalidate(5, $doc = value2));
  let text2;
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(2, item = $$props2.item);
    if ("data" in $$props2)
      $$invalidate(3, data2 = $$props2.data);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*data, $doc*/
    40) {
      $$invalidate(4, value = data2.path ? getProperty($doc, data2.path) ?? "" : "");
    }
    if ($$self.$$.dirty & /*data, value*/
    24) {
      {
        let localized = localize(`${data2.mapping?.[value] ?? value}`);
        $$invalidate(0, text2 = data2.formatting ? data2.formatting.replace("{#}", localized) : localized);
      }
    }
  };
  return [text2, doc, item, data2, value, $doc];
}
__name(instance$10, "instance$10");
const _CustomColumn = class _CustomColumn extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$10, create_fragment$13, safe_not_equal, { item: 2, data: 3 });
  }
};
__name(_CustomColumn, "CustomColumn");
let CustomColumn = _CustomColumn;
const QuantityColumn_svelte_svelte_type_style_lang = "";
function create_if_block$I(ctx) {
  let if_block_anchor;
  function select_block_type(ctx2, dirty) {
    if (
      /*$infiniteQuantityStore*/
      ctx2[6]
    )
      return create_if_block_1$v;
    if (
      /*showEditQuantity*/
      ctx2[3]
    )
      return create_if_block_2$l;
    if (!/*showEditQuantity*/
    ctx2[3])
      return create_if_block_3$h;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type && current_block_type(ctx);
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if (if_block)
          if_block.d(1);
        if_block = current_block_type && current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    d(detaching) {
      if (if_block) {
        if_block.d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block$I, "create_if_block$I");
function create_if_block_3$h(ctx) {
  let span;
  let t0_value = (
    /*showX*/
    ctx[1] ? "x" : ""
  );
  let t0;
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      span = element("span");
      t0 = text(t0_value);
      t1 = text(
        /*$quantityStore*/
        ctx[2]
      );
      toggle_class(span, "item-piles-clickable-link", game.user.isGM);
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t0);
      append(span, t1);
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*click_handler*/
          ctx[13]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*showX*/
      2 && t0_value !== (t0_value = /*showX*/
      ctx2[1] ? "x" : ""))
        set_data(t0, t0_value);
      if (dirty & /*$quantityStore*/
      4)
        set_data(
          t1,
          /*$quantityStore*/
          ctx2[2]
        );
      if (dirty & /*game*/
      0) {
        toggle_class(span, "item-piles-clickable-link", game.user.isGM);
      }
    },
    d(detaching) {
      if (detaching)
        detach(span);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$h, "create_if_block_3$h");
function create_if_block_2$l(ctx) {
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      set_style(input, "height", "18px");
      set_style(input, "max-width", "35px");
      attr(input, "type", "text");
      input.autofocus = true;
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*editQuantity*/
        ctx[4]
      );
      input.focus();
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[10]
          ),
          listen(
            input,
            "change",
            /*change_handler*/
            ctx[11]
          ),
          listen(
            input,
            "keydown",
            /*keydown_handler*/
            ctx[12]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*editQuantity*/
      16 && input.value !== /*editQuantity*/
      ctx2[4]) {
        set_input_value(
          input,
          /*editQuantity*/
          ctx2[4]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_2$l, "create_if_block_2$l");
function create_if_block_1$v(ctx) {
  let span;
  return {
    c() {
      span = element("span");
      span.textContent = "∞";
    },
    m(target, anchor) {
      insert(target, span, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_if_block_1$v, "create_if_block_1$v");
function create_fragment$12(ctx) {
  let div;
  let if_block = (
    /*$displayQuantityStore*/
    ctx[5] && /*item*/
    ctx[0].canStack && create_if_block$I(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block)
        if_block.c();
      attr(div, "class", "svelte-1hmsnh9");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block)
        if_block.m(div, null);
    },
    p(ctx2, [dirty]) {
      if (
        /*$displayQuantityStore*/
        ctx2[5] && /*item*/
        ctx2[0].canStack
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$I(ctx2);
          if_block.c();
          if_block.m(div, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
    }
  };
}
__name(create_fragment$12, "create_fragment$12");
function instance$$($$self, $$props, $$invalidate) {
  let editQuantity;
  let $quantityStore;
  let $displayQuantityStore;
  let $infiniteQuantityStore;
  let { item } = $$props;
  let { showX = false } = $$props;
  item.store;
  const displayQuantityStore = item.displayQuantity;
  component_subscribe($$self, displayQuantityStore, (value) => $$invalidate(5, $displayQuantityStore = value));
  const infiniteQuantityStore = item.infiniteQuantity;
  component_subscribe($$self, infiniteQuantityStore, (value) => $$invalidate(6, $infiniteQuantityStore = value));
  const quantityStore = item.quantity;
  component_subscribe($$self, quantityStore, (value) => $$invalidate(2, $quantityStore = value));
  let showEditQuantity = false;
  function input_input_handler() {
    editQuantity = this.value;
    $$invalidate(4, editQuantity), $$invalidate(2, $quantityStore);
  }
  __name(input_input_handler, "input_input_handler");
  const change_handler = /* @__PURE__ */ __name(() => {
    $$invalidate(3, showEditQuantity = false);
    item.updateQuantity(editQuantity);
  }, "change_handler");
  const keydown_handler = /* @__PURE__ */ __name((evt) => {
    if (evt.key === "Enter")
      $$invalidate(3, showEditQuantity = false);
  }, "keydown_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    if (game.user.isGM)
      $$invalidate(3, showEditQuantity = true);
  }, "click_handler");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
    if ("showX" in $$props2)
      $$invalidate(1, showX = $$props2.showX);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$quantityStore*/
    4) {
      $$invalidate(4, editQuantity = $quantityStore);
    }
  };
  return [
    item,
    showX,
    $quantityStore,
    showEditQuantity,
    editQuantity,
    $displayQuantityStore,
    $infiniteQuantityStore,
    displayQuantityStore,
    infiniteQuantityStore,
    quantityStore,
    input_input_handler,
    change_handler,
    keydown_handler,
    click_handler
  ];
}
__name(instance$$, "instance$$");
const _QuantityColumn = class _QuantityColumn extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$$, create_fragment$12, safe_not_equal, { item: 0, showX: 1 });
  }
};
__name(_QuantityColumn, "QuantityColumn");
let QuantityColumn = _QuantityColumn;
const ItemEntry_svelte_svelte_type_style_lang = "";
const get_right_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_right_slot_changes");
const get_right_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_right_slot_context");
function create_else_block$h(ctx) {
  let t;
  return {
    c() {
      t = text(
        /*itemName*/
        ctx[2]
      );
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*itemName*/
      4)
        set_data(
          t,
          /*itemName*/
          ctx2[2]
        );
    },
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(create_else_block$h, "create_else_block$h");
function create_if_block_1$u(ctx) {
  let a;
  let t;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      t = text(
        /*itemName*/
        ctx[2]
      );
      attr(a, "class", "item-piles-clickable");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, t);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[25]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*itemName*/
      4)
        set_data(
          t,
          /*itemName*/
          ctx2[2]
        );
    },
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$u, "create_if_block_1$u");
function create_if_block$H(ctx) {
  let div;
  let quantitycolumn;
  let current;
  quantitycolumn = new QuantityColumn({
    props: { item: (
      /*item*/
      ctx[0]
    ), showX: true }
  });
  return {
    c() {
      div = element("div");
      create_component(quantitycolumn.$$.fragment);
      attr(div, "class", "item-piles-quantity-container svelte-1dzqiyw");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(quantitycolumn, div, null);
      current = true;
    },
    p(ctx2, dirty) {
      const quantitycolumn_changes = {};
      if (dirty[0] & /*item*/
      1)
        quantitycolumn_changes.item = /*item*/
        ctx2[0];
      quantitycolumn.$set(quantitycolumn_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(quantitycolumn.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(quantitycolumn.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(quantitycolumn);
    }
  };
}
__name(create_if_block$H, "create_if_block$H");
function create_fragment$11(ctx) {
  let div3;
  let div0;
  let img;
  let img_src_value;
  let div0_data_fast_tooltip_value;
  let t0;
  let div2;
  let div1;
  let span;
  let t1;
  let t2;
  let current;
  function select_block_type(ctx2, dirty) {
    if (
      /*$pileData*/
      ctx2[7].canInspectItems || game.user.isGM
    )
      return create_if_block_1$u;
    return create_else_block$h;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block0 = current_block_type(ctx);
  let if_block1 = (
    /*showQuantity*/
    ctx[1] && create_if_block$H(ctx)
  );
  const right_slot_template = (
    /*#slots*/
    ctx[24].right
  );
  const right_slot = create_slot(
    right_slot_template,
    ctx,
    /*$$scope*/
    ctx[23],
    get_right_slot_context
  );
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      span = element("span");
      if_block0.c();
      t1 = space();
      if (if_block1)
        if_block1.c();
      t2 = space();
      if (right_slot)
        right_slot.c();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*$itemImage*/
      ctx[5]))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container svelte-1dzqiyw");
      attr(div0, "data-fast-tooltip", div0_data_fast_tooltip_value = /*itemFlagData*/
      ctx[4].notForSale ? "Not for sale" : "");
      toggle_class(
        div0,
        "not-for-sale",
        /*itemFlagData*/
        ctx[4].notForSale || !/*quantity*/
        ctx[3]
      );
      set_style(
        span,
        "color",
        /*$itemRarityColor*/
        ctx[6] || "inherit"
      );
      attr(div1, "class", "item-piles-name-container");
      attr(div2, "class", "item-piles-name item-piles-text svelte-1dzqiyw");
      attr(div3, "class", "item-piles-merchant-item-container svelte-1dzqiyw");
      toggle_class(
        div3,
        "merchant-item-hidden",
        /*itemFlagData*/
        ctx[4].hidden
      );
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, span);
      if_block0.m(span, null);
      append(div3, t1);
      if (if_block1)
        if_block1.m(div3, null);
      append(div3, t2);
      if (right_slot) {
        right_slot.m(div3, null);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (!current || dirty[0] & /*$itemImage*/
      32 && !src_url_equal(img.src, img_src_value = /*$itemImage*/
      ctx2[5])) {
        attr(img, "src", img_src_value);
      }
      if (!current || dirty[0] & /*itemFlagData*/
      16 && div0_data_fast_tooltip_value !== (div0_data_fast_tooltip_value = /*itemFlagData*/
      ctx2[4].notForSale ? "Not for sale" : "")) {
        attr(div0, "data-fast-tooltip", div0_data_fast_tooltip_value);
      }
      if (!current || dirty[0] & /*itemFlagData, quantity*/
      24) {
        toggle_class(
          div0,
          "not-for-sale",
          /*itemFlagData*/
          ctx2[4].notForSale || !/*quantity*/
          ctx2[3]
        );
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block0) {
        if_block0.p(ctx2, dirty);
      } else {
        if_block0.d(1);
        if_block0 = current_block_type(ctx2);
        if (if_block0) {
          if_block0.c();
          if_block0.m(span, null);
        }
      }
      if (!current || dirty[0] & /*$itemRarityColor*/
      64) {
        set_style(
          span,
          "color",
          /*$itemRarityColor*/
          ctx2[6] || "inherit"
        );
      }
      if (
        /*showQuantity*/
        ctx2[1]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*showQuantity*/
          2) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block$H(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div3, t2);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (right_slot) {
        if (right_slot.p && (!current || dirty[0] & /*$$scope*/
        8388608)) {
          update_slot_base(
            right_slot,
            right_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[23],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[23]
            ) : get_slot_changes(
              right_slot_template,
              /*$$scope*/
              ctx2[23],
              dirty,
              get_right_slot_changes
            ),
            get_right_slot_context
          );
        }
      }
      if (!current || dirty[0] & /*itemFlagData*/
      16) {
        toggle_class(
          div3,
          "merchant-item-hidden",
          /*itemFlagData*/
          ctx2[4].hidden
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block1);
      transition_in(right_slot, local);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      transition_out(right_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if_block0.d();
      if (if_block1)
        if_block1.d();
      if (right_slot)
        right_slot.d(detaching);
    }
  };
}
__name(create_fragment$11, "create_fragment$11");
function instance$_($$self, $$props, $$invalidate) {
  let itemFlagData;
  let quantity;
  let itemName;
  let $itemQuantityForPrice;
  let $itemNameStore;
  let $quantityStore;
  let $infiniteQuantityStore;
  let $displayQuantityStore;
  let $itemFlagDataStore;
  let $itemImage;
  let $itemRarityColor;
  let $pileData;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { item } = $$props;
  let { showQuantity = false } = $$props;
  const itemNameStore = item.name;
  component_subscribe($$self, itemNameStore, (value) => $$invalidate(18, $itemNameStore = value));
  const itemImage = item.img;
  component_subscribe($$self, itemImage, (value) => $$invalidate(5, $itemImage = value));
  const itemRarityColor = item.rarityColor;
  component_subscribe($$self, itemRarityColor, (value) => $$invalidate(6, $itemRarityColor = value));
  const itemQuantityForPrice = item.quantityForPrice;
  component_subscribe($$self, itemQuantityForPrice, (value) => $$invalidate(17, $itemQuantityForPrice = value));
  const store = item.store;
  const pileData = store.pileData;
  component_subscribe($$self, pileData, (value) => $$invalidate(7, $pileData = value));
  const displayQuantityStore = item.displayQuantity;
  component_subscribe($$self, displayQuantityStore, (value) => $$invalidate(21, $displayQuantityStore = value));
  const infiniteQuantityStore = item.infiniteQuantity;
  component_subscribe($$self, infiniteQuantityStore, (value) => $$invalidate(20, $infiniteQuantityStore = value));
  const quantityStore = item.quantity;
  component_subscribe($$self, quantityStore, (value) => $$invalidate(19, $quantityStore = value));
  const itemFlagDataStore = item.itemFlagData;
  component_subscribe($$self, itemFlagDataStore, (value) => $$invalidate(22, $itemFlagDataStore = value));
  store.actor.isOwner;
  !!store.recipient;
  const click_handler = /* @__PURE__ */ __name(() => {
    item.preview();
  }, "click_handler");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
    if ("showQuantity" in $$props2)
      $$invalidate(1, showQuantity = $$props2.showQuantity);
    if ("$$scope" in $$props2)
      $$invalidate(23, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*$itemFlagDataStore*/
    4194304) {
      $$invalidate(4, itemFlagData = $itemFlagDataStore);
    }
    if ($$self.$$.dirty[0] & /*$displayQuantityStore*/
    2097152)
      ;
    if ($$self.$$.dirty[0] & /*$infiniteQuantityStore*/
    1048576)
      ;
    if ($$self.$$.dirty[0] & /*$quantityStore*/
    524288) {
      $$invalidate(3, quantity = $quantityStore);
    }
    if ($$self.$$.dirty[0] & /*$quantityStore*/
    524288)
      ;
    if ($$self.$$.dirty[0] & /*$itemNameStore, $itemQuantityForPrice*/
    393216) {
      $$invalidate(2, itemName = $itemNameStore + ($itemQuantityForPrice > 1 ? ` (${$itemQuantityForPrice})` : ""));
    }
  };
  return [
    item,
    showQuantity,
    itemName,
    quantity,
    itemFlagData,
    $itemImage,
    $itemRarityColor,
    $pileData,
    itemNameStore,
    itemImage,
    itemRarityColor,
    itemQuantityForPrice,
    pileData,
    displayQuantityStore,
    infiniteQuantityStore,
    quantityStore,
    itemFlagDataStore,
    $itemQuantityForPrice,
    $itemNameStore,
    $quantityStore,
    $infiniteQuantityStore,
    $displayQuantityStore,
    $itemFlagDataStore,
    $$scope,
    slots,
    click_handler
  ];
}
__name(instance$_, "instance$_");
const _ItemEntry = class _ItemEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$_, create_fragment$11, safe_not_equal, { item: 0, showQuantity: 1 }, null, [-1, -1]);
  }
};
__name(_ItemEntry, "ItemEntry");
let ItemEntry = _ItemEntry;
const existingStores = /* @__PURE__ */ new Map();
const _ItemPriceStore = class _ItemPriceStore {
  constructor(item) {
    this.item = item;
    this.itemDoc = new TJSDocument(this.item);
    const quantityForPriceProp = game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE;
    this.price = writable$1(0);
    this.quantityForPrice = writable$1(getProperty(item, quantityForPriceProp) ?? 1);
    const data2 = getItemFlagData(this.item);
    data2.prices.forEach((group) => {
      group.forEach((price) => {
        if (!price.id) {
          price.id = randomID();
        }
      });
    });
    this.data = writable$1(data2);
    this.itemDoc.subscribe((item2, changes) => {
      const { data: data3 } = changes;
      if (hasProperty(data3, CONSTANTS.FLAGS.ITEM)) {
        const newData = getProperty(data3, CONSTANTS.FLAGS.ITEM);
        const oldData = get_store_value(this.data);
        this.data.set(foundry.utils.mergeObject(oldData, newData));
      }
      this.price.set(getItemCost(this.item));
      const quantityForPriceProp2 = game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE;
      if (quantityForPriceProp2 && hasProperty(data3, quantityForPriceProp2)) {
        this.quantityForPrice.set(getProperty(item2, quantityForPriceProp2));
      }
    });
  }
  static make(item) {
    if (existingStores.has(item.id)) {
      return existingStores.get(item.id);
    }
    return new this(item);
  }
  removeGroup(groupIndex) {
    const data2 = get_store_value(this.data);
    data2.prices.splice(groupIndex, 1);
    this.data.set(data2);
  }
  export() {
    const data2 = {
      data: {
        [game.itempiles.API.ITEM_PRICE_ATTRIBUTE]: get_store_value(this.price)
      },
      flags: get_store_value(this.data)
    };
    if (game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE) {
      data2["data"][game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE] = get_store_value(this.quantityForPrice);
    }
    return data2;
  }
};
__name(_ItemPriceStore, "ItemPriceStore");
let ItemPriceStore = _ItemPriceStore;
const FilePicker_svelte_svelte_type_style_lang = "";
function create_if_block_1$t(ctx) {
  let div;
  let img;
  let img_src_value;
  return {
    c() {
      div = element("div");
      img = element("img");
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*value*/
      ctx[0]))
        attr(img, "src", img_src_value);
      attr(div, "class", "item-piles-img-container svelte-ofs97j");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, img);
    },
    p(ctx2, dirty) {
      if (dirty & /*value*/
      1 && !src_url_equal(img.src, img_src_value = /*value*/
      ctx2[0])) {
        attr(img, "src", img_src_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_1$t, "create_if_block_1$t");
function create_if_block$G(ctx) {
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      attr(input, "type", "text");
      attr(
        input,
        "placeholder",
        /*placeholder*/
        ctx[1]
      );
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*value*/
        ctx[0]
      );
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*placeholder*/
      2) {
        attr(
          input,
          "placeholder",
          /*placeholder*/
          ctx2[1]
        );
      }
      if (dirty & /*value*/
      1 && input.value !== /*value*/
      ctx2[0]) {
        set_input_value(
          input,
          /*value*/
          ctx2[0]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$G, "create_if_block$G");
function create_fragment$10(ctx) {
  let div;
  let t0;
  let t1;
  let button;
  let mounted;
  let dispose;
  let if_block0 = (
    /*showImage*/
    ctx[2] && create_if_block_1$t(ctx)
  );
  let if_block1 = (
    /*showInput*/
    ctx[3] && create_if_block$G(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      if (if_block1)
        if_block1.c();
      t1 = space();
      button = element("button");
      button.innerHTML = `<i class="fas fa-file-import"></i>`;
      attr(button, "type", "button");
      attr(button, "class", "svelte-ofs97j");
      attr(div, "class", "svelte-ofs97j");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t0);
      if (if_block1)
        if_block1.m(div, null);
      append(div, t1);
      append(div, button);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*handleClick*/
          ctx[4]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (
        /*showImage*/
        ctx2[2]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_1$t(ctx2);
          if_block0.c();
          if_block0.m(div, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*showInput*/
        ctx2[3]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block$G(ctx2);
          if_block1.c();
          if_block1.m(div, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$10, "create_fragment$10");
function instance$Z($$self, $$props, $$invalidate) {
  let { value } = $$props;
  let { type } = $$props;
  let { placeholder = "" } = $$props;
  let { showImage = false } = $$props;
  let { showInput = true } = $$props;
  let filePicker = false;
  function handleClick() {
    if (!filePicker) {
      filePicker = new FilePicker({
        type,
        current: value,
        callback: (path) => {
          $$invalidate(0, value = path);
          filePicker = false;
        }
      });
    }
    filePicker.render(true, { focus: true });
  }
  __name(handleClick, "handleClick");
  function input_input_handler() {
    value = this.value;
    $$invalidate(0, value);
  }
  __name(input_input_handler, "input_input_handler");
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(0, value = $$props2.value);
    if ("type" in $$props2)
      $$invalidate(5, type = $$props2.type);
    if ("placeholder" in $$props2)
      $$invalidate(1, placeholder = $$props2.placeholder);
    if ("showImage" in $$props2)
      $$invalidate(2, showImage = $$props2.showImage);
    if ("showInput" in $$props2)
      $$invalidate(3, showInput = $$props2.showInput);
  };
  return [
    value,
    placeholder,
    showImage,
    showInput,
    handleClick,
    type,
    input_input_handler
  ];
}
__name(instance$Z, "instance$Z");
const _FilePicker_1 = class _FilePicker_1 extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$Z, create_fragment$10, safe_not_equal, {
      value: 0,
      type: 5,
      placeholder: 1,
      showImage: 2,
      showInput: 3
    });
  }
};
__name(_FilePicker_1, "FilePicker_1");
let FilePicker_1 = _FilePicker_1;
function flip$1(node, { from, to }, params = {}) {
  const style = getComputedStyle(node);
  const transform = style.transform === "none" ? "" : style.transform;
  const [ox, oy] = style.transformOrigin.split(" ").map(parseFloat);
  const dx = from.left + from.width * ox / to.width - (to.left + ox);
  const dy = from.top + from.height * oy / to.height - (to.top + oy);
  const { delay = 0, duration = /* @__PURE__ */ __name((d) => Math.sqrt(d) * 120, "duration"), easing = cubicOut } = params;
  return {
    delay,
    duration: is_function(duration) ? duration(Math.sqrt(dx * dx + dy * dy)) : duration,
    easing,
    css: (t, u) => {
      const x = u * dx;
      const y = u * dy;
      const sx = t + u * from.width / to.width;
      const sy = t + u * from.height / to.height;
      return `transform: ${transform} translate(${x}px, ${y}px) scale(${sx}, ${sy});`;
    }
  };
}
__name(flip$1, "flip$1");
const FINALIZE_EVENT_NAME = "finalize";
const CONSIDER_EVENT_NAME = "consider";
function dispatchFinalizeEvent(el, items, info) {
  el.dispatchEvent(
    new CustomEvent(FINALIZE_EVENT_NAME, {
      detail: { items, info }
    })
  );
}
__name(dispatchFinalizeEvent, "dispatchFinalizeEvent");
function dispatchConsiderEvent(el, items, info) {
  el.dispatchEvent(
    new CustomEvent(CONSIDER_EVENT_NAME, {
      detail: { items, info }
    })
  );
}
__name(dispatchConsiderEvent, "dispatchConsiderEvent");
const DRAGGED_ENTERED_EVENT_NAME = "draggedEntered";
const DRAGGED_LEFT_EVENT_NAME = "draggedLeft";
const DRAGGED_OVER_INDEX_EVENT_NAME = "draggedOverIndex";
const DRAGGED_LEFT_DOCUMENT_EVENT_NAME = "draggedLeftDocument";
const DRAGGED_LEFT_TYPES = {
  LEFT_FOR_ANOTHER: "leftForAnother",
  OUTSIDE_OF_ANY: "outsideOfAny"
};
function dispatchDraggedElementEnteredContainer(containerEl, indexObj, draggedEl2) {
  containerEl.dispatchEvent(
    new CustomEvent(DRAGGED_ENTERED_EVENT_NAME, {
      detail: { indexObj, draggedEl: draggedEl2 }
    })
  );
}
__name(dispatchDraggedElementEnteredContainer, "dispatchDraggedElementEnteredContainer");
function dispatchDraggedElementLeftContainerForAnother(containerEl, draggedEl2, theOtherDz) {
  containerEl.dispatchEvent(
    new CustomEvent(DRAGGED_LEFT_EVENT_NAME, {
      detail: { draggedEl: draggedEl2, type: DRAGGED_LEFT_TYPES.LEFT_FOR_ANOTHER, theOtherDz }
    })
  );
}
__name(dispatchDraggedElementLeftContainerForAnother, "dispatchDraggedElementLeftContainerForAnother");
function dispatchDraggedElementLeftContainerForNone(containerEl, draggedEl2) {
  containerEl.dispatchEvent(
    new CustomEvent(DRAGGED_LEFT_EVENT_NAME, {
      detail: { draggedEl: draggedEl2, type: DRAGGED_LEFT_TYPES.OUTSIDE_OF_ANY }
    })
  );
}
__name(dispatchDraggedElementLeftContainerForNone, "dispatchDraggedElementLeftContainerForNone");
function dispatchDraggedElementIsOverIndex(containerEl, indexObj, draggedEl2) {
  containerEl.dispatchEvent(
    new CustomEvent(DRAGGED_OVER_INDEX_EVENT_NAME, {
      detail: { indexObj, draggedEl: draggedEl2 }
    })
  );
}
__name(dispatchDraggedElementIsOverIndex, "dispatchDraggedElementIsOverIndex");
function dispatchDraggedLeftDocument(draggedEl2) {
  window.dispatchEvent(
    new CustomEvent(DRAGGED_LEFT_DOCUMENT_EVENT_NAME, {
      detail: { draggedEl: draggedEl2 }
    })
  );
}
__name(dispatchDraggedLeftDocument, "dispatchDraggedLeftDocument");
const TRIGGERS = {
  DRAG_STARTED: "dragStarted",
  DRAGGED_ENTERED: DRAGGED_ENTERED_EVENT_NAME,
  DRAGGED_ENTERED_ANOTHER: "dragEnteredAnother",
  DRAGGED_OVER_INDEX: DRAGGED_OVER_INDEX_EVENT_NAME,
  DRAGGED_LEFT: DRAGGED_LEFT_EVENT_NAME,
  DRAGGED_LEFT_ALL: "draggedLeftAll",
  DROPPED_INTO_ZONE: "droppedIntoZone",
  DROPPED_INTO_ANOTHER: "droppedIntoAnother",
  DROPPED_OUTSIDE_OF_ANY: "droppedOutsideOfAny",
  DRAG_STOPPED: "dragStopped"
};
const SOURCES = {
  POINTER: "pointer",
  KEYBOARD: "keyboard"
};
const SHADOW_ITEM_MARKER_PROPERTY_NAME = "isDndShadowItem";
const SHADOW_ELEMENT_ATTRIBUTE_NAME = "data-is-dnd-shadow-item-internal";
const SHADOW_ELEMENT_HINT_ATTRIBUTE_NAME = "data-is-dnd-shadow-item-hint";
const SHADOW_PLACEHOLDER_ITEM_ID = "id:dnd-shadow-placeholder-0000";
const DRAGGED_ELEMENT_ID = "dnd-action-dragged-el";
let ITEM_ID_KEY = "id";
let activeDndZoneCount = 0;
function incrementActiveDropZoneCount() {
  activeDndZoneCount++;
}
__name(incrementActiveDropZoneCount, "incrementActiveDropZoneCount");
function decrementActiveDropZoneCount() {
  if (activeDndZoneCount === 0) {
    throw new Error("Bug! trying to decrement when there are no dropzones");
  }
  activeDndZoneCount--;
}
__name(decrementActiveDropZoneCount, "decrementActiveDropZoneCount");
const isOnServer = typeof window === "undefined";
function getBoundingRectNoTransforms(el) {
  let ta;
  const rect = el.getBoundingClientRect();
  const style = getComputedStyle(el);
  const tx = style.transform;
  if (tx) {
    let sx, sy, dx, dy;
    if (tx.startsWith("matrix3d(")) {
      ta = tx.slice(9, -1).split(/, /);
      sx = +ta[0];
      sy = +ta[5];
      dx = +ta[12];
      dy = +ta[13];
    } else if (tx.startsWith("matrix(")) {
      ta = tx.slice(7, -1).split(/, /);
      sx = +ta[0];
      sy = +ta[3];
      dx = +ta[4];
      dy = +ta[5];
    } else {
      return rect;
    }
    const to = style.transformOrigin;
    const x = rect.x - dx - (1 - sx) * parseFloat(to);
    const y = rect.y - dy - (1 - sy) * parseFloat(to.slice(to.indexOf(" ") + 1));
    const w = sx ? rect.width / sx : el.offsetWidth;
    const h = sy ? rect.height / sy : el.offsetHeight;
    return {
      x,
      y,
      width: w,
      height: h,
      top: y,
      right: x + w,
      bottom: y + h,
      left: x
    };
  } else {
    return rect;
  }
}
__name(getBoundingRectNoTransforms, "getBoundingRectNoTransforms");
function getAbsoluteRectNoTransforms(el) {
  const rect = getBoundingRectNoTransforms(el);
  return {
    top: rect.top + window.scrollY,
    bottom: rect.bottom + window.scrollY,
    left: rect.left + window.scrollX,
    right: rect.right + window.scrollX
  };
}
__name(getAbsoluteRectNoTransforms, "getAbsoluteRectNoTransforms");
function getAbsoluteRect(el) {
  const rect = el.getBoundingClientRect();
  return {
    top: rect.top + window.scrollY,
    bottom: rect.bottom + window.scrollY,
    left: rect.left + window.scrollX,
    right: rect.right + window.scrollX
  };
}
__name(getAbsoluteRect, "getAbsoluteRect");
function findCenter(rect) {
  return {
    x: (rect.left + rect.right) / 2,
    y: (rect.top + rect.bottom) / 2
  };
}
__name(findCenter, "findCenter");
function calcDistance(pointA, pointB) {
  return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
}
__name(calcDistance, "calcDistance");
function isPointInsideRect(point, rect) {
  return point.y <= rect.bottom && point.y >= rect.top && point.x >= rect.left && point.x <= rect.right;
}
__name(isPointInsideRect, "isPointInsideRect");
function findCenterOfElement(el) {
  return findCenter(getAbsoluteRect(el));
}
__name(findCenterOfElement, "findCenterOfElement");
function isCenterOfAInsideB(elA, elB) {
  const centerOfA = findCenterOfElement(elA);
  const rectOfB = getAbsoluteRectNoTransforms(elB);
  return isPointInsideRect(centerOfA, rectOfB);
}
__name(isCenterOfAInsideB, "isCenterOfAInsideB");
function calcDistanceBetweenCenters(elA, elB) {
  const centerOfA = findCenterOfElement(elA);
  const centerOfB = findCenterOfElement(elB);
  return calcDistance(centerOfA, centerOfB);
}
__name(calcDistanceBetweenCenters, "calcDistanceBetweenCenters");
function isElementOffDocument(el) {
  const rect = getAbsoluteRect(el);
  return rect.right < 0 || rect.left > document.documentElement.scrollWidth || rect.bottom < 0 || rect.top > document.documentElement.scrollHeight;
}
__name(isElementOffDocument, "isElementOffDocument");
function calcInnerDistancesBetweenPointAndSidesOfElement(point, el) {
  const rect = getAbsoluteRect(el);
  if (!isPointInsideRect(point, rect)) {
    return null;
  }
  return {
    top: point.y - rect.top,
    bottom: rect.bottom - point.y,
    left: point.x - rect.left,
    // TODO - figure out what is so special about right (why the rect is too big)
    right: Math.min(rect.right, document.documentElement.clientWidth) - point.x
  };
}
__name(calcInnerDistancesBetweenPointAndSidesOfElement, "calcInnerDistancesBetweenPointAndSidesOfElement");
let dzToShadowIndexToRect;
function resetIndexesCache() {
  dzToShadowIndexToRect = /* @__PURE__ */ new Map();
}
__name(resetIndexesCache, "resetIndexesCache");
resetIndexesCache();
function resetIndexesCacheForDz(dz) {
  dzToShadowIndexToRect.delete(dz);
}
__name(resetIndexesCacheForDz, "resetIndexesCacheForDz");
function cacheShadowRect(dz) {
  const shadowElIndex = Array.from(dz.children).findIndex((child) => child.getAttribute(SHADOW_ELEMENT_ATTRIBUTE_NAME));
  if (shadowElIndex >= 0) {
    if (!dzToShadowIndexToRect.has(dz)) {
      dzToShadowIndexToRect.set(dz, /* @__PURE__ */ new Map());
    }
    dzToShadowIndexToRect.get(dz).set(shadowElIndex, getAbsoluteRectNoTransforms(dz.children[shadowElIndex]));
    return shadowElIndex;
  }
  return void 0;
}
__name(cacheShadowRect, "cacheShadowRect");
function findWouldBeIndex(floatingAboveEl, collectionBelowEl) {
  if (!isCenterOfAInsideB(floatingAboveEl, collectionBelowEl)) {
    return null;
  }
  const children2 = collectionBelowEl.children;
  if (children2.length === 0) {
    return { index: 0, isProximityBased: true };
  }
  const shadowElIndex = cacheShadowRect(collectionBelowEl);
  for (let i = 0; i < children2.length; i++) {
    if (isCenterOfAInsideB(floatingAboveEl, children2[i])) {
      const cachedShadowRect = dzToShadowIndexToRect.has(collectionBelowEl) && dzToShadowIndexToRect.get(collectionBelowEl).get(i);
      if (cachedShadowRect) {
        if (!isPointInsideRect(findCenterOfElement(floatingAboveEl), cachedShadowRect)) {
          return { index: shadowElIndex, isProximityBased: false };
        }
      }
      return { index: i, isProximityBased: false };
    }
  }
  let minDistanceSoFar = Number.MAX_VALUE;
  let indexOfMin = void 0;
  for (let i = 0; i < children2.length; i++) {
    const distance = calcDistanceBetweenCenters(floatingAboveEl, children2[i]);
    if (distance < minDistanceSoFar) {
      minDistanceSoFar = distance;
      indexOfMin = i;
    }
  }
  return { index: indexOfMin, isProximityBased: true };
}
__name(findWouldBeIndex, "findWouldBeIndex");
const SCROLL_ZONE_PX = 25;
function makeScroller() {
  let scrollingInfo;
  function resetScrolling2() {
    scrollingInfo = { directionObj: void 0, stepPx: 0 };
  }
  __name(resetScrolling2, "resetScrolling");
  resetScrolling2();
  function scrollContainer(containerEl) {
    const { directionObj, stepPx } = scrollingInfo;
    if (directionObj) {
      containerEl.scrollBy(directionObj.x * stepPx, directionObj.y * stepPx);
      window.requestAnimationFrame(() => scrollContainer(containerEl));
    }
  }
  __name(scrollContainer, "scrollContainer");
  function calcScrollStepPx(distancePx) {
    return SCROLL_ZONE_PX - distancePx;
  }
  __name(calcScrollStepPx, "calcScrollStepPx");
  function scrollIfNeeded2(pointer, elementToScroll) {
    if (!elementToScroll) {
      return false;
    }
    const distances = calcInnerDistancesBetweenPointAndSidesOfElement(pointer, elementToScroll);
    if (distances === null) {
      resetScrolling2();
      return false;
    }
    const isAlreadyScrolling = !!scrollingInfo.directionObj;
    let [scrollingVertically, scrollingHorizontally] = [false, false];
    if (elementToScroll.scrollHeight > elementToScroll.clientHeight) {
      if (distances.bottom < SCROLL_ZONE_PX) {
        scrollingVertically = true;
        scrollingInfo.directionObj = { x: 0, y: 1 };
        scrollingInfo.stepPx = calcScrollStepPx(distances.bottom);
      } else if (distances.top < SCROLL_ZONE_PX) {
        scrollingVertically = true;
        scrollingInfo.directionObj = { x: 0, y: -1 };
        scrollingInfo.stepPx = calcScrollStepPx(distances.top);
      }
      if (!isAlreadyScrolling && scrollingVertically) {
        scrollContainer(elementToScroll);
        return true;
      }
    }
    if (elementToScroll.scrollWidth > elementToScroll.clientWidth) {
      if (distances.right < SCROLL_ZONE_PX) {
        scrollingHorizontally = true;
        scrollingInfo.directionObj = { x: 1, y: 0 };
        scrollingInfo.stepPx = calcScrollStepPx(distances.right);
      } else if (distances.left < SCROLL_ZONE_PX) {
        scrollingHorizontally = true;
        scrollingInfo.directionObj = { x: -1, y: 0 };
        scrollingInfo.stepPx = calcScrollStepPx(distances.left);
      }
      if (!isAlreadyScrolling && scrollingHorizontally) {
        scrollContainer(elementToScroll);
        return true;
      }
    }
    resetScrolling2();
    return false;
  }
  __name(scrollIfNeeded2, "scrollIfNeeded");
  return {
    scrollIfNeeded: scrollIfNeeded2,
    resetScrolling: resetScrolling2
  };
}
__name(makeScroller, "makeScroller");
function toString(object) {
  return JSON.stringify(object, null, 2);
}
__name(toString, "toString");
function getDepth(node) {
  if (!node) {
    throw new Error("cannot get depth of a falsy node");
  }
  return _getDepth(node, 0);
}
__name(getDepth, "getDepth");
function _getDepth(node, countSoFar = 0) {
  if (!node.parentElement) {
    return countSoFar - 1;
  }
  return _getDepth(node.parentElement, countSoFar + 1);
}
__name(_getDepth, "_getDepth");
function areObjectsShallowEqual(objA, objB) {
  if (Object.keys(objA).length !== Object.keys(objB).length) {
    return false;
  }
  for (const keyA in objA) {
    if (!{}.hasOwnProperty.call(objB, keyA) || objB[keyA] !== objA[keyA]) {
      return false;
    }
  }
  return true;
}
__name(areObjectsShallowEqual, "areObjectsShallowEqual");
function areArraysShallowEqualSameOrder(arrA, arrB) {
  if (arrA.length !== arrB.length) {
    return false;
  }
  for (let i = 0; i < arrA.length; i++) {
    if (arrA[i] !== arrB[i]) {
      return false;
    }
  }
  return true;
}
__name(areArraysShallowEqualSameOrder, "areArraysShallowEqualSameOrder");
const INTERVAL_MS$1 = 200;
const TOLERANCE_PX = 10;
const { scrollIfNeeded: scrollIfNeeded$1, resetScrolling: resetScrolling$1 } = makeScroller();
let next$1;
function observe(draggedEl2, dropZones, intervalMs = INTERVAL_MS$1) {
  let lastDropZoneFound;
  let lastIndexFound;
  let lastIsDraggedInADropZone = false;
  let lastCentrePositionOfDragged;
  const dropZonesFromDeepToShallow = Array.from(dropZones).sort((dz1, dz2) => getDepth(dz2) - getDepth(dz1));
  function andNow() {
    const currentCenterOfDragged = findCenterOfElement(draggedEl2);
    const scrolled = scrollIfNeeded$1(currentCenterOfDragged, lastDropZoneFound);
    if (!scrolled && lastCentrePositionOfDragged && Math.abs(lastCentrePositionOfDragged.x - currentCenterOfDragged.x) < TOLERANCE_PX && Math.abs(lastCentrePositionOfDragged.y - currentCenterOfDragged.y) < TOLERANCE_PX) {
      next$1 = window.setTimeout(andNow, intervalMs);
      return;
    }
    if (isElementOffDocument(draggedEl2)) {
      dispatchDraggedLeftDocument(draggedEl2);
      return;
    }
    lastCentrePositionOfDragged = currentCenterOfDragged;
    let isDraggedInADropZone = false;
    for (const dz of dropZonesFromDeepToShallow) {
      if (scrolled)
        resetIndexesCacheForDz(lastDropZoneFound);
      const indexObj = findWouldBeIndex(draggedEl2, dz);
      if (indexObj === null) {
        continue;
      }
      const { index: index2 } = indexObj;
      isDraggedInADropZone = true;
      if (dz !== lastDropZoneFound) {
        lastDropZoneFound && dispatchDraggedElementLeftContainerForAnother(lastDropZoneFound, draggedEl2, dz);
        dispatchDraggedElementEnteredContainer(dz, indexObj, draggedEl2);
        lastDropZoneFound = dz;
      } else if (index2 !== lastIndexFound) {
        dispatchDraggedElementIsOverIndex(dz, indexObj, draggedEl2);
        lastIndexFound = index2;
      }
      break;
    }
    if (!isDraggedInADropZone && lastIsDraggedInADropZone && lastDropZoneFound) {
      dispatchDraggedElementLeftContainerForNone(lastDropZoneFound, draggedEl2);
      lastDropZoneFound = void 0;
      lastIndexFound = void 0;
      lastIsDraggedInADropZone = false;
    } else {
      lastIsDraggedInADropZone = true;
    }
    next$1 = window.setTimeout(andNow, intervalMs);
  }
  __name(andNow, "andNow");
  andNow();
}
__name(observe, "observe");
function unobserve() {
  clearTimeout(next$1);
  resetScrolling$1();
  resetIndexesCache();
}
__name(unobserve, "unobserve");
const INTERVAL_MS = 300;
let mousePosition;
function updateMousePosition(e) {
  const c = e.touches ? e.touches[0] : e;
  mousePosition = { x: c.clientX, y: c.clientY };
}
__name(updateMousePosition, "updateMousePosition");
const { scrollIfNeeded, resetScrolling } = makeScroller();
let next;
function loop() {
  if (mousePosition) {
    const scrolled = scrollIfNeeded(mousePosition, document.documentElement);
    if (scrolled)
      resetIndexesCache();
  }
  next = window.setTimeout(loop, INTERVAL_MS);
}
__name(loop, "loop");
function armWindowScroller() {
  window.addEventListener("mousemove", updateMousePosition);
  window.addEventListener("touchmove", updateMousePosition);
  loop();
}
__name(armWindowScroller, "armWindowScroller");
function disarmWindowScroller() {
  window.removeEventListener("mousemove", updateMousePosition);
  window.removeEventListener("touchmove", updateMousePosition);
  mousePosition = void 0;
  window.clearTimeout(next);
  resetScrolling();
}
__name(disarmWindowScroller, "disarmWindowScroller");
function svelteNodeClone(el) {
  const cloned = el.cloneNode(true);
  const values = [];
  const elIsSelect = el.tagName === "SELECT";
  const selects = elIsSelect ? [el] : [...el.querySelectorAll("select")];
  for (const select of selects) {
    values.push(select.value);
  }
  if (selects.length <= 0) {
    return cloned;
  }
  const clonedSelects = elIsSelect ? [cloned] : [...cloned.querySelectorAll("select")];
  for (let i = 0; i < clonedSelects.length; i++) {
    const select = clonedSelects[i];
    const value = values[i];
    const optionEl = select.querySelector(`option[value="${value}"`);
    if (optionEl) {
      optionEl.setAttribute("selected", true);
    }
  }
  return cloned;
}
__name(svelteNodeClone, "svelteNodeClone");
const FEATURE_FLAG_NAMES = Object.freeze({
  // This flag exists as a workaround for issue 454 (basically a browser bug) - seems like these rect values take time to update when in grid layout. Setting it to true can cause strange behaviour in the REPL for non-grid zones, see issue 470
  USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT: "USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT"
});
const featureFlagsMap = {
  [FEATURE_FLAG_NAMES.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT]: false
};
function getFeatureFlag(flagName) {
  if (!FEATURE_FLAG_NAMES[flagName])
    throw new Error(`Can't get non existing feature flag ${flagName}! Supported flags: ${Object.keys(FEATURE_FLAG_NAMES)}`);
  return featureFlagsMap[flagName];
}
__name(getFeatureFlag, "getFeatureFlag");
const TRANSITION_DURATION_SECONDS = 0.2;
function trs(property) {
  return `${property} ${TRANSITION_DURATION_SECONDS}s ease`;
}
__name(trs, "trs");
function createDraggedElementFrom(originalElement, positionCenterOnXY) {
  const rect = originalElement.getBoundingClientRect();
  const draggedEl2 = svelteNodeClone(originalElement);
  copyStylesFromTo(originalElement, draggedEl2);
  draggedEl2.id = DRAGGED_ELEMENT_ID;
  draggedEl2.style.position = "fixed";
  let elTopPx = rect.top;
  let elLeftPx = rect.left;
  draggedEl2.style.top = `${elTopPx}px`;
  draggedEl2.style.left = `${elLeftPx}px`;
  if (positionCenterOnXY) {
    const center = findCenter(rect);
    elTopPx -= center.y - positionCenterOnXY.y;
    elLeftPx -= center.x - positionCenterOnXY.x;
    window.setTimeout(() => {
      draggedEl2.style.top = `${elTopPx}px`;
      draggedEl2.style.left = `${elLeftPx}px`;
    }, 0);
  }
  draggedEl2.style.margin = "0";
  draggedEl2.style.boxSizing = "border-box";
  draggedEl2.style.height = `${rect.height}px`;
  draggedEl2.style.width = `${rect.width}px`;
  draggedEl2.style.transition = `${trs("top")}, ${trs("left")}, ${trs("background-color")}, ${trs("opacity")}, ${trs("color")} `;
  window.setTimeout(() => draggedEl2.style.transition += `, ${trs("width")}, ${trs("height")}`, 0);
  draggedEl2.style.zIndex = "9999";
  draggedEl2.style.cursor = "grabbing";
  return draggedEl2;
}
__name(createDraggedElementFrom, "createDraggedElementFrom");
function moveDraggedElementToWasDroppedState(draggedEl2) {
  draggedEl2.style.cursor = "grab";
}
__name(moveDraggedElementToWasDroppedState, "moveDraggedElementToWasDroppedState");
function morphDraggedElementToBeLike(draggedEl2, copyFromEl, currentMouseX, currentMouseY) {
  copyStylesFromTo(copyFromEl, draggedEl2);
  const newRect = copyFromEl.getBoundingClientRect();
  const draggedElRect = draggedEl2.getBoundingClientRect();
  const widthChange = newRect.width - draggedElRect.width;
  const heightChange = newRect.height - draggedElRect.height;
  if (widthChange || heightChange) {
    const relativeDistanceOfMousePointerFromDraggedSides = {
      left: (currentMouseX - draggedElRect.left) / draggedElRect.width,
      top: (currentMouseY - draggedElRect.top) / draggedElRect.height
    };
    if (!getFeatureFlag(FEATURE_FLAG_NAMES.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT)) {
      draggedEl2.style.height = `${newRect.height}px`;
      draggedEl2.style.width = `${newRect.width}px`;
    }
    draggedEl2.style.left = `${parseFloat(draggedEl2.style.left) - relativeDistanceOfMousePointerFromDraggedSides.left * widthChange}px`;
    draggedEl2.style.top = `${parseFloat(draggedEl2.style.top) - relativeDistanceOfMousePointerFromDraggedSides.top * heightChange}px`;
  }
}
__name(morphDraggedElementToBeLike, "morphDraggedElementToBeLike");
function copyStylesFromTo(copyFromEl, copyToEl) {
  const computedStyle = window.getComputedStyle(copyFromEl);
  Array.from(computedStyle).filter(
    (s) => s.startsWith("background") || s.startsWith("padding") || s.startsWith("font") || s.startsWith("text") || s.startsWith("align") || s.startsWith("justify") || s.startsWith("display") || s.startsWith("flex") || s.startsWith("border") || s === "opacity" || s === "color" || s === "list-style-type" || // copying with and height to make up for rect update timing issues in some browsers
    getFeatureFlag(FEATURE_FLAG_NAMES.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT) && (s === "width" || s === "height")
  ).forEach((s) => copyToEl.style.setProperty(s, computedStyle.getPropertyValue(s), computedStyle.getPropertyPriority(s)));
}
__name(copyStylesFromTo, "copyStylesFromTo");
function styleDraggable(draggableEl, dragDisabled) {
  draggableEl.draggable = false;
  draggableEl.ondragstart = () => false;
  if (!dragDisabled) {
    draggableEl.style.userSelect = "none";
    draggableEl.style.WebkitUserSelect = "none";
    draggableEl.style.cursor = "grab";
  } else {
    draggableEl.style.userSelect = "";
    draggableEl.style.WebkitUserSelect = "";
    draggableEl.style.cursor = "";
  }
}
__name(styleDraggable, "styleDraggable");
function hideElement(dragTarget) {
  dragTarget.style.display = "none";
  dragTarget.style.position = "fixed";
  dragTarget.style.zIndex = "-5";
}
__name(hideElement, "hideElement");
function decorateShadowEl(shadowEl) {
  shadowEl.style.visibility = "hidden";
  shadowEl.setAttribute(SHADOW_ELEMENT_ATTRIBUTE_NAME, "true");
}
__name(decorateShadowEl, "decorateShadowEl");
function unDecorateShadowElement(shadowEl) {
  shadowEl.style.visibility = "";
  shadowEl.removeAttribute(SHADOW_ELEMENT_ATTRIBUTE_NAME);
}
__name(unDecorateShadowElement, "unDecorateShadowElement");
function styleActiveDropZones(dropZones, getStyles = () => {
}, getClasses = () => []) {
  dropZones.forEach((dz) => {
    const styles2 = getStyles(dz);
    Object.keys(styles2).forEach((style) => {
      dz.style[style] = styles2[style];
    });
    getClasses(dz).forEach((c) => dz.classList.add(c));
  });
}
__name(styleActiveDropZones, "styleActiveDropZones");
function styleInactiveDropZones(dropZones, getStyles = () => {
}, getClasses = () => []) {
  dropZones.forEach((dz) => {
    const styles2 = getStyles(dz);
    Object.keys(styles2).forEach((style) => {
      dz.style[style] = "";
    });
    getClasses(dz).forEach((c) => dz.classList.contains(c) && dz.classList.remove(c));
  });
}
__name(styleInactiveDropZones, "styleInactiveDropZones");
function preventShrinking(el) {
  const originalMinHeight = el.style.minHeight;
  el.style.minHeight = window.getComputedStyle(el).getPropertyValue("height");
  const originalMinWidth = el.style.minWidth;
  el.style.minWidth = window.getComputedStyle(el).getPropertyValue("width");
  return /* @__PURE__ */ __name(function undo() {
    el.style.minHeight = originalMinHeight;
    el.style.minWidth = originalMinWidth;
  }, "undo");
}
__name(preventShrinking, "preventShrinking");
const DEFAULT_DROP_ZONE_TYPE$1 = "--any--";
const MIN_OBSERVATION_INTERVAL_MS = 100;
const DISABLED_OBSERVATION_INTERVAL_MS = 20;
const MIN_MOVEMENT_BEFORE_DRAG_START_PX = 3;
const DEFAULT_DROP_TARGET_STYLE$1 = {
  outline: "rgba(255, 255, 102, 0.7) solid 2px"
};
const ORIGINAL_DRAGGED_ITEM_MARKER_ATTRIBUTE = "data-is-dnd-original-dragged-item";
let originalDragTarget;
let draggedEl;
let draggedElData;
let draggedElType;
let originDropZone;
let originIndex;
let shadowElData;
let shadowElDropZone;
let dragStartMousePosition;
let currentMousePosition;
let isWorkingOnPreviousDrag = false;
let finalizingPreviousDrag = false;
let unlockOriginDzMinDimensions;
let isDraggedOutsideOfAnyDz = false;
let scheduledForRemovalAfterDrop = [];
const typeToDropZones$1 = /* @__PURE__ */ new Map();
const dzToConfig$1 = /* @__PURE__ */ new Map();
const elToMouseDownListener = /* @__PURE__ */ new WeakMap();
function registerDropZone$1(dropZoneEl, type) {
  if (!typeToDropZones$1.has(type)) {
    typeToDropZones$1.set(type, /* @__PURE__ */ new Set());
  }
  if (!typeToDropZones$1.get(type).has(dropZoneEl)) {
    typeToDropZones$1.get(type).add(dropZoneEl);
    incrementActiveDropZoneCount();
  }
}
__name(registerDropZone$1, "registerDropZone$1");
function unregisterDropZone$1(dropZoneEl, type) {
  typeToDropZones$1.get(type).delete(dropZoneEl);
  decrementActiveDropZoneCount();
  if (typeToDropZones$1.get(type).size === 0) {
    typeToDropZones$1.delete(type);
  }
}
__name(unregisterDropZone$1, "unregisterDropZone$1");
function watchDraggedElement() {
  armWindowScroller();
  const dropZones = typeToDropZones$1.get(draggedElType);
  for (const dz of dropZones) {
    dz.addEventListener(DRAGGED_ENTERED_EVENT_NAME, handleDraggedEntered);
    dz.addEventListener(DRAGGED_LEFT_EVENT_NAME, handleDraggedLeft);
    dz.addEventListener(DRAGGED_OVER_INDEX_EVENT_NAME, handleDraggedIsOverIndex);
  }
  window.addEventListener(DRAGGED_LEFT_DOCUMENT_EVENT_NAME, handleDrop$1);
  const setIntervalMs = Math.max(...Array.from(dropZones.keys()).map((dz) => dzToConfig$1.get(dz).dropAnimationDurationMs));
  const observationIntervalMs = setIntervalMs === 0 ? DISABLED_OBSERVATION_INTERVAL_MS : Math.max(setIntervalMs, MIN_OBSERVATION_INTERVAL_MS);
  observe(draggedEl, dropZones, observationIntervalMs * 1.07);
}
__name(watchDraggedElement, "watchDraggedElement");
function unWatchDraggedElement() {
  disarmWindowScroller();
  const dropZones = typeToDropZones$1.get(draggedElType);
  for (const dz of dropZones) {
    dz.removeEventListener(DRAGGED_ENTERED_EVENT_NAME, handleDraggedEntered);
    dz.removeEventListener(DRAGGED_LEFT_EVENT_NAME, handleDraggedLeft);
    dz.removeEventListener(DRAGGED_OVER_INDEX_EVENT_NAME, handleDraggedIsOverIndex);
  }
  window.removeEventListener(DRAGGED_LEFT_DOCUMENT_EVENT_NAME, handleDrop$1);
  unobserve();
}
__name(unWatchDraggedElement, "unWatchDraggedElement");
function findShadowElementIdx(items) {
  return items.findIndex((item) => !!item[SHADOW_ITEM_MARKER_PROPERTY_NAME]);
}
__name(findShadowElementIdx, "findShadowElementIdx");
function handleDraggedEntered(e) {
  let { items, dropFromOthersDisabled } = dzToConfig$1.get(e.currentTarget);
  if (dropFromOthersDisabled && e.currentTarget !== originDropZone) {
    return;
  }
  isDraggedOutsideOfAnyDz = false;
  items = items.filter((item) => item[ITEM_ID_KEY] !== shadowElData[ITEM_ID_KEY]);
  if (originDropZone !== e.currentTarget) {
    const originZoneItems = dzToConfig$1.get(originDropZone).items;
    const newOriginZoneItems = originZoneItems.filter((item) => !item[SHADOW_ITEM_MARKER_PROPERTY_NAME]);
    dispatchConsiderEvent(originDropZone, newOriginZoneItems, {
      trigger: TRIGGERS.DRAGGED_ENTERED_ANOTHER,
      id: draggedElData[ITEM_ID_KEY],
      source: SOURCES.POINTER
    });
  }
  const { index: index2, isProximityBased } = e.detail.indexObj;
  const shadowElIdx = isProximityBased && index2 === e.currentTarget.children.length - 1 ? index2 + 1 : index2;
  shadowElDropZone = e.currentTarget;
  items.splice(shadowElIdx, 0, shadowElData);
  dispatchConsiderEvent(e.currentTarget, items, { trigger: TRIGGERS.DRAGGED_ENTERED, id: draggedElData[ITEM_ID_KEY], source: SOURCES.POINTER });
}
__name(handleDraggedEntered, "handleDraggedEntered");
function handleDraggedLeft(e) {
  if (!isWorkingOnPreviousDrag)
    return;
  const { items, dropFromOthersDisabled } = dzToConfig$1.get(e.currentTarget);
  if (dropFromOthersDisabled && e.currentTarget !== originDropZone && e.currentTarget !== shadowElDropZone) {
    return;
  }
  const shadowElIdx = findShadowElementIdx(items);
  const shadowItem = items.splice(shadowElIdx, 1)[0];
  shadowElDropZone = void 0;
  const { type, theOtherDz } = e.detail;
  if (type === DRAGGED_LEFT_TYPES.OUTSIDE_OF_ANY || type === DRAGGED_LEFT_TYPES.LEFT_FOR_ANOTHER && theOtherDz !== originDropZone && dzToConfig$1.get(theOtherDz).dropFromOthersDisabled) {
    isDraggedOutsideOfAnyDz = true;
    shadowElDropZone = originDropZone;
    const originZoneItems = dzToConfig$1.get(originDropZone).items;
    originZoneItems.splice(originIndex, 0, shadowItem);
    dispatchConsiderEvent(originDropZone, originZoneItems, {
      trigger: TRIGGERS.DRAGGED_LEFT_ALL,
      id: draggedElData[ITEM_ID_KEY],
      source: SOURCES.POINTER
    });
  }
  dispatchConsiderEvent(e.currentTarget, items, {
    trigger: TRIGGERS.DRAGGED_LEFT,
    id: draggedElData[ITEM_ID_KEY],
    source: SOURCES.POINTER
  });
}
__name(handleDraggedLeft, "handleDraggedLeft");
function handleDraggedIsOverIndex(e) {
  const { items, dropFromOthersDisabled } = dzToConfig$1.get(e.currentTarget);
  if (dropFromOthersDisabled && e.currentTarget !== originDropZone) {
    return;
  }
  isDraggedOutsideOfAnyDz = false;
  const { index: index2 } = e.detail.indexObj;
  const shadowElIdx = findShadowElementIdx(items);
  items.splice(shadowElIdx, 1);
  items.splice(index2, 0, shadowElData);
  dispatchConsiderEvent(e.currentTarget, items, { trigger: TRIGGERS.DRAGGED_OVER_INDEX, id: draggedElData[ITEM_ID_KEY], source: SOURCES.POINTER });
}
__name(handleDraggedIsOverIndex, "handleDraggedIsOverIndex");
function handleMouseMove(e) {
  e.preventDefault();
  const c = e.touches ? e.touches[0] : e;
  currentMousePosition = { x: c.clientX, y: c.clientY };
  draggedEl.style.transform = `translate3d(${currentMousePosition.x - dragStartMousePosition.x}px, ${currentMousePosition.y - dragStartMousePosition.y}px, 0)`;
}
__name(handleMouseMove, "handleMouseMove");
function handleDrop$1() {
  finalizingPreviousDrag = true;
  window.removeEventListener("mousemove", handleMouseMove);
  window.removeEventListener("touchmove", handleMouseMove);
  window.removeEventListener("mouseup", handleDrop$1);
  window.removeEventListener("touchend", handleDrop$1);
  unWatchDraggedElement();
  moveDraggedElementToWasDroppedState(draggedEl);
  if (!shadowElDropZone) {
    shadowElDropZone = originDropZone;
  }
  let { items, type } = dzToConfig$1.get(shadowElDropZone);
  styleInactiveDropZones(
    typeToDropZones$1.get(type),
    (dz) => dzToConfig$1.get(dz).dropTargetStyle,
    (dz) => dzToConfig$1.get(dz).dropTargetClasses
  );
  let shadowElIdx = findShadowElementIdx(items);
  if (shadowElIdx === -1)
    shadowElIdx = originIndex;
  items = items.map((item) => item[SHADOW_ITEM_MARKER_PROPERTY_NAME] ? draggedElData : item);
  function finalizeWithinZone() {
    unlockOriginDzMinDimensions();
    dispatchFinalizeEvent(shadowElDropZone, items, {
      trigger: isDraggedOutsideOfAnyDz ? TRIGGERS.DROPPED_OUTSIDE_OF_ANY : TRIGGERS.DROPPED_INTO_ZONE,
      id: draggedElData[ITEM_ID_KEY],
      source: SOURCES.POINTER
    });
    if (shadowElDropZone !== originDropZone) {
      dispatchFinalizeEvent(originDropZone, dzToConfig$1.get(originDropZone).items, {
        trigger: TRIGGERS.DROPPED_INTO_ANOTHER,
        id: draggedElData[ITEM_ID_KEY],
        source: SOURCES.POINTER
      });
    }
    unDecorateShadowElement(shadowElDropZone.children[shadowElIdx]);
    cleanupPostDrop();
  }
  __name(finalizeWithinZone, "finalizeWithinZone");
  animateDraggedToFinalPosition(shadowElIdx, finalizeWithinZone);
}
__name(handleDrop$1, "handleDrop$1");
function animateDraggedToFinalPosition(shadowElIdx, callback) {
  const shadowElRect = getBoundingRectNoTransforms(shadowElDropZone.children[shadowElIdx]);
  const newTransform = {
    x: shadowElRect.left - parseFloat(draggedEl.style.left),
    y: shadowElRect.top - parseFloat(draggedEl.style.top)
  };
  const { dropAnimationDurationMs } = dzToConfig$1.get(shadowElDropZone);
  const transition = `transform ${dropAnimationDurationMs}ms ease`;
  draggedEl.style.transition = draggedEl.style.transition ? draggedEl.style.transition + "," + transition : transition;
  draggedEl.style.transform = `translate3d(${newTransform.x}px, ${newTransform.y}px, 0)`;
  window.setTimeout(callback, dropAnimationDurationMs);
}
__name(animateDraggedToFinalPosition, "animateDraggedToFinalPosition");
function scheduleDZForRemovalAfterDrop(dz, destroy) {
  scheduledForRemovalAfterDrop.push({ dz, destroy });
  window.requestAnimationFrame(() => {
    hideElement(dz);
    document.body.appendChild(dz);
  });
}
__name(scheduleDZForRemovalAfterDrop, "scheduleDZForRemovalAfterDrop");
function cleanupPostDrop() {
  draggedEl.remove();
  originalDragTarget.remove();
  if (scheduledForRemovalAfterDrop.length) {
    scheduledForRemovalAfterDrop.forEach(({ dz, destroy }) => {
      destroy();
      dz.remove();
    });
    scheduledForRemovalAfterDrop = [];
  }
  draggedEl = void 0;
  originalDragTarget = void 0;
  draggedElData = void 0;
  draggedElType = void 0;
  originDropZone = void 0;
  originIndex = void 0;
  shadowElData = void 0;
  shadowElDropZone = void 0;
  dragStartMousePosition = void 0;
  currentMousePosition = void 0;
  isWorkingOnPreviousDrag = false;
  finalizingPreviousDrag = false;
  unlockOriginDzMinDimensions = void 0;
  isDraggedOutsideOfAnyDz = false;
}
__name(cleanupPostDrop, "cleanupPostDrop");
function dndzone$2(node, options) {
  let initialized = false;
  const config = {
    items: void 0,
    type: void 0,
    flipDurationMs: 0,
    dragDisabled: false,
    morphDisabled: false,
    dropFromOthersDisabled: false,
    dropTargetStyle: DEFAULT_DROP_TARGET_STYLE$1,
    dropTargetClasses: [],
    transformDraggedElement: () => {
    },
    centreDraggedOnCursor: false
  };
  let elToIdx = /* @__PURE__ */ new Map();
  function addMaybeListeners() {
    window.addEventListener("mousemove", handleMouseMoveMaybeDragStart, { passive: false });
    window.addEventListener("touchmove", handleMouseMoveMaybeDragStart, { passive: false, capture: false });
    window.addEventListener("mouseup", handleFalseAlarm, { passive: false });
    window.addEventListener("touchend", handleFalseAlarm, { passive: false });
  }
  __name(addMaybeListeners, "addMaybeListeners");
  function removeMaybeListeners() {
    window.removeEventListener("mousemove", handleMouseMoveMaybeDragStart);
    window.removeEventListener("touchmove", handleMouseMoveMaybeDragStart);
    window.removeEventListener("mouseup", handleFalseAlarm);
    window.removeEventListener("touchend", handleFalseAlarm);
  }
  __name(removeMaybeListeners, "removeMaybeListeners");
  function handleFalseAlarm() {
    removeMaybeListeners();
    originalDragTarget = void 0;
    dragStartMousePosition = void 0;
    currentMousePosition = void 0;
  }
  __name(handleFalseAlarm, "handleFalseAlarm");
  function handleMouseMoveMaybeDragStart(e) {
    e.preventDefault();
    const c = e.touches ? e.touches[0] : e;
    currentMousePosition = { x: c.clientX, y: c.clientY };
    if (Math.abs(currentMousePosition.x - dragStartMousePosition.x) >= MIN_MOVEMENT_BEFORE_DRAG_START_PX || Math.abs(currentMousePosition.y - dragStartMousePosition.y) >= MIN_MOVEMENT_BEFORE_DRAG_START_PX) {
      removeMaybeListeners();
      handleDragStart();
    }
  }
  __name(handleMouseMoveMaybeDragStart, "handleMouseMoveMaybeDragStart");
  function handleMouseDown(e) {
    if (e.target !== e.currentTarget && (e.target.value !== void 0 || e.target.isContentEditable)) {
      return;
    }
    if (e.button) {
      return;
    }
    if (isWorkingOnPreviousDrag) {
      return;
    }
    e.stopPropagation();
    const c = e.touches ? e.touches[0] : e;
    dragStartMousePosition = { x: c.clientX, y: c.clientY };
    currentMousePosition = { ...dragStartMousePosition };
    originalDragTarget = e.currentTarget;
    addMaybeListeners();
  }
  __name(handleMouseDown, "handleMouseDown");
  function handleDragStart() {
    isWorkingOnPreviousDrag = true;
    const currentIdx = elToIdx.get(originalDragTarget);
    originIndex = currentIdx;
    originDropZone = originalDragTarget.parentElement;
    const rootNode = originDropZone.getRootNode();
    const originDropZoneRoot = rootNode.body || rootNode;
    const { items, type, centreDraggedOnCursor } = config;
    draggedElData = { ...items[currentIdx] };
    draggedElType = type;
    shadowElData = { ...draggedElData, [SHADOW_ITEM_MARKER_PROPERTY_NAME]: true, [ITEM_ID_KEY]: SHADOW_PLACEHOLDER_ITEM_ID };
    draggedEl = createDraggedElementFrom(originalDragTarget, centreDraggedOnCursor && currentMousePosition);
    originalDragTarget.setAttribute(ORIGINAL_DRAGGED_ITEM_MARKER_ATTRIBUTE, true);
    function keepOriginalElementInDom() {
      if (!draggedEl.parentElement) {
        originDropZoneRoot.appendChild(draggedEl);
        draggedEl.focus();
        watchDraggedElement();
        hideElement(originalDragTarget);
        originDropZoneRoot.appendChild(originalDragTarget);
      } else {
        window.requestAnimationFrame(keepOriginalElementInDom);
      }
    }
    __name(keepOriginalElementInDom, "keepOriginalElementInDom");
    window.requestAnimationFrame(keepOriginalElementInDom);
    styleActiveDropZones(
      Array.from(typeToDropZones$1.get(config.type)).filter((dz) => dz === originDropZone || !dzToConfig$1.get(dz).dropFromOthersDisabled),
      (dz) => dzToConfig$1.get(dz).dropTargetStyle,
      (dz) => dzToConfig$1.get(dz).dropTargetClasses
    );
    items.splice(currentIdx, 1, shadowElData);
    unlockOriginDzMinDimensions = preventShrinking(originDropZone);
    dispatchConsiderEvent(originDropZone, items, { trigger: TRIGGERS.DRAG_STARTED, id: draggedElData[ITEM_ID_KEY], source: SOURCES.POINTER });
    window.addEventListener("mousemove", handleMouseMove, { passive: false });
    window.addEventListener("touchmove", handleMouseMove, { passive: false, capture: false });
    window.addEventListener("mouseup", handleDrop$1, { passive: false });
    window.addEventListener("touchend", handleDrop$1, { passive: false });
  }
  __name(handleDragStart, "handleDragStart");
  function configure({
    items = void 0,
    flipDurationMs: dropAnimationDurationMs = 0,
    type: newType = DEFAULT_DROP_ZONE_TYPE$1,
    dragDisabled = false,
    morphDisabled = false,
    dropFromOthersDisabled = false,
    dropTargetStyle = DEFAULT_DROP_TARGET_STYLE$1,
    dropTargetClasses = [],
    transformDraggedElement = /* @__PURE__ */ __name(() => {
    }, "transformDraggedElement"),
    centreDraggedOnCursor = false
  }) {
    config.dropAnimationDurationMs = dropAnimationDurationMs;
    if (config.type && newType !== config.type) {
      unregisterDropZone$1(node, config.type);
    }
    config.type = newType;
    config.items = [...items];
    config.dragDisabled = dragDisabled;
    config.morphDisabled = morphDisabled;
    config.transformDraggedElement = transformDraggedElement;
    config.centreDraggedOnCursor = centreDraggedOnCursor;
    if (initialized && isWorkingOnPreviousDrag && !finalizingPreviousDrag && (!areObjectsShallowEqual(dropTargetStyle, config.dropTargetStyle) || !areArraysShallowEqualSameOrder(dropTargetClasses, config.dropTargetClasses))) {
      styleInactiveDropZones(
        [node],
        () => config.dropTargetStyle,
        () => dropTargetClasses
      );
      styleActiveDropZones(
        [node],
        () => dropTargetStyle,
        () => dropTargetClasses
      );
    }
    config.dropTargetStyle = dropTargetStyle;
    config.dropTargetClasses = [...dropTargetClasses];
    function getConfigProp(dz, propName) {
      return dzToConfig$1.get(dz) ? dzToConfig$1.get(dz)[propName] : config[propName];
    }
    __name(getConfigProp, "getConfigProp");
    if (initialized && isWorkingOnPreviousDrag && config.dropFromOthersDisabled !== dropFromOthersDisabled) {
      if (dropFromOthersDisabled) {
        styleInactiveDropZones(
          [node],
          (dz) => getConfigProp(dz, "dropTargetStyle"),
          (dz) => getConfigProp(dz, "dropTargetClasses")
        );
      } else {
        styleActiveDropZones(
          [node],
          (dz) => getConfigProp(dz, "dropTargetStyle"),
          (dz) => getConfigProp(dz, "dropTargetClasses")
        );
      }
    }
    config.dropFromOthersDisabled = dropFromOthersDisabled;
    dzToConfig$1.set(node, config);
    registerDropZone$1(node, newType);
    const shadowElIdx = findShadowElementIdx(config.items);
    for (let idx = 0; idx < node.children.length; idx++) {
      const draggableEl = node.children[idx];
      styleDraggable(draggableEl, dragDisabled);
      if (idx === shadowElIdx) {
        config.transformDraggedElement(draggedEl, draggedElData, idx);
        if (!morphDisabled) {
          morphDraggedElementToBeLike(draggedEl, draggableEl, currentMousePosition.x, currentMousePosition.y);
        }
        decorateShadowEl(draggableEl);
        continue;
      }
      draggableEl.removeEventListener("mousedown", elToMouseDownListener.get(draggableEl));
      draggableEl.removeEventListener("touchstart", elToMouseDownListener.get(draggableEl));
      if (!dragDisabled) {
        draggableEl.addEventListener("mousedown", handleMouseDown);
        draggableEl.addEventListener("touchstart", handleMouseDown);
        elToMouseDownListener.set(draggableEl, handleMouseDown);
      }
      elToIdx.set(draggableEl, idx);
      if (!initialized) {
        initialized = true;
      }
    }
  }
  __name(configure, "configure");
  configure(options);
  return {
    update: (newOptions) => {
      configure(newOptions);
    },
    destroy: () => {
      function destroyDz() {
        unregisterDropZone$1(node, dzToConfig$1.get(node).type);
        dzToConfig$1.delete(node);
      }
      __name(destroyDz, "destroyDz");
      if (isWorkingOnPreviousDrag && !node.closest(`[${ORIGINAL_DRAGGED_ITEM_MARKER_ATTRIBUTE}]`)) {
        scheduleDZForRemovalAfterDrop(node, destroyDz);
      } else {
        destroyDz();
      }
    }
  };
}
__name(dndzone$2, "dndzone$2");
const INSTRUCTION_IDs$1 = {
  DND_ZONE_ACTIVE: "dnd-zone-active",
  DND_ZONE_DRAG_DISABLED: "dnd-zone-drag-disabled"
};
const ID_TO_INSTRUCTION = {
  [INSTRUCTION_IDs$1.DND_ZONE_ACTIVE]: "Tab to one the items and press space-bar or enter to start dragging it",
  [INSTRUCTION_IDs$1.DND_ZONE_DRAG_DISABLED]: "This is a disabled drag and drop list"
};
const ALERT_DIV_ID = "dnd-action-aria-alert";
let alertsDiv;
function initAriaOnBrowser() {
  if (alertsDiv) {
    return;
  }
  alertsDiv = document.createElement("div");
  (/* @__PURE__ */ __name(function initAlertsDiv() {
    alertsDiv.id = ALERT_DIV_ID;
    alertsDiv.style.position = "fixed";
    alertsDiv.style.bottom = "0";
    alertsDiv.style.left = "0";
    alertsDiv.style.zIndex = "-5";
    alertsDiv.style.opacity = "0";
    alertsDiv.style.height = "0";
    alertsDiv.style.width = "0";
    alertsDiv.setAttribute("role", "alert");
  }, "initAlertsDiv"))();
  document.body.prepend(alertsDiv);
  Object.entries(ID_TO_INSTRUCTION).forEach(([id, txt]) => document.body.prepend(instructionToHiddenDiv(id, txt)));
}
__name(initAriaOnBrowser, "initAriaOnBrowser");
function initAria() {
  if (isOnServer)
    return null;
  if (document.readyState === "complete") {
    initAriaOnBrowser();
  } else {
    window.addEventListener("DOMContentLoaded", initAriaOnBrowser);
  }
  return { ...INSTRUCTION_IDs$1 };
}
__name(initAria, "initAria");
function destroyAria() {
  if (isOnServer || !alertsDiv)
    return;
  Object.keys(ID_TO_INSTRUCTION).forEach((id) => document.getElementById(id)?.remove());
  alertsDiv.remove();
  alertsDiv = void 0;
}
__name(destroyAria, "destroyAria");
function instructionToHiddenDiv(id, txt) {
  const div = document.createElement("div");
  div.id = id;
  div.innerHTML = `<p>${txt}</p>`;
  div.style.display = "none";
  div.style.position = "fixed";
  div.style.zIndex = "-5";
  return div;
}
__name(instructionToHiddenDiv, "instructionToHiddenDiv");
function alertToScreenReader(txt) {
  if (isOnServer)
    return;
  if (!alertsDiv) {
    initAriaOnBrowser();
  }
  alertsDiv.innerHTML = "";
  const alertText = document.createTextNode(txt);
  alertsDiv.appendChild(alertText);
  alertsDiv.style.display = "none";
  alertsDiv.style.display = "inline";
}
__name(alertToScreenReader, "alertToScreenReader");
const DEFAULT_DROP_ZONE_TYPE = "--any--";
const DEFAULT_DROP_TARGET_STYLE = {
  outline: "rgba(255, 255, 102, 0.7) solid 2px"
};
let isDragging = false;
let draggedItemType;
let focusedDz;
let focusedDzLabel = "";
let focusedItem;
let focusedItemId;
let focusedItemLabel = "";
const allDragTargets = /* @__PURE__ */ new WeakSet();
const elToKeyDownListeners = /* @__PURE__ */ new WeakMap();
const elToFocusListeners = /* @__PURE__ */ new WeakMap();
const dzToHandles = /* @__PURE__ */ new Map();
const dzToConfig = /* @__PURE__ */ new Map();
const typeToDropZones = /* @__PURE__ */ new Map();
let INSTRUCTION_IDs;
function registerDropZone(dropZoneEl, type) {
  if (typeToDropZones.size === 0) {
    INSTRUCTION_IDs = initAria();
    window.addEventListener("keydown", globalKeyDownHandler);
    window.addEventListener("click", globalClickHandler);
  }
  if (!typeToDropZones.has(type)) {
    typeToDropZones.set(type, /* @__PURE__ */ new Set());
  }
  if (!typeToDropZones.get(type).has(dropZoneEl)) {
    typeToDropZones.get(type).add(dropZoneEl);
    incrementActiveDropZoneCount();
  }
}
__name(registerDropZone, "registerDropZone");
function unregisterDropZone(dropZoneEl, type) {
  if (focusedDz === dropZoneEl) {
    handleDrop();
  }
  typeToDropZones.get(type).delete(dropZoneEl);
  decrementActiveDropZoneCount();
  if (typeToDropZones.get(type).size === 0) {
    typeToDropZones.delete(type);
  }
  if (typeToDropZones.size === 0) {
    window.removeEventListener("keydown", globalKeyDownHandler);
    window.removeEventListener("click", globalClickHandler);
    INSTRUCTION_IDs = void 0;
    destroyAria();
  }
}
__name(unregisterDropZone, "unregisterDropZone");
function globalKeyDownHandler(e) {
  if (!isDragging)
    return;
  switch (e.key) {
    case "Escape": {
      handleDrop();
      break;
    }
  }
}
__name(globalKeyDownHandler, "globalKeyDownHandler");
function globalClickHandler() {
  if (!isDragging)
    return;
  if (!allDragTargets.has(document.activeElement)) {
    handleDrop();
  }
}
__name(globalClickHandler, "globalClickHandler");
function handleZoneFocus(e) {
  if (!isDragging)
    return;
  const newlyFocusedDz = e.currentTarget;
  if (newlyFocusedDz === focusedDz)
    return;
  focusedDzLabel = newlyFocusedDz.getAttribute("aria-label") || "";
  const { items: originItems } = dzToConfig.get(focusedDz);
  const originItem = originItems.find((item) => item[ITEM_ID_KEY] === focusedItemId);
  const originIdx = originItems.indexOf(originItem);
  const itemToMove = originItems.splice(originIdx, 1)[0];
  const { items: targetItems, autoAriaDisabled } = dzToConfig.get(newlyFocusedDz);
  if (newlyFocusedDz.getBoundingClientRect().top < focusedDz.getBoundingClientRect().top || newlyFocusedDz.getBoundingClientRect().left < focusedDz.getBoundingClientRect().left) {
    targetItems.push(itemToMove);
    if (!autoAriaDisabled) {
      alertToScreenReader(`Moved item ${focusedItemLabel} to the end of the list ${focusedDzLabel}`);
    }
  } else {
    targetItems.unshift(itemToMove);
    if (!autoAriaDisabled) {
      alertToScreenReader(`Moved item ${focusedItemLabel} to the beginning of the list ${focusedDzLabel}`);
    }
  }
  const dzFrom = focusedDz;
  dispatchFinalizeEvent(dzFrom, originItems, { trigger: TRIGGERS.DROPPED_INTO_ANOTHER, id: focusedItemId, source: SOURCES.KEYBOARD });
  dispatchFinalizeEvent(newlyFocusedDz, targetItems, { trigger: TRIGGERS.DROPPED_INTO_ZONE, id: focusedItemId, source: SOURCES.KEYBOARD });
  focusedDz = newlyFocusedDz;
}
__name(handleZoneFocus, "handleZoneFocus");
function triggerAllDzsUpdate() {
  dzToHandles.forEach(({ update: update2 }, dz) => update2(dzToConfig.get(dz)));
}
__name(triggerAllDzsUpdate, "triggerAllDzsUpdate");
function handleDrop(dispatchConsider = true) {
  if (!dzToConfig.get(focusedDz).autoAriaDisabled) {
    alertToScreenReader(`Stopped dragging item ${focusedItemLabel}`);
  }
  if (allDragTargets.has(document.activeElement)) {
    document.activeElement.blur();
  }
  if (dispatchConsider) {
    dispatchConsiderEvent(focusedDz, dzToConfig.get(focusedDz).items, {
      trigger: TRIGGERS.DRAG_STOPPED,
      id: focusedItemId,
      source: SOURCES.KEYBOARD
    });
  }
  styleInactiveDropZones(
    typeToDropZones.get(draggedItemType),
    (dz) => dzToConfig.get(dz).dropTargetStyle,
    (dz) => dzToConfig.get(dz).dropTargetClasses
  );
  focusedItem = null;
  focusedItemId = null;
  focusedItemLabel = "";
  draggedItemType = null;
  focusedDz = null;
  focusedDzLabel = "";
  isDragging = false;
  triggerAllDzsUpdate();
}
__name(handleDrop, "handleDrop");
function dndzone$1(node, options) {
  const config = {
    items: void 0,
    type: void 0,
    dragDisabled: false,
    zoneTabIndex: 0,
    zoneItemTabIndex: 0,
    dropFromOthersDisabled: false,
    dropTargetStyle: DEFAULT_DROP_TARGET_STYLE,
    dropTargetClasses: [],
    autoAriaDisabled: false
  };
  function swap(arr, i, j) {
    if (arr.length <= 1)
      return;
    arr.splice(j, 1, arr.splice(i, 1, arr[j])[0]);
  }
  __name(swap, "swap");
  function handleKeyDown(e) {
    switch (e.key) {
      case "Enter":
      case " ": {
        if ((e.target.disabled !== void 0 || e.target.href || e.target.isContentEditable) && !allDragTargets.has(e.target)) {
          return;
        }
        e.preventDefault();
        e.stopPropagation();
        if (isDragging) {
          handleDrop();
        } else {
          handleDragStart(e);
        }
        break;
      }
      case "ArrowDown":
      case "ArrowRight": {
        if (!isDragging)
          return;
        e.preventDefault();
        e.stopPropagation();
        const { items } = dzToConfig.get(node);
        const children2 = Array.from(node.children);
        const idx = children2.indexOf(e.currentTarget);
        if (idx < children2.length - 1) {
          if (!config.autoAriaDisabled) {
            alertToScreenReader(`Moved item ${focusedItemLabel} to position ${idx + 2} in the list ${focusedDzLabel}`);
          }
          swap(items, idx, idx + 1);
          dispatchFinalizeEvent(node, items, { trigger: TRIGGERS.DROPPED_INTO_ZONE, id: focusedItemId, source: SOURCES.KEYBOARD });
        }
        break;
      }
      case "ArrowUp":
      case "ArrowLeft": {
        if (!isDragging)
          return;
        e.preventDefault();
        e.stopPropagation();
        const { items } = dzToConfig.get(node);
        const children2 = Array.from(node.children);
        const idx = children2.indexOf(e.currentTarget);
        if (idx > 0) {
          if (!config.autoAriaDisabled) {
            alertToScreenReader(`Moved item ${focusedItemLabel} to position ${idx} in the list ${focusedDzLabel}`);
          }
          swap(items, idx, idx - 1);
          dispatchFinalizeEvent(node, items, { trigger: TRIGGERS.DROPPED_INTO_ZONE, id: focusedItemId, source: SOURCES.KEYBOARD });
        }
        break;
      }
    }
  }
  __name(handleKeyDown, "handleKeyDown");
  function handleDragStart(e) {
    setCurrentFocusedItem(e.currentTarget);
    focusedDz = node;
    draggedItemType = config.type;
    isDragging = true;
    const dropTargets = Array.from(typeToDropZones.get(config.type)).filter((dz) => dz === focusedDz || !dzToConfig.get(dz).dropFromOthersDisabled);
    styleActiveDropZones(
      dropTargets,
      (dz) => dzToConfig.get(dz).dropTargetStyle,
      (dz) => dzToConfig.get(dz).dropTargetClasses
    );
    if (!config.autoAriaDisabled) {
      let msg = `Started dragging item ${focusedItemLabel}. Use the arrow keys to move it within its list ${focusedDzLabel}`;
      if (dropTargets.length > 1) {
        msg += `, or tab to another list in order to move the item into it`;
      }
      alertToScreenReader(msg);
    }
    dispatchConsiderEvent(node, dzToConfig.get(node).items, { trigger: TRIGGERS.DRAG_STARTED, id: focusedItemId, source: SOURCES.KEYBOARD });
    triggerAllDzsUpdate();
  }
  __name(handleDragStart, "handleDragStart");
  function handleClick(e) {
    if (!isDragging)
      return;
    if (e.currentTarget === focusedItem)
      return;
    e.stopPropagation();
    handleDrop(false);
    handleDragStart(e);
  }
  __name(handleClick, "handleClick");
  function setCurrentFocusedItem(draggableEl) {
    const { items } = dzToConfig.get(node);
    const children2 = Array.from(node.children);
    const focusedItemIdx = children2.indexOf(draggableEl);
    focusedItem = draggableEl;
    focusedItem.tabIndex = config.zoneItemTabIndex;
    focusedItemId = items[focusedItemIdx][ITEM_ID_KEY];
    focusedItemLabel = children2[focusedItemIdx].getAttribute("aria-label") || "";
  }
  __name(setCurrentFocusedItem, "setCurrentFocusedItem");
  function configure({
    items = [],
    type: newType = DEFAULT_DROP_ZONE_TYPE,
    dragDisabled = false,
    zoneTabIndex = 0,
    zoneItemTabIndex = 0,
    dropFromOthersDisabled = false,
    dropTargetStyle = DEFAULT_DROP_TARGET_STYLE,
    dropTargetClasses = [],
    autoAriaDisabled = false
  }) {
    config.items = [...items];
    config.dragDisabled = dragDisabled;
    config.dropFromOthersDisabled = dropFromOthersDisabled;
    config.zoneTabIndex = zoneTabIndex;
    config.zoneItemTabIndex = zoneItemTabIndex;
    config.dropTargetStyle = dropTargetStyle;
    config.dropTargetClasses = dropTargetClasses;
    config.autoAriaDisabled = autoAriaDisabled;
    if (config.type && newType !== config.type) {
      unregisterDropZone(node, config.type);
    }
    config.type = newType;
    registerDropZone(node, newType);
    if (!autoAriaDisabled) {
      node.setAttribute("aria-disabled", dragDisabled);
      node.setAttribute("role", "list");
      node.setAttribute("aria-describedby", dragDisabled ? INSTRUCTION_IDs.DND_ZONE_DRAG_DISABLED : INSTRUCTION_IDs.DND_ZONE_ACTIVE);
    }
    dzToConfig.set(node, config);
    if (isDragging) {
      node.tabIndex = node === focusedDz || focusedItem.contains(node) || config.dropFromOthersDisabled || focusedDz && config.type !== dzToConfig.get(focusedDz).type ? -1 : 0;
    } else {
      node.tabIndex = config.zoneTabIndex;
    }
    node.addEventListener("focus", handleZoneFocus);
    for (let i = 0; i < node.children.length; i++) {
      const draggableEl = node.children[i];
      allDragTargets.add(draggableEl);
      draggableEl.tabIndex = isDragging ? -1 : config.zoneItemTabIndex;
      if (!autoAriaDisabled) {
        draggableEl.setAttribute("role", "listitem");
      }
      draggableEl.removeEventListener("keydown", elToKeyDownListeners.get(draggableEl));
      draggableEl.removeEventListener("click", elToFocusListeners.get(draggableEl));
      if (!dragDisabled) {
        draggableEl.addEventListener("keydown", handleKeyDown);
        elToKeyDownListeners.set(draggableEl, handleKeyDown);
        draggableEl.addEventListener("click", handleClick);
        elToFocusListeners.set(draggableEl, handleClick);
      }
      if (isDragging && config.items[i][ITEM_ID_KEY] === focusedItemId) {
        focusedItem = draggableEl;
        focusedItem.tabIndex = config.zoneItemTabIndex;
        draggableEl.focus();
      }
    }
  }
  __name(configure, "configure");
  configure(options);
  const handles = {
    update: (newOptions) => {
      configure(newOptions);
    },
    destroy: () => {
      unregisterDropZone(node, config.type);
      dzToConfig.delete(node);
      dzToHandles.delete(node);
    }
  };
  dzToHandles.set(node, handles);
  return handles;
}
__name(dndzone$1, "dndzone$1");
function dndzone(node, options) {
  if (shouldIgnoreZone(node)) {
    return {
      update: () => {
      },
      destroy: () => {
      }
    };
  }
  validateOptions(options);
  const pointerZone = dndzone$2(node, options);
  const keyboardZone = dndzone$1(node, options);
  return {
    update: (newOptions) => {
      validateOptions(newOptions);
      pointerZone.update(newOptions);
      keyboardZone.update(newOptions);
    },
    destroy: () => {
      pointerZone.destroy();
      keyboardZone.destroy();
    }
  };
}
__name(dndzone, "dndzone");
function shouldIgnoreZone(node) {
  return !!node.closest(`[${SHADOW_ELEMENT_HINT_ATTRIBUTE_NAME}="true"]`);
}
__name(shouldIgnoreZone, "shouldIgnoreZone");
function validateOptions(options) {
  const {
    items,
    flipDurationMs: flipDurationMs2,
    type,
    dragDisabled,
    morphDisabled,
    dropFromOthersDisabled,
    zoneTabIndex,
    zoneItemTabIndex,
    dropTargetStyle,
    dropTargetClasses,
    transformDraggedElement,
    autoAriaDisabled,
    centreDraggedOnCursor,
    ...rest
  } = options;
  if (Object.keys(rest).length > 0) {
    console.warn(`dndzone will ignore unknown options`, rest);
  }
  if (!items) {
    throw new Error("no 'items' key provided to dndzone");
  }
  const itemWithMissingId = items.find((item) => !{}.hasOwnProperty.call(item, ITEM_ID_KEY));
  if (itemWithMissingId) {
    throw new Error(`missing '${ITEM_ID_KEY}' property for item ${toString(itemWithMissingId)}`);
  }
  if (dropTargetClasses && !Array.isArray(dropTargetClasses)) {
    throw new Error(`dropTargetClasses should be an array but instead it is a ${typeof dropTargetClasses}, ${toString(dropTargetClasses)}`);
  }
  if (zoneTabIndex && !isInt(zoneTabIndex)) {
    throw new Error(`zoneTabIndex should be a number but instead it is a ${typeof zoneTabIndex}, ${toString(zoneTabIndex)}`);
  }
  if (zoneItemTabIndex && !isInt(zoneItemTabIndex)) {
    throw new Error(`zoneItemTabIndex should be a number but instead it is a ${typeof zoneItemTabIndex}, ${toString(zoneItemTabIndex)}`);
  }
}
__name(validateOptions, "validateOptions");
function isInt(value) {
  return !isNaN(value) && function(x) {
    return (x | 0) === x;
  }(parseFloat(value));
}
__name(isInt, "isInt");
function create_fragment$$(ctx) {
  let div;
  let div_class_value;
  let div_style_value;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[12].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[11],
    null
  );
  return {
    c() {
      div = element("div");
      if (default_slot)
        default_slot.c();
      attr(div, "class", div_class_value = /*$$props*/
      ctx[4].class);
      attr(div, "style", div_style_value = /*$$props*/
      ctx[4].style);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (default_slot) {
        default_slot.m(div, null);
      }
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            div,
            "dragenter",
            /*enter*/
            ctx[2]
          ),
          listen(
            div,
            "dragleave",
            /*leave*/
            ctx[3]
          ),
          listen(div, "dragover", function() {
            if (is_function(
              /*overCallback*/
              ctx[0]
            ))
              ctx[0].apply(this, arguments);
          }),
          listen(div, "dragstart", prevent_default(
            /*dragstart_handler*/
            ctx[13]
          )),
          listen(div, "drop", prevent_default(
            /*dropData*/
            ctx[1]
          ))
        ];
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx = new_ctx;
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        2048)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx,
            /*$$scope*/
            ctx[11],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[11]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx[11],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty & /*$$props*/
      16 && div_class_value !== (div_class_value = /*$$props*/
      ctx[4].class)) {
        attr(div, "class", div_class_value);
      }
      if (!current || dirty & /*$$props*/
      16 && div_style_value !== (div_style_value = /*$$props*/
      ctx[4].style)) {
        attr(div, "style", div_style_value);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (default_slot)
        default_slot.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$$, "create_fragment$$");
function instance$Y($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { callback } = $$props;
  let { isHovering } = $$props;
  let { active: active2 = true } = $$props;
  let { enterCallback = /* @__PURE__ */ __name(() => {
  }, "enterCallback") } = $$props;
  let { overCallback = /* @__PURE__ */ __name(() => {
  }, "overCallback") } = $$props;
  let { leaveCallback = /* @__PURE__ */ __name(() => {
  }, "leaveCallback") } = $$props;
  function dropData(event, ...args) {
    if (!active2)
      return;
    $$invalidate(10, counter = 0);
    let data2;
    try {
      data2 = JSON.parse(event.dataTransfer.getData("text/plain"));
    } catch (err) {
      return false;
    }
    callback(data2, event, ...args);
  }
  __name(dropData, "dropData");
  let counter = 0;
  function enter(event) {
    if (!active2)
      return;
    $$invalidate(10, counter++, counter);
    if (counter === 1) {
      enterCallback(event);
    }
  }
  __name(enter, "enter");
  function leave(event) {
    if (!active2)
      return;
    $$invalidate(10, counter--, counter);
    if (counter === 0) {
      leaveCallback(event);
    }
  }
  __name(leave, "leave");
  function dragstart_handler(event) {
    bubble.call(this, $$self, event);
  }
  __name(dragstart_handler, "dragstart_handler");
  $$self.$$set = ($$new_props) => {
    $$invalidate(4, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
    if ("callback" in $$new_props)
      $$invalidate(6, callback = $$new_props.callback);
    if ("isHovering" in $$new_props)
      $$invalidate(5, isHovering = $$new_props.isHovering);
    if ("active" in $$new_props)
      $$invalidate(7, active2 = $$new_props.active);
    if ("enterCallback" in $$new_props)
      $$invalidate(8, enterCallback = $$new_props.enterCallback);
    if ("overCallback" in $$new_props)
      $$invalidate(0, overCallback = $$new_props.overCallback);
    if ("leaveCallback" in $$new_props)
      $$invalidate(9, leaveCallback = $$new_props.leaveCallback);
    if ("$$scope" in $$new_props)
      $$invalidate(11, $$scope = $$new_props.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*counter*/
    1024) {
      $$invalidate(5, isHovering = counter > 0);
    }
  };
  $$props = exclude_internal_props($$props);
  return [
    overCallback,
    dropData,
    enter,
    leave,
    $$props,
    isHovering,
    callback,
    active2,
    enterCallback,
    leaveCallback,
    counter,
    $$scope,
    slots,
    dragstart_handler
  ];
}
__name(instance$Y, "instance$Y");
const _DropZone = class _DropZone extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$Y, create_fragment$$, safe_not_equal, {
      callback: 6,
      isHovering: 5,
      active: 7,
      enterCallback: 8,
      overCallback: 0,
      leaveCallback: 9
    });
  }
};
__name(_DropZone, "DropZone");
let DropZone = _DropZone;
const PriceList_svelte_svelte_type_style_lang = "";
function get_each_context$v(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[35] = i;
  return child_ctx;
}
__name(get_each_context$v, "get_each_context$v");
function get_each_context_1$e(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[36] = list;
  child_ctx[35] = i;
  return child_ctx;
}
__name(get_each_context_1$e, "get_each_context_1$e");
function create_if_block_3$g(ctx) {
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.innerHTML = `<i class="fas fa-times"></i>`;
      attr(a, "class", "item-piles-clickable-red");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[17]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$g, "create_if_block_3$g");
function create_if_block_2$k(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = "Drop to add";
      attr(div, "class", "drop-to-add svelte-1c30usg");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_2$k, "create_if_block_2$k");
function create_else_block$g(ctx) {
  let button;
  let mounted;
  let dispose;
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[25](
        /*index*/
        ctx[35]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    c() {
      button = element("button");
      button.innerHTML = `<i class="fas fa-eye"></i> View item`;
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(button, "click", click_handler_1);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$g, "create_else_block$g");
function create_if_block_1$s(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx[24].call(
      input,
      /*each_value_1*/
      ctx[36],
      /*index*/
      ctx[35]
    );
  }
  __name(input_input_handler, "input_input_handler");
  return {
    c() {
      input = element("input");
      attr(input, "type", "text");
      attr(input, "placeholder", "system.attributes.hp.value");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*price*/
        ctx[33].data.path
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*prices*/
      1 && input.value !== /*price*/
      ctx[33].data.path) {
        set_input_value(
          input,
          /*price*/
          ctx[33].data.path
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$s, "create_if_block_1$s");
function create_each_block_1$e(key_1, ctx) {
  let div9;
  let div0;
  let i0;
  let div0_tabindex_value;
  let div0_style_value;
  let t0;
  let div1;
  let input0;
  let t1;
  let div2;
  let input1;
  let t2;
  let div3;
  let input2;
  let input2_max_value;
  let t3;
  let div4;
  let input3;
  let t4;
  let div5;
  let input4;
  let t5;
  let div6;
  let filepicker;
  let updating_value;
  let t6;
  let div7;
  let t7;
  let div8;
  let button;
  let rect;
  let stop_animation = noop;
  let current;
  let mounted;
  let dispose;
  function input0_input_handler() {
    ctx[18].call(
      input0,
      /*each_value_1*/
      ctx[36],
      /*index*/
      ctx[35]
    );
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler() {
    ctx[19].call(
      input1,
      /*each_value_1*/
      ctx[36],
      /*index*/
      ctx[35]
    );
  }
  __name(input1_input_handler, "input1_input_handler");
  function input2_change_handler() {
    ctx[20].call(
      input2,
      /*each_value_1*/
      ctx[36],
      /*index*/
      ctx[35]
    );
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler() {
    ctx[21].call(
      input3,
      /*each_value_1*/
      ctx[36],
      /*index*/
      ctx[35]
    );
  }
  __name(input3_change_handler, "input3_change_handler");
  function input4_input_handler() {
    ctx[22].call(
      input4,
      /*each_value_1*/
      ctx[36],
      /*index*/
      ctx[35]
    );
  }
  __name(input4_input_handler, "input4_input_handler");
  function filepicker_value_binding(value) {
    ctx[23](
      value,
      /*price*/
      ctx[33]
    );
  }
  __name(filepicker_value_binding, "filepicker_value_binding");
  let filepicker_props = {
    type: "imagevideo",
    showImage: true,
    showInput: false
  };
  if (
    /*price*/
    ctx[33].img !== void 0
  ) {
    filepicker_props.value = /*price*/
    ctx[33].img;
  }
  filepicker = new FilePicker_1({ props: filepicker_props });
  binding_callbacks.push(() => bind(filepicker, "value", filepicker_value_binding));
  function select_block_type(ctx2, dirty) {
    if (
      /*price*/
      ctx2[33].type === "attribute"
    )
      return create_if_block_1$s;
    return create_else_block$g;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx[26](
        /*index*/
        ctx[35]
      )
    );
  }
  __name(click_handler_2, "click_handler_2");
  return {
    key: key_1,
    first: null,
    c() {
      div9 = element("div");
      div0 = element("div");
      i0 = element("i");
      t0 = space();
      div1 = element("div");
      input0 = element("input");
      t1 = space();
      div2 = element("div");
      input1 = element("input");
      t2 = space();
      div3 = element("div");
      input2 = element("input");
      t3 = space();
      div4 = element("div");
      input3 = element("input");
      t4 = space();
      div5 = element("div");
      input4 = element("input");
      t5 = space();
      div6 = element("div");
      create_component(filepicker.$$.fragment);
      t6 = space();
      div7 = element("div");
      if_block.c();
      t7 = space();
      div8 = element("div");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      attr(i0, "class", "fas fa-bars");
      attr(div0, "tabindex", div0_tabindex_value = /*dragDisabled*/
      ctx[4] ? 0 : -1);
      attr(div0, "aria-label", "drag-handle");
      attr(div0, "style", div0_style_value = /*dragDisabled*/
      ctx[4] ? "cursor: grab" : "cursor: grabbing");
      attr(input0, "type", "text");
      attr(input1, "type", "number");
      attr(input2, "type", "checkbox");
      attr(input2, "min", "0");
      attr(input2, "max", input2_max_value = /*price*/
      ctx[33].percent ? 100 : 1e15);
      attr(input3, "type", "checkbox");
      attr(input4, "type", "text");
      attr(button, "type", "button");
      attr(div9, "class", "item-piles-sortable-list-columns item-piles-sortable-list-entry item-piles-even-color svelte-1c30usg");
      this.first = div9;
    },
    m(target, anchor) {
      insert(target, div9, anchor);
      append(div9, div0);
      append(div0, i0);
      append(div9, t0);
      append(div9, div1);
      append(div1, input0);
      set_input_value(
        input0,
        /*price*/
        ctx[33].name
      );
      append(div9, t1);
      append(div9, div2);
      append(div2, input1);
      set_input_value(
        input1,
        /*price*/
        ctx[33].quantity
      );
      append(div9, t2);
      append(div9, div3);
      append(div3, input2);
      input2.checked = /*price*/
      ctx[33].fixed;
      append(div9, t3);
      append(div9, div4);
      append(div4, input3);
      input3.checked = /*price*/
      ctx[33].percent;
      append(div9, t4);
      append(div9, div5);
      append(div5, input4);
      set_input_value(
        input4,
        /*price*/
        ctx[33].abbreviation
      );
      append(div9, t5);
      append(div9, div6);
      mount_component(filepicker, div6, null);
      append(div9, t6);
      append(div9, div7);
      if_block.m(div7, null);
      append(div9, t7);
      append(div9, div8);
      append(div8, button);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            div0,
            "mousedown",
            /*startDrag*/
            ctx[14]
          ),
          listen(
            div0,
            "touchstart",
            /*startDrag*/
            ctx[14]
          ),
          listen(
            div0,
            "keydown",
            /*handleKeyDown*/
            ctx[15]
          ),
          listen(input0, "input", input0_input_handler),
          listen(input1, "input", input1_input_handler),
          listen(input2, "change", input2_change_handler),
          listen(input3, "change", input3_change_handler),
          listen(input4, "input", input4_input_handler),
          listen(button, "click", click_handler_2)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (!current || dirty[0] & /*dragDisabled*/
      16 && div0_tabindex_value !== (div0_tabindex_value = /*dragDisabled*/
      ctx[4] ? 0 : -1)) {
        attr(div0, "tabindex", div0_tabindex_value);
      }
      if (!current || dirty[0] & /*dragDisabled*/
      16 && div0_style_value !== (div0_style_value = /*dragDisabled*/
      ctx[4] ? "cursor: grab" : "cursor: grabbing")) {
        attr(div0, "style", div0_style_value);
      }
      if (dirty[0] & /*prices*/
      1 && input0.value !== /*price*/
      ctx[33].name) {
        set_input_value(
          input0,
          /*price*/
          ctx[33].name
        );
      }
      if (dirty[0] & /*prices*/
      1 && to_number(input1.value) !== /*price*/
      ctx[33].quantity) {
        set_input_value(
          input1,
          /*price*/
          ctx[33].quantity
        );
      }
      if (!current || dirty[0] & /*prices*/
      1 && input2_max_value !== (input2_max_value = /*price*/
      ctx[33].percent ? 100 : 1e15)) {
        attr(input2, "max", input2_max_value);
      }
      if (dirty[0] & /*prices*/
      1) {
        input2.checked = /*price*/
        ctx[33].fixed;
      }
      if (dirty[0] & /*prices*/
      1) {
        input3.checked = /*price*/
        ctx[33].percent;
      }
      if (dirty[0] & /*prices*/
      1 && input4.value !== /*price*/
      ctx[33].abbreviation) {
        set_input_value(
          input4,
          /*price*/
          ctx[33].abbreviation
        );
      }
      const filepicker_changes = {};
      if (!updating_value && dirty[0] & /*prices*/
      1) {
        updating_value = true;
        filepicker_changes.value = /*price*/
        ctx[33].img;
        add_flush_callback(() => updating_value = false);
      }
      filepicker.$set(filepicker_changes);
      if (current_block_type === (current_block_type = select_block_type(ctx)) && if_block) {
        if_block.p(ctx, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx);
        if (if_block) {
          if_block.c();
          if_block.m(div7, null);
        }
      }
    },
    r() {
      rect = div9.getBoundingClientRect();
    },
    f() {
      fix_position(div9);
      stop_animation();
    },
    a() {
      stop_animation();
      stop_animation = create_animation(div9, rect, flip$1, { duration: flipDurationMs });
    },
    i(local) {
      if (current)
        return;
      transition_in(filepicker.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filepicker.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div9);
      destroy_component(filepicker);
      if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_1$e, "create_each_block_1$e");
function create_if_block$F(ctx) {
  let div;
  let span;
  let t1;
  let select;
  let option;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let mounted;
  let dispose;
  let each_value = (
    /*presetPrices*/
    ctx[6]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[35]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$v(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$v(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      span = element("span");
      span.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.PricePreset")}`;
      t1 = space();
      select = element("select");
      option = element("option");
      option.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.SelectPreset")}`;
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      set_style(span, "margin-right", "0.25rem");
      option.__value = "";
      option.value = option.__value;
      attr(select, "class", "price-preset-selector svelte-1c30usg");
      if (
        /*selectedPreset*/
        ctx[5] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[28].call(select)
        ));
      attr(div, "class", "full-span svelte-1c30usg");
      set_style(div, "margin-top", "0.5rem");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      append(div, t1);
      append(div, select);
      append(select, option);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*selectedPreset*/
        ctx[5],
        true
      );
      if (!mounted) {
        dispose = [
          listen(
            select,
            "change",
            /*select_change_handler*/
            ctx[28]
          ),
          listen(
            select,
            "change",
            /*change_handler*/
            ctx[29]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*presetPrices*/
      64) {
        each_value = /*presetPrices*/
        ctx2[6];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, select, destroy_block, create_each_block$v, null, get_each_context$v);
      }
      if (dirty[0] & /*selectedPreset, presetPrices*/
      96) {
        select_option(
          select,
          /*selectedPreset*/
          ctx2[5]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block$F, "create_if_block$F");
function create_each_block$v(key_1, ctx) {
  let option;
  let t_value = (
    /*price*/
    ctx[33].name + ""
  );
  let t;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = /*index*/
      ctx[35];
      option.value = option.__value;
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$v, "create_each_block$v");
function create_default_slot$o(ctx) {
  let div12;
  let div9;
  let div0;
  let t0;
  let div1;
  let t2;
  let div2;
  let t4;
  let div3;
  let t6;
  let div4;
  let t8;
  let div5;
  let t10;
  let div6;
  let t12;
  let div7;
  let t14;
  let div8;
  let t15;
  let section;
  let t16;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t17;
  let div11;
  let div10;
  let a;
  let t19;
  let dndzone_action;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*remove*/
    ctx[1] && create_if_block_3$g(ctx)
  );
  let if_block1 = (
    /*isHovering*/
    ctx[3] && create_if_block_2$k()
  );
  let each_value_1 = (
    /*prices*/
    ctx[0]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*price*/
    ctx2[33].id
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$e(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$e(key, child_ctx));
  }
  let if_block2 = (
    /*presetPrices*/
    ctx[6].length && /*presets*/
    ctx[2] && create_if_block$F(ctx)
  );
  return {
    c() {
      div12 = element("div");
      div9 = element("div");
      div0 = element("div");
      t0 = space();
      div1 = element("div");
      div1.textContent = "Name";
      t2 = space();
      div2 = element("div");
      div2.textContent = "Cost";
      t4 = space();
      div3 = element("div");
      div3.textContent = "Fixed";
      t6 = space();
      div4 = element("div");
      div4.textContent = "%";
      t8 = space();
      div5 = element("div");
      div5.textContent = "Short";
      t10 = space();
      div6 = element("div");
      div6.textContent = "Icon";
      t12 = space();
      div7 = element("div");
      div7.textContent = "Data";
      t14 = space();
      div8 = element("div");
      if (if_block0)
        if_block0.c();
      t15 = space();
      section = element("section");
      if (if_block1)
        if_block1.c();
      t16 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t17 = space();
      div11 = element("div");
      div10 = element("div");
      a = element("a");
      a.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.DropMeClickMe")}`;
      t19 = space();
      if (if_block2)
        if_block2.c();
      attr(div9, "class", "item-piles-sortable-list-columns header svelte-1c30usg");
      attr(a, "class", "svelte-1c30usg");
      toggle_class(
        a,
        "invisible",
        /*isHovering*/
        ctx[3]
      );
      attr(div10, "class", "full-span svelte-1c30usg");
      attr(div11, "class", "item-piles-sortable-list-columns svelte-1c30usg");
      set_style(div11, "margin-top", "0.5rem");
      attr(div12, "class", "table-container item-piles-top-divider svelte-1c30usg");
    },
    m(target, anchor) {
      insert(target, div12, anchor);
      append(div12, div9);
      append(div9, div0);
      append(div9, t0);
      append(div9, div1);
      append(div9, t2);
      append(div9, div2);
      append(div9, t4);
      append(div9, div3);
      append(div9, t6);
      append(div9, div4);
      append(div9, t8);
      append(div9, div5);
      append(div9, t10);
      append(div9, div6);
      append(div9, t12);
      append(div9, div7);
      append(div9, t14);
      append(div9, div8);
      if (if_block0)
        if_block0.m(div8, null);
      append(div12, t15);
      append(div12, section);
      if (if_block1)
        if_block1.m(section, null);
      append(section, t16);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(section, null);
        }
      }
      append(section, t17);
      append(section, div11);
      append(div11, div10);
      append(div10, a);
      append(div11, t19);
      if (if_block2)
        if_block2.m(div11, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*click_handler_3*/
            ctx[27]
          ),
          listen(
            section,
            "consider",
            /*handleConsider*/
            ctx[12]
          ),
          listen(
            section,
            "finalize",
            /*handleFinalize*/
            ctx[13]
          ),
          action_destroyer(dndzone_action = dndzone.call(null, section, {
            items: (
              /*prices*/
              ctx[0]
            ),
            dragDisabled: (
              /*dragDisabled*/
              ctx[4]
            ),
            flipDurationMs
          }))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*remove*/
        ctx2[1]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_3$g(ctx2);
          if_block0.c();
          if_block0.m(div8, null);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*isHovering*/
        ctx2[3]
      ) {
        if (if_block1)
          ;
        else {
          if_block1 = create_if_block_2$k();
          if_block1.c();
          if_block1.m(section, t16);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty[0] & /*removeEntry, prices, editItem, dragDisabled, startDrag, handleKeyDown*/
      51345) {
        each_value_1 = /*prices*/
        ctx2[0];
        group_outros();
        for (let i = 0; i < each_blocks.length; i += 1)
          each_blocks[i].r();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_1, each_1_lookup, section, fix_and_outro_and_destroy_block, create_each_block_1$e, t17, get_each_context_1$e);
        for (let i = 0; i < each_blocks.length; i += 1)
          each_blocks[i].a();
        check_outros();
      }
      if (!current || dirty[0] & /*isHovering*/
      8) {
        toggle_class(
          a,
          "invisible",
          /*isHovering*/
          ctx2[3]
        );
      }
      if (
        /*presetPrices*/
        ctx2[6].length && /*presets*/
        ctx2[2]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block$F(ctx2);
          if_block2.c();
          if_block2.m(div11, null);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (dndzone_action && is_function(dndzone_action.update) && dirty[0] & /*prices, dragDisabled*/
      17)
        dndzone_action.update.call(null, {
          items: (
            /*prices*/
            ctx2[0]
          ),
          dragDisabled: (
            /*dragDisabled*/
            ctx2[4]
          ),
          flipDurationMs
        });
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div12);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if (if_block2)
        if_block2.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$o, "create_default_slot$o");
function create_fragment$_(ctx) {
  let dropzone;
  let updating_isHovering;
  let current;
  function dropzone_isHovering_binding(value) {
    ctx[30](value);
  }
  __name(dropzone_isHovering_binding, "dropzone_isHovering_binding");
  let dropzone_props = {
    callback: (
      /*dropData*/
      ctx[10]
    ),
    $$slots: { default: [create_default_slot$o] },
    $$scope: { ctx }
  };
  if (
    /*isHovering*/
    ctx[3] !== void 0
  ) {
    dropzone_props.isHovering = /*isHovering*/
    ctx[3];
  }
  dropzone = new DropZone({ props: dropzone_props });
  binding_callbacks.push(() => bind(dropzone, "isHovering", dropzone_isHovering_binding));
  return {
    c() {
      create_component(dropzone.$$.fragment);
    },
    m(target, anchor) {
      mount_component(dropzone, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const dropzone_changes = {};
      if (dirty[0] & /*prices, dragDisabled, selectedPreset, presets, isHovering, remove*/
      63 | dirty[1] & /*$$scope*/
      64) {
        dropzone_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_isHovering && dirty[0] & /*isHovering*/
      8) {
        updating_isHovering = true;
        dropzone_changes.isHovering = /*isHovering*/
        ctx2[3];
        add_flush_callback(() => updating_isHovering = false);
      }
      dropzone.$set(dropzone_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dropzone.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropzone.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(dropzone, detaching);
    }
  };
}
__name(create_fragment$_, "create_fragment$_");
let flipDurationMs = 200;
function instance$X($$self, $$props, $$invalidate) {
  let { prices } = $$props;
  let { item } = $$props;
  let { remove = false } = $$props;
  let { presets = true } = $$props;
  let currencies = getSetting(SETTINGS$1.CURRENCIES);
  let secondaryCurrencies = getSetting(SETTINGS$1.SECONDARY_CURRENCIES);
  if (item?.parent) {
    const flags = getActorFlagData(item?.parent);
    if (flags.overrideCurrencies) {
      currencies = flags.overrideCurrencies;
    }
    if (flags.overrideSecondaryCurrencies) {
      secondaryCurrencies = flags.overrideSecondaryCurrencies;
    }
  }
  let presetPrices = currencies.concat(secondaryCurrencies).map((currency) => {
    return {
      id: randomID(),
      quantity: 1,
      fixed: true,
      percent: false,
      ...currency
    };
  }).concat(getSetting(SETTINGS$1.PRICE_PRESETS));
  let isHovering = false;
  let dragDisabled = true;
  let selectedPreset = "";
  function removeEntry(index2) {
    prices.splice(index2, 1);
    $$invalidate(0, prices);
  }
  __name(removeEntry, "removeEntry");
  function addAttribute() {
    $$invalidate(0, prices = [
      ...prices,
      {
        id: randomID(),
        type: "attribute",
        name: "New Attribute",
        img: "",
        abbreviation: "{#}N",
        data: { path: "" },
        quantity: 1,
        fixed: true,
        percent: false
      }
    ]);
  }
  __name(addAttribute, "addAttribute");
  function addPreset(index2) {
    const preset = foundry.utils.duplicate(presetPrices[index2]);
    preset.id = randomID();
    $$invalidate(0, prices = [...prices, preset]);
  }
  __name(addPreset, "addPreset");
  async function dropData(data2) {
    if (!data2.type) {
      throw custom_error("Something went wrong when dropping this item!");
    }
    if (data2.type !== "Item") {
      throw custom_error("You must drop an item, not " + data2.type.toLowerCase() + "!");
    }
    let uuid = false;
    if (data2.pack) {
      uuid = "Compendium" + data2.pack + "." + data2.id;
    }
    let item2 = await Item.implementation.fromDropData(data2);
    let itemData = item2.toObject();
    if (!itemData) {
      console.error(data2);
      throw custom_error("Something went wrong when dropping this item!");
    }
    const itemCurrencies = prices.map((entry) => entry.data?.item ?? {});
    const foundItem = findSimilarItem(itemCurrencies, itemData);
    if (!uuid) {
      uuid = (await findOrCreateItemInCompendium(itemData)).uuid;
    }
    if (foundItem) {
      const index2 = itemCurrencies.indexOf(foundItem);
      $$invalidate(0, prices[index2].data = { uuid }, prices);
      custom_notify(`Updated item data for ${localize(prices[index2].name)} (item name ${itemData.name})`);
    } else {
      $$invalidate(0, prices = [
        ...prices,
        {
          id: randomID(),
          type: "item",
          name: itemData.name,
          img: itemData.img,
          abbreviation: "{#} " + itemData.name,
          data: { uuid },
          quantity: 1,
          fixed: true,
          percent: false
        }
      ]);
    }
  }
  __name(dropData, "dropData");
  async function editItem(index2) {
    const data2 = prices[index2].data;
    let item2 = await fromUuid(data2.uuid);
    item2.sheet.render(true);
  }
  __name(editItem, "editItem");
  function handleConsider(e) {
    const { items: newItems, info: { source, trigger } } = e.detail;
    $$invalidate(0, prices = newItems);
    if (source === SOURCES.KEYBOARD && trigger === TRIGGERS.DRAG_STOPPED) {
      $$invalidate(4, dragDisabled = true);
    }
  }
  __name(handleConsider, "handleConsider");
  function handleFinalize(e) {
    const { items: newItems, info: { source } } = e.detail;
    $$invalidate(0, prices = newItems);
    if (source === SOURCES.POINTER) {
      $$invalidate(4, dragDisabled = true);
    }
  }
  __name(handleFinalize, "handleFinalize");
  function startDrag(e) {
    e.preventDefault();
    $$invalidate(4, dragDisabled = false);
  }
  __name(startDrag, "startDrag");
  function handleKeyDown(e) {
    if ((e.key === "Enter" || e.key === " ") && dragDisabled)
      $$invalidate(4, dragDisabled = false);
  }
  __name(handleKeyDown, "handleKeyDown");
  const click_handler = /* @__PURE__ */ __name(() => remove(), "click_handler");
  function input0_input_handler(each_value_1, index2) {
    each_value_1[index2].name = this.value;
    $$invalidate(0, prices);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler(each_value_1, index2) {
    each_value_1[index2].quantity = to_number(this.value);
    $$invalidate(0, prices);
  }
  __name(input1_input_handler, "input1_input_handler");
  function input2_change_handler(each_value_1, index2) {
    each_value_1[index2].fixed = this.checked;
    $$invalidate(0, prices);
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler(each_value_1, index2) {
    each_value_1[index2].percent = this.checked;
    $$invalidate(0, prices);
  }
  __name(input3_change_handler, "input3_change_handler");
  function input4_input_handler(each_value_1, index2) {
    each_value_1[index2].abbreviation = this.value;
    $$invalidate(0, prices);
  }
  __name(input4_input_handler, "input4_input_handler");
  function filepicker_value_binding(value, price) {
    if ($$self.$$.not_equal(price.img, value)) {
      price.img = value;
      $$invalidate(0, prices);
    }
  }
  __name(filepicker_value_binding, "filepicker_value_binding");
  function input_input_handler(each_value_1, index2) {
    each_value_1[index2].data.path = this.value;
    $$invalidate(0, prices);
  }
  __name(input_input_handler, "input_input_handler");
  const click_handler_1 = /* @__PURE__ */ __name((index2) => editItem(index2), "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name((index2) => removeEntry(index2), "click_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name(() => addAttribute(), "click_handler_3");
  function select_change_handler() {
    selectedPreset = select_value(this);
    $$invalidate(5, selectedPreset);
    $$invalidate(6, presetPrices);
  }
  __name(select_change_handler, "select_change_handler");
  const change_handler = /* @__PURE__ */ __name(() => {
    addPreset(selectedPreset);
    $$invalidate(5, selectedPreset = "");
  }, "change_handler");
  function dropzone_isHovering_binding(value) {
    isHovering = value;
    $$invalidate(3, isHovering);
  }
  __name(dropzone_isHovering_binding, "dropzone_isHovering_binding");
  $$self.$$set = ($$props2) => {
    if ("prices" in $$props2)
      $$invalidate(0, prices = $$props2.prices);
    if ("item" in $$props2)
      $$invalidate(16, item = $$props2.item);
    if ("remove" in $$props2)
      $$invalidate(1, remove = $$props2.remove);
    if ("presets" in $$props2)
      $$invalidate(2, presets = $$props2.presets);
  };
  return [
    prices,
    remove,
    presets,
    isHovering,
    dragDisabled,
    selectedPreset,
    presetPrices,
    removeEntry,
    addAttribute,
    addPreset,
    dropData,
    editItem,
    handleConsider,
    handleFinalize,
    startDrag,
    handleKeyDown,
    item,
    click_handler,
    input0_input_handler,
    input1_input_handler,
    input2_change_handler,
    input3_change_handler,
    input4_input_handler,
    filepicker_value_binding,
    input_input_handler,
    click_handler_1,
    click_handler_2,
    click_handler_32,
    select_change_handler,
    change_handler,
    dropzone_isHovering_binding
  ];
}
__name(instance$X, "instance$X");
const _PriceList = class _PriceList extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$X,
      create_fragment$_,
      safe_not_equal,
      {
        prices: 0,
        item: 16,
        remove: 1,
        presets: 2
      },
      null,
      [-1, -1]
    );
  }
};
__name(_PriceList, "PriceList");
let PriceList = _PriceList;
function get_each_context$u(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[10] = list[i];
  return child_ctx;
}
__name(get_each_context$u, "get_each_context$u");
function create_each_block$u(key_1, ctx) {
  let option;
  let t_value = (
    /*m*/
    (ctx[10].text ?? "") + ""
  );
  let t;
  let option_value_value;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*m*/
      ctx[10].name;
      option.value = option.__value;
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$macros*/
      2 && t_value !== (t_value = /*m*/
      (ctx[10].text ?? "") + ""))
        set_data(t, t_value);
      if (dirty & /*$macros*/
      2 && option_value_value !== (option_value_value = /*m*/
      ctx[10].name)) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$u, "create_each_block$u");
function create_fragment$Z(ctx) {
  let div;
  let input;
  let t0;
  let datalist;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t1;
  let i;
  let mounted;
  let dispose;
  let each_value = (
    /*$macros*/
    ctx[1]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*m*/
    ctx2[10].id
  ), "get_key");
  for (let i2 = 0; i2 < each_value.length; i2 += 1) {
    let child_ctx = get_each_context$u(ctx, each_value, i2);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i2] = create_each_block$u(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      input = element("input");
      t0 = space();
      datalist = element("datalist");
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        each_blocks[i2].c();
      }
      t1 = space();
      i = element("i");
      attr(
        input,
        "list",
        /*id*/
        ctx[3]
      );
      attr(input, "placeholder", localize("ITEM-PILES.Applications.ItemPileConfig.Main.MacroPlaceholder"));
      set_style(input, "flex", "1");
      set_style(input, "margin-right", "5px");
      attr(input, "type", "text");
      attr(
        datalist,
        "id",
        /*id*/
        ctx[3]
      );
      attr(i, "class", "fas fa-edit item-piles-clickable-link");
      attr(i, "data-fast-tooltip", "Open Macro");
      set_style(i, "margin-top", "5px");
      set_style(i, "font-size", "1rem");
      set_style(i, "flex", "0");
      attr(div, "class", "item-piles-flexrow");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*macro*/
        ctx[0]
      );
      append(div, t0);
      append(div, datalist);
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        if (each_blocks[i2]) {
          each_blocks[i2].m(datalist, null);
        }
      }
      append(div, t1);
      append(div, i);
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[6]
          ),
          listen(
            input,
            "change",
            /*change_handler*/
            ctx[7]
          ),
          listen(
            input,
            "keyup",
            /*keyup_handler*/
            ctx[8]
          ),
          listen(
            i,
            "click",
            /*click_handler*/
            ctx[9]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*macro*/
      1 && input.value !== /*macro*/
      ctx2[0]) {
        set_input_value(
          input,
          /*macro*/
          ctx2[0]
        );
      }
      if (dirty & /*$macros*/
      2) {
        each_value = /*$macros*/
        ctx2[1];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, datalist, destroy_block, create_each_block$u, null, get_each_context$u);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        each_blocks[i2].d();
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$Z, "create_fragment$Z");
function instance$W($$self, $$props, $$invalidate) {
  let $macros;
  let { macro } = $$props;
  let macros = writable$1([]);
  component_subscribe($$self, macros, (value) => $$invalidate(1, $macros = value));
  const id = randomID() + "-list";
  function filterMacros() {
    let allResults = Array.from(game.macros).map((m) => ({ id: m.id, name: m.name }));
    const compendiums = Array.from(game.packs).filter((pack) => pack.documentName === "Macro").map((pack) => ({
      id: pack.metadata.id,
      name: "Compendium." + pack.metadata.id
    }));
    allResults = allResults.concat(compendiums);
    allResults = allResults.filter((m) => {
      return m.name.toLowerCase().includes(macro.toLowerCase()) || !macro;
    });
    if (macro.startsWith("Compendium.") && allResults.length === 1) {
      allResults = Array.from(game.packs.get(allResults[0].id).index).map((m) => {
        return {
          id: allResults[0].id + "." + m._id,
          name: allResults[0].name + "." + m.name
        };
      });
    }
    macros.set(allResults);
  }
  __name(filterMacros, "filterMacros");
  async function openMacro() {
    if (macro.startsWith("Compendium")) {
      let packArray = macro.split(".");
      let pack = game.packs.get(`${packArray[1]}.${packArray[2]}`);
      if (!pack) {
        custom_notify(`Compendium ${packArray[1]}.${packArray[2]} was not found`);
        return;
      }
      let macroFilter = pack.index.filter((m) => m.name === packArray[3]);
      if (!macroFilter.length) {
        custom_notify(`A macro named ${packArray[3]} was not found in Compendium ${packArray[1]}.${packArray[2]}`);
        return;
      }
      let macroDocument = await pack.getDocument(macroFilter[0]._id);
      macroDocument.sheet.render(true);
    } else {
      if (!macro) {
        return;
      }
      let getTest = game.macros.getName(macro);
      if (!getTest) {
        custom_notify(`Could not find the macro named ${macro}`);
        return;
      }
      game.macros.getName(macro).sheet.render(true);
    }
  }
  __name(openMacro, "openMacro");
  filterMacros();
  function input_input_handler() {
    macro = this.value;
    $$invalidate(0, macro);
  }
  __name(input_input_handler, "input_input_handler");
  const change_handler = /* @__PURE__ */ __name(() => {
    filterMacros();
  }, "change_handler");
  const keyup_handler = /* @__PURE__ */ __name(() => {
    filterMacros();
  }, "keyup_handler");
  const click_handler = /* @__PURE__ */ __name(() => openMacro(), "click_handler");
  $$self.$$set = ($$props2) => {
    if ("macro" in $$props2)
      $$invalidate(0, macro = $$props2.macro);
  };
  return [
    macro,
    $macros,
    macros,
    id,
    filterMacros,
    openMacro,
    input_input_handler,
    change_handler,
    keyup_handler,
    click_handler
  ];
}
__name(instance$W, "instance$W");
const _MacroSelector = class _MacroSelector extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$W, create_fragment$Z, safe_not_equal, { macro: 0 });
  }
};
__name(_MacroSelector, "MacroSelector");
let MacroSelector = _MacroSelector;
function get_each_context$t(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
__name(get_each_context$t, "get_each_context$t");
function create_if_block$E(ctx) {
  let datalist;
  let each_value = (
    /*$currentCustomCategories*/
    ctx[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$t(get_each_context$t(ctx, each_value, i));
  }
  return {
    c() {
      datalist = element("datalist");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(datalist, "id", "item-editor-list-" + /*id*/
      ctx[5]);
    },
    m(target, anchor) {
      insert(target, datalist, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(datalist, null);
        }
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$currentCustomCategories*/
      4) {
        each_value = /*$currentCustomCategories*/
        ctx2[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$t(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block$t(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(datalist, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching)
        detach(datalist);
      destroy_each(each_blocks, detaching);
    }
  };
}
__name(create_if_block$E, "create_if_block$E");
function create_each_block$t(ctx) {
  let option;
  let t_value = (
    /*category*/
    ctx[8] + ""
  );
  let t;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*category*/
      ctx[8];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*$currentCustomCategories*/
      4 && t_value !== (t_value = /*category*/
      ctx2[8] + ""))
        set_data(t, t_value);
      if (dirty & /*$currentCustomCategories*/
      4 && option_value_value !== (option_value_value = /*category*/
      ctx2[8])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$t, "create_each_block$t");
function create_fragment$Y(ctx) {
  let div;
  let input;
  let t0;
  let a;
  let t1;
  let mounted;
  let dispose;
  let if_block = (
    /*$currentCustomCategories*/
    ctx[2].length && create_if_block$E(ctx)
  );
  return {
    c() {
      div = element("div");
      input = element("input");
      t0 = space();
      a = element("a");
      a.innerHTML = `<i class="fas fa-cog"></i>`;
      t1 = space();
      if (if_block)
        if_block.c();
      attr(input, "list", "item-editor-list-" + /*id*/
      ctx[5]);
      attr(
        input,
        "placeholder",
        /*placeholder*/
        ctx[1]
      );
      attr(input, "type", "text");
      set_style(a, "flex", "0");
      set_style(a, "margin", "0 0.5rem");
      attr(div, "class", "item-piles-flexrow");
      set_style(div, "align-items", "center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*value*/
        ctx[0]
      );
      append(div, t0);
      append(div, a);
      append(div, t1);
      if (if_block)
        if_block.m(div, null);
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[6]
          ),
          listen(
            a,
            "click",
            /*click_handler*/
            ctx[7]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*placeholder*/
      2) {
        attr(
          input,
          "placeholder",
          /*placeholder*/
          ctx2[1]
        );
      }
      if (dirty & /*value*/
      1 && input.value !== /*value*/
      ctx2[0]) {
        set_input_value(
          input,
          /*value*/
          ctx2[0]
        );
      }
      if (
        /*$currentCustomCategories*/
        ctx2[2].length
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$E(ctx2);
          if_block.c();
          if_block.m(div, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$Y, "create_fragment$Y");
function instance$V($$self, $$props, $$invalidate) {
  let $currentCustomCategories;
  let { value } = $$props;
  let { placeholder = "" } = $$props;
  async function showCustomItemCategoryEditor() {
    openEditor(SETTINGS$1.CUSTOM_ITEM_CATEGORIES).then((result) => {
      setSetting(SETTINGS$1.CUSTOM_ITEM_CATEGORIES, Array.from(new Set(result)));
      currentCustomCategories.set(getSetting(SETTINGS$1.CUSTOM_ITEM_CATEGORIES));
    });
  }
  __name(showCustomItemCategoryEditor, "showCustomItemCategoryEditor");
  let currentCustomCategories = writable$1(Array.from(new Set(getSetting(SETTINGS$1.CUSTOM_ITEM_CATEGORIES))));
  component_subscribe($$self, currentCustomCategories, (value2) => $$invalidate(2, $currentCustomCategories = value2));
  const id = randomID();
  function input_input_handler() {
    value = this.value;
    $$invalidate(0, value);
  }
  __name(input_input_handler, "input_input_handler");
  const click_handler = /* @__PURE__ */ __name(() => showCustomItemCategoryEditor(), "click_handler");
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(0, value = $$props2.value);
    if ("placeholder" in $$props2)
      $$invalidate(1, placeholder = $$props2.placeholder);
  };
  return [
    value,
    placeholder,
    $currentCustomCategories,
    showCustomItemCategoryEditor,
    currentCustomCategories,
    id,
    input_input_handler,
    click_handler
  ];
}
__name(instance$V, "instance$V");
const _CustomCategoryInput = class _CustomCategoryInput extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$V, create_fragment$Y, safe_not_equal, { value: 0, placeholder: 1 });
  }
};
__name(_CustomCategoryInput, "CustomCategoryInput");
let CustomCategoryInput = _CustomCategoryInput;
const itemEditorShell_svelte_svelte_type_style_lang = "";
function get_each_context$s(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[48] = list[i];
  child_ctx[49] = list;
  child_ctx[50] = i;
  return child_ctx;
}
__name(get_each_context$s, "get_each_context$s");
function create_if_block_5$9(ctx) {
  let div1;
  let label0;
  let t0_value = localize("ITEM-PILES.Applications.ItemEditor.CustomCategory") + "";
  let t0;
  let br0;
  let t1;
  let p0;
  let t3;
  let div0;
  let customcategoryinput;
  let updating_value;
  let t4;
  let div2;
  let label1;
  let t5_value = localize("ITEM-PILES.Applications.ItemEditor.Hidden") + "";
  let t5;
  let br1;
  let t6;
  let p1;
  let t8;
  let input0;
  let t9;
  let div3;
  let label2;
  let t10_value = localize("ITEM-PILES.Applications.ItemEditor.CanStack") + "";
  let t10;
  let br2;
  let t11;
  let p2;
  let t13;
  let select0;
  let option0;
  let option1;
  let option2;
  let t19;
  let div4;
  let label3;
  let t20_value = localize("ITEM-PILES.Applications.ItemEditor.NotForSale") + "";
  let t20;
  let br3;
  let t21;
  let p3;
  let t23;
  let input1;
  let t24;
  let div5;
  let label4;
  let t25_value = localize("ITEM-PILES.Applications.ItemEditor.CantBeSoldToMerchants") + "";
  let t25;
  let br4;
  let t26;
  let p4;
  let t28;
  let input2;
  let t29;
  let div6;
  let label5;
  let t30_value = localize("ITEM-PILES.Applications.ItemEditor.InfiniteQuantity") + "";
  let t30;
  let br5;
  let t31;
  let p5;
  let t33;
  let select1;
  let option3;
  let option4;
  let option5;
  let t39;
  let div7;
  let label6;
  let span0;
  let t41;
  let p6;
  let t43;
  let input3;
  let t44;
  let div8;
  let label7;
  let span1;
  let t46;
  let p7;
  let t48;
  let input4;
  let t49;
  let div9;
  let label8;
  let t50_value = localize("ITEM-PILES.Applications.ItemEditor.DisplayQuantity") + "";
  let t50;
  let br6;
  let t51;
  let p8;
  let t53;
  let select2;
  let option6;
  let option7;
  let option8;
  let t59;
  let div10;
  let label9;
  let t60_value = localize("ITEM-PILES.Applications.ItemEditor.Service") + "";
  let t60;
  let br7;
  let t61;
  let p9;
  let t63;
  let input5;
  let t64;
  let div11;
  let label10;
  let span2;
  let t66;
  let p10;
  let t68;
  let div12;
  let macroselector;
  let updating_macro;
  let current;
  let mounted;
  let dispose;
  function customcategoryinput_value_binding(value) {
    ctx[18](value);
  }
  __name(customcategoryinput_value_binding, "customcategoryinput_value_binding");
  let customcategoryinput_props = { placeholder: (
    /*item*/
    ctx[1].type
  ) };
  if (
    /*itemFlagData*/
    ctx[6].customCategory !== void 0
  ) {
    customcategoryinput_props.value = /*itemFlagData*/
    ctx[6].customCategory;
  }
  customcategoryinput = new CustomCategoryInput({ props: customcategoryinput_props });
  binding_callbacks.push(() => bind(customcategoryinput, "value", customcategoryinput_value_binding));
  function macroselector_macro_binding(value) {
    ctx[28](value);
  }
  __name(macroselector_macro_binding, "macroselector_macro_binding");
  let macroselector_props = {};
  if (
    /*itemFlagData*/
    ctx[6].macro !== void 0
  ) {
    macroselector_props.macro = /*itemFlagData*/
    ctx[6].macro;
  }
  macroselector = new MacroSelector({ props: macroselector_props });
  binding_callbacks.push(() => bind(macroselector, "macro", macroselector_macro_binding));
  return {
    c() {
      div1 = element("div");
      label0 = element("label");
      t0 = text(t0_value);
      br0 = element("br");
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.CustomCategoryExplanation")}`;
      t3 = space();
      div0 = element("div");
      create_component(customcategoryinput.$$.fragment);
      t4 = space();
      div2 = element("div");
      label1 = element("label");
      t5 = text(t5_value);
      br1 = element("br");
      t6 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.HiddenExplanation")}`;
      t8 = space();
      input0 = element("input");
      t9 = space();
      div3 = element("div");
      label2 = element("label");
      t10 = text(t10_value);
      br2 = element("br");
      t11 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.CanStackExplanation")}`;
      t13 = space();
      select0 = element("select");
      option0 = element("option");
      option0.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.CanStackDefault")} 
							`;
      option1 = element("option");
      option1.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.CanStackYes")} 
							`;
      option2 = element("option");
      option2.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.CanStackNo")}`;
      t19 = space();
      div4 = element("div");
      label3 = element("label");
      t20 = text(t20_value);
      br3 = element("br");
      t21 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.NotForSaleExplanation")}`;
      t23 = space();
      input1 = element("input");
      t24 = space();
      div5 = element("div");
      label4 = element("label");
      t25 = text(t25_value);
      br4 = element("br");
      t26 = space();
      p4 = element("p");
      p4.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.CantBeSoldToMerchantsExplanation")}`;
      t28 = space();
      input2 = element("input");
      t29 = space();
      div6 = element("div");
      label5 = element("label");
      t30 = text(t30_value);
      br5 = element("br");
      t31 = space();
      p5 = element("p");
      p5.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.InfiniteQuantityExplanation")}`;
      t33 = space();
      select1 = element("select");
      option3 = element("option");
      option3.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.InfiniteQuantityDefault")} 
							`;
      option4 = element("option");
      option4.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.InfiniteQuantityYes")} 
							`;
      option5 = element("option");
      option5.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.InfiniteQuantityNo")}`;
      t39 = space();
      div7 = element("div");
      label6 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.KeepZero")}`;
      t41 = space();
      p6 = element("p");
      p6.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.KeepZeroExplanation")}`;
      t43 = space();
      input3 = element("input");
      t44 = space();
      div8 = element("div");
      label7 = element("label");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.KeepOnMerchant")}`;
      t46 = space();
      p7 = element("p");
      p7.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.KeepOnMerchantExplanation")}`;
      t48 = space();
      input4 = element("input");
      t49 = space();
      div9 = element("div");
      label8 = element("label");
      t50 = text(t50_value);
      br6 = element("br");
      t51 = space();
      p8 = element("p");
      p8.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.DisplayQuantityExplanation")}`;
      t53 = space();
      select2 = element("select");
      option6 = element("option");
      option6.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.DisplayQuantityDefault")} 
							`;
      option7 = element("option");
      option7.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.DisplayQuantityYes")} 
							`;
      option8 = element("option");
      option8.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.DisplayQuantityNo")}`;
      t59 = space();
      div10 = element("div");
      label9 = element("label");
      t60 = text(t60_value);
      br7 = element("br");
      t61 = space();
      p9 = element("p");
      p9.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.ServiceExplanation")}`;
      t63 = space();
      input5 = element("input");
      t64 = space();
      div11 = element("div");
      label10 = element("label");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.PurchaseMacro")}`;
      t66 = space();
      p10 = element("p");
      p10.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.PurchaseMacroExplanation")}`;
      t68 = space();
      div12 = element("div");
      create_component(macroselector.$$.fragment);
      set_style(label0, "flex", "4");
      set_style(div0, "flex", "4");
      attr(div1, "class", "form-group");
      set_style(label1, "flex", "4");
      attr(input0, "type", "checkbox");
      attr(div2, "class", "form-group");
      set_style(label2, "flex", "4");
      option0.__value = "default";
      option0.value = option0.__value;
      option1.__value = "yes";
      option1.value = option1.__value;
      option2.__value = "no";
      option2.value = option2.__value;
      set_style(select0, "flex", "0 1 auto");
      if (
        /*itemFlagData*/
        ctx[6].canStack === void 0
      )
        add_render_callback(() => (
          /*select0_change_handler*/
          ctx[20].call(select0)
        ));
      attr(div3, "class", "form-group");
      set_style(label3, "flex", "4");
      attr(input1, "type", "checkbox");
      attr(div4, "class", "form-group");
      set_style(label4, "flex", "4");
      attr(input2, "type", "checkbox");
      attr(div5, "class", "form-group");
      option3.__value = "default";
      option3.value = option3.__value;
      option4.__value = "yes";
      option4.value = option4.__value;
      option5.__value = "no";
      option5.value = option5.__value;
      set_style(select1, "flex", "0 1 auto");
      if (
        /*itemFlagData*/
        ctx[6].infiniteQuantity === void 0
      )
        add_render_callback(() => (
          /*select1_change_handler*/
          ctx[23].call(select1)
        ));
      attr(div6, "class", "form-group");
      attr(input3, "type", "checkbox");
      attr(div7, "class", "form-group");
      attr(input4, "type", "checkbox");
      attr(div8, "class", "form-group");
      option6.__value = "default";
      option6.value = option6.__value;
      option7.__value = "yes";
      option7.value = option7.__value;
      option8.__value = "no";
      option8.value = option8.__value;
      set_style(select2, "flex", "0 1 auto");
      if (
        /*itemFlagData*/
        ctx[6].displayQuantity === void 0
      )
        add_render_callback(() => (
          /*select2_change_handler*/
          ctx[26].call(select2)
        ));
      attr(div9, "class", "form-group");
      set_style(label9, "flex", "4");
      attr(input5, "type", "checkbox");
      attr(div10, "class", "form-group");
      set_style(label10, "flex", "4");
      attr(div11, "class", "form-group");
      attr(div12, "class", "form-group");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, label0);
      append(label0, t0);
      append(label0, br0);
      append(label0, t1);
      append(label0, p0);
      append(div1, t3);
      append(div1, div0);
      mount_component(customcategoryinput, div0, null);
      insert(target, t4, anchor);
      insert(target, div2, anchor);
      append(div2, label1);
      append(label1, t5);
      append(label1, br1);
      append(label1, t6);
      append(label1, p1);
      append(div2, t8);
      append(div2, input0);
      input0.checked = /*itemFlagData*/
      ctx[6].hidden;
      insert(target, t9, anchor);
      insert(target, div3, anchor);
      append(div3, label2);
      append(label2, t10);
      append(label2, br2);
      append(label2, t11);
      append(label2, p2);
      append(div3, t13);
      append(div3, select0);
      append(select0, option0);
      append(select0, option1);
      append(select0, option2);
      select_option(
        select0,
        /*itemFlagData*/
        ctx[6].canStack,
        true
      );
      insert(target, t19, anchor);
      insert(target, div4, anchor);
      append(div4, label3);
      append(label3, t20);
      append(label3, br3);
      append(label3, t21);
      append(label3, p3);
      append(div4, t23);
      append(div4, input1);
      input1.checked = /*itemFlagData*/
      ctx[6].notForSale;
      insert(target, t24, anchor);
      insert(target, div5, anchor);
      append(div5, label4);
      append(label4, t25);
      append(label4, br4);
      append(label4, t26);
      append(label4, p4);
      append(div5, t28);
      append(div5, input2);
      input2.checked = /*itemFlagData*/
      ctx[6].cantBeSoldToMerchants;
      insert(target, t29, anchor);
      insert(target, div6, anchor);
      append(div6, label5);
      append(label5, t30);
      append(label5, br5);
      append(label5, t31);
      append(label5, p5);
      append(div6, t33);
      append(div6, select1);
      append(select1, option3);
      append(select1, option4);
      append(select1, option5);
      select_option(
        select1,
        /*itemFlagData*/
        ctx[6].infiniteQuantity,
        true
      );
      insert(target, t39, anchor);
      insert(target, div7, anchor);
      append(div7, label6);
      append(label6, span0);
      append(label6, t41);
      append(label6, p6);
      append(div7, t43);
      append(div7, input3);
      input3.checked = /*itemFlagData*/
      ctx[6].keepZeroQuantity;
      insert(target, t44, anchor);
      insert(target, div8, anchor);
      append(div8, label7);
      append(label7, span1);
      append(label7, t46);
      append(label7, p7);
      append(div8, t48);
      append(div8, input4);
      input4.checked = /*itemFlagData*/
      ctx[6].keepOnMerchant;
      insert(target, t49, anchor);
      insert(target, div9, anchor);
      append(div9, label8);
      append(label8, t50);
      append(label8, br6);
      append(label8, t51);
      append(label8, p8);
      append(div9, t53);
      append(div9, select2);
      append(select2, option6);
      append(select2, option7);
      append(select2, option8);
      select_option(
        select2,
        /*itemFlagData*/
        ctx[6].displayQuantity,
        true
      );
      insert(target, t59, anchor);
      insert(target, div10, anchor);
      append(div10, label9);
      append(label9, t60);
      append(label9, br7);
      append(label9, t61);
      append(label9, p9);
      append(div10, t63);
      append(div10, input5);
      input5.checked = /*itemFlagData*/
      ctx[6].isService;
      insert(target, t64, anchor);
      insert(target, div11, anchor);
      append(div11, label10);
      append(label10, span2);
      append(label10, t66);
      append(label10, p10);
      insert(target, t68, anchor);
      insert(target, div12, anchor);
      mount_component(macroselector, div12, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler*/
            ctx[19]
          ),
          listen(
            select0,
            "change",
            /*select0_change_handler*/
            ctx[20]
          ),
          listen(
            input1,
            "change",
            /*input1_change_handler*/
            ctx[21]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler*/
            ctx[22]
          ),
          listen(
            select1,
            "change",
            /*select1_change_handler*/
            ctx[23]
          ),
          listen(
            input3,
            "change",
            /*input3_change_handler*/
            ctx[24]
          ),
          listen(
            input4,
            "change",
            /*input4_change_handler*/
            ctx[25]
          ),
          listen(
            select2,
            "change",
            /*select2_change_handler*/
            ctx[26]
          ),
          listen(
            input5,
            "change",
            /*input5_change_handler*/
            ctx[27]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const customcategoryinput_changes = {};
      if (dirty[0] & /*item*/
      2)
        customcategoryinput_changes.placeholder = /*item*/
        ctx2[1].type;
      if (!updating_value && dirty[0] & /*itemFlagData*/
      64) {
        updating_value = true;
        customcategoryinput_changes.value = /*itemFlagData*/
        ctx2[6].customCategory;
        add_flush_callback(() => updating_value = false);
      }
      customcategoryinput.$set(customcategoryinput_changes);
      if (dirty[0] & /*itemFlagData*/
      64) {
        input0.checked = /*itemFlagData*/
        ctx2[6].hidden;
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        select_option(
          select0,
          /*itemFlagData*/
          ctx2[6].canStack
        );
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        input1.checked = /*itemFlagData*/
        ctx2[6].notForSale;
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        input2.checked = /*itemFlagData*/
        ctx2[6].cantBeSoldToMerchants;
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        select_option(
          select1,
          /*itemFlagData*/
          ctx2[6].infiniteQuantity
        );
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        input3.checked = /*itemFlagData*/
        ctx2[6].keepZeroQuantity;
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        input4.checked = /*itemFlagData*/
        ctx2[6].keepOnMerchant;
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        select_option(
          select2,
          /*itemFlagData*/
          ctx2[6].displayQuantity
        );
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        input5.checked = /*itemFlagData*/
        ctx2[6].isService;
      }
      const macroselector_changes = {};
      if (!updating_macro && dirty[0] & /*itemFlagData*/
      64) {
        updating_macro = true;
        macroselector_changes.macro = /*itemFlagData*/
        ctx2[6].macro;
        add_flush_callback(() => updating_macro = false);
      }
      macroselector.$set(macroselector_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(customcategoryinput.$$.fragment, local);
      transition_in(macroselector.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(customcategoryinput.$$.fragment, local);
      transition_out(macroselector.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      destroy_component(customcategoryinput);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(div2);
      if (detaching)
        detach(t9);
      if (detaching)
        detach(div3);
      if (detaching)
        detach(t19);
      if (detaching)
        detach(div4);
      if (detaching)
        detach(t24);
      if (detaching)
        detach(div5);
      if (detaching)
        detach(t29);
      if (detaching)
        detach(div6);
      if (detaching)
        detach(t39);
      if (detaching)
        detach(div7);
      if (detaching)
        detach(t44);
      if (detaching)
        detach(div8);
      if (detaching)
        detach(t49);
      if (detaching)
        detach(div9);
      if (detaching)
        detach(t59);
      if (detaching)
        detach(div10);
      if (detaching)
        detach(t64);
      if (detaching)
        detach(div11);
      if (detaching)
        detach(t68);
      if (detaching)
        detach(div12);
      destroy_component(macroselector);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_5$9, "create_if_block_5$9");
function create_if_block_1$r(ctx) {
  let t0;
  let div0;
  let label0;
  let t1_value = localize("ITEM-PILES.Applications.ItemEditor.Free") + "";
  let t1;
  let br0;
  let t2;
  let p0;
  let t4;
  let input0;
  let t5;
  let div1;
  let label1;
  let t6_value = localize("ITEM-PILES.Applications.ItemEditor.DisableNormalCost") + "";
  let t6;
  let br1;
  let t7;
  let p1;
  let t9;
  let input1;
  let t10;
  let div2;
  let label2;
  let t11_value = localize("ITEM-PILES.Applications.ItemEditor.PurchaseOptions") + "";
  let t11;
  let br2;
  let t12;
  let p2;
  let t14;
  let button;
  let i;
  let t15;
  let t16_value = localize("ITEM-PILES.Applications.ItemEditor.AddPurchaseOption") + "";
  let t16;
  let t17;
  let if_block1_anchor;
  let current;
  let mounted;
  let dispose;
  let if_block0 = game.system.id !== "pf2e" && create_if_block_3$f(ctx);
  let if_block1 = (
    /*itemFlagData*/
    ctx[6].prices.length && create_if_block_2$j(ctx)
  );
  return {
    c() {
      if (if_block0)
        if_block0.c();
      t0 = space();
      div0 = element("div");
      label0 = element("label");
      t1 = text(t1_value);
      br0 = element("br");
      t2 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.FreeExplanation")}`;
      t4 = space();
      input0 = element("input");
      t5 = space();
      div1 = element("div");
      label1 = element("label");
      t6 = text(t6_value);
      br1 = element("br");
      t7 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.DisableNormalCostExplanation")}`;
      t9 = space();
      input1 = element("input");
      t10 = space();
      div2 = element("div");
      label2 = element("label");
      t11 = text(t11_value);
      br2 = element("br");
      t12 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.PurchaseOptionsExplanation")}`;
      t14 = space();
      button = element("button");
      i = element("i");
      t15 = space();
      t16 = text(t16_value);
      t17 = space();
      if (if_block1)
        if_block1.c();
      if_block1_anchor = empty();
      set_style(label0, "flex", "4");
      attr(input0, "type", "checkbox");
      attr(div0, "class", "form-group");
      set_style(label1, "flex", "4");
      attr(input1, "type", "checkbox");
      attr(div1, "class", "form-group");
      set_style(label2, "flex", "4");
      attr(i, "class", "fas fa-plus");
      attr(button, "type", "button");
      attr(div2, "class", "form-group");
    },
    m(target, anchor) {
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, div0, anchor);
      append(div0, label0);
      append(label0, t1);
      append(label0, br0);
      append(label0, t2);
      append(label0, p0);
      append(div0, t4);
      append(div0, input0);
      input0.checked = /*itemFlagData*/
      ctx[6].free;
      insert(target, t5, anchor);
      insert(target, div1, anchor);
      append(div1, label1);
      append(label1, t6);
      append(label1, br1);
      append(label1, t7);
      append(label1, p1);
      append(div1, t9);
      append(div1, input1);
      input1.checked = /*itemFlagData*/
      ctx[6].disableNormalCost;
      insert(target, t10, anchor);
      insert(target, div2, anchor);
      append(div2, label2);
      append(label2, t11);
      append(label2, br2);
      append(label2, t12);
      append(label2, p2);
      append(div2, t14);
      append(div2, button);
      append(button, i);
      append(button, t15);
      append(button, t16);
      insert(target, t17, anchor);
      if (if_block1)
        if_block1.m(target, anchor);
      insert(target, if_block1_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler_1*/
            ctx[32]
          ),
          listen(
            input1,
            "change",
            /*input1_change_handler_1*/
            ctx[33]
          ),
          listen(
            button,
            "click",
            /*click_handler*/
            ctx[34]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (game.system.id !== "pf2e")
        if_block0.p(ctx2, dirty);
      if (dirty[0] & /*itemFlagData*/
      64) {
        input0.checked = /*itemFlagData*/
        ctx2[6].free;
      }
      if (dirty[0] & /*itemFlagData*/
      64) {
        input1.checked = /*itemFlagData*/
        ctx2[6].disableNormalCost;
      }
      if (
        /*itemFlagData*/
        ctx2[6].prices.length
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*itemFlagData*/
          64) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_2$j(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (if_block0)
        if_block0.d(detaching);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t5);
      if (detaching)
        detach(div1);
      if (detaching)
        detach(t10);
      if (detaching)
        detach(div2);
      if (detaching)
        detach(t17);
      if (if_block1)
        if_block1.d(detaching);
      if (detaching)
        detach(if_block1_anchor);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_1$r, "create_if_block_1$r");
function create_if_block_3$f(ctx) {
  let t0;
  let div;
  let label;
  let t1_value = localize("ITEM-PILES.Applications.ItemEditor.QuantityForPrice") + "";
  let t1;
  let br;
  let t2;
  let p;
  let t4;
  let input;
  let mounted;
  let dispose;
  let if_block = game.system.id !== "wfrp4e" && create_if_block_4$d(ctx);
  return {
    c() {
      if (if_block)
        if_block.c();
      t0 = space();
      div = element("div");
      label = element("label");
      t1 = text(t1_value);
      br = element("br");
      t2 = space();
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.QuantityForPriceExplanation")}`;
      t4 = space();
      input = element("input");
      set_style(label, "flex", "4");
      attr(input, "type", "number");
      attr(div, "class", "form-group");
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, div, anchor);
      append(div, label);
      append(label, t1);
      append(label, br);
      append(label, t2);
      append(label, p);
      append(div, t4);
      append(div, input);
      set_input_value(
        input,
        /*$quantityForPrice*/
        ctx[8]
      );
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler_1*/
          ctx[31]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (game.system.id !== "wfrp4e")
        if_block.p(ctx2, dirty);
      if (dirty[0] & /*$quantityForPrice*/
      256 && to_number(input.value) !== /*$quantityForPrice*/
      ctx2[8]) {
        set_input_value(
          input,
          /*$quantityForPrice*/
          ctx2[8]
        );
      }
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$f, "create_if_block_3$f");
function create_if_block_4$d(ctx) {
  let div;
  let label;
  let t0_value = localize("ITEM-PILES.Applications.ItemEditor.BasePrice") + "";
  let t0;
  let br;
  let t1;
  let p;
  let t3;
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      label = element("label");
      t0 = text(t0_value);
      br = element("br");
      t1 = space();
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.BasePriceExplanation")}`;
      t3 = space();
      input = element("input");
      set_style(label, "flex", "4");
      attr(input, "type", "text");
      attr(div, "class", "form-group");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, t0);
      append(label, br);
      append(label, t1);
      append(label, p);
      append(div, t3);
      append(div, input);
      set_input_value(
        input,
        /*$price*/
        ctx[7]
      );
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[29]
          ),
          listen(
            input,
            "change",
            /*change_handler*/
            ctx[30]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$price*/
      128 && input.value !== /*$price*/
      ctx2[7]) {
        set_input_value(
          input,
          /*$price*/
          ctx2[7]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_4$d, "create_if_block_4$d");
function create_if_block_2$j(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let current;
  let each_value = (
    /*itemFlagData*/
    ctx[6].prices
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*groupIndex*/
    ctx2[50]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$s(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$s(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*item, store, itemFlagData*/
      1090) {
        each_value = /*itemFlagData*/
        ctx2[6].prices;
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, each_1_anchor.parentNode, outro_and_destroy_block, create_each_block$s, each_1_anchor, get_each_context$s);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block_2$j, "create_if_block_2$j");
function create_each_block$s(key_1, ctx) {
  let first;
  let pricelist;
  let updating_prices;
  let current;
  function func2() {
    return (
      /*func*/
      ctx[35](
        /*groupIndex*/
        ctx[50]
      )
    );
  }
  __name(func2, "func");
  function pricelist_prices_binding(value) {
    ctx[36](
      value,
      /*prices*/
      ctx[48],
      /*each_value*/
      ctx[49],
      /*groupIndex*/
      ctx[50]
    );
  }
  __name(pricelist_prices_binding, "pricelist_prices_binding");
  let pricelist_props = { item: (
    /*item*/
    ctx[1]
  ), remove: func2 };
  if (
    /*prices*/
    ctx[48] !== void 0
  ) {
    pricelist_props.prices = /*prices*/
    ctx[48];
  }
  pricelist = new PriceList({ props: pricelist_props });
  binding_callbacks.push(() => bind(pricelist, "prices", pricelist_prices_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(pricelist.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(pricelist, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const pricelist_changes = {};
      if (dirty[0] & /*item*/
      2)
        pricelist_changes.item = /*item*/
        ctx[1];
      if (dirty[0] & /*itemFlagData*/
      64)
        pricelist_changes.remove = func2;
      if (!updating_prices && dirty[0] & /*itemFlagData*/
      64) {
        updating_prices = true;
        pricelist_changes.prices = /*prices*/
        ctx[48];
        add_flush_callback(() => updating_prices = false);
      }
      pricelist.$set(pricelist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(pricelist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(pricelist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(pricelist, detaching);
    }
  };
}
__name(create_each_block$s, "create_each_block$s");
function create_if_block$D(ctx) {
  let div3;
  let label0;
  let t0_value = localize("ITEM-PILES.Applications.ItemEditor.GridSize") + "";
  let t0;
  let br0;
  let t1;
  let p0;
  let t3;
  let div2;
  let div0;
  let i0;
  let t5;
  let i1;
  let t7;
  let div1;
  let input0;
  let t8;
  let span0;
  let t10;
  let input1;
  let t11;
  let div5;
  let label1;
  let t12_value = localize("ITEM-PILES.Applications.ItemEditor.VaultImage") + "";
  let t12;
  let br1;
  let t13;
  let p1;
  let t15;
  let div4;
  let filepicker0;
  let updating_value;
  let t16;
  let div7;
  let label2;
  let t17_value = localize("ITEM-PILES.Applications.ItemEditor.VaultImageRotated") + "";
  let t17;
  let br2;
  let t18;
  let p2;
  let t20;
  let div6;
  let filepicker1;
  let updating_value_1;
  let t21;
  let div8;
  let label3;
  let t22_value = localize("ITEM-PILES.Applications.ItemEditor.VaultExpander") + "";
  let t22;
  let br3;
  let t23;
  let p3;
  let t25;
  let input2;
  let t26;
  let div12;
  let label4;
  let span1;
  let t28;
  let p4;
  let t30;
  let div11;
  let div9;
  let i2;
  let t32;
  let i3;
  let t34;
  let div10;
  let input3;
  let t35;
  let span2;
  let t37;
  let input4;
  let current;
  let mounted;
  let dispose;
  function filepicker0_value_binding(value) {
    ctx[39](value);
  }
  __name(filepicker0_value_binding, "filepicker0_value_binding");
  let filepicker0_props = {
    placeholder: "path/image.png",
    type: "imagevideo"
  };
  if (
    /*itemFlagData*/
    ctx[6].vaultImage !== void 0
  ) {
    filepicker0_props.value = /*itemFlagData*/
    ctx[6].vaultImage;
  }
  filepicker0 = new FilePicker_1({ props: filepicker0_props });
  binding_callbacks.push(() => bind(filepicker0, "value", filepicker0_value_binding));
  function filepicker1_value_binding(value) {
    ctx[40](value);
  }
  __name(filepicker1_value_binding, "filepicker1_value_binding");
  let filepicker1_props = {
    placeholder: "path/image.png",
    type: "imagevideo"
  };
  if (
    /*itemFlagData*/
    ctx[6].vaultImageFlipped !== void 0
  ) {
    filepicker1_props.value = /*itemFlagData*/
    ctx[6].vaultImageFlipped;
  }
  filepicker1 = new FilePicker_1({ props: filepicker1_props });
  binding_callbacks.push(() => bind(filepicker1, "value", filepicker1_value_binding));
  return {
    c() {
      div3 = element("div");
      label0 = element("label");
      t0 = text(t0_value);
      br0 = element("br");
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.GridSizeExplanation")}`;
      t3 = space();
      div2 = element("div");
      div0 = element("div");
      i0 = element("i");
      i0.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.GridWidth")}`;
      t5 = space();
      i1 = element("i");
      i1.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.GridHeight")}`;
      t7 = space();
      div1 = element("div");
      input0 = element("input");
      t8 = space();
      span0 = element("span");
      span0.textContent = "x";
      t10 = space();
      input1 = element("input");
      t11 = space();
      div5 = element("div");
      label1 = element("label");
      t12 = text(t12_value);
      br1 = element("br");
      t13 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.VaultImageExplanation")}`;
      t15 = space();
      div4 = element("div");
      create_component(filepicker0.$$.fragment);
      t16 = space();
      div7 = element("div");
      label2 = element("label");
      t17 = text(t17_value);
      br2 = element("br");
      t18 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.VaultImageRotatedExplanation")}`;
      t20 = space();
      div6 = element("div");
      create_component(filepicker1.$$.fragment);
      t21 = space();
      div8 = element("div");
      label3 = element("label");
      t22 = text(t22_value);
      br3 = element("br");
      t23 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.VaultExpanderExplanation")}`;
      t25 = space();
      input2 = element("input");
      t26 = space();
      div12 = element("div");
      label4 = element("label");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.ExpandColumnsRows")}`;
      t28 = space();
      p4 = element("p");
      p4.textContent = `${localize("ITEM-PILES.Applications.ItemEditor.ExpandColumnsRowsExplanation")}`;
      t30 = space();
      div11 = element("div");
      div9 = element("div");
      i2 = element("i");
      i2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Columns")}`;
      t32 = space();
      i3 = element("i");
      i3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Rows")}`;
      t34 = space();
      div10 = element("div");
      input3 = element("input");
      t35 = space();
      span2 = element("span");
      span2.textContent = "x";
      t37 = space();
      input4 = element("input");
      set_style(label0, "flex", "6");
      attr(i0, "class", "svelte-h8uqq1");
      attr(i1, "class", "svelte-h8uqq1");
      set_style(div0, "text-align", "center");
      set_style(div0, "font-size", "0.7rem");
      attr(div0, "class", "svelte-h8uqq1");
      set_style(input0, "text-align", "right");
      attr(input0, "type", "number");
      attr(input0, "placeholder", "Enter a number...");
      attr(input0, "class", "svelte-h8uqq1");
      set_style(span0, "flex", "0");
      attr(span0, "class", "svelte-h8uqq1");
      attr(input1, "type", "number");
      attr(input1, "placeholder", "Enter a number...");
      attr(input1, "class", "svelte-h8uqq1");
      set_style(div1, "align-items", "center");
      attr(div1, "class", "svelte-h8uqq1");
      attr(div2, "class", "item-piles-grid-columns svelte-h8uqq1");
      set_style(div2, "flex", "3");
      attr(div3, "class", "form-group");
      set_style(label1, "flex", "4");
      attr(div4, "class", "form-fields");
      attr(div5, "class", "form-group");
      set_style(label2, "flex", "4");
      attr(div6, "class", "form-fields");
      attr(div7, "class", "form-group");
      set_style(label3, "flex", "4");
      attr(input2, "type", "checkbox");
      attr(div8, "class", "form-group");
      set_style(label4, "flex", "6");
      attr(i2, "class", "svelte-h8uqq1");
      attr(i3, "class", "svelte-h8uqq1");
      set_style(div9, "text-align", "center");
      set_style(div9, "font-size", "0.7rem");
      attr(div9, "class", "svelte-h8uqq1");
      set_style(input3, "text-align", "right");
      attr(input3, "type", "number");
      attr(input3, "placeholder", "Enter a number...");
      attr(input3, "class", "svelte-h8uqq1");
      set_style(span2, "flex", "0");
      attr(span2, "class", "svelte-h8uqq1");
      attr(input4, "type", "number");
      attr(input4, "placeholder", "Enter a number...");
      attr(input4, "class", "svelte-h8uqq1");
      set_style(div10, "align-items", "center");
      attr(div10, "class", "svelte-h8uqq1");
      attr(div11, "class", "item-piles-grid-columns svelte-h8uqq1");
      set_style(div11, "flex", "3");
      attr(div12, "class", "form-group");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, label0);
      append(label0, t0);
      append(label0, br0);
      append(label0, t1);
      append(label0, p0);
      append(div3, t3);
      append(div3, div2);
      append(div2, div0);
      append(div0, i0);
      append(div0, t5);
      append(div0, i1);
      append(div2, t7);
      append(div2, div1);
      append(div1, input0);
      set_input_value(
        input0,
        /*itemFlagData*/
        ctx[6].width
      );
      append(div1, t8);
      append(div1, span0);
      append(div1, t10);
      append(div1, input1);
      set_input_value(
        input1,
        /*itemFlagData*/
        ctx[6].height
      );
      insert(target, t11, anchor);
      insert(target, div5, anchor);
      append(div5, label1);
      append(label1, t12);
      append(label1, br1);
      append(label1, t13);
      append(label1, p1);
      append(div5, t15);
      append(div5, div4);
      mount_component(filepicker0, div4, null);
      insert(target, t16, anchor);
      insert(target, div7, anchor);
      append(div7, label2);
      append(label2, t17);
      append(label2, br2);
      append(label2, t18);
      append(label2, p2);
      append(div7, t20);
      append(div7, div6);
      mount_component(filepicker1, div6, null);
      insert(target, t21, anchor);
      insert(target, div8, anchor);
      append(div8, label3);
      append(label3, t22);
      append(label3, br3);
      append(label3, t23);
      append(label3, p3);
      append(div8, t25);
      append(div8, input2);
      input2.checked = /*itemFlagData*/
      ctx[6].vaultExpander;
      insert(target, t26, anchor);
      insert(target, div12, anchor);
      append(div12, label4);
      append(label4, span1);
      append(label4, t28);
      append(label4, p4);
      append(div12, t30);
      append(div12, div11);
      append(div11, div9);
      append(div9, i2);
      append(div9, t32);
      append(div9, i3);
      append(div11, t34);
      append(div11, div10);
      append(div10, input3);
      set_input_value(
        input3,
        /*itemFlagData*/
        ctx[6].addsCols
      );
      append(div10, t35);
      append(div10, span2);
      append(div10, t37);
      append(div10, input4);
      set_input_value(
        input4,
        /*itemFlagData*/
        ctx[6].addsRows
      );
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "input",
            /*input0_input_handler*/
            ctx[37]
          ),
          listen(
            input1,
            "input",
            /*input1_input_handler*/
            ctx[38]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler_1*/
            ctx[41]
          ),
          listen(
            input3,
            "input",
            /*input3_input_handler*/
            ctx[42]
          ),
          listen(
            input4,
            "input",
            /*input4_input_handler*/
            ctx[43]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*itemFlagData*/
      64 && to_number(input0.value) !== /*itemFlagData*/
      ctx2[6].width) {
        set_input_value(
          input0,
          /*itemFlagData*/
          ctx2[6].width
        );
      }
      if (dirty[0] & /*itemFlagData*/
      64 && to_number(input1.value) !== /*itemFlagData*/
      ctx2[6].height) {
        set_input_value(
          input1,
          /*itemFlagData*/
          ctx2[6].height
        );
      }
      const filepicker0_changes = {};
      if (!updating_value && dirty[0] & /*itemFlagData*/
      64) {
        updating_value = true;
        filepicker0_changes.value = /*itemFlagData*/
        ctx2[6].vaultImage;
        add_flush_callback(() => updating_value = false);
      }
      filepicker0.$set(filepicker0_changes);
      const filepicker1_changes = {};
      if (!updating_value_1 && dirty[0] & /*itemFlagData*/
      64) {
        updating_value_1 = true;
        filepicker1_changes.value = /*itemFlagData*/
        ctx2[6].vaultImageFlipped;
        add_flush_callback(() => updating_value_1 = false);
      }
      filepicker1.$set(filepicker1_changes);
      if (dirty[0] & /*itemFlagData*/
      64) {
        input2.checked = /*itemFlagData*/
        ctx2[6].vaultExpander;
      }
      if (dirty[0] & /*itemFlagData*/
      64 && to_number(input3.value) !== /*itemFlagData*/
      ctx2[6].addsCols) {
        set_input_value(
          input3,
          /*itemFlagData*/
          ctx2[6].addsCols
        );
      }
      if (dirty[0] & /*itemFlagData*/
      64 && to_number(input4.value) !== /*itemFlagData*/
      ctx2[6].addsRows) {
        set_input_value(
          input4,
          /*itemFlagData*/
          ctx2[6].addsRows
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(filepicker0.$$.fragment, local);
      transition_in(filepicker1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filepicker0.$$.fragment, local);
      transition_out(filepicker1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if (detaching)
        detach(t11);
      if (detaching)
        detach(div5);
      destroy_component(filepicker0);
      if (detaching)
        detach(t16);
      if (detaching)
        detach(div7);
      destroy_component(filepicker1);
      if (detaching)
        detach(t21);
      if (detaching)
        detach(div8);
      if (detaching)
        detach(t26);
      if (detaching)
        detach(div12);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block$D, "create_if_block$D");
function create_default_slot$n(ctx) {
  let form_1;
  let tabs;
  let updating_activeTab;
  let t0;
  let section;
  let div;
  let t1;
  let t2;
  let t3;
  let footer;
  let button0;
  let i0;
  let t4;
  let t5_value = localize("ITEM-PILES.Applications.ItemEditor.Update") + "";
  let t5;
  let t6;
  let button1;
  let i1;
  let t7;
  let t8_value = localize("Cancel") + "";
  let t8;
  let current;
  let mounted;
  let dispose;
  function tabs_activeTab_binding(value) {
    ctx[17](value);
  }
  __name(tabs_activeTab_binding, "tabs_activeTab_binding");
  let tabs_props = {
    tabs: [
      {
        value: "general",
        label: localize("ITEM-PILES.Applications.ItemEditor.General")
      },
      {
        value: "price",
        label: localize("ITEM-PILES.Applications.ItemEditor.Price")
      },
      {
        value: "vault",
        label: localize("ITEM-PILES.Applications.ItemEditor.Vault")
      }
    ]
  };
  if (
    /*activeTab*/
    ctx[5] !== void 0
  ) {
    tabs_props.activeTab = /*activeTab*/
    ctx[5];
  }
  tabs = new Tabs({ props: tabs_props });
  binding_callbacks.push(() => bind(tabs, "activeTab", tabs_activeTab_binding));
  let if_block0 = (
    /*activeTab*/
    ctx[5] === "general" && create_if_block_5$9(ctx)
  );
  let if_block1 = (
    /*activeTab*/
    ctx[5] === "price" && create_if_block_1$r(ctx)
  );
  let if_block2 = (
    /*activeTab*/
    ctx[5] === "vault" && create_if_block$D(ctx)
  );
  return {
    c() {
      form_1 = element("form");
      create_component(tabs.$$.fragment);
      t0 = space();
      section = element("section");
      div = element("div");
      if (if_block0)
        if_block0.c();
      t1 = space();
      if (if_block1)
        if_block1.c();
      t2 = space();
      if (if_block2)
        if_block2.c();
      t3 = space();
      footer = element("footer");
      button0 = element("button");
      i0 = element("i");
      t4 = space();
      t5 = text(t5_value);
      t6 = space();
      button1 = element("button");
      i1 = element("i");
      t7 = space();
      t8 = text(t8_value);
      attr(div, "class", "tab flex svelte-h8uqq1");
      attr(section, "class", "tab-body");
      attr(i0, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i1, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-config-container");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      mount_component(tabs, form_1, null);
      append(form_1, t0);
      append(form_1, section);
      append(section, div);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t1);
      if (if_block1)
        if_block1.m(div, null);
      append(div, t2);
      if (if_block2)
        if_block2.m(div, null);
      append(form_1, t3);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i0);
      append(button0, t4);
      append(button0, t5);
      append(footer, t6);
      append(footer, button1);
      append(button1, i1);
      append(button1, t7);
      append(button1, t8);
      ctx[45](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[2],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler_1*/
            ctx[44],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[14]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const tabs_changes = {};
      if (!updating_activeTab && dirty[0] & /*activeTab*/
      32) {
        updating_activeTab = true;
        tabs_changes.activeTab = /*activeTab*/
        ctx2[5];
        add_flush_callback(() => updating_activeTab = false);
      }
      tabs.$set(tabs_changes);
      if (
        /*activeTab*/
        ctx2[5] === "general"
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*activeTab*/
          32) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_5$9(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div, t1);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*activeTab*/
        ctx2[5] === "price"
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*activeTab*/
          32) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_1$r(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div, t2);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*activeTab*/
        ctx2[5] === "vault"
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty[0] & /*activeTab*/
          32) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block$D(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div, null);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(tabs.$$.fragment, local);
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(tabs.$$.fragment, local);
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      destroy_component(tabs);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      ctx[45](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$n, "create_default_slot$n");
function create_fragment$X(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[46](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$n] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*form, itemFlagData, activeTab, item, $quantityForPrice, $price, oldPrice*/
      506 | dirty[1] & /*$$scope*/
      1048576) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$X, "create_fragment$X");
function instance$U($$self, $$props, $$invalidate) {
  let itemFlagData;
  let $flagDataStore;
  let $price;
  let $quantityForPrice;
  const { application } = getContext("#external");
  let { item } = $$props;
  let { elementRoot } = $$props;
  let store = ItemPriceStore.make(item);
  let currentCustomCategories = writable$1(Array.from(new Set(getSetting(SETTINGS$1.CUSTOM_ITEM_CATEGORIES))));
  const flagDataStore = store.data;
  component_subscribe($$self, flagDataStore, (value) => $$invalidate(16, $flagDataStore = value));
  let price = store.price;
  component_subscribe($$self, price, (value) => $$invalidate(7, $price = value));
  let quantityForPrice = store.quantityForPrice;
  component_subscribe($$self, quantityForPrice, (value) => $$invalidate(8, $quantityForPrice = value));
  let oldPrice = get_store_value(price);
  let form;
  async function updateSettings() {
    const flagData = store.export();
    if (flagData.flags.customCategory) {
      let customCategories = get_store_value(currentCustomCategories);
      customCategories.push(flagData.flags.customCategory);
      await setSetting(SETTINGS$1.CUSTOM_ITEM_CATEGORIES, Array.from(new Set(customCategories)));
    }
    await updateItemData(item, flagData);
    application.options.resolve();
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function addGroup() {
    $$invalidate(6, itemFlagData.prices = [...itemFlagData.prices, []], itemFlagData);
  }
  __name(addGroup, "addGroup");
  let activeTab = "general";
  function tabs_activeTab_binding(value) {
    activeTab = value;
    $$invalidate(5, activeTab);
  }
  __name(tabs_activeTab_binding, "tabs_activeTab_binding");
  function customcategoryinput_value_binding(value) {
    if ($$self.$$.not_equal(itemFlagData.customCategory, value)) {
      itemFlagData.customCategory = value;
      $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
    }
  }
  __name(customcategoryinput_value_binding, "customcategoryinput_value_binding");
  function input0_change_handler() {
    itemFlagData.hidden = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input0_change_handler, "input0_change_handler");
  function select0_change_handler() {
    itemFlagData.canStack = select_value(this);
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(select0_change_handler, "select0_change_handler");
  function input1_change_handler() {
    itemFlagData.notForSale = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input1_change_handler, "input1_change_handler");
  function input2_change_handler() {
    itemFlagData.cantBeSoldToMerchants = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input2_change_handler, "input2_change_handler");
  function select1_change_handler() {
    itemFlagData.infiniteQuantity = select_value(this);
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(select1_change_handler, "select1_change_handler");
  function input3_change_handler() {
    itemFlagData.keepZeroQuantity = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input3_change_handler, "input3_change_handler");
  function input4_change_handler() {
    itemFlagData.keepOnMerchant = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input4_change_handler, "input4_change_handler");
  function select2_change_handler() {
    itemFlagData.displayQuantity = select_value(this);
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(select2_change_handler, "select2_change_handler");
  function input5_change_handler() {
    itemFlagData.isService = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input5_change_handler, "input5_change_handler");
  function macroselector_macro_binding(value) {
    if ($$self.$$.not_equal(itemFlagData.macro, value)) {
      itemFlagData.macro = value;
      $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
    }
  }
  __name(macroselector_macro_binding, "macroselector_macro_binding");
  function input_input_handler() {
    $price = this.value;
    price.set($price);
  }
  __name(input_input_handler, "input_input_handler");
  const change_handler = /* @__PURE__ */ __name(() => {
    const forceNumber = game.system.id === "dnd5e";
    const isPriceNumber = !isNaN(Number($price));
    set_store_value(
      price,
      $price = isPriceNumber || forceNumber ? Math.max(0, isPriceNumber ? Number($price) : oldPrice) : $price,
      $price
    );
    $$invalidate(3, oldPrice = $price);
  }, "change_handler");
  function input_input_handler_1() {
    $quantityForPrice = to_number(this.value);
    quantityForPrice.set($quantityForPrice);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  function input0_change_handler_1() {
    itemFlagData.free = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input0_change_handler_1, "input0_change_handler_1");
  function input1_change_handler_1() {
    itemFlagData.disableNormalCost = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input1_change_handler_1, "input1_change_handler_1");
  const click_handler = /* @__PURE__ */ __name(() => {
    addGroup();
  }, "click_handler");
  const func2 = /* @__PURE__ */ __name((groupIndex) => {
    store.removeGroup(groupIndex);
  }, "func");
  function pricelist_prices_binding(value, prices, each_value, groupIndex) {
    each_value[groupIndex] = value;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(pricelist_prices_binding, "pricelist_prices_binding");
  function input0_input_handler() {
    itemFlagData.width = to_number(this.value);
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler() {
    itemFlagData.height = to_number(this.value);
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input1_input_handler, "input1_input_handler");
  function filepicker0_value_binding(value) {
    if ($$self.$$.not_equal(itemFlagData.vaultImage, value)) {
      itemFlagData.vaultImage = value;
      $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
    }
  }
  __name(filepicker0_value_binding, "filepicker0_value_binding");
  function filepicker1_value_binding(value) {
    if ($$self.$$.not_equal(itemFlagData.vaultImageFlipped, value)) {
      itemFlagData.vaultImageFlipped = value;
      $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
    }
  }
  __name(filepicker1_value_binding, "filepicker1_value_binding");
  function input2_change_handler_1() {
    itemFlagData.vaultExpander = this.checked;
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input2_change_handler_1, "input2_change_handler_1");
  function input3_input_handler() {
    itemFlagData.addsCols = to_number(this.value);
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input3_input_handler, "input3_input_handler");
  function input4_input_handler() {
    itemFlagData.addsRows = to_number(this.value);
    $$invalidate(6, itemFlagData), $$invalidate(16, $flagDataStore);
  }
  __name(input4_input_handler, "input4_input_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler_1");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(4, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(1, item = $$props2.item);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*$flagDataStore*/
    65536) {
      $$invalidate(6, itemFlagData = $flagDataStore);
    }
  };
  return [
    elementRoot,
    item,
    requestSubmit,
    oldPrice,
    form,
    activeTab,
    itemFlagData,
    $price,
    $quantityForPrice,
    application,
    store,
    flagDataStore,
    price,
    quantityForPrice,
    updateSettings,
    addGroup,
    $flagDataStore,
    tabs_activeTab_binding,
    customcategoryinput_value_binding,
    input0_change_handler,
    select0_change_handler,
    input1_change_handler,
    input2_change_handler,
    select1_change_handler,
    input3_change_handler,
    input4_change_handler,
    select2_change_handler,
    input5_change_handler,
    macroselector_macro_binding,
    input_input_handler,
    change_handler,
    input_input_handler_1,
    input0_change_handler_1,
    input1_change_handler_1,
    click_handler,
    func2,
    pricelist_prices_binding,
    input0_input_handler,
    input1_input_handler,
    filepicker0_value_binding,
    filepicker1_value_binding,
    input2_change_handler_1,
    input3_input_handler,
    input4_input_handler,
    click_handler_1,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$U, "instance$U");
const _Item_editor_shell = class _Item_editor_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$U,
      create_fragment$X,
      safe_not_equal,
      {
        item: 1,
        elementRoot: 0,
        requestSubmit: 2
      },
      null,
      [-1, -1]
    );
  }
  get item() {
    return this.$$.ctx[1];
  }
  set item(item) {
    this.$$set({ item });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[2];
  }
};
__name(_Item_editor_shell, "Item_editor_shell");
let Item_editor_shell = _Item_editor_shell;
const _ItemEditor = class _ItemEditor extends SvelteApplication {
  constructor(item = false, options) {
    let title = game.i18n.format("ITEM-PILES.Applications.ItemEditor.Title", { item_name: item.name });
    if (options.extraTitle)
      title += options.extraTitle;
    super({
      id: `item-pile-item-editor-${item.id}-${randomID()}`,
      title,
      svelte: {
        class: Item_editor_shell,
        target: document.body,
        props: {
          item
        }
      },
      close: () => this.options.resolve(null),
      ...options
    });
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 500,
      height: "auto",
      classes: ["item-piles-app"]
    });
  }
  static getActiveApp(id) {
    return getActiveApps(`item-pile-item-editor-${id}`, true);
  }
  static async show(item = false, options = {}, dialogData = {}) {
    const app = this.getActiveApp(item.uuid);
    if (app)
      return app.render(false, { focus: true });
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(item, options, dialogData).render(true, { focus: true });
    });
  }
};
__name(_ItemEditor, "ItemEditor");
let ItemEditor = _ItemEditor;
const EntryButtons_svelte_svelte_type_style_lang = "";
function create_if_block_3$e(ctx) {
  let t0;
  let span0;
  let i0;
  let t1;
  let span1;
  let i1;
  let mounted;
  let dispose;
  let if_block = game.user.isGM && create_if_block_4$c(ctx);
  return {
    c() {
      if (if_block)
        if_block.c();
      t0 = space();
      span0 = element("span");
      i0 = element("i");
      t1 = space();
      span1 = element("span");
      i1 = element("i");
      attr(i0, "class", "fas");
      toggle_class(i0, "fa-eye", !/*$itemFlagDataStore*/
      ctx[1].hidden);
      toggle_class(
        i0,
        "fa-eye-slash",
        /*$itemFlagDataStore*/
        ctx[1].hidden
      );
      attr(span0, "class", "item-piles-clickable-link svelte-1bw7yl8");
      attr(i1, "class", "fas");
      toggle_class(i1, "fa-store", !/*$itemFlagDataStore*/
      ctx[1].notForSale);
      toggle_class(
        i1,
        "fa-store-slash",
        /*$itemFlagDataStore*/
        ctx[1].notForSale
      );
      attr(span1, "class", "item-piles-clickable-link svelte-1bw7yl8");
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, span0, anchor);
      append(span0, i0);
      insert(target, t1, anchor);
      insert(target, span1, anchor);
      append(span1, i1);
      if (!mounted) {
        dispose = [
          listen(
            span0,
            "click",
            /*click_handler_1*/
            ctx[10]
          ),
          listen(
            span1,
            "click",
            /*click_handler_2*/
            ctx[11]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (game.user.isGM)
        if_block.p(ctx2, dirty);
      if (dirty & /*$itemFlagDataStore*/
      2) {
        toggle_class(i0, "fa-eye", !/*$itemFlagDataStore*/
        ctx2[1].hidden);
      }
      if (dirty & /*$itemFlagDataStore*/
      2) {
        toggle_class(
          i0,
          "fa-eye-slash",
          /*$itemFlagDataStore*/
          ctx2[1].hidden
        );
      }
      if (dirty & /*$itemFlagDataStore*/
      2) {
        toggle_class(i1, "fa-store", !/*$itemFlagDataStore*/
        ctx2[1].notForSale);
      }
      if (dirty & /*$itemFlagDataStore*/
      2) {
        toggle_class(
          i1,
          "fa-store-slash",
          /*$itemFlagDataStore*/
          ctx2[1].notForSale
        );
      }
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(span0);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(span1);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_3$e, "create_if_block_3$e");
function create_if_block_4$c(ctx) {
  let span;
  let mounted;
  let dispose;
  return {
    c() {
      span = element("span");
      span.innerHTML = `<i class="fas fa-cog"></i>`;
      attr(span, "class", "item-piles-clickable-link svelte-1bw7yl8");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*click_handler*/
          ctx[9]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(span);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$c, "create_if_block_4$c");
function create_if_block$C(ctx) {
  let if_block_anchor;
  function select_block_type(ctx2, dirty) {
    if (
      /*isMerchant*/
      ctx2[5]
    )
      return create_if_block_1$q;
    return create_else_block$f;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if_block.p(ctx2, dirty);
    },
    d(detaching) {
      if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block$C, "create_if_block$C");
function create_else_block$f(ctx) {
  let span;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Merchant.Sell") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      span = element("span");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-hand-holding-usd");
      set_style(span, "margin-left", "0.25rem");
      attr(span, "class", "svelte-1bw7yl8");
      toggle_class(
        span,
        "item-piles-clickable-link",
        /*$quantity*/
        ctx[2] > 0 && !/*$itemFlagDataStore*/
        ctx[1].cantBeSoldToMerchants
      );
      toggle_class(
        span,
        "item-piles-clickable-link-disabled",
        /*$quantity*/
        ctx[2] <= 0 || /*$itemFlagDataStore*/
        ctx[1].cantBeSoldToMerchants
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, i);
      append(span, t0);
      append(span, t1);
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*click_handler_4*/
          ctx[13]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantity, $itemFlagDataStore*/
      6) {
        toggle_class(
          span,
          "item-piles-clickable-link",
          /*$quantity*/
          ctx2[2] > 0 && !/*$itemFlagDataStore*/
          ctx2[1].cantBeSoldToMerchants
        );
      }
      if (dirty & /*$quantity, $itemFlagDataStore*/
      6) {
        toggle_class(
          span,
          "item-piles-clickable-link-disabled",
          /*$quantity*/
          ctx2[2] <= 0 || /*$itemFlagDataStore*/
          ctx2[1].cantBeSoldToMerchants
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(span);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$f, "create_else_block$f");
function create_if_block_1$q(ctx) {
  let span;
  let i;
  let t;
  let mounted;
  let dispose;
  let if_block = !/*displayControlButtons*/
  ctx[7] && create_if_block_2$i();
  return {
    c() {
      span = element("span");
      i = element("i");
      t = space();
      if (if_block)
        if_block.c();
      attr(i, "class", "fas fa-shopping-cart");
      attr(span, "class", "svelte-1bw7yl8");
      toggle_class(span, "item-piles-clickable-link", !/*$itemFlagDataStore*/
      ctx[1].notForSale || game.user.isGM);
      toggle_class(
        span,
        "item-piles-clickable-link-disabled",
        /*$quantity*/
        ctx[2] <= 0 || /*$itemFlagDataStore*/
        ctx[1].notForSale && !game.user.isGM
      );
      toggle_class(
        span,
        "buy-button",
        /*displayControlButtons*/
        ctx[7]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, i);
      append(span, t);
      if (if_block)
        if_block.m(span, null);
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*click_handler_3*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!/*displayControlButtons*/
      ctx2[7])
        if_block.p(ctx2, dirty);
      if (dirty & /*$itemFlagDataStore, game*/
      2) {
        toggle_class(span, "item-piles-clickable-link", !/*$itemFlagDataStore*/
        ctx2[1].notForSale || game.user.isGM);
      }
      if (dirty & /*$quantity, $itemFlagDataStore, game*/
      6) {
        toggle_class(
          span,
          "item-piles-clickable-link-disabled",
          /*$quantity*/
          ctx2[2] <= 0 || /*$itemFlagDataStore*/
          ctx2[1].notForSale && !game.user.isGM
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(span);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$q, "create_if_block_1$q");
function create_if_block_2$i(ctx) {
  let t_value = localize("ITEM-PILES.Merchant.Buy") + "";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(create_if_block_2$i, "create_if_block_2$i");
function create_fragment$W(ctx) {
  let div;
  let t;
  let if_block0 = (
    /*displayControlButtons*/
    ctx[7] && /*isMerchant*/
    ctx[5] && create_if_block_3$e(ctx)
  );
  let if_block1 = (
    /*displayBuyButton*/
    ctx[8] && create_if_block$C(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t = space();
      if (if_block1)
        if_block1.c();
      attr(div, "class", "item-piles-flexrow sidebar-buttons svelte-1bw7yl8");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t);
      if (if_block1)
        if_block1.m(div, null);
    },
    p(ctx2, [dirty]) {
      if (
        /*displayControlButtons*/
        ctx2[7] && /*isMerchant*/
        ctx2[5]
      )
        if_block0.p(ctx2, dirty);
      if (
        /*displayBuyButton*/
        ctx2[8]
      )
        if_block1.p(ctx2, dirty);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
    }
  };
}
__name(create_fragment$W, "create_fragment$W");
function instance$T($$self, $$props, $$invalidate) {
  let $itemFlagDataStore;
  let $quantity;
  let { item } = $$props;
  item.name;
  item.img;
  const quantity = item.quantity;
  component_subscribe($$self, quantity, (value) => $$invalidate(2, $quantity = value));
  const store = item.store;
  const isMerchant = store.isMerchant;
  const itemFlagDataStore = item.itemFlagData;
  component_subscribe($$self, itemFlagDataStore, (value) => $$invalidate(1, $itemFlagDataStore = value));
  const displayControlButtons = item.store.actor.isOwner;
  const displayBuyButton = !!item.store.recipient;
  const click_handler = /* @__PURE__ */ __name(() => {
    ItemEditor.show(item.item);
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    item.toggleProperty("hidden");
  }, "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    item.toggleProperty("notForSale");
  }, "click_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name(() => {
    if ($quantity <= 0 || $itemFlagDataStore.notForSale && !game.user.isGM)
      return;
    store.tradeItem(item);
  }, "click_handler_3");
  const click_handler_4 = /* @__PURE__ */ __name(() => {
    if ($quantity <= 0 || $itemFlagDataStore.cantBeSoldToMerchants)
      return;
    store.tradeItem(item, true);
  }, "click_handler_4");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
  };
  return [
    item,
    $itemFlagDataStore,
    $quantity,
    quantity,
    store,
    isMerchant,
    itemFlagDataStore,
    displayControlButtons,
    displayBuyButton,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_32,
    click_handler_4
  ];
}
__name(instance$T, "instance$T");
const _EntryButtons = class _EntryButtons extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$T, create_fragment$W, safe_not_equal, { item: 0 });
  }
};
__name(_EntryButtons, "EntryButtons");
let EntryButtons = _EntryButtons;
const _MerchantStore = class _MerchantStore extends ItemPileStore {
  constructor(...args) {
    super(...args);
    this.services = writable$1({});
    this.editPrices = writable$1(false);
    this.typeFilter = writable$1("all");
    this.sortType = writable$1(0);
    this.priceModifiersPerType = writable$1({});
    this.priceModifiersForActor = writable$1({});
    this.priceSelector = writable$1("");
    this.closed = writable$1(false);
    this.itemColumns = writable$1([]);
    this.sortTypes = writable$1([]);
    this.inverseSort = writable$1(false);
    this.isMerchant = false;
    this.log = writable$1([]);
    this.visibleLogItems = writable$1(20);
    this.logSearch = writable$1("");
  }
  get ItemClass() {
    return PileMerchantItem;
  }
  setupStores() {
    super.setupStores();
    this.services.set({});
    this.editPrices.set(false);
    this.typeFilter.set("all");
    this.sortType.set(0);
    this.priceModifiersPerType.set({});
    this.priceModifiersForActor.set({});
    this.priceSelector.set("");
    this.closed.set(false);
    this.itemColumns.set([]);
    this.sortTypes.set([]);
    this.inverseSort.set(false);
    this.isMerchant = false;
    this.log.set([]);
    this.visibleLogItems.set(20);
    this.logSearch.set("");
  }
  getActorImage() {
    const pileData = get_store_value(this.pileData);
    return pileData?.merchantImage || this.actor.img;
  }
  setupSubscriptions() {
    let setup = false;
    super.setupSubscriptions();
    this.subscribeTo(this.document, () => {
      if (!setup)
        return;
      this.processLogEntries();
    });
    this.subscribeTo(this.pileData, (pileData) => {
      this.isMerchant = isItemPileMerchant(this.actor, pileData);
      this.setupColumns(pileData);
      if (!setup)
        return;
      this.updatePriceModifiers();
      this.updateOpenCloseStatus();
    });
    if (this.recipientDocument) {
      this.subscribeTo(this.recipientPileData, (pileData) => {
        if (isItemPileMerchant(this.recipient, pileData)) {
          this.setupColumns(pileData);
        }
        if (!setup)
          return;
        this.updatePriceModifiers();
      });
      this.subscribeTo(this.recipientDocument, () => {
        if (!setup)
          return;
        this.refreshItemPrices();
      });
    }
    this.subscribeTo(this.typeFilter, (val) => {
      if (!setup)
        return;
      this.refreshItems();
    });
    this.subscribeTo(this.sortType, (val) => {
      if (!setup)
        return;
      this.refreshItems();
    });
    this.subscribeTo(this.inverseSort, (val) => {
      if (!setup)
        return;
      this.refreshItems();
    });
    this.subscribeTo(this.logSearch, () => {
      if (!setup)
        return;
      this.filterLogEntries();
    });
    setup = true;
    this.updatePriceModifiers();
    this.updateOpenCloseStatus();
    this.refreshItems();
    this.processLogEntries();
  }
  setupColumns(pileData) {
    const customColumns = foundry.utils.deepClone(pileData.merchantColumns ?? []).filter((column) => {
      return this.isMerchant ? column?.buying ?? true : column?.selling ?? true;
    }).map((column) => ({
      label: localize(column.label),
      component: CustomColumn,
      data: column,
      sortMethod: (a, b, inverse) => {
        const path = column.path;
        const AProp = getProperty(b.item, path);
        const BProp = getProperty(a.item, path);
        if (!column?.mapping?.[AProp] || !column?.mapping?.[BProp]) {
          return (AProp > BProp ? 1 : -1) * (inverse ? -1 : 1);
        }
        const keys = Object.keys(column.mapping);
        return (keys.indexOf(AProp) - keys.indexOf(BProp)) * (inverse ? -1 : 1);
      }
    }));
    const columns = [];
    columns.push({
      label: "Type",
      component: ItemEntry
    });
    if (pileData.displayQuantity !== "alwaysno") {
      columns.push({
        label: "Quantity",
        component: QuantityColumn,
        sortMethod: (a, b, inverse) => {
          return (get_store_value(b.quantity) - get_store_value(a.quantity)) * (inverse ? -1 : 1);
        }
      });
    }
    columns.push(...customColumns);
    columns.push({
      label: "Price",
      component: PriceSelector,
      sortMethod: (a, b, inverse) => {
        const APrice = get_store_value(a.prices).find((price) => price.primary);
        const BPrice = get_store_value(b.prices).find((price) => price.primary);
        if (!APrice)
          return 1;
        if (!BPrice)
          return -1;
        return (BPrice.totalCost - APrice.totalCost) * (inverse ? -1 : 1);
      }
    });
    columns.push({
      label: false,
      component: EntryButtons
    });
    this.itemColumns.set(columns);
    const sortTypes = columns.filter((col) => col.label);
    sortTypes.splice(1, 0, { label: "Name" });
    this.sortTypes.set(sortTypes);
  }
  refreshItemPrices() {
    const pileData = get_store_value(this.pileData);
    const recipientPileData = get_store_value(this.recipientPileData);
    get_store_value(this.allItems).forEach((item) => {
      item.refreshPriceData(pileData, recipientPileData);
    });
  }
  visibleItemFilterFunction(entry, actorIsMerchant, pileData, recipientPileData) {
    const itemIsFree = !!get_store_value(entry.prices).find((price) => price.free);
    return super.visibleItemFilterFunction(entry, actorIsMerchant, pileData, recipientPileData) && (actorIsMerchant ? !(pileData?.hideItemsWithZeroCost && itemIsFree) : !(recipientPileData?.hideItemsWithZeroCost && itemIsFree));
  }
  itemSortFunction(a, b) {
    const sortType = get_store_value(this.sortType);
    const inverse = get_store_value(this.inverseSort);
    if (sortType <= 1) {
      return super.itemSortFunction(a, b, inverse);
    }
    const selectedSortType = get_store_value(this.sortTypes)[sortType];
    return selectedSortType?.sortMethod(a, b, inverse, selectedSortType);
  }
  createItem(item) {
    if (isItemInvalid(this.actor, item))
      return;
    const items = get_store_value(this.allItems);
    const itemClass = new this.ItemClass(this, item);
    itemClass.refreshPriceData();
    items.push(itemClass);
    this.allItems.set(items);
    this.refreshItems();
  }
  deleteItem(item) {
    if (isItemInvalid(this.actor, item))
      return;
    const items = get_store_value(this.allItems);
    const pileItem = items.find((pileItem2) => pileItem2.id === item.id);
    if (!pileItem)
      return;
    pileItem.unsubscribe();
    items.splice(items.indexOf(pileItem), 1);
    this.allItems.set(items);
    this.refreshItems();
  }
  updatePriceModifiers() {
    let pileData = get_store_value(this.pileData);
    let change = false;
    if (pileData.itemTypePriceModifiers && typeof pileData.itemTypePriceModifiers === "object") {
      change = true;
      this.priceModifiersPerType.set((pileData.itemTypePriceModifiers ?? {}).reduce((acc, priceData) => {
        acc[priceData.category.toLowerCase() || priceData.type] = priceData;
        return acc;
      }, {}));
    }
    if (this.recipient && pileData.actorPriceModifiers && Array.isArray(pileData.actorPriceModifiers)) {
      change = true;
      const recipientUuid = getUuid(this.recipient);
      const actorSpecificModifiers = pileData.actorPriceModifiers?.find((data2) => data2.actorUuid === recipientUuid);
      if (actorSpecificModifiers) {
        this.priceModifiersForActor.set(actorSpecificModifiers);
      }
    }
    if (change) {
      this.refreshItemPrices();
    }
  }
  addOverrideTypePrice(type) {
    const pileData = get_store_value(this.pileData);
    const custom = Object.keys(CONFIG.Item.typeLabels).indexOf(type) === -1;
    pileData.itemTypePriceModifiers.push({
      category: custom ? type : "",
      type: custom ? "custom" : type,
      override: false,
      buyPriceModifier: 1,
      sellPriceModifier: 1
    });
    this.pileData.set(pileData);
  }
  removeOverrideTypePrice(type) {
    const pileData = get_store_value(this.pileData);
    const priceMods = pileData.itemTypePriceModifiers;
    const typeEntry = priceMods.find((entry) => entry.type === type);
    priceMods.splice(priceMods.indexOf(typeEntry), 1);
    this.pileData.set(pileData);
  }
  async update() {
    const pileData = get_store_value(this.pileData);
    const priceModPerType = get_store_value(this.priceModifiersPerType);
    pileData.itemTypePriceModifiers = Object.values(priceModPerType);
    await updateItemPileData(this.actor, pileData);
    custom_notify(localize("ITEM-PILES.Notifications.UpdateMerchantSuccess"));
  }
  tradeItem(pileItem, selling) {
    if (get_store_value(pileItem.itemFlagData).notForSale && !game.user.isGM)
      return;
    TradeMerchantItemDialog.show(pileItem, this.actor, this.recipient, { selling });
  }
  async updateOpenCloseStatus() {
    const pileData = get_store_value(this.pileData);
    if (pileData.openTimes.status === "auto") {
      if (game.modules.get("foundryvtt-simple-calendar")?.active && pileData.openTimes.enabled) {
        const isClosed = isMerchantClosed(this.actor, { pileData });
        this.closed.set(isClosed);
      } else if (isResponsibleGM()) {
        pileData.openTimes.status = "open";
        await updateItemPileData(this.actor, pileData);
      }
    } else if (!pileData.openTimes.status.startsWith("auto")) {
      this.closed.set(pileData.openTimes.status === "closed");
    }
  }
  async setOpenStatus(status) {
    const pileData = get_store_value(this.pileData);
    pileData.openTimes.status = status;
    await updateItemPileData(this.actor, pileData);
  }
  processLogEntries() {
    const logEntries = getActorLog(this.actor);
    logEntries.sort((a, b) => b.date - a.date);
    logEntries.forEach((log) => {
      let instigator;
      if (log.actor !== void 0) {
        instigator = game.i18n.format("ITEM-PILES.Merchant.LogUserActor", {
          actor_name: log.actor || "Unknown character",
          user_name: game.users.get(log.user)?.name ?? "unknown user"
        });
      } else {
        instigator = game.users.get(log.user)?.name ?? "unknown user";
      }
      if (log.property) {
        const properties = {
          "notForSale": ["ITEM-PILES.Merchant.LogSetForSale", "ITEM-PILES.Merchant.LogSetNotForSale"],
          "hidden": ["ITEM-PILES.Merchant.LogSetVisible", "ITEM-PILES.Merchant.LogSetHidden"]
        };
        log.text = localize(properties[log.property][Number(log.value)], { instigator, item: log.item });
        log.class = log.value ? "item-piles-log-positive" : "item-piles-log-negative";
      } else if (log.sold !== void 0) {
        const quantity = Math.abs(log.qty) > 1 ? game.i18n.format("ITEM-PILES.Merchant.LogQuantity", { quantity: Math.abs(log.qty) }) : "";
        const action = localize("ITEM-PILES.Merchant." + (log.sold ? "LogSold" : "LogBought"));
        log.text = localize("ITEM-PILES.Merchant.LogTransaction", {
          instigator,
          quantity,
          item: `<strong>${log.item}</strong>`,
          action: `<span>${action}</span>`,
          price: log.price
        });
        log.class = log.sold ? "item-piles-log-sold" : "item-piles-log-bought";
      } else {
        log.text = localize("ITEM-PILES.Merchant.LogSetQuantity", {
          instigator,
          quantity: Math.abs(log.qty),
          item: `<strong>${log.item}</strong>`
        });
        log.class = "item-piles-log-other";
      }
      log.visible = true;
    });
    this.log.set(logEntries);
    this.filterLogEntries();
  }
  filterLogEntries() {
    const search = get_store_value(this.logSearch).toLowerCase();
    const regex = new RegExp(search, "g");
    this.log.update((logs) => {
      for (let log of logs) {
        log.visible = log.text.toLowerCase().search(regex) !== -1;
      }
      return logs;
    });
  }
};
__name(_MerchantStore, "MerchantStore");
let MerchantStore = _MerchantStore;
const _PileMerchantItem = class _PileMerchantItem extends PileItem {
  setupStores(...args) {
    super.setupStores(...args);
    this.prices = writable$1([]);
    this.displayQuantity = writable$1(false);
    this.selectedPriceGroup = writable$1(-1);
    this.quantityToBuy = writable$1(1);
    this.quantityForPrice = writable$1(1);
    this.infiniteQuantity = writable$1(false);
    this.isService = false;
  }
  setupSubscriptions() {
    let setup = false;
    super.setupSubscriptions();
    this.subscribeTo(this.store.pileData, () => {
      if (!setup)
        return;
      this.refreshPriceData();
      this.refreshDisplayQuantity();
    });
    if (this.store.recipient) {
      this.subscribeTo(this.store.recipientPileData, () => {
        if (!setup)
          return;
        this.refreshPriceData();
        this.refreshDisplayQuantity();
      });
    }
    this.subscribeTo(this.quantityToBuy, () => {
      if (!setup)
        return;
      this.refreshPriceData();
    });
    this.subscribeTo(this.itemDocument, () => {
      if (!setup)
        return;
      this.refreshPriceData();
      this.store.refreshItems();
    });
    this.subscribeTo(this.store.typeFilter, () => {
      if (!setup)
        return;
      this.filter();
    });
    this.subscribeTo(this.itemFlagData, (flagData) => {
      this.isService = flagData.isService;
      if (!setup)
        return;
      this.refreshPriceData();
      this.refreshDisplayQuantity();
    });
    this.refreshDisplayQuantity();
    setup = true;
  }
  refreshDisplayQuantity() {
    const pileData = get_store_value(this.store.pileData);
    const itemFlagData = get_store_value(this.itemFlagData);
    const isMerchant = isItemPileMerchant(this.store.actor, pileData);
    const merchantDisplayQuantity = pileData.displayQuantity;
    const itemFlagDataQuantity = itemFlagData.displayQuantity;
    const itemInfiniteQuantity = {
      "default": pileData.infiniteQuantity,
      "yes": true,
      "no": false
    }[isMerchant ? itemFlagData.infiniteQuantity ?? "default" : "no"];
    this.infiniteQuantity.set(itemInfiniteQuantity);
    if (itemFlagDataQuantity === "always") {
      return this.displayQuantity.set(true);
    }
    const itemDisplayQuantity = {
      "default": merchantDisplayQuantity === "yes",
      "yes": true,
      "no": false
    }[itemFlagDataQuantity ?? "default"];
    if (merchantDisplayQuantity.startsWith("always")) {
      return this.displayQuantity.set(merchantDisplayQuantity.endsWith("yes"));
    }
    this.displayQuantity.set(itemDisplayQuantity);
  }
  refreshPriceData(sellerFlagData, buyerFlagData) {
    const quantityToBuy = get_store_value(this.quantityToBuy);
    const itemFlagData = get_store_value(this.itemFlagData);
    sellerFlagData = sellerFlagData ?? get_store_value(this.store.pileData);
    buyerFlagData = buyerFlagData ?? get_store_value(this.store.recipientPileData);
    const priceData = getPriceData({
      item: this.item,
      seller: this.store.actor,
      buyer: this.store.recipient,
      sellerFlagData,
      buyerFlagData,
      itemFlagData,
      quantity: quantityToBuy
    });
    let selectedPriceGroup = get_store_value(this.selectedPriceGroup);
    if (selectedPriceGroup === -1) {
      selectedPriceGroup = Math.max(0, priceData.findIndex((price) => price.maxQuantity));
      this.selectedPriceGroup.set(selectedPriceGroup);
    }
    this.prices.set(priceData);
    this.quantityForPrice.set(game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE ? getProperty(this.item, game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE) ?? 1 : 1);
  }
  filter() {
    const name = get_store_value(this.name).trim();
    const type = get_store_value(this.category).type;
    const search = get_store_value(this.store.search).trim();
    const typeFilter = get_store_value(this.store.typeFilter);
    const searchFiltered = !name.toLowerCase().includes(search.toLowerCase());
    const typeFiltered = typeFilter !== "all" && typeFilter.toLowerCase() !== type.toLowerCase();
    this.filtered.set(searchFiltered || typeFiltered);
  }
  async toggleProperty(property) {
    this.itemFlagData.update((data2) => {
      data2[property] = !data2[property];
      return data2;
    });
    const itemFlagData = get_store_value(this.itemFlagData);
    await updateItemData(this.item, { flags: itemFlagData });
    const pileFlagData = get_store_value(this.store.pileData);
    if (pileFlagData.logMerchantActivity) {
      await updateMerchantLog(this.store.actor, {
        type: "event",
        user: game.user.id,
        item: this.item.name,
        property,
        value: !itemFlagData[property]
      });
    }
  }
  updateQuantity(quantity) {
    const pileFlagData = get_store_value(this.store.pileData);
    const itemFlagData = get_store_value(this.itemFlagData);
    const roll = new Roll(quantity).evaluate({ async: false });
    this.quantity.set(roll.total);
    const baseData = {};
    if (itemFlagData.isService || pileFlagData.keepZeroQuantity || itemFlagData.keepZeroQuantity) {
      baseData[CONSTANTS.FLAGS.ITEM + ".notForSale"] = roll.total <= 0;
    }
    if (pileFlagData.logMerchantActivity) {
      updateMerchantLog(this.store.actor, {
        type: "event",
        user: game.user.id,
        item: this.item.name,
        qty: roll.total
      });
    }
    return this.item.update(setItemQuantity(baseData, roll.total));
  }
};
__name(_PileMerchantItem, "PileMerchantItem");
let PileMerchantItem = _PileMerchantItem;
function create_default_slot$m(ctx) {
  let form_1;
  let tjsprosemirror;
  let updating_content;
  let t0;
  let footer;
  let button0;
  let i0;
  let t1;
  let t2_value = localize("Save") + "";
  let t2;
  let button0_disabled_value;
  let t3;
  let button1;
  let i1;
  let t4;
  let t5_value = localize("Cancel") + "";
  let t5;
  let current;
  let mounted;
  let dispose;
  function tjsprosemirror_content_binding(value) {
    ctx[7](value);
  }
  __name(tjsprosemirror_content_binding, "tjsprosemirror_content_binding");
  let tjsprosemirror_props = {};
  if (
    /*text*/
    ctx[0] !== void 0
  ) {
    tjsprosemirror_props.content = /*text*/
    ctx[0];
  }
  tjsprosemirror = new TJSProseMirror({ props: tjsprosemirror_props });
  binding_callbacks.push(() => bind(tjsprosemirror, "content", tjsprosemirror_content_binding));
  return {
    c() {
      form_1 = element("form");
      create_component(tjsprosemirror.$$.fragment);
      t0 = space();
      footer = element("footer");
      button0 = element("button");
      i0 = element("i");
      t1 = space();
      t2 = text(t2_value);
      t3 = space();
      button1 = element("button");
      i1 = element("i");
      t4 = space();
      t5 = text(t5_value);
      attr(i0, "class", "fas fa-download");
      button0.disabled = button0_disabled_value = /*originalText*/
      ctx[4] === /*text*/
      ctx[0];
      attr(button0, "type", "button");
      attr(i1, "class", "fas fa-times");
      attr(button1, "type", "button");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
      set_style(footer, "margin-top", "1rem");
      set_style(footer, "flex", "0");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-flexcol");
      set_style(form_1, "padding", "0.5rem");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      mount_component(tjsprosemirror, form_1, null);
      append(form_1, t0);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i0);
      append(button0, t1);
      append(button0, t2);
      append(footer, t3);
      append(footer, button1);
      append(button1, i1);
      append(button1, t4);
      append(button1, t5);
      ctx[9](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[5],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[8]
          ),
          listen(form_1, "submit", prevent_default(
            /*submit*/
            ctx[6]
          ), { once: true })
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const tjsprosemirror_changes = {};
      if (!updating_content && dirty & /*text*/
      1) {
        updating_content = true;
        tjsprosemirror_changes.content = /*text*/
        ctx2[0];
        add_flush_callback(() => updating_content = false);
      }
      tjsprosemirror.$set(tjsprosemirror_changes);
      if (!current || dirty & /*text*/
      1 && button0_disabled_value !== (button0_disabled_value = /*originalText*/
      ctx2[4] === /*text*/
      ctx2[0])) {
        button0.disabled = button0_disabled_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(tjsprosemirror.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tjsprosemirror.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      destroy_component(tjsprosemirror);
      ctx[9](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$m, "create_default_slot$m");
function create_fragment$V(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[10](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$m] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[1] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[1];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, text*/
      4101) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      2) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[1];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$V, "create_fragment$V");
function instance$S($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { text: text2 } = $$props;
  let { elementRoot } = $$props;
  application.options;
  const originalText = text2;
  let form;
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function submit() {
    application.options.resolve(text2);
    application.close();
  }
  __name(submit, "submit");
  function tjsprosemirror_content_binding(value) {
    text2 = value;
    $$invalidate(0, text2);
  }
  __name(tjsprosemirror_content_binding, "tjsprosemirror_content_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(1, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("text" in $$props2)
      $$invalidate(0, text2 = $$props2.text);
    if ("elementRoot" in $$props2)
      $$invalidate(1, elementRoot = $$props2.elementRoot);
  };
  return [
    text2,
    elementRoot,
    form,
    application,
    originalText,
    requestSubmit,
    submit,
    tjsprosemirror_content_binding,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$S, "instance$S");
const _Text_editor_dialog_shell = class _Text_editor_dialog_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$S, create_fragment$V, safe_not_equal, { text: 0, elementRoot: 1 });
  }
  get text() {
    return this.$$.ctx[0];
  }
  set text(text2) {
    this.$$set({ text: text2 });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[1];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
};
__name(_Text_editor_dialog_shell, "Text_editor_dialog_shell");
let Text_editor_dialog_shell = _Text_editor_dialog_shell;
const _TextEditorDialog = class _TextEditorDialog extends SvelteApplication {
  constructor(text2, options) {
    super({
      title: game.i18n.localize("ITEM-PILES.Dialogs.TextEditor.Title"),
      id: `item-piles-text-editor${options?.id ? "-" + options.id : ""}-${randomID()}`,
      svelte: {
        class: Text_editor_dialog_shell,
        target: document.body,
        props: {
          text: text2
        }
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 550,
      height: 450,
      classes: ["item-piles-app"],
      resizable: true
    });
  }
  static getActiveApps(id) {
    return getActiveApps(`item-pile-text-editor-${id}`);
  }
  static async show(text2, options = {}) {
    const apps = options.id ? this.getActiveApps(options.id) : [];
    if (apps.length) {
      for (let app of apps) {
        app.render(false, { focus: true });
      }
      return;
    }
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(text2, options).render(true, { focus: true });
    });
  }
};
__name(_TextEditorDialog, "TextEditorDialog");
let TextEditorDialog = _TextEditorDialog;
const MerchantLeftPane_svelte_svelte_type_style_lang = "";
function create_if_block$B(ctx) {
  let tabs_1;
  let updating_activeTab;
  let t0;
  let section;
  let t1;
  let current;
  function tabs_1_activeTab_binding(value) {
    ctx[11](value);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  let tabs_1_props = {
    style: "flex: 0 1 auto;",
    tabs: (
      /*tabs*/
      ctx[1]
    )
  };
  if (
    /*activeSidebarTab*/
    ctx[3] !== void 0
  ) {
    tabs_1_props.activeTab = /*activeSidebarTab*/
    ctx[3];
  }
  tabs_1 = new Tabs({ props: tabs_1_props });
  binding_callbacks.push(() => bind(tabs_1, "activeTab", tabs_1_activeTab_binding));
  let if_block0 = (
    /*activeSidebarTab*/
    ctx[3] === "description" && create_if_block_2$h(ctx)
  );
  let if_block1 = (
    /*activeSidebarTab*/
    ctx[3] === "settings" && create_if_block_1$p(ctx)
  );
  return {
    c() {
      create_component(tabs_1.$$.fragment);
      t0 = space();
      section = element("section");
      if (if_block0)
        if_block0.c();
      t1 = space();
      if (if_block1)
        if_block1.c();
      attr(section, "class", "tab-body item-piles-sections svelte-18k5cmo");
      set_style(section, "overflow-y", "auto");
    },
    m(target, anchor) {
      mount_component(tabs_1, target, anchor);
      insert(target, t0, anchor);
      insert(target, section, anchor);
      if (if_block0)
        if_block0.m(section, null);
      append(section, t1);
      if (if_block1)
        if_block1.m(section, null);
      current = true;
    },
    p(ctx2, dirty) {
      const tabs_1_changes = {};
      if (dirty & /*tabs*/
      2)
        tabs_1_changes.tabs = /*tabs*/
        ctx2[1];
      if (!updating_activeTab && dirty & /*activeSidebarTab*/
      8) {
        updating_activeTab = true;
        tabs_1_changes.activeTab = /*activeSidebarTab*/
        ctx2[3];
        add_flush_callback(() => updating_activeTab = false);
      }
      tabs_1.$set(tabs_1_changes);
      if (
        /*activeSidebarTab*/
        ctx2[3] === "description"
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*activeSidebarTab*/
          8) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_2$h(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(section, t1);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*activeSidebarTab*/
        ctx2[3] === "settings"
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*activeSidebarTab*/
          8) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_1$p(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(section, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(tabs_1.$$.fragment, local);
      transition_in(if_block0);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(tabs_1.$$.fragment, local);
      transition_out(if_block0);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      destroy_component(tabs_1, detaching);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(section);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
    }
  };
}
__name(create_if_block$B, "create_if_block$B");
function create_if_block_2$h(ctx) {
  let div;
  let tjsprosemirror;
  let t;
  let current;
  tjsprosemirror = new TJSProseMirror({
    props: {
      content: (
        /*description*/
        ctx[2]
      ),
      options: { editable: false, secrets: game.user.isGM },
      style: { "display": "block" }
    }
  });
  let if_block = game.user.isGM && !/*description*/
  ctx[2] && create_if_block_3$d(ctx);
  return {
    c() {
      div = element("div");
      create_component(tjsprosemirror.$$.fragment);
      t = space();
      if (if_block)
        if_block.c();
      attr(div, "class", "tab merchant-description svelte-18k5cmo");
      set_style(div, "padding", "0");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(tjsprosemirror, div, null);
      append(div, t);
      if (if_block)
        if_block.m(div, null);
      current = true;
    },
    p(ctx2, dirty) {
      const tjsprosemirror_changes = {};
      if (dirty & /*description*/
      4)
        tjsprosemirror_changes.content = /*description*/
        ctx2[2];
      tjsprosemirror.$set(tjsprosemirror_changes);
      if (game.user.isGM && !/*description*/
      ctx2[2]) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_3$d(ctx2);
          if_block.c();
          if_block.m(div, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(tjsprosemirror.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tjsprosemirror.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(tjsprosemirror);
      if (if_block)
        if_block.d();
    }
  };
}
__name(create_if_block_2$h, "create_if_block_2$h");
function create_if_block_3$d(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.EditDescription")}`;
      attr(button, "type", "button");
      set_style(button, "flex", "1");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$d, "create_if_block_3$d");
function create_if_block_1$p(ctx) {
  let div6;
  let div5;
  let div0;
  let label0;
  let span0;
  let t1;
  let p0;
  let t3;
  let input0;
  let t4;
  let div1;
  let label1;
  let span1;
  let t6;
  let p1;
  let t8;
  let input1;
  let t9;
  let div2;
  let label2;
  let span2;
  let t11;
  let p2;
  let t13;
  let input2;
  let t14;
  let div3;
  let label3;
  let t16;
  let sliderinput0;
  let updating_value;
  let t17;
  let div4;
  let label4;
  let t19;
  let sliderinput1;
  let updating_value_1;
  let t20;
  let button;
  let current;
  let mounted;
  let dispose;
  function sliderinput0_value_binding(value) {
    ctx[16](value);
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  let sliderinput0_props = {};
  if (
    /*$pileDataStore*/
    ctx[4].buyPriceModifier !== void 0
  ) {
    sliderinput0_props.value = /*$pileDataStore*/
    ctx[4].buyPriceModifier;
  }
  sliderinput0 = new SliderInput({ props: sliderinput0_props });
  binding_callbacks.push(() => bind(sliderinput0, "value", sliderinput0_value_binding));
  function sliderinput1_value_binding(value) {
    ctx[17](value);
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  let sliderinput1_props = { style: "flex:4;" };
  if (
    /*$pileDataStore*/
    ctx[4].sellPriceModifier !== void 0
  ) {
    sliderinput1_props.value = /*$pileDataStore*/
    ctx[4].sellPriceModifier;
  }
  sliderinput1 = new SliderInput({ props: sliderinput1_props });
  binding_callbacks.push(() => bind(sliderinput1, "value", sliderinput1_value_binding));
  return {
    c() {
      div6 = element("div");
      div5 = element("div");
      div0 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.PurchaseOnly")}`;
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.PurchaseOnlyExplanation")}`;
      t3 = space();
      input0 = element("input");
      t4 = space();
      div1 = element("div");
      label1 = element("label");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideNewItems")}`;
      t6 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideNewItemsExplanation")}`;
      t8 = space();
      input1 = element("input");
      t9 = space();
      div2 = element("div");
      label2 = element("label");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Merchant.EditTypePrices")}`;
      t11 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Merchant.EditTypePricesExplanation")}`;
      t13 = space();
      input2 = element("input");
      t14 = space();
      div3 = element("div");
      label3 = element("label");
      label3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.BuyPriceModifier")}`;
      t16 = space();
      create_component(sliderinput0.$$.fragment);
      t17 = space();
      div4 = element("div");
      label4 = element("label");
      label4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.SellPriceModifier")}`;
      t19 = space();
      create_component(sliderinput1.$$.fragment);
      t20 = space();
      button = element("button");
      button.innerHTML = `<i class="fas fa-download"></i> Update`;
      set_style(label0, "flex", "3");
      attr(input0, "type", "checkbox");
      attr(div0, "class", "form-group svelte-18k5cmo");
      set_style(label1, "flex", "3");
      attr(input1, "type", "checkbox");
      attr(div1, "class", "form-group svelte-18k5cmo");
      set_style(label2, "flex", "3");
      attr(input2, "type", "checkbox");
      attr(div2, "class", "form-group svelte-18k5cmo");
      attr(div3, "class", "form-group slider-group item-piles-flexcol svelte-18k5cmo");
      attr(div4, "class", "form-group slider-group item-piles-flexcol svelte-18k5cmo");
      attr(div5, "class", "setting-container item-piles-config-container svelte-18k5cmo");
      attr(button, "type", "button");
      attr(button, "class", "update-button svelte-18k5cmo");
      attr(div6, "class", "tab merchant-settings svelte-18k5cmo");
    },
    m(target, anchor) {
      insert(target, div6, anchor);
      append(div6, div5);
      append(div5, div0);
      append(div0, label0);
      append(label0, span0);
      append(label0, t1);
      append(label0, p0);
      append(div0, t3);
      append(div0, input0);
      input0.checked = /*$pileDataStore*/
      ctx[4].purchaseOnly;
      append(div5, t4);
      append(div5, div1);
      append(div1, label1);
      append(label1, span1);
      append(label1, t6);
      append(label1, p1);
      append(div1, t8);
      append(div1, input1);
      input1.checked = /*$pileDataStore*/
      ctx[4].hideNewItems;
      append(div5, t9);
      append(div5, div2);
      append(div2, label2);
      append(label2, span2);
      append(label2, t11);
      append(label2, p2);
      append(div2, t13);
      append(div2, input2);
      input2.checked = /*$editPrices*/
      ctx[6];
      append(div5, t14);
      append(div5, div3);
      append(div3, label3);
      append(div3, t16);
      mount_component(sliderinput0, div3, null);
      append(div5, t17);
      append(div5, div4);
      append(div4, label4);
      append(div4, t19);
      mount_component(sliderinput1, div4, null);
      append(div6, t20);
      append(div6, button);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler*/
            ctx[13]
          ),
          listen(
            input1,
            "change",
            /*input1_change_handler*/
            ctx[14]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler*/
            ctx[15]
          ),
          listen(
            button,
            "click",
            /*click_handler_1*/
            ctx[18]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$pileDataStore*/
      16) {
        input0.checked = /*$pileDataStore*/
        ctx2[4].purchaseOnly;
      }
      if (dirty & /*$pileDataStore*/
      16) {
        input1.checked = /*$pileDataStore*/
        ctx2[4].hideNewItems;
      }
      if (dirty & /*$editPrices*/
      64) {
        input2.checked = /*$editPrices*/
        ctx2[6];
      }
      const sliderinput0_changes = {};
      if (!updating_value && dirty & /*$pileDataStore*/
      16) {
        updating_value = true;
        sliderinput0_changes.value = /*$pileDataStore*/
        ctx2[4].buyPriceModifier;
        add_flush_callback(() => updating_value = false);
      }
      sliderinput0.$set(sliderinput0_changes);
      const sliderinput1_changes = {};
      if (!updating_value_1 && dirty & /*$pileDataStore*/
      16) {
        updating_value_1 = true;
        sliderinput1_changes.value = /*$pileDataStore*/
        ctx2[4].sellPriceModifier;
        add_flush_callback(() => updating_value_1 = false);
      }
      sliderinput1.$set(sliderinput1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sliderinput0.$$.fragment, local);
      transition_in(sliderinput1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sliderinput0.$$.fragment, local);
      transition_out(sliderinput1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div6);
      destroy_component(sliderinput0);
      destroy_component(sliderinput1);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_1$p, "create_if_block_1$p");
function create_fragment$U(ctx) {
  let div2;
  let div1;
  let div0;
  let img;
  let img_src_value;
  let t;
  let current;
  let if_block = (
    /*activeSidebarTab*/
    ctx[3] && create_if_block$B(ctx)
  );
  return {
    c() {
      div2 = element("div");
      div1 = element("div");
      div0 = element("div");
      img = element("img");
      t = space();
      if (if_block)
        if_block.c();
      if (!src_url_equal(img.src, img_src_value = /*$merchantImg*/
      ctx[5]))
        attr(img, "src", img_src_value);
      attr(img, "class", "svelte-18k5cmo");
      attr(div0, "class", "merchant-img svelte-18k5cmo");
      attr(div1, "class", "item-piles-bottom-divider");
      attr(div2, "class", "merchant-left-pane item-piles-flexcol svelte-18k5cmo");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div1);
      append(div1, div0);
      append(div0, img);
      append(div2, t);
      if (if_block)
        if_block.m(div2, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (!current || dirty & /*$merchantImg*/
      32 && !src_url_equal(img.src, img_src_value = /*$merchantImg*/
      ctx2[5])) {
        attr(img, "src", img_src_value);
      }
      if (
        /*activeSidebarTab*/
        ctx2[3]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*activeSidebarTab*/
          8) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$B(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div2, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      if (if_block)
        if_block.d();
    }
  };
}
__name(create_fragment$U, "create_fragment$U");
function instance$R($$self, $$props, $$invalidate) {
  let $pileDataStore;
  let $merchantImg;
  let $editPrices;
  let { store } = $$props;
  const merchantImg = store.img;
  component_subscribe($$self, merchantImg, (value) => $$invalidate(5, $merchantImg = value));
  const pileDataStore = store.pileData;
  component_subscribe($$self, pileDataStore, (value) => $$invalidate(4, $pileDataStore = value));
  const editPrices = store.editPrices;
  component_subscribe($$self, editPrices, (value) => $$invalidate(6, $editPrices = value));
  let tabs = [];
  let description;
  let activeSidebarTab = false;
  function showDescriptionEditor() {
    return TextEditorDialog.show(description, {
      id: "item-pile-text-editor-" + store.actor.id
    }).then((result) => {
      store.pileData.update((pileData) => {
        pileData.description = result || "";
        return pileData;
      });
      store.update();
    });
  }
  __name(showDescriptionEditor, "showDescriptionEditor");
  function tabs_1_activeTab_binding(value) {
    activeSidebarTab = value;
    $$invalidate(3, activeSidebarTab), $$invalidate(2, description), $$invalidate(1, tabs), $$invalidate(4, $pileDataStore);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    showDescriptionEditor();
  }, "click_handler");
  function input0_change_handler() {
    $pileDataStore.purchaseOnly = this.checked;
    pileDataStore.set($pileDataStore);
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_change_handler() {
    $pileDataStore.hideNewItems = this.checked;
    pileDataStore.set($pileDataStore);
  }
  __name(input1_change_handler, "input1_change_handler");
  function input2_change_handler() {
    $editPrices = this.checked;
    editPrices.set($editPrices);
  }
  __name(input2_change_handler, "input2_change_handler");
  function sliderinput0_value_binding(value) {
    if ($$self.$$.not_equal($pileDataStore.buyPriceModifier, value)) {
      $pileDataStore.buyPriceModifier = value;
      pileDataStore.set($pileDataStore);
    }
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  function sliderinput1_value_binding(value) {
    if ($$self.$$.not_equal($pileDataStore.sellPriceModifier, value)) {
      $pileDataStore.sellPriceModifier = value;
      pileDataStore.set($pileDataStore);
    }
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    store.update();
  }, "click_handler_1");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$pileDataStore*/
    16) {
      {
        $$invalidate(2, description = $pileDataStore.description);
      }
    }
    if ($$self.$$.dirty & /*description, activeSidebarTab, tabs*/
    14) {
      {
        $$invalidate(1, tabs = [
          {
            value: "description",
            label: `ITEM-PILES.Merchant.Description`,
            hidden: !game.user.isGM && !description
          },
          {
            value: "settings",
            label: `ITEM-PILES.Merchant.Settings`,
            hidden: !game.user.isGM
          }
        ]);
        $$invalidate(3, activeSidebarTab = activeSidebarTab || tabs.find((tab) => !tab.hidden)?.value);
      }
    }
  };
  return [
    store,
    tabs,
    description,
    activeSidebarTab,
    $pileDataStore,
    $merchantImg,
    $editPrices,
    merchantImg,
    pileDataStore,
    editPrices,
    showDescriptionEditor,
    tabs_1_activeTab_binding,
    click_handler,
    input0_change_handler,
    input1_change_handler,
    input2_change_handler,
    sliderinput0_value_binding,
    sliderinput1_value_binding,
    click_handler_1
  ];
}
__name(instance$R, "instance$R");
const _MerchantLeftPane = class _MerchantLeftPane extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$R, create_fragment$U, safe_not_equal, { store: 0 });
  }
};
__name(_MerchantLeftPane, "MerchantLeftPane");
let MerchantLeftPane = _MerchantLeftPane;
const MerchantItemEntry_svelte_svelte_type_style_lang = "";
function get_each_context$r(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[20] = list[i];
  return child_ctx;
}
__name(get_each_context$r, "get_each_context$r");
function create_else_block$e(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  var switch_value = (
    /*column*/
    ctx[20].component
  );
  function switch_props(ctx2) {
    return { props: { item: (
      /*item*/
      ctx2[0]
    ) } };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props(ctx));
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const switch_instance_changes = {};
      if (dirty & /*item*/
      1)
        switch_instance_changes.item = /*item*/
        ctx2[0];
      if (dirty & /*columns*/
      4 && switch_value !== (switch_value = /*column*/
      ctx2[20].component)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props(ctx2));
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
__name(create_else_block$e, "create_else_block$e");
function create_if_block$A(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  var switch_value = (
    /*column*/
    ctx[20].component
  );
  function switch_props(ctx2) {
    return {
      props: {
        item: (
          /*item*/
          ctx2[0]
        ),
        data: (
          /*column*/
          ctx2[20].data
        )
      }
    };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props(ctx));
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const switch_instance_changes = {};
      if (dirty & /*item*/
      1)
        switch_instance_changes.item = /*item*/
        ctx2[0];
      if (dirty & /*columns*/
      4)
        switch_instance_changes.data = /*column*/
        ctx2[20].data;
      if (dirty & /*columns*/
      4 && switch_value !== (switch_value = /*column*/
      ctx2[20].component)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props(ctx2));
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
__name(create_if_block$A, "create_if_block$A");
function create_each_block$r(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block$A, create_else_block$e];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*column*/
      ctx2[20]?.data
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if_blocks[current_block_type_index].d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block$r, "create_each_block$r");
function create_fragment$T(ctx) {
  let div;
  let div_transition;
  let current;
  let each_value = (
    /*columns*/
    ctx[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$r(get_each_context$r(ctx, each_value, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  }), "out");
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "item-piles-flexrow item-piles-item-row svelte-1o95obs");
      set_style(div, "flex", "1 0 auto");
      toggle_class(
        div,
        "item-piles-child-even-color",
        /*index*/
        ctx[1] % 2 === 0
      );
      toggle_class(
        div,
        "item-piles-child-odd-color",
        /*index*/
        ctx[1] % 2 === 1
      );
      toggle_class(
        div,
        "merchant-item-hidden",
        /*itemFlagData*/
        ctx[3].hidden
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx2, [dirty]) {
      if (dirty & /*columns, item*/
      5) {
        each_value = /*columns*/
        ctx2[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$r(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block$r(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
      if (!current || dirty & /*index*/
      2) {
        toggle_class(
          div,
          "item-piles-child-even-color",
          /*index*/
          ctx2[1] % 2 === 0
        );
      }
      if (!current || dirty & /*index*/
      2) {
        toggle_class(
          div,
          "item-piles-child-odd-color",
          /*index*/
          ctx2[1] % 2 === 1
        );
      }
      if (!current || dirty & /*itemFlagData*/
      8) {
        toggle_class(
          div,
          "merchant-item-hidden",
          /*itemFlagData*/
          ctx2[3].hidden
        );
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      if (local) {
        add_render_callback(() => {
          if (!current)
            return;
          if (!div_transition)
            div_transition = create_bidirectional_transition(div, fade, { duration: 250 }, true);
          div_transition.run(1);
        });
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      if (local) {
        if (!div_transition)
          div_transition = create_bidirectional_transition(div, fade, { duration: 250 }, false);
        div_transition.run(0);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_each(each_blocks, detaching);
      if (detaching && div_transition)
        div_transition.end();
    }
  };
}
__name(create_fragment$T, "create_fragment$T");
function instance$Q($$self, $$props, $$invalidate) {
  let itemFlagData;
  let $quantityStore;
  let $displayQuantityStore;
  let $itemFlagDataStore;
  let { item } = $$props;
  let { index: index2 } = $$props;
  let { columns } = $$props;
  item.name;
  item.img;
  const store = item.store;
  item.itemDocument;
  store.pileData;
  const displayQuantityStore = item.displayQuantity;
  component_subscribe($$self, displayQuantityStore, (value) => $$invalidate(8, $displayQuantityStore = value));
  const quantityStore = item.quantity;
  component_subscribe($$self, quantityStore, (value) => $$invalidate(7, $quantityStore = value));
  const itemFlagDataStore = item.itemFlagData;
  component_subscribe($$self, itemFlagDataStore, (value) => $$invalidate(9, $itemFlagDataStore = value));
  store.actor.isOwner;
  !!store.recipient;
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
    if ("index" in $$props2)
      $$invalidate(1, index2 = $$props2.index);
    if ("columns" in $$props2)
      $$invalidate(2, columns = $$props2.columns);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$itemFlagDataStore*/
    512) {
      $$invalidate(3, itemFlagData = $itemFlagDataStore);
    }
    if ($$self.$$.dirty & /*$displayQuantityStore*/
    256)
      ;
    if ($$self.$$.dirty & /*$quantityStore*/
    128)
      ;
    if ($$self.$$.dirty & /*$quantityStore*/
    128)
      ;
  };
  return [
    item,
    index2,
    columns,
    itemFlagData,
    displayQuantityStore,
    quantityStore,
    itemFlagDataStore,
    $quantityStore,
    $displayQuantityStore,
    $itemFlagDataStore
  ];
}
__name(instance$Q, "instance$Q");
const _MerchantItemEntry = class _MerchantItemEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$Q, create_fragment$T, safe_not_equal, { item: 0, index: 1, columns: 2 });
  }
};
__name(_MerchantItemEntry, "MerchantItemEntry");
let MerchantItemEntry = _MerchantItemEntry;
const CategoryHeader_svelte_svelte_type_style_lang = "";
function create_if_block$z(ctx) {
  let div0;
  let t;
  let div1;
  let current;
  let if_block0 = (
    /*$priceModifiersPerType*/
    ctx[5][
      /*type*/
      ctx[3]
    ] && create_if_block_2$g(ctx)
  );
  function select_block_type(ctx2, dirty) {
    if (
      /*$priceModifiersPerType*/
      ctx2[5][
        /*type*/
        ctx2[3]
      ]
    )
      return create_if_block_1$o;
    return create_else_block$d;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block1 = current_block_type(ctx);
  return {
    c() {
      div0 = element("div");
      if (if_block0)
        if_block0.c();
      t = space();
      div1 = element("div");
      if_block1.c();
      attr(div0, "class", "price-header svelte-vdtm3g");
      set_style(div0, "font-size", "0.75rem");
      set_style(div1, "flex", "0 1 auto");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      if (if_block0)
        if_block0.m(div0, null);
      insert(target, t, anchor);
      insert(target, div1, anchor);
      if_block1.m(div1, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*$priceModifiersPerType*/
        ctx2[5][
          /*type*/
          ctx2[3]
        ]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*$priceModifiersPerType, type*/
          40) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_2$g(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div0, null);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block1) {
        if_block1.p(ctx2, dirty);
      } else {
        if_block1.d(1);
        if_block1 = current_block_type(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div1, null);
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (if_block0)
        if_block0.d();
      if (detaching)
        detach(t);
      if (detaching)
        detach(div1);
      if_block1.d();
    }
  };
}
__name(create_if_block$z, "create_if_block$z");
function create_if_block_2$g(ctx) {
  let t0_value = localize("ITEM-PILES.Merchant.Override") + "";
  let t0;
  let t1;
  let input;
  let t2;
  let sliderinput;
  let updating_value;
  let current;
  let mounted;
  let dispose;
  function sliderinput_value_binding(value) {
    ctx[11](value);
  }
  __name(sliderinput_value_binding, "sliderinput_value_binding");
  let sliderinput_props = {};
  if (
    /*$priceModifiersPerType*/
    ctx[5][
      /*type*/
      ctx[3]
    ].buyPriceModifier !== void 0
  ) {
    sliderinput_props.value = /*$priceModifiersPerType*/
    ctx[5][
      /*type*/
      ctx[3]
    ].buyPriceModifier;
  }
  sliderinput = new SliderInput({ props: sliderinput_props });
  binding_callbacks.push(() => bind(sliderinput, "value", sliderinput_value_binding));
  return {
    c() {
      t0 = text(t0_value);
      t1 = text(":\r\n				");
      input = element("input");
      t2 = space();
      create_component(sliderinput.$$.fragment);
      attr(input, "type", "checkbox");
      attr(input, "class", "svelte-vdtm3g");
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, t1, anchor);
      insert(target, input, anchor);
      input.checked = /*$priceModifiersPerType*/
      ctx[5][
        /*type*/
        ctx[3]
      ].override;
      insert(target, t2, anchor);
      mount_component(sliderinput, target, anchor);
      current = true;
      if (!mounted) {
        dispose = listen(
          input,
          "change",
          /*input_change_handler*/
          ctx[10]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$priceModifiersPerType, type*/
      40) {
        input.checked = /*$priceModifiersPerType*/
        ctx2[5][
          /*type*/
          ctx2[3]
        ].override;
      }
      const sliderinput_changes = {};
      if (!updating_value && dirty & /*$priceModifiersPerType, type*/
      40) {
        updating_value = true;
        sliderinput_changes.value = /*$priceModifiersPerType*/
        ctx2[5][
          /*type*/
          ctx2[3]
        ].buyPriceModifier;
        add_flush_callback(() => updating_value = false);
      }
      sliderinput.$set(sliderinput_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sliderinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sliderinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(t0);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(input);
      if (detaching)
        detach(t2);
      destroy_component(sliderinput, detaching);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_2$g, "create_if_block_2$g");
function create_else_block$d(ctx) {
  let i;
  let mounted;
  let dispose;
  return {
    c() {
      i = element("i");
      attr(i, "class", "fas fa-plus item-piles-clickable-green");
    },
    m(target, anchor) {
      insert(target, i, anchor);
      if (!mounted) {
        dispose = listen(
          i,
          "click",
          /*click_handler_1*/
          ctx[13]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(i);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$d, "create_else_block$d");
function create_if_block_1$o(ctx) {
  let i;
  let mounted;
  let dispose;
  return {
    c() {
      i = element("i");
      attr(i, "class", "fas fa-times item-piles-clickable-red");
    },
    m(target, anchor) {
      insert(target, i, anchor);
      if (!mounted) {
        dispose = listen(
          i,
          "click",
          /*click_handler*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(i);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$o, "create_if_block_1$o");
function create_fragment$S(ctx) {
  let div;
  let h3;
  let t0_value = localize(
    /*category*/
    ctx[1].label
  ) + "";
  let t0;
  let t1;
  let current;
  let if_block = (
    /*$editPrices*/
    ctx[2] && create_if_block$z(ctx)
  );
  return {
    c() {
      div = element("div");
      h3 = element("h3");
      t0 = text(t0_value);
      t1 = space();
      if (if_block)
        if_block.c();
      attr(h3, "class", "svelte-vdtm3g");
      attr(div, "class", "merchant-item-group-type item-piles-flexrow svelte-vdtm3g");
      set_style(div, "grid-column", "1/" + /*colSpan*/
      ctx[4]);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, h3);
      append(h3, t0);
      append(div, t1);
      if (if_block)
        if_block.m(div, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      if ((!current || dirty & /*category*/
      2) && t0_value !== (t0_value = localize(
        /*category*/
        ctx2[1].label
      ) + ""))
        set_data(t0, t0_value);
      if (
        /*$editPrices*/
        ctx2[2]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*$editPrices*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$z(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty & /*colSpan*/
      16) {
        set_style(div, "grid-column", "1/" + /*colSpan*/
        ctx2[4]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
    }
  };
}
__name(create_fragment$S, "create_fragment$S");
function instance$P($$self, $$props, $$invalidate) {
  let colSpan;
  let type;
  let $columns;
  let $editPrices;
  let $priceModifiersPerType;
  let { store } = $$props;
  let { category } = $$props;
  store.pileData;
  store.search;
  store.visibleItems;
  store.itemsPerCategory;
  store.categories;
  const priceModifiersPerType = store.priceModifiersPerType;
  component_subscribe($$self, priceModifiersPerType, (value) => $$invalidate(5, $priceModifiersPerType = value));
  store.itemCategories;
  store.typeFilter;
  const editPrices = store.editPrices;
  component_subscribe($$self, editPrices, (value) => $$invalidate(2, $editPrices = value));
  const columns = store.itemColumns;
  component_subscribe($$self, columns, (value) => $$invalidate(9, $columns = value));
  function input_change_handler() {
    $priceModifiersPerType[type].override = this.checked;
    priceModifiersPerType.set($priceModifiersPerType);
  }
  __name(input_change_handler, "input_change_handler");
  function sliderinput_value_binding(value) {
    if ($$self.$$.not_equal($priceModifiersPerType[type].buyPriceModifier, value)) {
      $priceModifiersPerType[type].buyPriceModifier = value;
      priceModifiersPerType.set($priceModifiersPerType);
    }
  }
  __name(sliderinput_value_binding, "sliderinput_value_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    store.removeOverrideTypePrice(type);
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    store.addOverrideTypePrice(type);
  }, "click_handler_1");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
    if ("category" in $$props2)
      $$invalidate(1, category = $$props2.category);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$editPrices, $columns*/
    516) {
      $$invalidate(4, colSpan = $editPrices ? $columns.length + 1 : 1);
    }
    if ($$self.$$.dirty & /*category*/
    2) {
      $$invalidate(3, type = category.type === "custom" ? category.label.toLowerCase() : category.type);
    }
  };
  return [
    store,
    category,
    $editPrices,
    type,
    colSpan,
    $priceModifiersPerType,
    priceModifiersPerType,
    editPrices,
    columns,
    $columns,
    input_change_handler,
    sliderinput_value_binding,
    click_handler,
    click_handler_1
  ];
}
__name(instance$P, "instance$P");
const _CategoryHeader = class _CategoryHeader extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$P, create_fragment$S, safe_not_equal, { store: 0, category: 1 });
  }
};
__name(_CategoryHeader, "CategoryHeader");
let CategoryHeader = _CategoryHeader;
const MerchantItemTab_svelte_svelte_type_style_lang = "";
const { Boolean: Boolean_1 } = globals;
function get_each_context_3$3(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[42] = list[i];
  child_ctx[44] = i;
  return child_ctx;
}
__name(get_each_context_3$3, "get_each_context_3$3");
function get_each_context_4$2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[45] = list[i];
  child_ctx[47] = i;
  return child_ctx;
}
__name(get_each_context_4$2, "get_each_context_4$2");
function get_each_context$q(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[39] = list[i];
  child_ctx[41] = i;
  return child_ctx;
}
__name(get_each_context$q, "get_each_context$q");
function get_each_context_1$d(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[42] = list[i];
  child_ctx[44] = i;
  return child_ctx;
}
__name(get_each_context_1$d, "get_each_context_1$d");
function get_each_context_2$5(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[45] = list[i];
  child_ctx[47] = i;
  return child_ctx;
}
__name(get_each_context_2$5, "get_each_context_2$5");
function get_each_context_5$2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[45] = list[i];
  child_ctx[41] = i;
  return child_ctx;
}
__name(get_each_context_5$2, "get_each_context_5$2");
function get_each_context_6(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[39] = list[i];
  return child_ctx;
}
__name(get_each_context_6, "get_each_context_6");
function create_if_block_7$5(ctx) {
  let select;
  let option;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let mounted;
  let dispose;
  let each_value_6 = (
    /*categoryDropDown*/
    ctx[8]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*category*/
    ctx2[39].type
  ), "get_key");
  for (let i = 0; i < each_value_6.length; i += 1) {
    let child_ctx = get_each_context_6(ctx, each_value_6, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_6(key, child_ctx));
  }
  return {
    c() {
      select = element("select");
      option = element("option");
      option.textContent = `${localize("ITEM-PILES.Merchant.AllTypes")}`;
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      option.__value = "all";
      option.value = option.__value;
      set_style(select, "flex", "0 1 auto");
      set_style(select, "margin-left", "0.4rem");
      set_style(select, "height", "26px");
      if (
        /*$typeFilterStore*/
        ctx[10] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[33].call(select)
        ));
    },
    m(target, anchor) {
      insert(target, select, anchor);
      append(select, option);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*$typeFilterStore*/
        ctx[10],
        true
      );
      if (!mounted) {
        dispose = listen(
          select,
          "change",
          /*select_change_handler*/
          ctx[33]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*categoryDropDown*/
      256) {
        each_value_6 = /*categoryDropDown*/
        ctx2[8];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_6, each_1_lookup, select, destroy_block, create_each_block_6, null, get_each_context_6);
      }
      if (dirty[0] & /*$typeFilterStore, categoryDropDown*/
      1280) {
        select_option(
          select,
          /*$typeFilterStore*/
          ctx2[10]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_7$5, "create_if_block_7$5");
function create_each_block_6(key_1, ctx) {
  let option;
  let t_value = localize(
    /*category*/
    ctx[39].label
  ) + "";
  let t;
  let option_value_value;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*category*/
      ctx[39].type;
      option.value = option.__value;
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*categoryDropDown*/
      256 && t_value !== (t_value = localize(
        /*category*/
        ctx[39].label
      ) + ""))
        set_data(t, t_value);
      if (dirty[0] & /*categoryDropDown*/
      256 && option_value_value !== (option_value_value = /*category*/
      ctx[39].type)) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_6, "create_each_block_6");
function create_each_block_5$2(ctx) {
  let option;
  let t0;
  let t1_value = localize(
    /*column*/
    ctx[45].label
  ) + "";
  let t1;
  return {
    c() {
      option = element("option");
      t0 = text("Sort by: ");
      t1 = text(t1_value);
      option.__value = /*index*/
      ctx[41];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$sortTypesStore*/
      4096 && t1_value !== (t1_value = localize(
        /*column*/
        ctx2[45].label
      ) + ""))
        set_data(t1, t1_value);
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_5$2, "create_each_block_5$2");
function create_else_block_1$4(ctx) {
  let div;
  let t;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let each1_anchor;
  let current;
  let each_value_4 = (
    /*columns*/
    ctx[4]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_4.length; i += 1) {
    each_blocks_1[i] = create_each_block_4$2(get_each_context_4$2(ctx, each_value_4, i));
  }
  let each_value_3 = (
    /*items*/
    ctx[6]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[42].id
  ), "get_key");
  for (let i = 0; i < each_value_3.length; i += 1) {
    let child_ctx = get_each_context_3$3(ctx, each_value_3, i);
    let key = get_key(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block_3$3(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each1_anchor = empty();
      attr(div, "class", "item-piles-item-list-header svelte-1hkmdsd");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div, null);
        }
      }
      insert(target, t, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$inverseSortStore, $sortTypeStore, columns*/
      18448) {
        each_value_4 = /*columns*/
        ctx2[4];
        let i;
        for (i = 0; i < each_value_4.length; i += 1) {
          const child_ctx = get_each_context_4$2(ctx2, each_value_4, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
          } else {
            each_blocks_1[i] = create_each_block_4$2(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(div, null);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_4.length;
      }
      if (dirty[0] & /*items, $itemColumns*/
      68) {
        each_value_3 = /*items*/
        ctx2[6];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_3, each1_lookup, each1_anchor.parentNode, outro_and_destroy_block, create_each_block_3$3, each1_anchor, get_each_context_3$3);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_3.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_each(each_blocks_1, detaching);
      if (detaching)
        detach(t);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each1_anchor);
    }
  };
}
__name(create_else_block_1$4, "create_else_block_1$4");
function create_if_block_2$f(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let current;
  let each_value = (
    /*categories*/
    ctx[7]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*category*/
    ctx2[39].type
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$q(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$q(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$itemsPerCategoryStore, categories, $itemColumns, columns, store, $inverseSortStore, $sortTypeStore, $editPrices*/
      59541) {
        each_value = /*categories*/
        ctx2[7];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, each_1_anchor.parentNode, outro_and_destroy_block, create_each_block$q, each_1_anchor, get_each_context$q);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block_2$f, "create_if_block_2$f");
function create_else_block_2$1(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "svelte-1hkmdsd");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_else_block_2$1, "create_else_block_2$1");
function create_if_block_6$6(ctx) {
  let div;
  let a;
  let html_tag;
  let raw_value = (
    /*column*/
    ctx[45].label + ""
  );
  let t0;
  let i;
  let t1;
  let mounted;
  let dispose;
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[36](
        /*columnIndex*/
        ctx[47]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    c() {
      div = element("div");
      a = element("a");
      html_tag = new HtmlTag(false);
      t0 = space();
      i = element("i");
      t1 = space();
      html_tag.a = t0;
      attr(i, "class", "fas");
      toggle_class(i, "fa-chevron-down", !/*$inverseSortStore*/
      ctx[14] && /*$sortTypeStore*/
      ctx[11] === /*columnIndex*/
      ctx[47] + 1);
      toggle_class(
        i,
        "fa-chevron-up",
        /*$inverseSortStore*/
        ctx[14] && /*$sortTypeStore*/
        ctx[11] === /*columnIndex*/
        ctx[47] + 1
      );
      attr(div, "class", "item-piles-small-text svelte-1hkmdsd");
      toggle_class(div, "item-piles-merchant-first-label", !/*columnIndex*/
      ctx[47]);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, a);
      html_tag.m(raw_value, a);
      append(a, t0);
      append(a, i);
      append(div, t1);
      if (!mounted) {
        dispose = listen(a, "click", click_handler_1);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*columns*/
      16 && raw_value !== (raw_value = /*column*/
      ctx[45].label + ""))
        html_tag.p(raw_value);
      if (dirty[0] & /*$inverseSortStore, $sortTypeStore*/
      18432) {
        toggle_class(i, "fa-chevron-down", !/*$inverseSortStore*/
        ctx[14] && /*$sortTypeStore*/
        ctx[11] === /*columnIndex*/
        ctx[47] + 1);
      }
      if (dirty[0] & /*$inverseSortStore, $sortTypeStore*/
      18432) {
        toggle_class(
          i,
          "fa-chevron-up",
          /*$inverseSortStore*/
          ctx[14] && /*$sortTypeStore*/
          ctx[11] === /*columnIndex*/
          ctx[47] + 1
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_6$6, "create_if_block_6$6");
function create_each_block_4$2(ctx) {
  let if_block_anchor;
  function select_block_type_2(ctx2, dirty) {
    if (
      /*column*/
      ctx2[45].label
    )
      return create_if_block_6$6;
    return create_else_block_2$1;
  }
  __name(select_block_type_2, "select_block_type_2");
  let current_block_type = select_block_type_2(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_2(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    d(detaching) {
      if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block_4$2, "create_each_block_4$2");
function create_each_block_3$3(key_1, ctx) {
  let first;
  let merchantitementry;
  let current;
  merchantitementry = new MerchantItemEntry({
    props: {
      item: (
        /*item*/
        ctx[42]
      ),
      index: (
        /*itemIndex*/
        ctx[44]
      ),
      columns: (
        /*$itemColumns*/
        ctx[2]
      )
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(merchantitementry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(merchantitementry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const merchantitementry_changes = {};
      if (dirty[0] & /*items*/
      64)
        merchantitementry_changes.item = /*item*/
        ctx[42];
      if (dirty[0] & /*items*/
      64)
        merchantitementry_changes.index = /*itemIndex*/
        ctx[44];
      if (dirty[0] & /*$itemColumns*/
      4)
        merchantitementry_changes.columns = /*$itemColumns*/
        ctx[2];
      merchantitementry.$set(merchantitementry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantitementry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantitementry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(merchantitementry, detaching);
    }
  };
}
__name(create_each_block_3$3, "create_each_block_3$3");
function create_if_block_5$8(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "svelte-1hkmdsd");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_5$8, "create_if_block_5$8");
function create_if_block_4$b(ctx) {
  let div;
  let a;
  let html_tag;
  let raw_value = (
    /*column*/
    ctx[45].label + ""
  );
  let t0;
  let i;
  let t1;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx[35](
        /*columnIndex*/
        ctx[47]
      )
    );
  }
  __name(click_handler, "click_handler");
  return {
    c() {
      div = element("div");
      a = element("a");
      html_tag = new HtmlTag(false);
      t0 = space();
      i = element("i");
      t1 = space();
      html_tag.a = t0;
      attr(i, "class", "fas");
      toggle_class(i, "fa-chevron-down", !/*$inverseSortStore*/
      ctx[14] && /*$sortTypeStore*/
      ctx[11] === /*columnIndex*/
      ctx[47] + 1);
      toggle_class(
        i,
        "fa-chevron-up",
        /*$inverseSortStore*/
        ctx[14] && /*$sortTypeStore*/
        ctx[11] === /*columnIndex*/
        ctx[47] + 1
      );
      attr(div, "class", "item-piles-small-text svelte-1hkmdsd");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, a);
      html_tag.m(raw_value, a);
      append(a, t0);
      append(a, i);
      append(div, t1);
      if (!mounted) {
        dispose = listen(a, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*columns*/
      16 && raw_value !== (raw_value = /*column*/
      ctx[45].label + ""))
        html_tag.p(raw_value);
      if (dirty[0] & /*$inverseSortStore, $sortTypeStore*/
      18432) {
        toggle_class(i, "fa-chevron-down", !/*$inverseSortStore*/
        ctx[14] && /*$sortTypeStore*/
        ctx[11] === /*columnIndex*/
        ctx[47] + 1);
      }
      if (dirty[0] & /*$inverseSortStore, $sortTypeStore*/
      18432) {
        toggle_class(
          i,
          "fa-chevron-up",
          /*$inverseSortStore*/
          ctx[14] && /*$sortTypeStore*/
          ctx[11] === /*columnIndex*/
          ctx[47] + 1
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$b, "create_if_block_4$b");
function create_if_block_3$c(ctx) {
  let categoryheader;
  let current;
  categoryheader = new CategoryHeader({
    props: {
      store: (
        /*store*/
        ctx[0]
      ),
      category: (
        /*category*/
        ctx[39]
      )
    }
  });
  return {
    c() {
      create_component(categoryheader.$$.fragment);
    },
    m(target, anchor) {
      mount_component(categoryheader, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const categoryheader_changes = {};
      if (dirty[0] & /*store*/
      1)
        categoryheader_changes.store = /*store*/
        ctx2[0];
      if (dirty[0] & /*categories*/
      128)
        categoryheader_changes.category = /*category*/
        ctx2[39];
      categoryheader.$set(categoryheader_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(categoryheader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(categoryheader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(categoryheader, detaching);
    }
  };
}
__name(create_if_block_3$c, "create_if_block_3$c");
function create_each_block_2$5(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block_3$c, create_if_block_4$b, create_if_block_5$8];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (
      /*columnIndex*/
      ctx2[47] === 0
    )
      return 0;
    if (
      /*column*/
      ctx2[45].label && /*columnIndex*/
      ctx2[47] > 0 && /*index*/
      ctx2[41] === 0 && !/*$editPrices*/
      ctx2[13]
    )
      return 1;
    if (!/*$editPrices*/
    ctx2[13])
      return 2;
    return -1;
  }
  __name(select_block_type_1, "select_block_type_1");
  if (~(current_block_type_index = select_block_type_1(ctx))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block_2$5, "create_each_block_2$5");
function create_each_block_1$d(key_1, ctx) {
  let first;
  let merchantitementry;
  let current;
  merchantitementry = new MerchantItemEntry({
    props: {
      item: (
        /*item*/
        ctx[42]
      ),
      index: (
        /*itemIndex*/
        ctx[44]
      ),
      columns: (
        /*$itemColumns*/
        ctx[2]
      )
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(merchantitementry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(merchantitementry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const merchantitementry_changes = {};
      if (dirty[0] & /*$itemsPerCategoryStore, categories*/
      32896)
        merchantitementry_changes.item = /*item*/
        ctx[42];
      if (dirty[0] & /*$itemsPerCategoryStore, categories*/
      32896)
        merchantitementry_changes.index = /*itemIndex*/
        ctx[44];
      if (dirty[0] & /*$itemColumns*/
      4)
        merchantitementry_changes.columns = /*$itemColumns*/
        ctx[2];
      merchantitementry.$set(merchantitementry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantitementry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantitementry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(merchantitementry, detaching);
    }
  };
}
__name(create_each_block_1$d, "create_each_block_1$d");
function create_each_block$q(key_1, ctx) {
  let div;
  let t;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let each1_anchor;
  let current;
  let each_value_2 = (
    /*columns*/
    ctx[4]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks_1[i] = create_each_block_2$5(get_each_context_2$5(ctx, each_value_2, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  }), "out");
  let each_value_1 = (
    /*$itemsPerCategoryStore*/
    ctx[15][
      /*category*/
      ctx[39].type
    ].items
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[42].id
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$d(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block_1$d(key, child_ctx));
  }
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each1_anchor = empty();
      attr(div, "class", "item-piles-item-list-header svelte-1hkmdsd");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div, null);
        }
      }
      insert(target, t, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each1_anchor, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*store, categories, $inverseSortStore, $sortTypeStore, columns, $editPrices*/
      26769) {
        each_value_2 = /*columns*/
        ctx[4];
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_2$5(ctx, each_value_2, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_2$5(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(div, null);
          }
        }
        group_outros();
        for (i = each_value_2.length; i < each_blocks_1.length; i += 1) {
          out(i);
        }
        check_outros();
      }
      if (dirty[0] & /*$itemsPerCategoryStore, categories, $itemColumns*/
      32900) {
        each_value_1 = /*$itemsPerCategoryStore*/
        ctx[15][
          /*category*/
          ctx[39].type
        ].items;
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_1, each1_lookup, each1_anchor.parentNode, outro_and_destroy_block, create_each_block_1$d, each1_anchor, get_each_context_1$d);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_2.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean_1);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_each(each_blocks_1, detaching);
      if (detaching)
        detach(t);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each1_anchor);
    }
  };
}
__name(create_each_block$q, "create_each_block$q");
function create_if_block$y(ctx) {
  let div;
  let span;
  function select_block_type_3(ctx2, dirty) {
    if (
      /*visibleItems*/
      ctx2[5].length
    )
      return create_if_block_1$n;
    return create_else_block$c;
  }
  __name(select_block_type_3, "select_block_type_3");
  let current_block_type = select_block_type_3(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      span = element("span");
      if_block.c();
      attr(span, "class", "align-center-row");
      set_style(span, "font-size", "1.25rem");
      set_style(span, "opacity", "0.8");
      set_style(div, "height", "calc(100% - 51px)");
      attr(div, "class", "item-piles-flexcol align-center-col");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      if_block.m(span, null);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_3(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(span, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if_block.d();
    }
  };
}
__name(create_if_block$y, "create_if_block$y");
function create_else_block$c(ctx) {
  let t_value = localize(
    /*noItemsLabel*/
    ctx[1]
  ) + "";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*noItemsLabel*/
      2 && t_value !== (t_value = localize(
        /*noItemsLabel*/
        ctx2[1]
      ) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(create_else_block$c, "create_else_block$c");
function create_if_block_1$n(ctx) {
  let t_value = localize("ITEM-PILES.Merchant.NoMatchFound") + "";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(create_if_block_1$n, "create_if_block_1$n");
function create_fragment$R(ctx) {
  let div0;
  let input;
  let t0;
  let t1;
  let select;
  let t2;
  let div1;
  let current_block_type_index;
  let if_block1;
  let t3;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*categoryDropDown*/
    ctx[8].length > 1 && create_if_block_7$5(ctx)
  );
  let each_value_5 = (
    /*$sortTypesStore*/
    ctx[12]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_5.length; i += 1) {
    each_blocks[i] = create_each_block_5$2(get_each_context_5$2(ctx, each_value_5, i));
  }
  const if_block_creators = [create_if_block_2$f, create_else_block_1$4];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*$sortTypeStore*/
      ctx2[11] === 0 || /*$editPrices*/
      ctx2[13]
    )
      return 0;
    return 1;
  }
  __name(select_block_type, "select_block_type");
  current_block_type_index = select_block_type(ctx);
  if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block2 = !/*$categoryStore*/
  ctx[3].length && create_if_block$y(ctx);
  return {
    c() {
      div0 = element("div");
      input = element("input");
      t0 = space();
      if (if_block0)
        if_block0.c();
      t1 = space();
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t2 = space();
      div1 = element("div");
      if_block1.c();
      t3 = space();
      if (if_block2)
        if_block2.c();
      attr(input, "placeholder", "Type to search...");
      attr(input, "type", "text");
      set_style(select, "flex", "0 1 auto");
      set_style(select, "margin-left", "0.4rem");
      set_style(select, "height", "26px");
      if (
        /*$sortTypeStore*/
        ctx[11] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler_1*/
          ctx[34].call(select)
        ));
      attr(div0, "class", "item-piles-flexrow");
      attr(div1, "class", "item-piles-items-list svelte-1hkmdsd");
      set_style(div1, "grid-template-columns", "auto repeat(" + /*columns*/
      (ctx[4].length - 1) + ", max-content)");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, input);
      set_input_value(
        input,
        /*$searchStore*/
        ctx[9]
      );
      append(div0, t0);
      if (if_block0)
        if_block0.m(div0, null);
      append(div0, t1);
      append(div0, select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*$sortTypeStore*/
        ctx[11],
        true
      );
      insert(target, t2, anchor);
      insert(target, div1, anchor);
      if_blocks[current_block_type_index].m(div1, null);
      append(div1, t3);
      if (if_block2)
        if_block2.m(div1, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[32]
          ),
          listen(
            select,
            "change",
            /*select_change_handler_1*/
            ctx[34]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$searchStore*/
      512 && input.value !== /*$searchStore*/
      ctx2[9]) {
        set_input_value(
          input,
          /*$searchStore*/
          ctx2[9]
        );
      }
      if (
        /*categoryDropDown*/
        ctx2[8].length > 1
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_7$5(ctx2);
          if_block0.c();
          if_block0.m(div0, t1);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty[0] & /*$sortTypesStore*/
      4096) {
        each_value_5 = /*$sortTypesStore*/
        ctx2[12];
        let i;
        for (i = 0; i < each_value_5.length; i += 1) {
          const child_ctx = get_each_context_5$2(ctx2, each_value_5, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_5$2(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_5.length;
      }
      if (dirty[0] & /*$sortTypeStore*/
      2048) {
        select_option(
          select,
          /*$sortTypeStore*/
          ctx2[11]
        );
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block1 = if_blocks[current_block_type_index];
        if (!if_block1) {
          if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block1.c();
        } else {
          if_block1.p(ctx2, dirty);
        }
        transition_in(if_block1, 1);
        if_block1.m(div1, t3);
      }
      if (!/*$categoryStore*/
      ctx2[3].length) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block$y(ctx2);
          if_block2.c();
          if_block2.m(div1, null);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (!current || dirty[0] & /*columns*/
      16) {
        set_style(div1, "grid-template-columns", "auto repeat(" + /*columns*/
        (ctx2[4].length - 1) + ", max-content)");
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (if_block0)
        if_block0.d();
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(t2);
      if (detaching)
        detach(div1);
      if_blocks[current_block_type_index].d();
      if (if_block2)
        if_block2.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$R, "create_fragment$R");
function instance$O($$self, $$props, $$invalidate) {
  let categoryDropDown;
  let categories;
  let items;
  let visibleItems;
  let $itemColumns;
  let $visibleItemsStore;
  let $itemsStore;
  let $categoryStore;
  let $itemCategoriesStore;
  let $searchStore;
  let $typeFilterStore;
  let $sortTypeStore;
  let $sortTypesStore;
  let $editPrices;
  let $inverseSortStore;
  let $itemsPerCategoryStore;
  let { store } = $$props;
  let { noItemsLabel = "ITEM-PILES.Merchant.NoItemsForSale" } = $$props;
  let { services = false } = $$props;
  store.pileData;
  const searchStore = store.search;
  component_subscribe($$self, searchStore, (value) => $$invalidate(9, $searchStore = value));
  const visibleItemsStore = store.visibleItems;
  component_subscribe($$self, visibleItemsStore, (value) => $$invalidate(29, $visibleItemsStore = value));
  const itemsStore = store.items;
  component_subscribe($$self, itemsStore, (value) => $$invalidate(30, $itemsStore = value));
  const itemsPerCategoryStore = store.itemsPerCategory;
  component_subscribe($$self, itemsPerCategoryStore, (value) => $$invalidate(15, $itemsPerCategoryStore = value));
  const categoryStore = store.categories;
  component_subscribe($$self, categoryStore, (value) => $$invalidate(3, $categoryStore = value));
  store.priceModifiersPerType;
  const itemCategoriesStore = store.itemCategories;
  component_subscribe($$self, itemCategoriesStore, (value) => $$invalidate(31, $itemCategoriesStore = value));
  const typeFilterStore = store.typeFilter;
  component_subscribe($$self, typeFilterStore, (value) => $$invalidate(10, $typeFilterStore = value));
  const sortTypesStore = store.sortTypes;
  component_subscribe($$self, sortTypesStore, (value) => $$invalidate(12, $sortTypesStore = value));
  const sortTypeStore = store.sortType;
  component_subscribe($$self, sortTypeStore, (value) => $$invalidate(11, $sortTypeStore = value));
  const inverseSortStore = store.inverseSort;
  component_subscribe($$self, inverseSortStore, (value) => $$invalidate(14, $inverseSortStore = value));
  const editPrices = store.editPrices;
  component_subscribe($$self, editPrices, (value) => $$invalidate(13, $editPrices = value));
  const itemColumns = store.itemColumns;
  component_subscribe($$self, itemColumns, (value) => $$invalidate(2, $itemColumns = value));
  let columns = [];
  function input_input_handler() {
    $searchStore = this.value;
    searchStore.set($searchStore);
  }
  __name(input_input_handler, "input_input_handler");
  function select_change_handler() {
    $typeFilterStore = select_value(this);
    typeFilterStore.set($typeFilterStore);
    $$invalidate(8, categoryDropDown), $$invalidate(31, $itemCategoriesStore), $$invalidate(28, services);
  }
  __name(select_change_handler, "select_change_handler");
  function select_change_handler_1() {
    $sortTypeStore = select_value(this);
    sortTypeStore.set($sortTypeStore);
  }
  __name(select_change_handler_1, "select_change_handler_1");
  const click_handler = /* @__PURE__ */ __name((columnIndex) => {
    set_store_value(
      inverseSortStore,
      $inverseSortStore = $sortTypeStore === columnIndex + 1 ? !$inverseSortStore : false,
      $inverseSortStore
    );
    set_store_value(sortTypeStore, $sortTypeStore = columnIndex + 1, $sortTypeStore);
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name((columnIndex) => {
    set_store_value(
      inverseSortStore,
      $inverseSortStore = $sortTypeStore === columnIndex + 1 ? !$inverseSortStore : false,
      $inverseSortStore
    );
    set_store_value(sortTypeStore, $sortTypeStore = columnIndex + 1, $sortTypeStore);
  }, "click_handler_1");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
    if ("noItemsLabel" in $$props2)
      $$invalidate(1, noItemsLabel = $$props2.noItemsLabel);
    if ("services" in $$props2)
      $$invalidate(28, services = $$props2.services);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*services*/
    268435456 | $$self.$$.dirty[1] & /*$itemCategoriesStore*/
    1) {
      $$invalidate(8, categoryDropDown = $itemCategoriesStore.filter((category) => category.service === services));
    }
    if ($$self.$$.dirty[0] & /*$categoryStore, services*/
    268435464) {
      $$invalidate(7, categories = $categoryStore.filter((category) => category.service === services));
    }
    if ($$self.$$.dirty[0] & /*$itemsStore, services*/
    1342177280) {
      $$invalidate(6, items = $itemsStore.filter((item) => Boolean(get_store_value(item.itemFlagData)?.isService) === services));
    }
    if ($$self.$$.dirty[0] & /*$visibleItemsStore, services*/
    805306368) {
      $$invalidate(5, visibleItems = $visibleItemsStore.filter((item) => Boolean(get_store_value(item.itemFlagData)?.isService) === services));
    }
    if ($$self.$$.dirty[0] & /*$itemColumns*/
    4) {
      {
        $$invalidate(4, columns = [{ label: "Name", component: CategoryHeader }, ...$itemColumns.slice(1)]);
      }
    }
  };
  return [
    store,
    noItemsLabel,
    $itemColumns,
    $categoryStore,
    columns,
    visibleItems,
    items,
    categories,
    categoryDropDown,
    $searchStore,
    $typeFilterStore,
    $sortTypeStore,
    $sortTypesStore,
    $editPrices,
    $inverseSortStore,
    $itemsPerCategoryStore,
    searchStore,
    visibleItemsStore,
    itemsStore,
    itemsPerCategoryStore,
    categoryStore,
    itemCategoriesStore,
    typeFilterStore,
    sortTypesStore,
    sortTypeStore,
    inverseSortStore,
    editPrices,
    itemColumns,
    services,
    $visibleItemsStore,
    $itemsStore,
    $itemCategoriesStore,
    input_input_handler,
    select_change_handler,
    select_change_handler_1,
    click_handler,
    click_handler_1
  ];
}
__name(instance$O, "instance$O");
const _MerchantItemTab = class _MerchantItemTab extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$O, create_fragment$R, safe_not_equal, { store: 0, noItemsLabel: 1, services: 28 }, null, [-1, -1]);
  }
};
__name(_MerchantItemTab, "MerchantItemTab");
let MerchantItemTab = _MerchantItemTab;
const CustomDialog_svelte_svelte_type_style_lang = "";
function get_each_context$p(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[3] = list[i];
  return child_ctx;
}
__name(get_each_context$p, "get_each_context$p");
function create_if_block_2$e(ctx) {
  let p;
  let i;
  let i_class_value;
  return {
    c() {
      p = element("p");
      i = element("i");
      attr(i, "class", i_class_value = null_to_empty(
        /*icon*/
        ctx[0]
      ) + " svelte-iivrm9");
      attr(p, "class", "header-icon svelte-iivrm9");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, i);
    },
    p(ctx2, dirty) {
      if (dirty & /*icon*/
      1 && i_class_value !== (i_class_value = null_to_empty(
        /*icon*/
        ctx2[0]
      ) + " svelte-iivrm9")) {
        attr(i, "class", i_class_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_2$e, "create_if_block_2$e");
function create_if_block_1$m(ctx) {
  let p;
  let strong;
  let t;
  return {
    c() {
      p = element("p");
      strong = element("strong");
      t = text(
        /*header*/
        ctx[1]
      );
      attr(p, "class", "header svelte-iivrm9");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, strong);
      append(strong, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*header*/
      2)
        set_data(
          t,
          /*header*/
          ctx2[1]
        );
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_1$m, "create_if_block_1$m");
function create_else_block$b(ctx) {
  let p;
  return {
    c() {
      p = element("p");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      p.innerHTML = /*content*/
      ctx[2];
    },
    p(ctx2, dirty) {
      if (dirty & /*content*/
      4)
        p.innerHTML = /*content*/
        ctx2[2];
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_else_block$b, "create_else_block$b");
function create_if_block$x(ctx) {
  let each_1_anchor;
  let each_value = (
    /*content*/
    ctx[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$p(get_each_context$p(ctx, each_value, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*content*/
      4) {
        each_value = /*content*/
        ctx2[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$p(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block$p(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block$x, "create_if_block$x");
function create_each_block$p(ctx) {
  let p;
  let raw_value = (
    /*part*/
    ctx[3] + ""
  );
  return {
    c() {
      p = element("p");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      p.innerHTML = raw_value;
    },
    p(ctx2, dirty) {
      if (dirty & /*content*/
      4 && raw_value !== (raw_value = /*part*/
      ctx2[3] + ""))
        p.innerHTML = raw_value;
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_each_block$p, "create_each_block$p");
function create_fragment$Q(ctx) {
  let div;
  let t0;
  let t1;
  let show_if;
  let if_block0 = (
    /*icon*/
    ctx[0] && create_if_block_2$e(ctx)
  );
  let if_block1 = (
    /*header*/
    ctx[1] && create_if_block_1$m(ctx)
  );
  function select_block_type(ctx2, dirty) {
    if (dirty & /*content*/
    4)
      show_if = null;
    if (show_if == null)
      show_if = !!Array.isArray(
        /*content*/
        ctx2[2]
      );
    if (show_if)
      return create_if_block$x;
    return create_else_block$b;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx, -1);
  let if_block2 = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      if (if_block1)
        if_block1.c();
      t1 = space();
      if_block2.c();
      attr(div, "class", "svelte-iivrm9");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t0);
      if (if_block1)
        if_block1.m(div, null);
      append(div, t1);
      if_block2.m(div, null);
    },
    p(ctx2, [dirty]) {
      if (
        /*icon*/
        ctx2[0]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_2$e(ctx2);
          if_block0.c();
          if_block0.m(div, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*header*/
        ctx2[1]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_1$m(ctx2);
          if_block1.c();
          if_block1.m(div, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2, dirty)) && if_block2) {
        if_block2.p(ctx2, dirty);
      } else {
        if_block2.d(1);
        if_block2 = current_block_type(ctx2);
        if (if_block2) {
          if_block2.c();
          if_block2.m(div, null);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if_block2.d();
    }
  };
}
__name(create_fragment$Q, "create_fragment$Q");
function instance$N($$self, $$props, $$invalidate) {
  let { icon = "fas fa-exclamation-triangle" } = $$props;
  let { header = "Item Piles" } = $$props;
  let { content } = $$props;
  $$self.$$set = ($$props2) => {
    if ("icon" in $$props2)
      $$invalidate(0, icon = $$props2.icon);
    if ("header" in $$props2)
      $$invalidate(1, header = $$props2.header);
    if ("content" in $$props2)
      $$invalidate(2, content = $$props2.content);
  };
  return [icon, header, content];
}
__name(instance$N, "instance$N");
const _CustomDialog = class _CustomDialog extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$N, create_fragment$Q, safe_not_equal, { icon: 0, header: 1, content: 2 });
  }
};
__name(_CustomDialog, "CustomDialog");
let CustomDialog = _CustomDialog;
const MerchantPopulateItemsTab_svelte_svelte_type_style_lang = "";
function get_each_context$o(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[51] = list[i];
  child_ctx[52] = list;
  child_ctx[53] = i;
  return child_ctx;
}
__name(get_each_context$o, "get_each_context$o");
function get_each_context_1$c(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[54] = list[i][0];
  child_ctx[55] = list[i][1];
  return child_ctx;
}
__name(get_each_context_1$c, "get_each_context_1$c");
function get_each_context_2$4(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[55] = list[i];
  child_ctx[58] = list;
  child_ctx[59] = i;
  return child_ctx;
}
__name(get_each_context_2$4, "get_each_context_2$4");
function get_each_context_3$2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[51] = list[i];
  return child_ctx;
}
__name(get_each_context_3$2, "get_each_context_3$2");
function get_each_context_4$1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[51] = list[i];
  return child_ctx;
}
__name(get_each_context_4$1, "get_each_context_4$1");
function get_each_context_5$1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[51] = list[i];
  return child_ctx;
}
__name(get_each_context_5$1, "get_each_context_5$1");
function create_if_block_10$2(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = `${localize("ITEM-PILES.Merchant.BuyNoItems")}`;
      attr(div, "class", "item-piles-populate-header svelte-76hk6t");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_10$2, "create_if_block_10$2");
function create_if_block_9$2(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = `${localize("ITEM-PILES.Merchant.CurrentServices")}`;
      attr(div, "class", "item-piles-populate-header svelte-76hk6t");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_9$2, "create_if_block_9$2");
function create_right_slot_1(ctx) {
  let button;
  let i;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx[24](
        /*item*/
        ctx[51]
      )
    );
  }
  __name(click_handler, "click_handler");
  return {
    c() {
      button = element("button");
      i = element("i");
      attr(i, "class", "fas fa-trash svelte-76hk6t");
      attr(button, "slot", "right");
      attr(button, "class", "item-piles-rolled-item-button svelte-76hk6t");
      set_style(button, "color", "red");
      attr(button, "data-fast-tooltip", localize("ITEM-PILES.Merchant.RemoveItem"));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      if (!mounted) {
        dispose = listen(button, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_right_slot_1, "create_right_slot_1");
function create_each_block_5$1(key_1, ctx) {
  let div;
  let itementry;
  let current;
  itementry = new ItemEntry({
    props: {
      item: (
        /*item*/
        ctx[51]
      ),
      showQuantity: true,
      $$slots: { right: [create_right_slot_1] },
      $$scope: { ctx }
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      create_component(itementry.$$.fragment);
      attr(div, "class", "item-piles-flexrow item-piles-item-row item-piles-even-color");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(itementry, div, null);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const itementry_changes = {};
      if (dirty[0] & /*currentServices*/
      64)
        itementry_changes.item = /*item*/
        ctx[51];
      if (dirty[0] & /*currentServices*/
      64 | dirty[2] & /*$$scope*/
      16) {
        itementry_changes.$$scope = { dirty, ctx };
      }
      itementry.$set(itementry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(itementry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(itementry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(itementry);
    }
  };
}
__name(create_each_block_5$1, "create_each_block_5$1");
function create_if_block_8$2(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Merchant.ClearAllServices") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-trash");
      attr(button, "class", "item-piles-button svelte-76hk6t");
      set_style(button, "margin", "5px 0");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[25]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_8$2, "create_if_block_8$2");
function create_if_block_7$4(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = `${localize("ITEM-PILES.Merchant.CurrentItems")}`;
      attr(div, "class", "item-piles-populate-header svelte-76hk6t");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_7$4, "create_if_block_7$4");
function create_right_slot(ctx) {
  let button;
  let i;
  let mounted;
  let dispose;
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx[26](
        /*item*/
        ctx[51]
      )
    );
  }
  __name(click_handler_2, "click_handler_2");
  return {
    c() {
      button = element("button");
      i = element("i");
      attr(i, "class", "fas fa-trash svelte-76hk6t");
      attr(button, "slot", "right");
      attr(button, "class", "item-piles-rolled-item-button svelte-76hk6t");
      set_style(button, "color", "red");
      attr(button, "data-fast-tooltip", localize("ITEM-PILES.Merchant.RemoveItem"));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      if (!mounted) {
        dispose = listen(button, "click", click_handler_2);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_right_slot, "create_right_slot");
function create_each_block_4$1(key_1, ctx) {
  let div;
  let itementry;
  let current;
  itementry = new ItemEntry({
    props: {
      item: (
        /*item*/
        ctx[51]
      ),
      showQuantity: true,
      $$slots: { right: [create_right_slot] },
      $$scope: { ctx }
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      create_component(itementry.$$.fragment);
      attr(div, "class", "item-piles-flexrow item-piles-item-row item-piles-even-color");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(itementry, div, null);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const itementry_changes = {};
      if (dirty[0] & /*currentItems*/
      128)
        itementry_changes.item = /*item*/
        ctx[51];
      if (dirty[0] & /*currentItems*/
      128 | dirty[2] & /*$$scope*/
      16) {
        itementry_changes.$$scope = { dirty, ctx };
      }
      itementry.$set(itementry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(itementry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(itementry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(itementry);
    }
  };
}
__name(create_each_block_4$1, "create_each_block_4$1");
function create_if_block_6$5(ctx) {
  let button;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Merchant.ClearAllItems") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-trash");
      attr(button, "class", "item-piles-button svelte-76hk6t");
      set_style(button, "margin", "5px 0");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_3*/
          ctx[27]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_6$5, "create_if_block_6$5");
function create_if_block_3$b(ctx) {
  let div3;
  let div0;
  let label0;
  let t1;
  let customcategoryinput;
  let updating_value;
  let t2;
  let div2;
  let div1;
  let label1;
  let t3_value = localize("ITEM-PILES.Merchant.TableAddAllItems") + "";
  let t3;
  let label1_for_value;
  let t4;
  let input;
  let input_id_value;
  let t5;
  let t6;
  let div3_transition;
  let current;
  let mounted;
  let dispose;
  function customcategoryinput_value_binding(value) {
    ctx[32](
      value,
      /*table*/
      ctx[55]
    );
  }
  __name(customcategoryinput_value_binding, "customcategoryinput_value_binding");
  let customcategoryinput_props = {};
  if (
    /*table*/
    ctx[55].customCategory !== void 0
  ) {
    customcategoryinput_props.value = /*table*/
    ctx[55].customCategory;
  }
  customcategoryinput = new CustomCategoryInput({ props: customcategoryinput_props });
  binding_callbacks.push(() => bind(customcategoryinput, "value", customcategoryinput_value_binding));
  function input_change_handler() {
    ctx[33].call(
      input,
      /*each_value_2*/
      ctx[58],
      /*table_index*/
      ctx[59]
    );
  }
  __name(input_change_handler, "input_change_handler");
  function change_handler() {
    return (
      /*change_handler*/
      ctx[34](
        /*table*/
        ctx[55],
        /*each_value_2*/
        ctx[58],
        /*table_index*/
        ctx[59]
      )
    );
  }
  __name(change_handler, "change_handler");
  let if_block0 = !/*table*/
  ctx[55].addAll && create_if_block_5$7(ctx);
  let if_block1 = (
    /*table*/
    ctx[55].addAll && create_if_block_4$a(ctx)
  );
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      label0 = element("label");
      label0.textContent = `${localize("ITEM-PILES.Merchant.TableCustomCategory")}`;
      t1 = space();
      create_component(customcategoryinput.$$.fragment);
      t2 = space();
      div2 = element("div");
      div1 = element("div");
      label1 = element("label");
      t3 = text(t3_value);
      t4 = space();
      input = element("input");
      t5 = space();
      if (if_block0)
        if_block0.c();
      t6 = space();
      if (if_block1)
        if_block1.c();
      set_style(label0, "margin-right", "5px");
      attr(div0, "class", "item-piles-flexrow");
      set_style(div0, "align-items", "center");
      set_style(div0, "margin-bottom", "0.25rem");
      set_style(label1, "flex", "0 1 auto");
      set_style(label1, "margin-right", "5px");
      attr(label1, "for", label1_for_value = "table-id-" + /*table*/
      ctx[55].uuid);
      set_style(input, "width", "15px");
      set_style(input, "height", "15px");
      set_style(input, "margin", "0");
      set_style(input, "flex", "0");
      attr(input, "id", input_id_value = "table-id-" + /*table*/
      ctx[55].uuid);
      attr(input, "type", "checkbox");
      attr(div1, "class", "item-piles-flexrow");
      set_style(div1, "align-items", "center");
      set_style(div1, "flex", "0 1 auto");
      set_style(div1, "min-height", "26px");
      attr(div2, "class", "item-piles-flexrow");
      attr(div3, "class", "item-piles-flexcol");
      set_style(div3, "margin-top", "5px");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, label0);
      append(div0, t1);
      mount_component(customcategoryinput, div0, null);
      append(div3, t2);
      append(div3, div2);
      append(div2, div1);
      append(div1, label1);
      append(label1, t3);
      append(div1, t4);
      append(div1, input);
      input.checked = /*table*/
      ctx[55].addAll;
      append(div2, t5);
      if (if_block0)
        if_block0.m(div2, null);
      append(div3, t6);
      if (if_block1)
        if_block1.m(div3, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input, "change", input_change_handler),
          listen(input, "change", change_handler)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const customcategoryinput_changes = {};
      if (!updating_value && dirty[0] & /*$populationTables*/
      4) {
        updating_value = true;
        customcategoryinput_changes.value = /*table*/
        ctx[55].customCategory;
        add_flush_callback(() => updating_value = false);
      }
      customcategoryinput.$set(customcategoryinput_changes);
      if (!current || dirty[0] & /*$populationTables*/
      4 && label1_for_value !== (label1_for_value = "table-id-" + /*table*/
      ctx[55].uuid)) {
        attr(label1, "for", label1_for_value);
      }
      if (!current || dirty[0] & /*$populationTables*/
      4 && input_id_value !== (input_id_value = "table-id-" + /*table*/
      ctx[55].uuid)) {
        attr(input, "id", input_id_value);
      }
      if (dirty[0] & /*$populationTables*/
      4) {
        input.checked = /*table*/
        ctx[55].addAll;
      }
      if (!/*table*/
      ctx[55].addAll) {
        if (if_block0) {
          if_block0.p(ctx, dirty);
        } else {
          if_block0 = create_if_block_5$7(ctx);
          if_block0.c();
          if_block0.m(div2, null);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*table*/
        ctx[55].addAll
      ) {
        if (if_block1) {
          if_block1.p(ctx, dirty);
        } else {
          if_block1 = create_if_block_4$a(ctx);
          if_block1.c();
          if_block1.m(div3, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(customcategoryinput.$$.fragment, local);
      add_render_callback(() => {
        if (!current)
          return;
        if (!div3_transition)
          div3_transition = create_bidirectional_transition(div3, slide, { duration: 200, easing: quintOut }, true);
        div3_transition.run(1);
      });
      current = true;
    },
    o(local) {
      transition_out(customcategoryinput.$$.fragment, local);
      if (!div3_transition)
        div3_transition = create_bidirectional_transition(div3, slide, { duration: 200, easing: quintOut }, false);
      div3_transition.run(0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      destroy_component(customcategoryinput);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (detaching && div3_transition)
        div3_transition.end();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_3$b, "create_if_block_3$b");
function create_if_block_5$7(ctx) {
  let div;
  let label;
  let t1;
  let input;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx[35].call(
      input,
      /*each_value_2*/
      ctx[58],
      /*table_index*/
      ctx[59]
    );
  }
  __name(input_input_handler, "input_input_handler");
  return {
    c() {
      div = element("div");
      label = element("label");
      label.textContent = `${localize("ITEM-PILES.Merchant.TableTimesToRoll")}`;
      t1 = space();
      input = element("input");
      set_style(label, "margin-right", "5px");
      set_style(label, "text-align", "right");
      attr(input, "type", "text");
      attr(input, "placeholder", "2d6+4");
      set_style(input, "height", "20px");
      set_style(input, "margin", "3px");
      set_style(input, "max-width", "50px");
      set_style(input, "font-size", "0.75rem");
      attr(div, "class", "item-piles-flexrow item-piles-item-row");
      set_style(div, "align-items", "center");
      set_style(div, "flex", "1");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(div, t1);
      append(div, input);
      set_input_value(
        input,
        /*table*/
        ctx[55].timesToRoll
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*$populationTables*/
      4 && input.value !== /*table*/
      ctx[55].timesToRoll) {
        set_input_value(
          input,
          /*table*/
          ctx[55].timesToRoll
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_5$7, "create_if_block_5$7");
function create_if_block_4$a(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let each_value_3 = (
    /*$tables*/
    ctx[3][
      /*table*/
      ctx[55].uuid
    ].items
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[51].id
  ), "get_key");
  for (let i = 0; i < each_value_3.length; i += 1) {
    let child_ctx = get_each_context_3$2(ctx, each_value_3, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_3$2(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$populationTables, $tables*/
      12) {
        each_value_3 = /*$tables*/
        ctx2[3][
          /*table*/
          ctx2[55].uuid
        ].items;
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_3, each_1_lookup, each_1_anchor.parentNode, destroy_block, create_each_block_3$2, each_1_anchor, get_each_context_3$2);
      }
    },
    d(detaching) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block_4$a, "create_if_block_4$a");
function create_each_block_3$2(key_1, ctx) {
  let div5;
  let div0;
  let img;
  let img_src_value;
  let t0;
  let div2;
  let div1;
  let a;
  let t1_value = (
    /*item*/
    ctx[51].text + ""
  );
  let t1;
  let t2;
  let div4;
  let div3;
  let input;
  let input_value_value;
  let mounted;
  let dispose;
  function click_handler_8() {
    return (
      /*click_handler_8*/
      ctx[36](
        /*item*/
        ctx[51]
      )
    );
  }
  __name(click_handler_8, "click_handler_8");
  function change_handler_1(...args) {
    return (
      /*change_handler_1*/
      ctx[37](
        /*table*/
        ctx[55],
        /*item*/
        ctx[51],
        /*each_value_2*/
        ctx[58],
        /*table_index*/
        ctx[59],
        ...args
      )
    );
  }
  __name(change_handler_1, "change_handler_1");
  return {
    key: key_1,
    first: null,
    c() {
      div5 = element("div");
      div0 = element("div");
      img = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      a = element("a");
      t1 = text(t1_value);
      t2 = space();
      div4 = element("div");
      div3 = element("div");
      input = element("input");
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*item*/
      ctx[51].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      attr(a, "class", "item-piles-clickable");
      attr(div1, "class", "item-piles-name-container");
      attr(div2, "class", "item-piles-name item-piles-text svelte-76hk6t");
      attr(input, "class", "item-piles-quantity");
      attr(input, "type", "text");
      input.value = input_value_value = /*table*/
      ctx[55]?.items?.[
        /*item*/
        ctx[51].id
      ] ?? "1d4";
      attr(div3, "class", "item-piles-quantity-input-container svelte-76hk6t");
      attr(div4, "class", "item-piles-quantity-container svelte-76hk6t");
      set_style(div4, "flex", "0 1 75px");
      attr(div5, "class", "item-piles-flexrow item-piles-item-row item-piles-odd-color");
      this.first = div5;
    },
    m(target, anchor) {
      insert(target, div5, anchor);
      append(div5, div0);
      append(div0, img);
      append(div5, t0);
      append(div5, div2);
      append(div2, div1);
      append(div1, a);
      append(a, t1);
      append(div5, t2);
      append(div5, div4);
      append(div4, div3);
      append(div3, input);
      if (!mounted) {
        dispose = [
          listen(a, "click", click_handler_8),
          listen(input, "change", change_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*$tables, $populationTables*/
      12 && !src_url_equal(img.src, img_src_value = /*item*/
      ctx[51].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*$tables, $populationTables*/
      12 && t1_value !== (t1_value = /*item*/
      ctx[51].text + ""))
        set_data(t1, t1_value);
      if (dirty[0] & /*$populationTables, $tables*/
      12 && input_value_value !== (input_value_value = /*table*/
      ctx[55]?.items?.[
        /*item*/
        ctx[51].id
      ] ?? "1d4") && input.value !== input_value_value) {
        input.value = input_value_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div5);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_3$2, "create_each_block_3$2");
function create_each_block_2$4(ctx) {
  let div2;
  let div1;
  let div0;
  let strong;
  let t0_value = (
    /*$tables*/
    ctx[3][
      /*table*/
      ctx[55].uuid
    ].name + ""
  );
  let t0;
  let t1;
  let button0;
  let i0;
  let t2;
  let button1;
  let i1;
  let t3;
  let button2;
  let i2;
  let t4;
  let current;
  let mounted;
  let dispose;
  function click_handler_52() {
    return (
      /*click_handler_5*/
      ctx[29](
        /*table*/
        ctx[55]
      )
    );
  }
  __name(click_handler_52, "click_handler_5");
  function click_handler_6() {
    return (
      /*click_handler_6*/
      ctx[30](
        /*table*/
        ctx[55],
        /*each_value_2*/
        ctx[58],
        /*table_index*/
        ctx[59]
      )
    );
  }
  __name(click_handler_6, "click_handler_6");
  function click_handler_7() {
    return (
      /*click_handler_7*/
      ctx[31](
        /*table*/
        ctx[55],
        /*each_value_2*/
        ctx[58],
        /*table_index*/
        ctx[59]
      )
    );
  }
  __name(click_handler_7, "click_handler_7");
  let if_block = (
    /*table*/
    ctx[55].open && create_if_block_3$b(ctx)
  );
  return {
    c() {
      div2 = element("div");
      div1 = element("div");
      div0 = element("div");
      strong = element("strong");
      t0 = text(t0_value);
      t1 = space();
      button0 = element("button");
      i0 = element("i");
      t2 = space();
      button1 = element("button");
      i1 = element("i");
      t3 = space();
      button2 = element("button");
      i2 = element("i");
      t4 = space();
      if (if_block)
        if_block.c();
      set_style(strong, "max-width", "100%");
      set_style(strong, "word-break", "break-all");
      set_style(div0, "max-width", "100%");
      set_style(div0, "overflow", "hidden");
      set_style(div0, "text-overflow", "ellipsis");
      attr(i0, "class", "fas fa-trash svelte-76hk6t");
      set_style(i0, "color", "#de0e0e");
      attr(button0, "class", "item-piles-rolled-item-button svelte-76hk6t");
      attr(button0, "data-fast-tooltip", localize("ITEM-PILES.Merchant.ToolTipRemoveTable"));
      attr(button0, "data-fast-tooltip-direction", TooltipManager.TOOLTIP_DIRECTIONS.UP);
      attr(i1, "class", "fas fa-cog svelte-76hk6t");
      attr(button1, "class", "item-piles-rolled-item-button svelte-76hk6t");
      attr(button1, "data-fast-tooltip", localize("ITEM-PILES.Merchant.TooltipConfigureTable"));
      attr(button1, "data-fast-tooltip-direction", TooltipManager.TOOLTIP_DIRECTIONS.UP);
      attr(i2, "class", "fas fa-dice-d20 svelte-76hk6t");
      attr(button2, "class", "item-piles-rolled-item-button svelte-76hk6t");
      attr(button2, "data-fast-tooltip", localize("ITEM-PILES.Merchant.TooltipRollTable"));
      attr(button2, "data-fast-tooltip-direction", TooltipManager.TOOLTIP_DIRECTIONS.UP);
      set_style(button2, "margin-right", "0");
      attr(div1, "class", "item-piles-flexrow");
      set_style(div1, "align-items", "center");
      attr(div2, "class", "item-piles-item-row item-piles-even-color");
      set_style(div2, "min-height", "28px");
      set_style(div2, "padding", "3px 3px 3px 5px");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div1);
      append(div1, div0);
      append(div0, strong);
      append(strong, t0);
      append(div1, t1);
      append(div1, button0);
      append(button0, i0);
      append(div1, t2);
      append(div1, button1);
      append(button1, i1);
      append(div1, t3);
      append(div1, button2);
      append(button2, i2);
      append(div2, t4);
      if (if_block)
        if_block.m(div2, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(button0, "click", click_handler_52),
          listen(button1, "click", click_handler_6),
          listen(button2, "click", click_handler_7)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || dirty[0] & /*$tables, $populationTables*/
      12) && t0_value !== (t0_value = /*$tables*/
      ctx[3][
        /*table*/
        ctx[55].uuid
      ].name + ""))
        set_data(t0, t0_value);
      if (
        /*table*/
        ctx[55].open
      ) {
        if (if_block) {
          if_block.p(ctx, dirty);
          if (dirty[0] & /*$populationTables*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_3$b(ctx);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div2, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_2$4, "create_each_block_2$4");
function create_each_block_1$c(key_1, ctx) {
  let option;
  let t_value = (
    /*table*/
    ctx[55].name + ""
  );
  let t;
  let option_value_value;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*tableUuid*/
      ctx[54];
      option.value = option.__value;
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*selectableTables*/
      1 && t_value !== (t_value = /*table*/
      ctx[55].name + ""))
        set_data(t, t_value);
      if (dirty[0] & /*selectableTables*/
      1 && option_value_value !== (option_value_value = /*tableUuid*/
      ctx[54])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_1$c, "create_each_block_1$c");
function create_if_block_2$d(ctx) {
  let option;
  return {
    c() {
      option = element("option");
      option.textContent = `${localize("ITEM-PILES.Merchant.NoRollTables")}`;
      option.__value = "";
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_if_block_2$d, "create_if_block_2$d");
function create_if_block$w(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t0;
  let div;
  let button0;
  let t1_value = localize("ITEM-PILES.Merchant.AddAll") + "";
  let t1;
  let t2;
  let i0;
  let t3;
  let button1;
  let i1;
  let mounted;
  let dispose;
  let each_value = (
    /*$itemsRolled*/
    ctx[8]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[51].documentId
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$o(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$o(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t0 = space();
      div = element("div");
      button0 = element("button");
      t1 = text(t1_value);
      t2 = space();
      i0 = element("i");
      t3 = space();
      button1 = element("button");
      i1 = element("i");
      attr(i0, "class", "fas fa-arrow-left");
      attr(button0, "class", "item-piles-button svelte-76hk6t");
      attr(i1, "class", "fas fa-trash");
      attr(button1, "class", "item-piles-button svelte-76hk6t");
      set_style(button1, "color", "red");
      set_style(button1, "max-width", "30px");
      attr(button1, "data-fast-tooltip", localize("ITEM-PILES.Merchant.ToolTipRemoveAllRolledItems"));
      attr(div, "class", "item-piles-flexrow");
      set_style(div, "margin", "5px 0");
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, t0, anchor);
      insert(target, div, anchor);
      append(div, button0);
      append(button0, t1);
      append(button0, t2);
      append(button0, i0);
      append(div, t3);
      append(div, button1);
      append(button1, i1);
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*click_handler_13*/
            ctx[45]
          ),
          listen(
            button1,
            "click",
            /*click_handler_14*/
            ctx[46]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*removeItem, $itemsRolled, addItem*/
      98560) {
        each_value = /*$itemsRolled*/
        ctx2[8];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, t0.parentNode, destroy_block, create_each_block$o, t0, get_each_context$o);
      }
    },
    d(detaching) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(t0);
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block$w, "create_if_block$w");
function create_if_block_1$l(ctx) {
  let small;
  let t0_value = (
    /*item*/
    ctx[51].price + ""
  );
  let t0;
  let t1;
  let i;
  return {
    c() {
      small = element("small");
      t0 = text(t0_value);
      t1 = space();
      i = element("i");
      set_style(small, "white-space", "nowrap");
      attr(i, "class", "fas fa-times");
      set_style(i, "color", "#555");
      set_style(i, "font-size", "0.75rem");
      set_style(i, "opacity", "0.75");
    },
    m(target, anchor) {
      insert(target, small, anchor);
      append(small, t0);
      insert(target, t1, anchor);
      insert(target, i, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$itemsRolled*/
      256 && t0_value !== (t0_value = /*item*/
      ctx2[51].price + ""))
        set_data(t0, t0_value);
    },
    d(detaching) {
      if (detaching)
        detach(small);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(i);
    }
  };
}
__name(create_if_block_1$l, "create_if_block_1$l");
function create_each_block$o(key_1, ctx) {
  let div5;
  let button0;
  let i0;
  let t0;
  let div0;
  let img;
  let img_src_value;
  let t1;
  let div2;
  let div1;
  let a;
  let t2_value = (
    /*item*/
    ctx[51].text + ""
  );
  let t2;
  let t3;
  let div4;
  let t4;
  let div3;
  let input;
  let t5;
  let button1;
  let i1;
  let mounted;
  let dispose;
  function click_handler_10() {
    return (
      /*click_handler_10*/
      ctx[41](
        /*item*/
        ctx[51]
      )
    );
  }
  __name(click_handler_10, "click_handler_10");
  function click_handler_11(...args) {
    return (
      /*click_handler_11*/
      ctx[42](
        /*item*/
        ctx[51],
        ...args
      )
    );
  }
  __name(click_handler_11, "click_handler_11");
  let if_block = (
    /*item*/
    ctx[51].price && create_if_block_1$l(ctx)
  );
  function input_input_handler_1() {
    ctx[43].call(
      input,
      /*each_value*/
      ctx[52],
      /*item_index*/
      ctx[53]
    );
  }
  __name(input_input_handler_1, "input_input_handler_1");
  function click_handler_12() {
    return (
      /*click_handler_12*/
      ctx[44](
        /*item*/
        ctx[51]
      )
    );
  }
  __name(click_handler_12, "click_handler_12");
  return {
    key: key_1,
    first: null,
    c() {
      div5 = element("div");
      button0 = element("button");
      i0 = element("i");
      t0 = space();
      div0 = element("div");
      img = element("img");
      t1 = space();
      div2 = element("div");
      div1 = element("div");
      a = element("a");
      t2 = text(t2_value);
      t3 = space();
      div4 = element("div");
      if (if_block)
        if_block.c();
      t4 = space();
      div3 = element("div");
      input = element("input");
      t5 = space();
      button1 = element("button");
      i1 = element("i");
      attr(i0, "class", "fas fa-arrow-left svelte-76hk6t");
      attr(button0, "class", "item-piles-rolled-item-button svelte-76hk6t");
      attr(button0, "data-fast-tooltip", localize("ITEM-PILES.Merchant.AddItem"));
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*item*/
      ctx[51].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      attr(a, "class", "item-piles-clickable");
      attr(div1, "class", "item-piles-name-container");
      attr(div2, "class", "item-piles-name svelte-76hk6t");
      attr(input, "class", "item-piles-quantity");
      attr(input, "type", "number");
      attr(input, "min", "0");
      attr(div3, "class", "item-piles-quantity-input-container svelte-76hk6t");
      attr(div4, "class", "item-piles-quantity-container svelte-76hk6t");
      attr(i1, "class", "fas fa-trash svelte-76hk6t");
      attr(button1, "class", "item-piles-rolled-item-button svelte-76hk6t");
      set_style(button1, "color", "red");
      attr(button1, "data-fast-tooltip", localize("ITEM-PILES.Merchant.RemoveItem"));
      attr(div5, "class", "item-piles-flexrow item-piles-item-row item-piles-even-color");
      this.first = div5;
    },
    m(target, anchor) {
      insert(target, div5, anchor);
      append(div5, button0);
      append(button0, i0);
      append(div5, t0);
      append(div5, div0);
      append(div0, img);
      append(div5, t1);
      append(div5, div2);
      append(div2, div1);
      append(div1, a);
      append(a, t2);
      append(div5, t3);
      append(div5, div4);
      if (if_block)
        if_block.m(div4, null);
      append(div4, t4);
      append(div4, div3);
      append(div3, input);
      set_input_value(
        input,
        /*item*/
        ctx[51].quantity
      );
      append(div5, t5);
      append(div5, button1);
      append(button1, i1);
      if (!mounted) {
        dispose = [
          listen(button0, "click", click_handler_10),
          listen(a, "click", click_handler_11),
          listen(input, "input", input_input_handler_1),
          listen(button1, "click", click_handler_12)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*$itemsRolled*/
      256 && !src_url_equal(img.src, img_src_value = /*item*/
      ctx[51].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty[0] & /*$itemsRolled*/
      256 && t2_value !== (t2_value = /*item*/
      ctx[51].text + ""))
        set_data(t2, t2_value);
      if (
        /*item*/
        ctx[51].price
      ) {
        if (if_block) {
          if_block.p(ctx, dirty);
        } else {
          if_block = create_if_block_1$l(ctx);
          if_block.c();
          if_block.m(div4, t4);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty[0] & /*$itemsRolled*/
      256 && to_number(input.value) !== /*item*/
      ctx[51].quantity) {
        set_input_value(
          input,
          /*item*/
          ctx[51].quantity
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div5);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$o, "create_each_block$o");
function create_fragment$P(ctx) {
  let div6;
  let div0;
  let t0;
  let t1;
  let each_blocks_3 = [];
  let each0_lookup = /* @__PURE__ */ new Map();
  let t2;
  let t3;
  let t4;
  let each_blocks_2 = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let t5;
  let t6;
  let div5;
  let div1;
  let span;
  let t8;
  let button0;
  let i;
  let t9;
  let t10_value = localize("ITEM-PILES.Merchant.RollAllTables") + "";
  let t10;
  let t11;
  let t12;
  let div2;
  let select;
  let each_blocks = [];
  let each3_lookup = /* @__PURE__ */ new Map();
  let each3_anchor;
  let show_if = foundry.utils.isEmpty(
    /*$tables*/
    ctx[3]
  );
  let t13;
  let button1;
  let t15;
  let hr;
  let t16;
  let div4;
  let label0;
  let t17_value = localize(
    /*timesRolled*/
    ctx[4] && /*$itemsRolled*/
    ctx[8].length ? "ITEM-PILES.Merchant.RolledTimes" : "ITEM-PILES.Merchant.ClickRoll",
    { rolls: (
      /*timesRolled*/
      ctx[4]
    ) }
  ) + "";
  let t17;
  let t18;
  let div3;
  let label1;
  let t20;
  let input;
  let t21;
  let current;
  let mounted;
  let dispose;
  let if_block0 = !/*currentItems*/
  (ctx[7].length + /*currentServices*/
  ctx[6].length) && create_if_block_10$2();
  let if_block1 = (
    /*currentServices*/
    ctx[6].length && create_if_block_9$2()
  );
  let each_value_5 = (
    /*currentServices*/
    ctx[6]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[51].id
  ), "get_key");
  for (let i2 = 0; i2 < each_value_5.length; i2 += 1) {
    let child_ctx = get_each_context_5$1(ctx, each_value_5, i2);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_3[i2] = create_each_block_5$1(key, child_ctx));
  }
  let if_block2 = (
    /*currentServices*/
    ctx[6].length && create_if_block_8$2(ctx)
  );
  let if_block3 = (
    /*currentItems*/
    ctx[7].length && create_if_block_7$4()
  );
  let each_value_4 = (
    /*currentItems*/
    ctx[7]
  );
  const get_key_1 = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[51].id
  ), "get_key_1");
  for (let i2 = 0; i2 < each_value_4.length; i2 += 1) {
    let child_ctx = get_each_context_4$1(ctx, each_value_4, i2);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks_2[i2] = create_each_block_4$1(key, child_ctx));
  }
  let if_block4 = (
    /*currentItems*/
    ctx[7].length && create_if_block_6$5(ctx)
  );
  let each_value_2 = (
    /*$populationTables*/
    ctx[2]
  );
  let each_blocks_1 = [];
  for (let i2 = 0; i2 < each_value_2.length; i2 += 1) {
    each_blocks_1[i2] = create_each_block_2$4(get_each_context_2$4(ctx, each_value_2, i2));
  }
  const out = /* @__PURE__ */ __name((i2) => transition_out(each_blocks_1[i2], 1, 1, () => {
    each_blocks_1[i2] = null;
  }), "out");
  let each_value_1 = (
    /*selectableTables*/
    ctx[0]
  );
  const get_key_2 = /* @__PURE__ */ __name((ctx2) => (
    /*tableUuid*/
    ctx2[54]
  ), "get_key_2");
  for (let i2 = 0; i2 < each_value_1.length; i2 += 1) {
    let child_ctx = get_each_context_1$c(ctx, each_value_1, i2);
    let key = get_key_2(child_ctx);
    each3_lookup.set(key, each_blocks[i2] = create_each_block_1$c(key, child_ctx));
  }
  let if_block5 = show_if && create_if_block_2$d();
  let if_block6 = (
    /*$itemsRolled*/
    ctx[8].length && create_if_block$w(ctx)
  );
  return {
    c() {
      div6 = element("div");
      div0 = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      if (if_block1)
        if_block1.c();
      t1 = space();
      for (let i2 = 0; i2 < each_blocks_3.length; i2 += 1) {
        each_blocks_3[i2].c();
      }
      t2 = space();
      if (if_block2)
        if_block2.c();
      t3 = space();
      if (if_block3)
        if_block3.c();
      t4 = space();
      for (let i2 = 0; i2 < each_blocks_2.length; i2 += 1) {
        each_blocks_2[i2].c();
      }
      t5 = space();
      if (if_block4)
        if_block4.c();
      t6 = space();
      div5 = element("div");
      div1 = element("div");
      span = element("span");
      span.textContent = `${localize("ITEM-PILES.Merchant.RollableTables")}`;
      t8 = space();
      button0 = element("button");
      i = element("i");
      t9 = space();
      t10 = text(t10_value);
      t11 = space();
      for (let i2 = 0; i2 < each_blocks_1.length; i2 += 1) {
        each_blocks_1[i2].c();
      }
      t12 = space();
      div2 = element("div");
      select = element("select");
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        each_blocks[i2].c();
      }
      each3_anchor = empty();
      if (if_block5)
        if_block5.c();
      t13 = space();
      button1 = element("button");
      button1.textContent = `${localize("ITEM-PILES.Merchant.AddTable")}`;
      t15 = space();
      hr = element("hr");
      t16 = space();
      div4 = element("div");
      label0 = element("label");
      t17 = text(t17_value);
      t18 = space();
      div3 = element("div");
      label1 = element("label");
      label1.textContent = `${localize("ITEM-PILES.Merchant.KeepRolled")}`;
      t20 = space();
      input = element("input");
      t21 = space();
      if (if_block6)
        if_block6.c();
      set_style(div0, "margin-right", "0.5rem");
      set_style(div0, "max-width", "50%");
      set_style(div0, "max-height", "100%");
      set_style(div0, "overflow-y", "scroll");
      set_style(span, "flex", "1 0 auto");
      attr(i, "class", "fas fa-dice-d20");
      set_style(button0, "height", "20px");
      set_style(button0, "line-height", "inherit");
      set_style(button0, "font-size", "0.75rem");
      set_style(button0, "flex", "1 0 auto");
      set_style(button0, "margin", "0");
      attr(div1, "class", "item-piles-populate-header svelte-76hk6t");
      set_style(select, "max-width", "calc(100% - 81px)");
      if (
        /*selectedTable*/
        ctx[1] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[38].call(select)
        ));
      attr(button1, "class", "item-piles-button svelte-76hk6t");
      set_style(button1, "max-width", "80px");
      set_style(button1, "min-width", "80px");
      attr(div2, "class", "item-piles-flexrow");
      set_style(div2, "margin-top", "0.5rem");
      set_style(div2, "flex-wrap", "nowrap");
      set_style(hr, "margin", "5px 0");
      attr(input, "type", "checkbox");
      attr(input, "class", "svelte-76hk6t");
      attr(div3, "class", "item-piles-flexrow item-piles-keep-rolled svelte-76hk6t");
      attr(div4, "class", "item-piles-flexrow item-piles-roll-header svelte-76hk6t");
      set_style(div5, "padding-right", "0.25rem");
      set_style(div5, "max-width", "50%");
      set_style(div5, "max-height", "100%");
      set_style(div5, "overflow-y", "scroll");
      attr(div6, "class", "item-piles-flexrow");
      set_style(div6, "height", "100%");
    },
    m(target, anchor) {
      insert(target, div6, anchor);
      append(div6, div0);
      if (if_block0)
        if_block0.m(div0, null);
      append(div0, t0);
      if (if_block1)
        if_block1.m(div0, null);
      append(div0, t1);
      for (let i2 = 0; i2 < each_blocks_3.length; i2 += 1) {
        if (each_blocks_3[i2]) {
          each_blocks_3[i2].m(div0, null);
        }
      }
      append(div0, t2);
      if (if_block2)
        if_block2.m(div0, null);
      append(div0, t3);
      if (if_block3)
        if_block3.m(div0, null);
      append(div0, t4);
      for (let i2 = 0; i2 < each_blocks_2.length; i2 += 1) {
        if (each_blocks_2[i2]) {
          each_blocks_2[i2].m(div0, null);
        }
      }
      append(div0, t5);
      if (if_block4)
        if_block4.m(div0, null);
      append(div6, t6);
      append(div6, div5);
      append(div5, div1);
      append(div1, span);
      append(div1, t8);
      append(div1, button0);
      append(button0, i);
      append(button0, t9);
      append(button0, t10);
      append(div5, t11);
      for (let i2 = 0; i2 < each_blocks_1.length; i2 += 1) {
        if (each_blocks_1[i2]) {
          each_blocks_1[i2].m(div5, null);
        }
      }
      append(div5, t12);
      append(div5, div2);
      append(div2, select);
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        if (each_blocks[i2]) {
          each_blocks[i2].m(select, null);
        }
      }
      append(select, each3_anchor);
      if (if_block5)
        if_block5.m(select, null);
      select_option(
        select,
        /*selectedTable*/
        ctx[1],
        true
      );
      append(div2, t13);
      append(div2, button1);
      append(div5, t15);
      append(div5, hr);
      append(div5, t16);
      append(div5, div4);
      append(div4, label0);
      append(label0, t17);
      append(div4, t18);
      append(div4, div3);
      append(div3, label1);
      append(div3, t20);
      append(div3, input);
      input.checked = /*keepRolled*/
      ctx[5];
      append(div5, t21);
      if (if_block6)
        if_block6.m(div5, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*click_handler_4*/
            ctx[28]
          ),
          listen(
            select,
            "change",
            /*select_change_handler*/
            ctx[38]
          ),
          listen(
            button1,
            "click",
            /*click_handler_9*/
            ctx[39]
          ),
          listen(
            input,
            "change",
            /*input_change_handler_1*/
            ctx[40]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!/*currentItems*/
      (ctx2[7].length + /*currentServices*/
      ctx2[6].length)) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_10$2();
          if_block0.c();
          if_block0.m(div0, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*currentServices*/
        ctx2[6].length
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_9$2();
          if_block1.c();
          if_block1.m(div0, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty[0] & /*currentServices, removeAddedItem*/
      524352) {
        each_value_5 = /*currentServices*/
        ctx2[6];
        group_outros();
        each_blocks_3 = update_keyed_each(each_blocks_3, dirty, get_key, 1, ctx2, each_value_5, each0_lookup, div0, outro_and_destroy_block, create_each_block_5$1, t2, get_each_context_5$1);
        check_outros();
      }
      if (
        /*currentServices*/
        ctx2[6].length
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block_8$2(ctx2);
          if_block2.c();
          if_block2.m(div0, t3);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (
        /*currentItems*/
        ctx2[7].length
      ) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
        } else {
          if_block3 = create_if_block_7$4();
          if_block3.c();
          if_block3.m(div0, t4);
        }
      } else if (if_block3) {
        if_block3.d(1);
        if_block3 = null;
      }
      if (dirty[0] & /*currentItems, removeAddedItem*/
      524416) {
        each_value_4 = /*currentItems*/
        ctx2[7];
        group_outros();
        each_blocks_2 = update_keyed_each(each_blocks_2, dirty, get_key_1, 1, ctx2, each_value_4, each1_lookup, div0, outro_and_destroy_block, create_each_block_4$1, t5, get_each_context_4$1);
        check_outros();
      }
      if (
        /*currentItems*/
        ctx2[7].length
      ) {
        if (if_block4) {
          if_block4.p(ctx2, dirty);
        } else {
          if_block4 = create_if_block_6$5(ctx2);
          if_block4.c();
          if_block4.m(div0, null);
        }
      } else if (if_block4) {
        if_block4.d(1);
        if_block4 = null;
      }
      if (dirty[0] & /*$tables, $populationTables, evaluateTable, keepRolled, removeTable*/
      2113580) {
        each_value_2 = /*$populationTables*/
        ctx2[2];
        let i2;
        for (i2 = 0; i2 < each_value_2.length; i2 += 1) {
          const child_ctx = get_each_context_2$4(ctx2, each_value_2, i2);
          if (each_blocks_1[i2]) {
            each_blocks_1[i2].p(child_ctx, dirty);
            transition_in(each_blocks_1[i2], 1);
          } else {
            each_blocks_1[i2] = create_each_block_2$4(child_ctx);
            each_blocks_1[i2].c();
            transition_in(each_blocks_1[i2], 1);
            each_blocks_1[i2].m(div5, t12);
          }
        }
        group_outros();
        for (i2 = each_value_2.length; i2 < each_blocks_1.length; i2 += 1) {
          out(i2);
        }
        check_outros();
      }
      if (dirty[0] & /*selectableTables*/
      1) {
        each_value_1 = /*selectableTables*/
        ctx2[0];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_2, 1, ctx2, each_value_1, each3_lookup, select, destroy_block, create_each_block_1$c, each3_anchor, get_each_context_1$c);
      }
      if (dirty[0] & /*$tables*/
      8)
        show_if = foundry.utils.isEmpty(
          /*$tables*/
          ctx2[3]
        );
      if (show_if) {
        if (if_block5) {
          if_block5.p(ctx2, dirty);
        } else {
          if_block5 = create_if_block_2$d();
          if_block5.c();
          if_block5.m(select, null);
        }
      } else if (if_block5) {
        if_block5.d(1);
        if_block5 = null;
      }
      if (dirty[0] & /*selectedTable, selectableTables*/
      3) {
        select_option(
          select,
          /*selectedTable*/
          ctx2[1]
        );
      }
      if ((!current || dirty[0] & /*timesRolled, $itemsRolled*/
      272) && t17_value !== (t17_value = localize(
        /*timesRolled*/
        ctx2[4] && /*$itemsRolled*/
        ctx2[8].length ? "ITEM-PILES.Merchant.RolledTimes" : "ITEM-PILES.Merchant.ClickRoll",
        { rolls: (
          /*timesRolled*/
          ctx2[4]
        ) }
      ) + ""))
        set_data(t17, t17_value);
      if (dirty[0] & /*keepRolled*/
      32) {
        input.checked = /*keepRolled*/
        ctx2[5];
      }
      if (
        /*$itemsRolled*/
        ctx2[8].length
      ) {
        if (if_block6) {
          if_block6.p(ctx2, dirty);
        } else {
          if_block6 = create_if_block$w(ctx2);
          if_block6.c();
          if_block6.m(div5, null);
        }
      } else if (if_block6) {
        if_block6.d(1);
        if_block6 = null;
      }
    },
    i(local) {
      if (current)
        return;
      for (let i2 = 0; i2 < each_value_5.length; i2 += 1) {
        transition_in(each_blocks_3[i2]);
      }
      for (let i2 = 0; i2 < each_value_4.length; i2 += 1) {
        transition_in(each_blocks_2[i2]);
      }
      for (let i2 = 0; i2 < each_value_2.length; i2 += 1) {
        transition_in(each_blocks_1[i2]);
      }
      current = true;
    },
    o(local) {
      for (let i2 = 0; i2 < each_blocks_3.length; i2 += 1) {
        transition_out(each_blocks_3[i2]);
      }
      for (let i2 = 0; i2 < each_blocks_2.length; i2 += 1) {
        transition_out(each_blocks_2[i2]);
      }
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i2 = 0; i2 < each_blocks_1.length; i2 += 1) {
        transition_out(each_blocks_1[i2]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div6);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      for (let i2 = 0; i2 < each_blocks_3.length; i2 += 1) {
        each_blocks_3[i2].d();
      }
      if (if_block2)
        if_block2.d();
      if (if_block3)
        if_block3.d();
      for (let i2 = 0; i2 < each_blocks_2.length; i2 += 1) {
        each_blocks_2[i2].d();
      }
      if (if_block4)
        if_block4.d();
      destroy_each(each_blocks_1, detaching);
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        each_blocks[i2].d();
      }
      if (if_block5)
        if_block5.d();
      if (if_block6)
        if_block6.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$P, "create_fragment$P");
function recurseThroughFoldersForTables(folderId) {
  const folder = game.folders.find((f) => f.type === "RollTable" && f.id === folderId);
  let folders = [folder.id];
  for (const child of folder.children) {
    folders = folders.concat(recurseThroughFoldersForTables(child.folder.id));
  }
  return folders;
}
__name(recurseThroughFoldersForTables, "recurseThroughFoldersForTables");
async function previewItem(itemData) {
  itemData.item?.sheet?.render(true);
}
__name(previewItem, "previewItem");
function instance$M($$self, $$props, $$invalidate) {
  let currentItems;
  let currentServices;
  let $itemsRolled;
  let $populationTables;
  let $tables;
  let $itemStore;
  let { store } = $$props;
  let tables = writable$1(getTables());
  component_subscribe($$self, tables, (value) => $$invalidate(3, $tables = value));
  let populationTables = writable$1((get_store_value(store.pileData).tablesForPopulate ?? []).map((t) => {
    if (t.id) {
      t.uuid = game.tables.get(t.id).uuid;
    }
    return {
      uuid: t.uuid,
      addAll: t.addAll ?? false,
      open: false,
      timesToRoll: t.timesToRoll ?? "1d4",
      items: t.items ?? {},
      customCategory: t.customCategory ?? ""
    };
  }));
  component_subscribe($$self, populationTables, (value) => $$invalidate(2, $populationTables = value));
  let timesRolled = "";
  let keepRolled = false;
  let itemStore = store.items;
  component_subscribe($$self, itemStore, (value) => $$invalidate(23, $itemStore = value));
  const debounceSave = foundry.utils.debounce(
    (popTables, actualTables) => {
      const pileData = foundry.utils.deepClone(get_store_value(store.pileData));
      pileData.tablesForPopulate = popTables.filter((t) => actualTables[t.uuid]).map((t) => ({
        uuid: t.uuid,
        addAll: t.addAll,
        items: t.items,
        timesToRoll: t.timesToRoll,
        customCategory: t.customCategory
      }));
      updateItemPileData(store.actor, pileData);
    },
    200
  );
  let selectableTables = [];
  let selectedTable = "";
  let itemsRolled = writable$1([]);
  component_subscribe($$self, itemsRolled, (value) => $$invalidate(8, $itemsRolled = value));
  function getTables() {
    let tables2 = Array.from(game.tables);
    const folderId = getSetting(SETTINGS$1.POPULATION_TABLES_FOLDER);
    if (folderId !== "root" && game.folders.find((f) => f.type === "RollTable" && f.id === folderId)) {
      const folderIds = recurseThroughFoldersForTables(folderId);
      tables2 = tables2.filter((t) => folderIds.includes(t.folder?.id));
    }
    const mappedTables = {};
    for (const table of tables2) {
      mappedTables[table.uuid] = {
        name: table.name,
        items: Array.from(table.collections.results)
      };
    }
    return mappedTables;
  }
  __name(getTables, "getTables");
  async function rollAllTables() {
    if (!keepRolled) {
      itemsRolled.set([]);
    }
    for (const table of $populationTables) {
      table.open = false;
      await evaluateTable(table, true);
    }
    $$invalidate(4, timesRolled = $itemsRolled.reduce(
      (total, item) => {
        return total + item.quantity;
      },
      0
    ));
  }
  __name(rollAllTables, "rollAllTables");
  async function evaluateTable(table, keepRolledItems) {
    const rollableTable = await fromUuid(table.uuid);
    if (!rollableTable)
      return;
    if (!keepRolledItems) {
      itemsRolled.set([]);
    }
    const newItems = await rollMerchantTables({ tableData: [table] });
    const processedItems = newItems.map((itemData) => {
      const prices = game.itempiles.API.getPricesForItem(itemData.item, { seller: store.actor });
      itemData.price = prices[0]?.free ? localize("ITEM-PILES.Merchant.ItemFree") : prices[0]?.priceString;
      return itemData;
    });
    itemsRolled.update((items) => {
      processedItems.forEach((newItem) => {
        const existingItem = items.find((item) => item.documentId === newItem.documentId);
        if (existingItem) {
          existingItem.quantity += newItem.quantity;
        } else {
          items.push(newItem);
        }
      });
      items.sort((a, b) => {
        return a.text < b.text ? -1 : 1;
      });
      return items;
    });
  }
  __name(evaluateTable, "evaluateTable");
  async function addItem(itemToAdd) {
    await game.itempiles.API.addItems(store.actor, [itemToAdd].map((entry) => ({
      item: entry.item,
      quantity: entry.quantity,
      flags: entry.flags
    })));
    removeItem(itemToAdd);
  }
  __name(addItem, "addItem");
  function removeItem(itemToRemove) {
    itemsRolled.update((items) => {
      const existingItemIndex = items.findIndex((item) => item.documentId === itemToRemove.documentId);
      items.splice(existingItemIndex, 1);
      return items;
    });
  }
  __name(removeItem, "removeItem");
  async function addAllItems() {
    const itemsToAdd = get_store_value(itemsRolled).map((entry) => ({
      item: entry.item,
      quantity: entry.quantity,
      flags: entry.flags
    }));
    await game.itempiles.API.addItems(store.actor, itemsToAdd);
    itemsRolled.set([]);
  }
  __name(addAllItems, "addAllItems");
  async function clearAllItems(services = false) {
    const localization = services ? "Services" : "Items";
    const doContinue = await TJSDialog.confirm({
      title: "Item Piles - " + localize(`ITEM-PILES.Dialogs.ClearAll${localization}.Title`),
      content: {
        class: CustomDialog,
        props: {
          icon: "fas fa-exclamation-triangle",
          content: localize(`ITEM-PILES.Dialogs.ClearAll${localization}.Content`)
        }
      },
      modal: true,
      draggable: false,
      options: {
        height: "auto",
        headerButtonNoClose: true
      }
    });
    if (!doContinue)
      return false;
    await game.itempiles.API.removeItems(store.actor, game.itempiles.API.getActorItems(store.actor).filter((item) => {
      const itemFlags = getItemFlagData(item);
      return services === itemFlags.isService && !itemFlags.keepOnMerchant && !itemFlags.keepIfZero;
    }));
  }
  __name(clearAllItems, "clearAllItems");
  async function removeAddedItem(itemToRemove) {
    store.actor.deleteEmbeddedDocuments("Item", [itemToRemove.item.id]);
  }
  __name(removeAddedItem, "removeAddedItem");
  function addTable() {
    populationTables.update((tabs) => {
      tabs.push({
        uuid: selectedTable,
        addAll: false,
        open: false,
        timesToRoll: "1d4-1",
        customCategory: "",
        items: {}
      });
      return tabs;
    });
  }
  __name(addTable, "addTable");
  async function removeTable(tableUuid) {
    const table = get_store_value(tables)[tableUuid];
    const doContinue = await TJSDialog.confirm({
      title: "Item Piles - " + game.i18n.localize("ITEM-PILES.Dialogs.RemoveMerchantTable.Title"),
      content: {
        class: CustomDialog,
        props: {
          header: game.i18n.localize("ITEM-PILES.Dialogs.RemoveMerchantTable.Title"),
          content: game.i18n.format("ITEM-PILES.Dialogs.RemoveMerchantTable.Content", { table_name: table.name }),
          icon: "fas fa-exclamation-triangle"
        }
      },
      modal: true,
      draggable: false,
      rejectClose: false,
      defaultYes: true,
      options: { height: "auto" }
    });
    if (!doContinue)
      return;
    populationTables.update((tabs) => {
      return tabs.filter((t) => t.uuid !== tableUuid);
    });
  }
  __name(removeTable, "removeTable");
  let createId = Hooks.on("createRollTable", () => {
    tables.set(getTables());
  });
  let deleteId = Hooks.on("deleteRollTable", () => {
    tables.update(() => {
      const newTables = getTables();
      populationTables.update((values) => values.filter((t) => newTables[t.uuid]));
      return newTables;
    });
  });
  onDestroy(() => {
    Hooks.off("createRollTable", createId);
    Hooks.off("deleteRollTable", deleteId);
  });
  const click_handler = /* @__PURE__ */ __name((item) => removeAddedItem(item), "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => clearAllItems(true), "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name((item) => removeAddedItem(item), "click_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name(() => clearAllItems(), "click_handler_3");
  const click_handler_4 = /* @__PURE__ */ __name(() => {
    rollAllTables();
  }, "click_handler_4");
  const click_handler_52 = /* @__PURE__ */ __name((table) => {
    removeTable(table.uuid);
  }, "click_handler_5");
  const click_handler_6 = /* @__PURE__ */ __name((table, each_value_2, table_index) => {
    set_store_value(populationTables, each_value_2[table_index].open = !table.open, $populationTables);
  }, "click_handler_6");
  const click_handler_7 = /* @__PURE__ */ __name((table, each_value_2, table_index) => {
    set_store_value(populationTables, each_value_2[table_index].open = false, $populationTables);
    evaluateTable(table, keepRolled);
  }, "click_handler_7");
  function customcategoryinput_value_binding(value, table) {
    if ($$self.$$.not_equal(table.customCategory, value)) {
      table.customCategory = value;
      populationTables.set($populationTables);
    }
  }
  __name(customcategoryinput_value_binding, "customcategoryinput_value_binding");
  function input_change_handler(each_value_2, table_index) {
    each_value_2[table_index].addAll = this.checked;
    populationTables.set($populationTables);
  }
  __name(input_change_handler, "input_change_handler");
  const change_handler = /* @__PURE__ */ __name((table, each_value_2, table_index) => {
    if (!table.addAll)
      return;
    set_store_value(populationTables, each_value_2[table_index].items = Object.fromEntries($tables[table.uuid].items.map((item) => [item.id, "1d4"])), $populationTables);
  }, "change_handler");
  function input_input_handler(each_value_2, table_index) {
    each_value_2[table_index].timesToRoll = this.value;
    populationTables.set($populationTables);
  }
  __name(input_input_handler, "input_input_handler");
  const click_handler_8 = /* @__PURE__ */ __name((item) => previewItem(item), "click_handler_8");
  const change_handler_1 = /* @__PURE__ */ __name((table, item, each_value_2, table_index, event) => {
    set_store_value(populationTables, each_value_2[table_index].items[item.id] = event.target.value, $populationTables);
  }, "change_handler_1");
  function select_change_handler() {
    selectedTable = select_value(this);
    $$invalidate(1, selectedTable), $$invalidate(3, $tables), $$invalidate(2, $populationTables), $$invalidate(0, selectableTables);
    $$invalidate(0, selectableTables), $$invalidate(3, $tables), $$invalidate(2, $populationTables), $$invalidate(1, selectedTable);
  }
  __name(select_change_handler, "select_change_handler");
  const click_handler_9 = /* @__PURE__ */ __name(() => addTable(), "click_handler_9");
  function input_change_handler_1() {
    keepRolled = this.checked;
    $$invalidate(5, keepRolled);
  }
  __name(input_change_handler_1, "input_change_handler_1");
  const click_handler_10 = /* @__PURE__ */ __name((item) => addItem(item), "click_handler_10");
  const click_handler_11 = /* @__PURE__ */ __name((item, _) => previewItem(item), "click_handler_11");
  function input_input_handler_1(each_value, item_index) {
    each_value[item_index].quantity = to_number(this.value);
    itemsRolled.set($itemsRolled);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  const click_handler_12 = /* @__PURE__ */ __name((item) => removeItem(item), "click_handler_12");
  const click_handler_13 = /* @__PURE__ */ __name(() => addAllItems(), "click_handler_13");
  const click_handler_14 = /* @__PURE__ */ __name(() => {
    set_store_value(itemsRolled, $itemsRolled = [], $itemsRolled);
  }, "click_handler_14");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(22, store = $$props2.store);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*$itemStore*/
    8388608) {
      $$invalidate(7, currentItems = $itemStore.sort((a, b) => {
        return a.item.name < b.item.name ? -1 : 1;
      }).filter((item) => !item.isService));
    }
    if ($$self.$$.dirty[0] & /*$itemStore*/
    8388608) {
      $$invalidate(6, currentServices = $itemStore.sort((a, b) => {
        return a.item.name < b.item.name ? -1 : 1;
      }).filter((item) => item.isService));
    }
    if ($$self.$$.dirty[0] & /*$populationTables, $tables*/
    12) {
      {
        debounceSave($populationTables, $tables);
      }
    }
    if ($$self.$$.dirty[0] & /*$tables, $populationTables, selectableTables, selectedTable*/
    15) {
      {
        $$invalidate(0, selectableTables = Object.entries($tables).filter((entry) => !$populationTables.some((table) => table.uuid === entry[0])));
        const tableSet = new Set(selectableTables.map((e) => e[0]));
        $$invalidate(1, selectedTable = tableSet.has(selectedTable) ? selectedTable : tableSet.first());
      }
    }
  };
  return [
    selectableTables,
    selectedTable,
    $populationTables,
    $tables,
    timesRolled,
    keepRolled,
    currentServices,
    currentItems,
    $itemsRolled,
    tables,
    populationTables,
    itemStore,
    itemsRolled,
    rollAllTables,
    evaluateTable,
    addItem,
    removeItem,
    addAllItems,
    clearAllItems,
    removeAddedItem,
    addTable,
    removeTable,
    store,
    $itemStore,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_32,
    click_handler_4,
    click_handler_52,
    click_handler_6,
    click_handler_7,
    customcategoryinput_value_binding,
    input_change_handler,
    change_handler,
    input_input_handler,
    click_handler_8,
    change_handler_1,
    select_change_handler,
    click_handler_9,
    input_change_handler_1,
    click_handler_10,
    click_handler_11,
    input_input_handler_1,
    click_handler_12,
    click_handler_13,
    click_handler_14
  ];
}
__name(instance$M, "instance$M");
const _MerchantPopulateItemsTab = class _MerchantPopulateItemsTab extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$M, create_fragment$P, safe_not_equal, { store: 22 }, null, [-1, -1, -1]);
  }
};
__name(_MerchantPopulateItemsTab, "MerchantPopulateItemsTab");
let MerchantPopulateItemsTab = _MerchantPopulateItemsTab;
function create_fragment$O(ctx) {
  let div3;
  let div0;
  let img_1;
  let img_1_src_value;
  let t0;
  let div2;
  let div1;
  let t1;
  let div3_class_value;
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      img_1 = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      t1 = text(
        /*text*/
        ctx[2]
      );
      attr(img_1, "class", "item-piles-img");
      if (!src_url_equal(img_1.src, img_1_src_value = /*$img*/
      ctx[3]))
        attr(img_1, "src", img_1_src_value);
      attr(div0, "class", "item-piles-img-container");
      set_style(
        div0,
        "min-height",
        /*options*/
        ctx[0].imgSize + "px"
      );
      set_style(
        div0,
        "min-width",
        /*options*/
        ctx[0].imgSize + "px"
      );
      set_style(
        div0,
        "max-width",
        /*options*/
        ctx[0].imgSize + "px"
      );
      set_style(
        div0,
        "max-height",
        /*options*/
        ctx[0].imgSize + "px"
      );
      attr(div1, "class", "item-piles-name-container");
      attr(div2, "class", "item-piles-name item-piles-text");
      set_style(div2, "flex", "0 1 auto");
      set_style(div2, "margin", "0 0.25rem");
      attr(div3, "class", div3_class_value = "item-piles-flexrow" + /*options*/
      (ctx[0].reverse ? "-reverse" : "") + " item-piles-item-row");
      attr(
        div3,
        "data-fast-tooltip",
        /*$name*/
        ctx[1]
      );
      attr(div3, "data-fast-tooltip-activation-speed", "0");
      attr(div3, "data-fast-tooltip-deactivation-speed", "0");
      set_style(div3, "flex", "0 1 auto");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img_1);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, t1);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*$img*/
      8 && !src_url_equal(img_1.src, img_1_src_value = /*$img*/
      ctx2[3])) {
        attr(img_1, "src", img_1_src_value);
      }
      if (dirty & /*options*/
      1) {
        set_style(
          div0,
          "min-height",
          /*options*/
          ctx2[0].imgSize + "px"
        );
      }
      if (dirty & /*options*/
      1) {
        set_style(
          div0,
          "min-width",
          /*options*/
          ctx2[0].imgSize + "px"
        );
      }
      if (dirty & /*options*/
      1) {
        set_style(
          div0,
          "max-width",
          /*options*/
          ctx2[0].imgSize + "px"
        );
      }
      if (dirty & /*options*/
      1) {
        set_style(
          div0,
          "max-height",
          /*options*/
          ctx2[0].imgSize + "px"
        );
      }
      if (dirty & /*text*/
      4)
        set_data(
          t1,
          /*text*/
          ctx2[2]
        );
      if (dirty & /*options*/
      1 && div3_class_value !== (div3_class_value = "item-piles-flexrow" + /*options*/
      (ctx2[0].reverse ? "-reverse" : "") + " item-piles-item-row")) {
        attr(div3, "class", div3_class_value);
      }
      if (dirty & /*$name*/
      2) {
        attr(
          div3,
          "data-fast-tooltip",
          /*$name*/
          ctx2[1]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div3);
    }
  };
}
__name(create_fragment$O, "create_fragment$O");
function instance$L($$self, $$props, $$invalidate) {
  let $quantity;
  let $name;
  let $abbreviation;
  let $img;
  let { currency } = $$props;
  let { options } = $$props;
  let name = currency.name;
  component_subscribe($$self, name, (value) => $$invalidate(1, $name = value));
  let img = currency.img;
  component_subscribe($$self, img, (value) => $$invalidate(3, $img = value));
  let abbreviation = currency.abbreviation;
  component_subscribe($$self, abbreviation, (value) => $$invalidate(10, $abbreviation = value));
  let quantity = currency.quantity;
  component_subscribe($$self, quantity, (value) => $$invalidate(9, $quantity = value));
  let text2 = "";
  $$self.$$set = ($$props2) => {
    if ("currency" in $$props2)
      $$invalidate(8, currency = $$props2.currency);
    if ("options" in $$props2)
      $$invalidate(0, options = $$props2.options);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*options, $quantity, $abbreviation, $name*/
    1539) {
      {
        let number = options.abbreviateNumbers ? abbreviateNumbers($quantity) : $quantity;
        if ($abbreviation) {
          if (options.abbreviations) {
            $$invalidate(2, text2 = $abbreviation.replace("{#}", number));
          } else {
            $$invalidate(2, text2 = number);
          }
        } else {
          $$invalidate(2, text2 = `${$name} (x${$quantity})`);
        }
      }
    }
  };
  return [
    options,
    $name,
    text2,
    $img,
    name,
    img,
    abbreviation,
    quantity,
    currency,
    $quantity,
    $abbreviation
  ];
}
__name(instance$L, "instance$L");
const _CurrencyListEntry = class _CurrencyListEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$L, create_fragment$O, safe_not_equal, { currency: 8, options: 0 });
  }
};
__name(_CurrencyListEntry, "CurrencyListEntry");
let CurrencyListEntry = _CurrencyListEntry;
const CurrencyList_svelte_svelte_type_style_lang$1 = "";
function get_each_context$n(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
__name(get_each_context$n, "get_each_context$n");
function get_each_context_1$b(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
__name(get_each_context_1$b, "get_each_context_1$b");
function create_each_block_1$b(key_1, ctx) {
  let first;
  let currencylistentry;
  let current;
  currencylistentry = new CurrencyListEntry({
    props: {
      currency: (
        /*currency*/
        ctx[8]
      ),
      options: (
        /*options*/
        ctx[0]
      )
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(currencylistentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(currencylistentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const currencylistentry_changes = {};
      if (dirty & /*primary*/
      8)
        currencylistentry_changes.currency = /*currency*/
        ctx[8];
      if (dirty & /*options*/
      1)
        currencylistentry_changes.options = /*options*/
        ctx[0];
      currencylistentry.$set(currencylistentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(currencylistentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(currencylistentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(currencylistentry, detaching);
    }
  };
}
__name(create_each_block_1$b, "create_each_block_1$b");
function create_if_block$v(ctx) {
  let div;
  let t;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let current;
  let each_value = (
    /*secondary*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*currency*/
    ctx2[8].identifier
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$n(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$n(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      t = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
      attr(div, "class", "item-piles-vertical-divider svelte-qj1bpn");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      insert(target, t, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*secondary, options*/
      5) {
        each_value = /*secondary*/
        ctx2[2];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, each_1_anchor.parentNode, outro_and_destroy_block, create_each_block$n, each_1_anchor, get_each_context$n);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block$v, "create_if_block$v");
function create_each_block$n(key_1, ctx) {
  let first;
  let currencylistentry;
  let current;
  currencylistentry = new CurrencyListEntry({
    props: {
      currency: (
        /*currency*/
        ctx[8]
      ),
      options: (
        /*options*/
        ctx[0]
      )
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(currencylistentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(currencylistentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const currencylistentry_changes = {};
      if (dirty & /*secondary*/
      4)
        currencylistentry_changes.currency = /*currency*/
        ctx[8];
      if (dirty & /*options*/
      1)
        currencylistentry_changes.options = /*options*/
        ctx[0];
      currencylistentry.$set(currencylistentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(currencylistentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(currencylistentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(currencylistentry, detaching);
    }
  };
}
__name(create_each_block$n, "create_each_block$n");
function create_fragment$N(ctx) {
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t0;
  let t1;
  let div_style_value;
  let current;
  let each_value_1 = (
    /*primary*/
    ctx[3]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*currency*/
    ctx2[8].identifier
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$b(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$b(key, child_ctx));
  }
  let if_block = (
    /*secondary*/
    ctx[2].length && create_if_block$v(ctx)
  );
  const default_slot_template = (
    /*#slots*/
    ctx[7].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[6],
    null
  );
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t0 = space();
      if (if_block)
        if_block.c();
      t1 = space();
      if (default_slot)
        default_slot.c();
      attr(div, "class", "item-piles-flexrow item-piles-currency-list");
      attr(div, "style", div_style_value = /*$$props*/
      ctx[4].style);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      append(div, t0);
      if (if_block)
        if_block.m(div, null);
      append(div, t1);
      if (default_slot) {
        default_slot.m(div, null);
      }
      current = true;
    },
    p(ctx2, [dirty]) {
      if (dirty & /*primary, options*/
      9) {
        each_value_1 = /*primary*/
        ctx2[3];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_1, each_1_lookup, div, outro_and_destroy_block, create_each_block_1$b, t0, get_each_context_1$b);
        check_outros();
      }
      if (
        /*secondary*/
        ctx2[2].length
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*secondary*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$v(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div, t1);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        64)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[6],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[6]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[6],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty & /*$$props*/
      16 && div_style_value !== (div_style_value = /*$$props*/
      ctx2[4].style)) {
        attr(div, "style", div_style_value);
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(if_block);
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      transition_out(if_block);
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if (if_block)
        if_block.d();
      if (default_slot)
        default_slot.d(detaching);
    }
  };
}
__name(create_fragment$N, "create_fragment$N");
function instance$K($$self, $$props, $$invalidate) {
  let primary;
  let secondary;
  let $currencies, $$unsubscribe_currencies = noop, $$subscribe_currencies = /* @__PURE__ */ __name(() => ($$unsubscribe_currencies(), $$unsubscribe_currencies = subscribe(currencies, ($$value) => $$invalidate(5, $currencies = $$value)), currencies), "$$subscribe_currencies");
  $$self.$$.on_destroy.push(() => $$unsubscribe_currencies());
  let { $$slots: slots = {}, $$scope } = $$props;
  let { currencies } = $$props;
  $$subscribe_currencies();
  let { options = {} } = $$props;
  options = foundry.utils.mergeObject(
    {
      reverse: false,
      abbreviations: false,
      abbreviateNumbers: false,
      imgSize: 24
    },
    options
  );
  $$self.$$set = ($$new_props) => {
    $$invalidate(4, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
    if ("currencies" in $$new_props)
      $$subscribe_currencies($$invalidate(1, currencies = $$new_props.currencies));
    if ("options" in $$new_props)
      $$invalidate(0, options = $$new_props.options);
    if ("$$scope" in $$new_props)
      $$invalidate(6, $$scope = $$new_props.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$currencies*/
    32) {
      $$invalidate(3, primary = $currencies.filter((currency) => !currency.isSecondaryCurrency));
    }
    if ($$self.$$.dirty & /*$currencies*/
    32) {
      $$invalidate(2, secondary = $currencies.filter((currency) => currency.isSecondaryCurrency));
    }
  };
  $$props = exclude_internal_props($$props);
  return [options, currencies, secondary, primary, $$props, $currencies, $$scope, slots];
}
__name(instance$K, "instance$K");
let CurrencyList$1 = (_b = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$K, create_fragment$N, safe_not_equal, { currencies: 1, options: 0 });
  }
}, __name(_b, "CurrencyList"), _b);
const MerchantFooter_svelte_svelte_type_style_lang = "";
function create_if_block_1$k(ctx) {
  let div1;
  let div0;
  let a;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Inspect.AddCurrency") + "";
  let t1;
  let t2;
  let currencylist;
  let current;
  let mounted;
  let dispose;
  currencylist = new CurrencyList$1({
    props: {
      currencies: (
        /*merchantCurrencies*/
        ctx[6]
      ),
      options: {
        abbreviations: false,
        imgSize: 18,
        abbreviateNumbers: true
      },
      class: "item-piles-currency-list"
    }
  });
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      a = element("a");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      t2 = space();
      create_component(currencylist.$$.fragment);
      attr(i, "class", "fas fa-plus");
      attr(a, "class", "item-piles-clickable item-piles-text-right item-piles-small-text item-piles-middle");
      set_style(div0, "flex", "0 1 auto");
      attr(div1, "class", "item-piles-flexrow merchant-bottom-row svelte-1rngao0");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, a);
      append(a, i);
      append(a, t0);
      append(a, t1);
      append(div1, t2);
      mount_component(currencylist, div1, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[8]
        );
        mounted = true;
      }
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(currencylist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(currencylist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      destroy_component(currencylist);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$k, "create_if_block_1$k");
function create_if_block$u(ctx) {
  let div1;
  let div0;
  let t0_value = localize("ITEM-PILES.Merchant.ShoppingAs", {
    actorName: (
      /*$recipientDocument*/
      ctx[4].name
    )
  }) + "";
  let t0;
  let t1;
  let currencylist;
  let current;
  currencylist = new CurrencyList$1({
    props: {
      currencies: (
        /*currencies*/
        ctx[3]
      ),
      options: {
        abbreviations: false,
        imgSize: 18,
        abbreviateNumbers: true
      },
      class: "item-piles-currency-list"
    }
  });
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      t0 = text(t0_value);
      t1 = space();
      create_component(currencylist.$$.fragment);
      set_style(div0, "flex", "0 1 auto");
      attr(div1, "class", "item-piles-flexrow merchant-bottom-row svelte-1rngao0");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, t0);
      append(div1, t1);
      mount_component(currencylist, div1, null);
      current = true;
    },
    p(ctx2, dirty) {
      if ((!current || dirty & /*$recipientDocument*/
      16) && t0_value !== (t0_value = localize("ITEM-PILES.Merchant.ShoppingAs", {
        actorName: (
          /*$recipientDocument*/
          ctx2[4].name
        )
      }) + ""))
        set_data(t0, t0_value);
      const currencylist_changes = {};
      if (dirty & /*currencies*/
      8)
        currencylist_changes.currencies = /*currencies*/
        ctx2[3];
      currencylist.$set(currencylist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(currencylist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(currencylist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      destroy_component(currencylist);
    }
  };
}
__name(create_if_block$u, "create_if_block$u");
function create_fragment$M(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block$u, create_if_block_1$k];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*recipientStore*/
      ctx2[1]
    )
      return 0;
    if (game.user.isGM && !/*$merchantPileData*/
    ctx2[5].infiniteCurrencies)
      return 1;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_fragment$M, "create_fragment$M");
function instance$J($$self, $$props, $$invalidate) {
  let $recipientDocument, $$unsubscribe_recipientDocument = noop, $$subscribe_recipientDocument = /* @__PURE__ */ __name(() => ($$unsubscribe_recipientDocument(), $$unsubscribe_recipientDocument = subscribe(recipientDocument, ($$value) => $$invalidate(4, $recipientDocument = $$value)), recipientDocument), "$$subscribe_recipientDocument");
  let $merchantPileData;
  $$self.$$.on_destroy.push(() => $$unsubscribe_recipientDocument());
  let { store } = $$props;
  let { recipientStore } = $$props;
  let recipientDocument = writable$1({});
  $$subscribe_recipientDocument();
  let currencies = writable$1([]);
  const merchantCurrencies = store?.allCurrencies;
  const merchantPileData = store.pileData;
  component_subscribe($$self, merchantPileData, (value) => $$invalidate(5, $merchantPileData = value));
  const click_handler = /* @__PURE__ */ __name(() => store.addCurrency(), "click_handler");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
    if ("recipientStore" in $$props2)
      $$invalidate(1, recipientStore = $$props2.recipientStore);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*recipientStore*/
    2) {
      {
        $$subscribe_recipientDocument($$invalidate(2, recipientDocument = recipientStore?.document));
        $$invalidate(3, currencies = recipientStore?.allCurrencies);
      }
    }
  };
  return [
    store,
    recipientStore,
    recipientDocument,
    currencies,
    $recipientDocument,
    $merchantPileData,
    merchantCurrencies,
    merchantPileData,
    click_handler
  ];
}
__name(instance$J, "instance$J");
const _MerchantFooter = class _MerchantFooter extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$J, create_fragment$M, safe_not_equal, { store: 0, recipientStore: 1 });
  }
};
__name(_MerchantFooter, "MerchantFooter");
let MerchantFooter = _MerchantFooter;
function get_each_context$m(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[12] = list[i];
  child_ctx[14] = i;
  return child_ctx;
}
__name(get_each_context$m, "get_each_context$m");
function create_each_block$m(key_1, ctx) {
  let div;
  let html_tag;
  let raw_value = (
    /*log*/
    ctx[12].text + ""
  );
  let t0;
  let t1_value = timeSince(
    /*log*/
    ctx[12].date
  ) + "";
  let t1;
  let t2;
  let div_class_value;
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      html_tag = new HtmlTag(false);
      t0 = text(" - ");
      t1 = text(t1_value);
      t2 = text(" ago");
      html_tag.a = t0;
      attr(div, "class", div_class_value = /*log*/
      ctx[12].class);
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      html_tag.m(raw_value, div);
      append(div, t0);
      append(div, t1);
      append(div, t2);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$logStore, $visibleLogItems*/
      12 && raw_value !== (raw_value = /*log*/
      ctx[12].text + ""))
        html_tag.p(raw_value);
      if (dirty & /*$logStore, $visibleLogItems*/
      12 && t1_value !== (t1_value = timeSince(
        /*log*/
        ctx[12].date
      ) + ""))
        set_data(t1, t1_value);
      if (dirty & /*$logStore, $visibleLogItems*/
      12 && div_class_value !== (div_class_value = /*log*/
      ctx[12].class)) {
        attr(div, "class", div_class_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_each_block$m, "create_each_block$m");
function create_if_block$t(ctx) {
  let div;
  let a;
  let i;
  let t0;
  let t1;
  let t2;
  let t3_value = (
    /*$logStore*/
    ctx[2].length + ""
  );
  let t3;
  let t4;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      a = element("a");
      i = element("i");
      t0 = text("Load more transactions (");
      t1 = text(
        /*$visibleLogItems*/
        ctx[3]
      );
      t2 = text("\r\n				/ ");
      t3 = text(t3_value);
      t4 = text(")...");
      attr(div, "class", "item-piles-top-divider");
      set_style(div, "text-align", "center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, a);
      append(a, i);
      append(i, t0);
      append(i, t1);
      append(i, t2);
      append(i, t3);
      append(i, t4);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[10]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$visibleLogItems*/
      8)
        set_data(
          t1,
          /*$visibleLogItems*/
          ctx2[3]
        );
      if (dirty & /*$logStore*/
      4 && t3_value !== (t3_value = /*$logStore*/
      ctx2[2].length + ""))
        set_data(t3, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$t, "create_if_block$t");
function create_fragment$L(ctx) {
  let div0;
  let label;
  let t1;
  let input;
  let t2;
  let div1;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t3;
  let mounted;
  let dispose;
  let each_value = (
    /*$logStore*/
    ctx[2].slice(
      0,
      /*$visibleLogItems*/
      ctx[3]
    ).filter(func)
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[14]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$m(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$m(key, child_ctx));
  }
  let if_block = (
    /*$logStore*/
    ctx[2].length > /*$visibleLogItems*/
    ctx[3] && create_if_block$t(ctx)
  );
  return {
    c() {
      div0 = element("div");
      label = element("label");
      label.textContent = `${localize("ITEM-PILES.Merchant.LogSearch")}`;
      t1 = space();
      input = element("input");
      t2 = space();
      div1 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t3 = space();
      if (if_block)
        if_block.c();
      set_style(label, "flex", "0 1 auto");
      set_style(label, "margin-right", "5px");
      attr(input, "type", "text");
      attr(div0, "class", "form-group item-piles-flexrow item-piles-bottom-divider");
      set_style(div0, "margin", "0.25rem 0");
      set_style(div0, "align-items", "center");
      set_style(div0, "flex", "0 1 auto");
      attr(div1, "class", "item-piles-merchant-log");
      set_style(
        div1,
        "max-height",
        /*$applicationHeight*/
        ctx[1] - 130 + "px"
      );
      set_style(div1, "overflow-y", "scroll");
      set_style(div1, "font-size", "0.75rem");
      set_style(div1, "padding-right", "0.5rem");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, label);
      append(div0, t1);
      append(div0, input);
      set_input_value(
        input,
        /*$logSearchStore*/
        ctx[0]
      );
      insert(target, t2, anchor);
      insert(target, div1, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div1, null);
        }
      }
      append(div1, t3);
      if (if_block)
        if_block.m(div1, null);
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler*/
          ctx[9]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*$logSearchStore*/
      1 && input.value !== /*$logSearchStore*/
      ctx2[0]) {
        set_input_value(
          input,
          /*$logSearchStore*/
          ctx2[0]
        );
      }
      if (dirty & /*$logStore, $visibleLogItems, Helpers*/
      12) {
        each_value = /*$logStore*/
        ctx2[2].slice(
          0,
          /*$visibleLogItems*/
          ctx2[3]
        ).filter(func);
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div1, destroy_block, create_each_block$m, t3, get_each_context$m);
      }
      if (
        /*$logStore*/
        ctx2[2].length > /*$visibleLogItems*/
        ctx2[3]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$t(ctx2);
          if_block.c();
          if_block.m(div1, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*$applicationHeight*/
      2) {
        set_style(
          div1,
          "max-height",
          /*$applicationHeight*/
          ctx2[1] - 130 + "px"
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t2);
      if (detaching)
        detach(div1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$L, "create_fragment$L");
const func = /* @__PURE__ */ __name((log) => log.visible, "func");
function instance$I($$self, $$props, $$invalidate) {
  let $logSearchStore;
  let $applicationHeight;
  let $logStore;
  let $visibleLogItems;
  let { store } = $$props;
  const { application } = getContext("#external");
  const logStore = store.log;
  component_subscribe($$self, logStore, (value) => $$invalidate(2, $logStore = value));
  const logSearchStore = store.logSearch;
  component_subscribe($$self, logSearchStore, (value) => $$invalidate(0, $logSearchStore = value));
  const visibleLogItems = store.visibleLogItems;
  component_subscribe($$self, visibleLogItems, (value) => $$invalidate(3, $visibleLogItems = value));
  const applicationHeight = application.position.stores.height;
  component_subscribe($$self, applicationHeight, (value) => $$invalidate(1, $applicationHeight = value));
  function input_input_handler() {
    $logSearchStore = this.value;
    logSearchStore.set($logSearchStore);
  }
  __name(input_input_handler, "input_input_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    set_store_value(visibleLogItems, $visibleLogItems += 20, $visibleLogItems);
  }, "click_handler");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(8, store = $$props2.store);
  };
  return [
    $logSearchStore,
    $applicationHeight,
    $logStore,
    $visibleLogItems,
    logStore,
    logSearchStore,
    visibleLogItems,
    applicationHeight,
    store,
    input_input_handler,
    click_handler
  ];
}
__name(instance$I, "instance$I");
const _MerchantActivityLog = class _MerchantActivityLog extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$I, create_fragment$L, safe_not_equal, { store: 8 });
  }
};
__name(_MerchantActivityLog, "MerchantActivityLog");
let MerchantActivityLog = _MerchantActivityLog;
const MerchantRightPane_svelte_svelte_type_style_lang = "";
function create_if_block_5$6(ctx) {
  let merchantactivitylog;
  let current;
  merchantactivitylog = new MerchantActivityLog({ props: { store: (
    /*store*/
    ctx[0]
  ) } });
  return {
    c() {
      create_component(merchantactivitylog.$$.fragment);
    },
    m(target, anchor) {
      mount_component(merchantactivitylog, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const merchantactivitylog_changes = {};
      if (dirty & /*store*/
      1)
        merchantactivitylog_changes.store = /*store*/
        ctx2[0];
      merchantactivitylog.$set(merchantactivitylog_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantactivitylog.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantactivitylog.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchantactivitylog, detaching);
    }
  };
}
__name(create_if_block_5$6, "create_if_block_5$6");
function create_if_block_4$9(ctx) {
  let merchantpopulateitemstab;
  let current;
  merchantpopulateitemstab = new MerchantPopulateItemsTab({ props: { store: (
    /*store*/
    ctx[0]
  ) } });
  return {
    c() {
      create_component(merchantpopulateitemstab.$$.fragment);
    },
    m(target, anchor) {
      mount_component(merchantpopulateitemstab, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const merchantpopulateitemstab_changes = {};
      if (dirty & /*store*/
      1)
        merchantpopulateitemstab_changes.store = /*store*/
        ctx2[0];
      merchantpopulateitemstab.$set(merchantpopulateitemstab_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantpopulateitemstab.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantpopulateitemstab.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchantpopulateitemstab, detaching);
    }
  };
}
__name(create_if_block_4$9, "create_if_block_4$9");
function create_if_block_3$a(ctx) {
  let merchantitemtab;
  let current;
  merchantitemtab = new MerchantItemTab({
    props: {
      store: (
        /*recipientStore*/
        ctx[1]
      ),
      noItemsLabel: "ITEM-PILES.Merchant.NoItemsToSell"
    }
  });
  return {
    c() {
      create_component(merchantitemtab.$$.fragment);
    },
    m(target, anchor) {
      mount_component(merchantitemtab, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const merchantitemtab_changes = {};
      if (dirty & /*recipientStore*/
      2)
        merchantitemtab_changes.store = /*recipientStore*/
        ctx2[1];
      merchantitemtab.$set(merchantitemtab_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantitemtab.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantitemtab.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchantitemtab, detaching);
    }
  };
}
__name(create_if_block_3$a, "create_if_block_3$a");
function create_if_block_2$c(ctx) {
  let merchantitemtab;
  let current;
  merchantitemtab = new MerchantItemTab({
    props: { store: (
      /*store*/
      ctx[0]
    ), services: true }
  });
  return {
    c() {
      create_component(merchantitemtab.$$.fragment);
    },
    m(target, anchor) {
      mount_component(merchantitemtab, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const merchantitemtab_changes = {};
      if (dirty & /*store*/
      1)
        merchantitemtab_changes.store = /*store*/
        ctx2[0];
      merchantitemtab.$set(merchantitemtab_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantitemtab.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantitemtab.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchantitemtab, detaching);
    }
  };
}
__name(create_if_block_2$c, "create_if_block_2$c");
function create_if_block_1$j(ctx) {
  let merchantitemtab;
  let current;
  merchantitemtab = new MerchantItemTab({
    props: {
      store: (
        /*store*/
        ctx[0]
      ),
      noItemsLabel: "ITEM-PILES.Merchant.NoItemsForSale"
    }
  });
  return {
    c() {
      create_component(merchantitemtab.$$.fragment);
    },
    m(target, anchor) {
      mount_component(merchantitemtab, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const merchantitemtab_changes = {};
      if (dirty & /*store*/
      1)
        merchantitemtab_changes.store = /*store*/
        ctx2[0];
      merchantitemtab.$set(merchantitemtab_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantitemtab.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantitemtab.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchantitemtab, detaching);
    }
  };
}
__name(create_if_block_1$j, "create_if_block_1$j");
function create_if_block$s(ctx) {
  let div;
  let span;
  return {
    c() {
      div = element("div");
      span = element("span");
      span.textContent = `${localize("ITEM-PILES.Merchant.MerchantClosed")}`;
      set_style(div, "display", "grid");
      set_style(div, "place-items", "center");
      set_style(div, "height", "100%");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block$s, "create_if_block$s");
function create_fragment$K(ctx) {
  let div1;
  let div0;
  let current_block_type_index;
  let if_block;
  let t;
  let merchantfooter;
  let current;
  const if_block_creators = [
    create_if_block$s,
    create_if_block_1$j,
    create_if_block_2$c,
    create_if_block_3$a,
    create_if_block_4$9,
    create_if_block_5$6
  ];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*$closed*/
      ctx2[4] && !game.user.isGM
    )
      return 0;
    if (
      /*$activeTab*/
      ctx2[5] === "buy"
    )
      return 1;
    if (
      /*$activeTab*/
      ctx2[5] === "services"
    )
      return 2;
    if (
      /*$activeTab*/
      ctx2[5] === "sell"
    )
      return 3;
    if (
      /*$activeTab*/
      ctx2[5] === "tables"
    )
      return 4;
    if (
      /*$activeTab*/
      ctx2[5] === "log"
    )
      return 5;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  merchantfooter = new MerchantFooter({
    props: {
      recipientStore: (
        /*recipientStore*/
        ctx[1]
      ),
      store: (
        /*store*/
        ctx[0]
      )
    }
  });
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      if (if_block)
        if_block.c();
      t = space();
      create_component(merchantfooter.$$.fragment);
      attr(div0, "class", "merchant-tabbed-center svelte-j5dp8x");
      set_style(div0, "flex", "1");
      set_style(div0, "max-height", "calc(100% - " + /*recipientStore*/
      (ctx[1] && /*$currencies*/
      ctx[3].length ? "34px" : "0px") + ")");
      attr(div1, "class", "merchant-right-pane item-piles-flexcol svelte-j5dp8x");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div0, null);
      }
      append(div1, t);
      mount_component(merchantfooter, div1, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(div0, null);
        } else {
          if_block = null;
        }
      }
      if (!current || dirty & /*recipientStore, $currencies*/
      10) {
        set_style(div0, "max-height", "calc(100% - " + /*recipientStore*/
        (ctx2[1] && /*$currencies*/
        ctx2[3].length ? "34px" : "0px") + ")");
      }
      const merchantfooter_changes = {};
      if (dirty & /*recipientStore*/
      2)
        merchantfooter_changes.recipientStore = /*recipientStore*/
        ctx2[1];
      if (dirty & /*store*/
      1)
        merchantfooter_changes.store = /*store*/
        ctx2[0];
      merchantfooter.$set(merchantfooter_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      transition_in(merchantfooter.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      transition_out(merchantfooter.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
      destroy_component(merchantfooter);
    }
  };
}
__name(create_fragment$K, "create_fragment$K");
function instance$H($$self, $$props, $$invalidate) {
  let $currencies;
  let $closed;
  let $activeTab, $$unsubscribe_activeTab = noop, $$subscribe_activeTab = /* @__PURE__ */ __name(() => ($$unsubscribe_activeTab(), $$unsubscribe_activeTab = subscribe(activeTab, ($$value) => $$invalidate(5, $activeTab = $$value)), activeTab), "$$subscribe_activeTab");
  $$self.$$.on_destroy.push(() => $$unsubscribe_activeTab());
  let { store } = $$props;
  let { recipientStore } = $$props;
  let { activeTab } = $$props;
  $$subscribe_activeTab();
  store.categories;
  let closed = store.closed;
  component_subscribe($$self, closed, (value) => $$invalidate(4, $closed = value));
  const currencies = recipientStore?.allCurrencies || writable$1([]);
  component_subscribe($$self, currencies, (value) => $$invalidate(3, $currencies = value));
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
    if ("recipientStore" in $$props2)
      $$invalidate(1, recipientStore = $$props2.recipientStore);
    if ("activeTab" in $$props2)
      $$subscribe_activeTab($$invalidate(2, activeTab = $$props2.activeTab));
  };
  return [
    store,
    recipientStore,
    activeTab,
    $currencies,
    $closed,
    $activeTab,
    closed,
    currencies
  ];
}
__name(instance$H, "instance$H");
const _MerchantRightPane = class _MerchantRightPane extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$H, create_fragment$K, safe_not_equal, {
      store: 0,
      recipientStore: 1,
      activeTab: 2
    });
  }
};
__name(_MerchantRightPane, "MerchantRightPane");
let MerchantRightPane = _MerchantRightPane;
const MerchantTopBar_svelte_svelte_type_style_lang = "";
function create_if_block_3$9(ctx) {
  let a;
  let i;
  let t0;
  let t1_value = localize(`ITEM-PILES.Merchant.${!/*$closed*/
  ctx[4] ? "Open" : "Closed"}`) + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas");
      toggle_class(i, "fa-door-open", !/*$closed*/
      ctx[4]);
      toggle_class(
        i,
        "fa-door-closed",
        /*$closed*/
        ctx[4]
      );
      set_style(a, "flex", "0");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, i);
      append(a, t0);
      append(a, t1);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler_2*/
          ctx[13]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$closed*/
      16) {
        toggle_class(i, "fa-door-open", !/*$closed*/
        ctx2[4]);
      }
      if (dirty & /*$closed*/
      16) {
        toggle_class(
          i,
          "fa-door-closed",
          /*$closed*/
          ctx2[4]
        );
      }
      if (dirty & /*$closed*/
      16 && t1_value !== (t1_value = localize(`ITEM-PILES.Merchant.${!/*$closed*/
      ctx2[4] ? "Open" : "Closed"}`) + ""))
        set_data(t1, t1_value);
    },
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$9, "create_if_block_3$9");
function create_if_block$r(ctx) {
  let span0;
  let t1;
  let span1;
  let t2;
  let t3;
  let if_block = game.user.isGM && create_if_block_1$i(ctx);
  return {
    c() {
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Merchant.OpenTimes")}`;
      t1 = space();
      span1 = element("span");
      if (if_block)
        if_block.c();
      t2 = space();
      t3 = text(
        /*openTimeText*/
        ctx[2]
      );
      set_style(span1, "font-style", "italic");
    },
    m(target, anchor) {
      insert(target, span0, anchor);
      insert(target, t1, anchor);
      insert(target, span1, anchor);
      if (if_block)
        if_block.m(span1, null);
      append(span1, t2);
      append(span1, t3);
    },
    p(ctx2, dirty) {
      if (game.user.isGM)
        if_block.p(ctx2, dirty);
      if (dirty & /*openTimeText*/
      4)
        set_data(
          t3,
          /*openTimeText*/
          ctx2[2]
        );
    },
    d(detaching) {
      if (detaching)
        detach(span0);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(span1);
      if (if_block)
        if_block.d();
    }
  };
}
__name(create_if_block$r, "create_if_block$r");
function create_if_block_1$i(ctx) {
  let t0;
  let a;
  let i;
  let t1;
  let t2_value = localize(`ITEM-PILES.Merchant.${!/*$closed*/
  ctx[4] ? "Open" : "Closed"}`) + "";
  let t2;
  let mounted;
  let dispose;
  let if_block = (
    /*aboutTimeEnabled*/
    ctx[8] && /*$pileDataStore*/
    ctx[1].openTimes.status !== "auto" && create_if_block_2$b(ctx)
  );
  return {
    c() {
      if (if_block)
        if_block.c();
      t0 = space();
      a = element("a");
      i = element("i");
      t1 = space();
      t2 = text(t2_value);
      attr(i, "class", "fas");
      toggle_class(i, "fa-door-open", !/*$closed*/
      ctx[4]);
      toggle_class(
        i,
        "fa-door-closed",
        /*$closed*/
        ctx[4]
      );
      attr(a, "class", "item-piles-right-divider svelte-18jt6ec");
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, a, anchor);
      append(a, i);
      append(a, t1);
      append(a, t2);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler_1*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*aboutTimeEnabled*/
        ctx2[8] && /*$pileDataStore*/
        ctx2[1].openTimes.status !== "auto"
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_2$b(ctx2);
          if_block.c();
          if_block.m(t0.parentNode, t0);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*$closed*/
      16) {
        toggle_class(i, "fa-door-open", !/*$closed*/
        ctx2[4]);
      }
      if (dirty & /*$closed*/
      16) {
        toggle_class(
          i,
          "fa-door-closed",
          /*$closed*/
          ctx2[4]
        );
      }
      if (dirty & /*$closed*/
      16 && t2_value !== (t2_value = localize(`ITEM-PILES.Merchant.${!/*$closed*/
      ctx2[4] ? "Open" : "Closed"}`) + ""))
        set_data(t2, t2_value);
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$i, "create_if_block_1$i");
function create_if_block_2$b(ctx) {
  let a;
  let i;
  let t0;
  let t1_value = localize(`ITEM-PILES.Merchant.OpenCloseAuto`) + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-clock");
      attr(a, "class", "item-piles-right-divider svelte-18jt6ec");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, i);
      append(a, t0);
      append(a, t1);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[11]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_2$b, "create_if_block_2$b");
function create_fragment$J(ctx) {
  let div2;
  let div0;
  let t0;
  let t1;
  let div1;
  function select_block_type(ctx2, dirty) {
    if (
      /*$pileDataStore*/
      ctx2[1].openTimes.enabled
    )
      return create_if_block$r;
    if (game.user.isGM)
      return create_if_block_3$9;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type && current_block_type(ctx);
  return {
    c() {
      div2 = element("div");
      div0 = element("div");
      t0 = text(
        /*$merchantName*/
        ctx[3]
      );
      t1 = space();
      div1 = element("div");
      if (if_block)
        if_block.c();
      attr(div0, "class", "merchant-name svelte-18jt6ec");
      attr(div1, "class", "opening-hours item-piles-flexcol svelte-18jt6ec");
      attr(div2, "class", "item-piles-flexrow merchant-top-bar item-piles-bottom-divider svelte-18jt6ec");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div0);
      append(div0, t0);
      append(div2, t1);
      append(div2, div1);
      if (if_block)
        if_block.m(div1, null);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*$merchantName*/
      8)
        set_data(
          t0,
          /*$merchantName*/
          ctx2[3]
        );
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if (if_block)
          if_block.d(1);
        if_block = current_block_type && current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(div1, null);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div2);
      if (if_block) {
        if_block.d();
      }
    }
  };
}
__name(create_fragment$J, "create_fragment$J");
function instance$G($$self, $$props, $$invalidate) {
  let open;
  let close;
  let $pileDataStore;
  let $merchantName;
  let $closed;
  let { store } = $$props;
  const pileDataStore = store.pileData;
  component_subscribe($$self, pileDataStore, (value) => $$invalidate(1, $pileDataStore = value));
  const merchantName = store.name;
  component_subscribe($$self, merchantName, (value) => $$invalidate(3, $merchantName = value));
  const closed = store.closed;
  component_subscribe($$self, closed, (value) => $$invalidate(4, $closed = value));
  let openTimeText = "";
  const aboutTimeEnabled = game.modules.get("foundryvtt-simple-calendar")?.active || false;
  const click_handler = /* @__PURE__ */ __name(() => {
    store.setOpenStatus("auto");
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    store.setOpenStatus($closed ? "open" : "closed");
  }, "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    store.setOpenStatus($closed ? "open" : "closed");
  }, "click_handler_2");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$pileDataStore*/
    2) {
      $$invalidate(10, open = $pileDataStore.openTimes.enabled ? $pileDataStore.openTimes?.open : false);
    }
    if ($$self.$$.dirty & /*$pileDataStore*/
    2) {
      $$invalidate(9, close = $pileDataStore.openTimes.enabled ? $pileDataStore.openTimes?.close : false);
    }
    if ($$self.$$.dirty & /*$pileDataStore, open, close*/
    1538) {
      {
        if ($pileDataStore.openTimes.enabled) {
          let openText = `${open.hour.toString().padStart(2, "0")}:${open.minute.toString().padStart(2, "0")}`;
          let closeText = `${close.hour.toString().padStart(2, "0")}:${close.minute.toString().padStart(2, "0")}`;
          $$invalidate(2, openTimeText = `${openText} - ${closeText}`);
        }
      }
    }
  };
  return [
    store,
    $pileDataStore,
    openTimeText,
    $merchantName,
    $closed,
    pileDataStore,
    merchantName,
    closed,
    aboutTimeEnabled,
    close,
    open,
    click_handler,
    click_handler_1,
    click_handler_2
  ];
}
__name(instance$G, "instance$G");
const _MerchantTopBar = class _MerchantTopBar extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$G, create_fragment$J, safe_not_equal, { store: 0 });
  }
};
__name(_MerchantTopBar, "MerchantTopBar");
let MerchantTopBar = _MerchantTopBar;
const merchantAppShell_svelte_svelte_type_style_lang = "";
function create_if_block$q(ctx) {
  let merchantleftpane;
  let current;
  merchantleftpane = new MerchantLeftPane({ props: { store: (
    /*store*/
    ctx[2]
  ) } });
  return {
    c() {
      create_component(merchantleftpane.$$.fragment);
    },
    m(target, anchor) {
      mount_component(merchantleftpane, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const merchantleftpane_changes = {};
      if (dirty & /*store*/
      4)
        merchantleftpane_changes.store = /*store*/
        ctx2[2];
      merchantleftpane.$set(merchantleftpane_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantleftpane.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantleftpane.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchantleftpane, detaching);
    }
  };
}
__name(create_if_block$q, "create_if_block$q");
function create_default_slot_1$2(ctx) {
  let merchanttopbar;
  let t0;
  let tabs_1;
  let updating_activeTab;
  let updating_tabs;
  let t1;
  let div;
  let t2;
  let merchantrightpane;
  let current;
  merchanttopbar = new MerchantTopBar({ props: { store: (
    /*store*/
    ctx[2]
  ) } });
  function tabs_1_activeTab_binding(value) {
    ctx[16](value);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  function tabs_1_tabs_binding(value) {
    ctx[17](value);
  }
  __name(tabs_1_tabs_binding, "tabs_1_tabs_binding");
  let tabs_1_props = {
    separateElements: true,
    style: "flex: 0 1 auto; font-size: 1.1rem; justify-content: flex-start;",
    underscore: true
  };
  if (
    /*$activeTab*/
    ctx[4] !== void 0
  ) {
    tabs_1_props.activeTab = /*$activeTab*/
    ctx[4];
  }
  if (
    /*tabs*/
    ctx[3] !== void 0
  ) {
    tabs_1_props.tabs = /*tabs*/
    ctx[3];
  }
  tabs_1 = new Tabs({ props: tabs_1_props });
  binding_callbacks.push(() => bind(tabs_1, "activeTab", tabs_1_activeTab_binding));
  binding_callbacks.push(() => bind(tabs_1, "tabs", tabs_1_tabs_binding));
  let if_block = (
    /*$activeTab*/
    ctx[4] !== "tables" && create_if_block$q(ctx)
  );
  merchantrightpane = new MerchantRightPane({
    props: {
      activeTab: (
        /*activeTab*/
        ctx[10]
      ),
      recipientStore: (
        /*recipientStore*/
        ctx[0]
      ),
      store: (
        /*store*/
        ctx[2]
      )
    }
  });
  return {
    c() {
      create_component(merchanttopbar.$$.fragment);
      t0 = space();
      create_component(tabs_1.$$.fragment);
      t1 = space();
      div = element("div");
      if (if_block)
        if_block.c();
      t2 = space();
      create_component(merchantrightpane.$$.fragment);
      attr(div, "class", "item-piles-flexrow item-pile-merchant-content svelte-1lp0e8w");
    },
    m(target, anchor) {
      mount_component(merchanttopbar, target, anchor);
      insert(target, t0, anchor);
      mount_component(tabs_1, target, anchor);
      insert(target, t1, anchor);
      insert(target, div, anchor);
      if (if_block)
        if_block.m(div, null);
      append(div, t2);
      mount_component(merchantrightpane, div, null);
      current = true;
    },
    p(ctx2, dirty) {
      const merchanttopbar_changes = {};
      if (dirty & /*store*/
      4)
        merchanttopbar_changes.store = /*store*/
        ctx2[2];
      merchanttopbar.$set(merchanttopbar_changes);
      const tabs_1_changes = {};
      if (!updating_activeTab && dirty & /*$activeTab*/
      16) {
        updating_activeTab = true;
        tabs_1_changes.activeTab = /*$activeTab*/
        ctx2[4];
        add_flush_callback(() => updating_activeTab = false);
      }
      if (!updating_tabs && dirty & /*tabs*/
      8) {
        updating_tabs = true;
        tabs_1_changes.tabs = /*tabs*/
        ctx2[3];
        add_flush_callback(() => updating_tabs = false);
      }
      tabs_1.$set(tabs_1_changes);
      if (
        /*$activeTab*/
        ctx2[4] !== "tables"
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*$activeTab*/
          16) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$q(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div, t2);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      const merchantrightpane_changes = {};
      if (dirty & /*recipientStore*/
      1)
        merchantrightpane_changes.recipientStore = /*recipientStore*/
        ctx2[0];
      if (dirty & /*store*/
      4)
        merchantrightpane_changes.store = /*store*/
        ctx2[2];
      merchantrightpane.$set(merchantrightpane_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchanttopbar.$$.fragment, local);
      transition_in(tabs_1.$$.fragment, local);
      transition_in(if_block);
      transition_in(merchantrightpane.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchanttopbar.$$.fragment, local);
      transition_out(tabs_1.$$.fragment, local);
      transition_out(if_block);
      transition_out(merchantrightpane.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchanttopbar, detaching);
      if (detaching)
        detach(t0);
      destroy_component(tabs_1, detaching);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
      destroy_component(merchantrightpane);
    }
  };
}
__name(create_default_slot_1$2, "create_default_slot_1$2");
function create_default_slot$l(ctx) {
  let dropzone;
  let current;
  dropzone = new DropZone({
    props: {
      callback: (
        /*dropData*/
        ctx[9]
      ),
      style: "display: flex; flex-direction: column; height: 100%;",
      $$slots: { default: [create_default_slot_1$2] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(dropzone.$$.fragment);
    },
    m(target, anchor) {
      mount_component(dropzone, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const dropzone_changes = {};
      if (dirty & /*$$scope, recipientStore, store, $activeTab, tabs*/
      2097181) {
        dropzone_changes.$$scope = { dirty, ctx: ctx2 };
      }
      dropzone.$set(dropzone_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dropzone.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropzone.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(dropzone, detaching);
    }
  };
}
__name(create_default_slot$l, "create_default_slot$l");
function create_fragment$I(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  let mounted;
  let dispose;
  function applicationshell_elementRoot_binding(value) {
    ctx[18](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$l] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[1] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[1];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
      if (!mounted) {
        dispose = listen(
          window,
          "click",
          /*click_handler*/
          ctx[15]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, recipientStore, store, $activeTab, tabs*/
      2097181) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      2) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[1];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$I, "create_fragment$I");
function instance$F($$self, $$props, $$invalidate) {
  let $activeTab;
  let $pileData;
  let $visibleItems;
  let $priceSelector;
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let { merchant } = $$props;
  let { recipient } = $$props;
  let { store = MerchantStore.make(application, merchant, recipient) } = $$props;
  let { recipientStore = recipient ? MerchantStore.make(application, recipient, merchant, { recipientPileData: store.pileData }) : false } = $$props;
  let pileData = store.pileData;
  component_subscribe($$self, pileData, (value) => $$invalidate(13, $pileData = value));
  onDestroy(() => {
    store.onDestroy();
    if (recipientStore)
      recipientStore.onDestroy();
  });
  let priceSelector = store.priceSelector;
  component_subscribe($$self, priceSelector, (value) => $$invalidate(5, $priceSelector = value));
  store.categories;
  let visibleItems = store.visibleItems;
  component_subscribe($$self, visibleItems, (value) => $$invalidate(14, $visibleItems = value));
  async function dropData(data2) {
    if (!game.user.isGM)
      return;
    if (!data2.type) {
      throw custom_error("Something went wrong when dropping this item!");
    }
    if (data2.type === "Actor") {
      const newRecipient = data2.uuid ? await fromUuid(data2.uuid) : game.actors.get(data2.id);
      store.updateRecipient(newRecipient);
      if (recipientStore) {
        return recipientStore.updateSource(newRecipient);
      }
      $$invalidate(0, recipientStore = MerchantStore.make(application, newRecipient, merchant, { recipientPileData: store.pileData }));
      return;
    }
    if (data2.type !== "Item") {
      throw custom_error("You must drop an item, not " + data2.type.toLowerCase() + "!");
    }
    const item = await Item.implementation.fromDropData(data2);
    const validItem = await checkItemType(merchant, item, {
      errorText: "ITEM-PILES.Errors.DisallowedItemTrade",
      warningTitle: "ITEM-PILES.Dialogs.TypeWarning.Title",
      warningContent: "ITEM-PILES.Dialogs.TypeWarning.TradeContent"
    });
    if (!validItem)
      return;
    return game.itempiles.API.addItems(merchant, [{ item: validItem, quantity: 1 }]);
  }
  __name(dropData, "dropData");
  const activeTab = writable$1("buy");
  component_subscribe($$self, activeTab, (value) => $$invalidate(4, $activeTab = value));
  let tabs;
  const click_handler = /* @__PURE__ */ __name(() => {
    set_store_value(priceSelector, $priceSelector = "", $priceSelector);
  }, "click_handler");
  function tabs_1_activeTab_binding(value) {
    $activeTab = value;
    activeTab.set($activeTab);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  function tabs_1_tabs_binding(value) {
    tabs = value;
    $$invalidate(3, tabs), $$invalidate(14, $visibleItems), $$invalidate(13, $pileData), $$invalidate(0, recipientStore), $$invalidate(11, merchant), $$invalidate(4, $activeTab);
  }
  __name(tabs_1_tabs_binding, "tabs_1_tabs_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(1, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(1, elementRoot = $$props2.elementRoot);
    if ("merchant" in $$props2)
      $$invalidate(11, merchant = $$props2.merchant);
    if ("recipient" in $$props2)
      $$invalidate(12, recipient = $$props2.recipient);
    if ("store" in $$props2)
      $$invalidate(2, store = $$props2.store);
    if ("recipientStore" in $$props2)
      $$invalidate(0, recipientStore = $$props2.recipientStore);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$visibleItems, $pileData, recipientStore, merchant, tabs, $activeTab*/
    26649) {
      {
        const hasItems = $visibleItems.some((item) => !get_store_value(item.category).service);
        const hasServices = $visibleItems.some((item) => get_store_value(item.category).service);
        const canSell = !$pileData.purchaseOnly && recipientStore;
        const showBuy = hasItems || !hasItems && !hasServices && !canSell;
        $$invalidate(3, tabs = [
          {
            value: "buy",
            label: game.i18n.localize("ITEM-PILES.Merchant.BuyItems"),
            hidden: !showBuy
          },
          {
            value: "services",
            label: game.i18n.localize("ITEM-PILES.Merchant.BuyServices"),
            hidden: !hasServices
          },
          {
            value: "sell",
            label: game.i18n.localize("ITEM-PILES.Merchant.SellItems"),
            hidden: !canSell
          },
          {
            value: "tables",
            label: game.i18n.localize("ITEM-PILES.Merchant.PopulateItems"),
            hidden: !game.user.isGM
          },
          {
            value: "log",
            label: game.i18n.localize("ITEM-PILES.Merchant.Log"),
            hidden: !merchant.isOwner || !$pileData.logMerchantActivity
          }
        ]);
        if (tabs.find((tab) => tab.value === $activeTab).hidden) {
          set_store_value(activeTab, $activeTab = tabs.find((tab) => !tab.hidden).value, $activeTab);
        }
      }
    }
  };
  return [
    recipientStore,
    elementRoot,
    store,
    tabs,
    $activeTab,
    $priceSelector,
    pileData,
    priceSelector,
    visibleItems,
    dropData,
    activeTab,
    merchant,
    recipient,
    $pileData,
    $visibleItems,
    click_handler,
    tabs_1_activeTab_binding,
    tabs_1_tabs_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$F, "instance$F");
const _Merchant_app_shell = class _Merchant_app_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$F, create_fragment$I, safe_not_equal, {
      elementRoot: 1,
      merchant: 11,
      recipient: 12,
      store: 2,
      recipientStore: 0
    });
  }
  get elementRoot() {
    return this.$$.ctx[1];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get merchant() {
    return this.$$.ctx[11];
  }
  set merchant(merchant) {
    this.$$set({ merchant });
    flush();
  }
  get recipient() {
    return this.$$.ctx[12];
  }
  set recipient(recipient) {
    this.$$set({ recipient });
    flush();
  }
  get store() {
    return this.$$.ctx[2];
  }
  set store(store) {
    this.$$set({ store });
    flush();
  }
  get recipientStore() {
    return this.$$.ctx[0];
  }
  set recipientStore(recipientStore) {
    this.$$set({ recipientStore });
    flush();
  }
};
__name(_Merchant_app_shell, "Merchant_app_shell");
let Merchant_app_shell = _Merchant_app_shell;
function get_each_context$l(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[9] = list[i];
  child_ctx[10] = list;
  child_ctx[11] = i;
  return child_ctx;
}
__name(get_each_context$l, "get_each_context$l");
function create_each_block$l(key_1, ctx) {
  let div;
  let label;
  let t0_value = (
    /*user*/
    ctx[9].name + ""
  );
  let t0;
  let label_for_value;
  let t1;
  let input;
  let input_id_value;
  let mounted;
  let dispose;
  function input_change_handler() {
    ctx[5].call(
      input,
      /*each_value*/
      ctx[10],
      /*user_index*/
      ctx[11]
    );
  }
  __name(input_change_handler, "input_change_handler");
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      label = element("label");
      t0 = text(t0_value);
      t1 = space();
      input = element("input");
      attr(label, "for", label_for_value = "item-piles-user-" + /*user*/
      ctx[9].id);
      attr(label, "class", "item-piles-clickable");
      attr(div, "class", "item-piles-flexrow");
      set_style(div, "align-items", "center");
      attr(input, "id", input_id_value = "item-piles-user-" + /*user*/
      ctx[9].id);
      attr(input, "type", "checkbox");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, t0);
      insert(target, t1, anchor);
      insert(target, input, anchor);
      input.checked = /*user*/
      ctx[9].selected;
      if (!mounted) {
        dispose = listen(input, "change", input_change_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*users*/
      4 && t0_value !== (t0_value = /*user*/
      ctx[9].name + ""))
        set_data(t0, t0_value);
      if (dirty & /*users*/
      4 && label_for_value !== (label_for_value = "item-piles-user-" + /*user*/
      ctx[9].id)) {
        attr(label, "for", label_for_value);
      }
      if (dirty & /*users*/
      4 && input_id_value !== (input_id_value = "item-piles-user-" + /*user*/
      ctx[9].id)) {
        attr(input, "id", input_id_value);
      }
      if (dirty & /*users*/
      4) {
        input.checked = /*user*/
        ctx[9].selected;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_each_block$l, "create_each_block$l");
function create_default_slot$k(ctx) {
  let form_1;
  let p;
  let strong;
  let t1;
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t2;
  let footer;
  let button;
  let i;
  let t3;
  let t4_value = localize("Okay") + "";
  let t4;
  let mounted;
  let dispose;
  let each_value = (
    /*users*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*user*/
    ctx2[9].id
  ), "get_key");
  for (let i2 = 0; i2 < each_value.length; i2 += 1) {
    let child_ctx = get_each_context$l(ctx, each_value, i2);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i2] = create_each_block$l(key, child_ctx));
  }
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      strong = element("strong");
      strong.textContent = `${localize("ITEM-PILES.Dialogs.UserSelect.Content")}`;
      t1 = space();
      div = element("div");
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        each_blocks[i2].c();
      }
      t2 = space();
      footer = element("footer");
      button = element("button");
      i = element("i");
      t3 = space();
      t4 = text(t4_value);
      set_style(p, "margin-top", "0");
      set_style(p, "text-align", "center");
      set_style(div, "display", "grid");
      set_style(div, "grid-template-columns", "auto 25px");
      attr(i, "class", "fas fa-check");
      attr(button, "type", "button");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
      set_style(footer, "margin-top", "1rem");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-flexcol");
      set_style(form_1, "padding", "0.5rem");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(p, strong);
      append(form_1, t1);
      append(form_1, div);
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        if (each_blocks[i2]) {
          each_blocks[i2].m(div, null);
        }
      }
      append(form_1, t2);
      append(form_1, footer);
      append(footer, button);
      append(button, i);
      append(button, t3);
      append(button, t4);
      ctx[6](form_1);
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*requestSubmit*/
            ctx[3],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*submit*/
            ctx[4]
          ), { once: true })
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*users*/
      4) {
        each_value = /*users*/
        ctx2[2];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, destroy_block, create_each_block$l, null, get_each_context$l);
      }
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      for (let i2 = 0; i2 < each_blocks.length; i2 += 1) {
        each_blocks[i2].d();
      }
      ctx[6](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$k, "create_default_slot$k");
function create_fragment$H(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[7](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$k] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, users*/
      4102) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$H, "create_fragment$H");
function instance$E($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let form;
  getUserCharacter();
  const users = game.users.filter((u) => u.active && (getUserCharacter(u) || u.isGM) && !(application.options.excludeSelf && u === game.user)).map((u) => ({ id: u.id, name: u.name, selected: true }));
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function submit() {
    const finalUsers = users.filter((user) => user.selected).map((user) => user.id);
    application.options.resolve(finalUsers);
    application.close();
  }
  __name(submit, "submit");
  function input_change_handler(each_value, user_index) {
    each_value[user_index].selected = this.checked;
    $$invalidate(2, users);
  }
  __name(input_change_handler, "input_change_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(1, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  return [
    elementRoot,
    form,
    users,
    requestSubmit,
    submit,
    input_change_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$E, "instance$E");
const _User_select_dialog_shell = class _User_select_dialog_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$E, create_fragment$H, safe_not_equal, { elementRoot: 0 });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
};
__name(_User_select_dialog_shell, "User_select_dialog_shell");
let User_select_dialog_shell = _User_select_dialog_shell;
const _UserSelectDialog = class _UserSelectDialog extends SvelteApplication {
  /**
   * @param options
   */
  constructor(options = {}) {
    super({
      title: game.i18n.localize("ITEM-PILES.Dialogs.UserSelect.Title"),
      svelte: {
        class: User_select_dialog_shell,
        target: document.body
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 200,
      height: "auto",
      classes: ["item-piles-app"]
    });
  }
  static async show(options = {}) {
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(options).render(true, { focus: true });
    });
  }
};
__name(_UserSelectDialog, "UserSelectDialog");
let UserSelectDialog = _UserSelectDialog;
const _MerchantApp = class _MerchantApp extends SvelteApplication {
  constructor(merchant, recipient = false, options = {}, dialogData = {}) {
    super({
      title: `Merchant: ${merchant.name}`,
      id: `item-pile-merchant-${merchant.id}-${randomID()}`,
      svelte: {
        class: Merchant_app_shell,
        target: document.body,
        props: {
          merchant,
          recipient
        }
      },
      zIndex: 100,
      ...options
    }, dialogData);
    this.merchant = merchant;
    this.recipient = recipient;
    hooks.callAll(CONSTANTS.HOOKS.OPEN_INTERFACE, this, merchant, recipient, options, dialogData);
  }
  /** @inheritdoc */
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      classes: ["app window-app sheet", "item-piles-merchant-sheet", "item-piles", "item-piles-app"],
      width: 800,
      height: 700,
      closeOnSubmit: false,
      resizable: true
    });
  }
  static getActiveApp(id) {
    return getActiveApps(`item-pile-merchant-${id}`, true);
  }
  static async show(merchant, recipient = false, options = {}, dialogData = {}) {
    const merchantActor = getActor(merchant);
    const recipientActor = getActor(recipient);
    const result = hooks.call(CONSTANTS.HOOKS.PRE_OPEN_INTERFACE, merchantActor, recipientActor, options, dialogData);
    if (result === false)
      return;
    const app = this.getActiveApp(merchant.uuid);
    if (app)
      return app.render(false, { focus: true });
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(merchant, recipientActor, options, dialogData).render(true, { focus: true, bypassItemPiles: true });
    });
  }
  refreshItems() {
    this.svelte.applicationShell.store.refreshItems();
  }
  /** @override */
  _getHeaderButtons() {
    let buttons = super._getHeaderButtons();
    const newButtons = [];
    if (this.merchant.isOwner) {
      newButtons.push(
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.Inspect.OpenSheet" : "",
          class: "item-piles-open-actor-sheet",
          icon: "fas fa-user",
          onclick: () => {
            this.merchant.sheet.render(true, { focus: true, bypassItemPiles: true });
          }
        }
      );
    }
    if (game.user.isGM) {
      newButtons.push(
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.ContextMenu.ShowToPlayers" : "",
          class: "item-piles-show-to-players",
          icon: "fas fa-eye",
          onclick: async (event) => {
            const activeUsers = Array.from(game.users).filter((u) => u.active && u !== game.user).map((u) => u.id);
            if (!activeUsers.length) {
              return custom_warning(game.i18n.localize("ITEM-PILES.Warnings.NoPlayersActive"), true);
            }
            const users = event.altKey ? activeUsers : await UserSelectDialog.show({ excludeSelf: true });
            if (!users || !users.length)
              return;
            custom_notify(game.i18n.format("ITEM-PILES.Notifications.ShownToPlayers", { actor_name: this.merchant.name }));
            return game.itempiles.API.renderItemPileInterface(this.merchant, {
              userIds: users,
              useDefaultCharacter: true
            });
          }
        },
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.HUD.Configure" : "",
          class: "item-piles-configure-pile",
          icon: "fas fa-box-open",
          onclick: () => {
            ItemPileConfig.show(this.merchant);
          }
        }
      );
    }
    return newButtons.concat(buttons);
  }
  async close(options) {
    const result = hooks.call(CONSTANTS.HOOKS.PRE_CLOSE_INTERFACE, this, this.merchant, this.recipient);
    if (result === false)
      return;
    for (const app of Object.values(ui.windows)) {
      if (app !== this && this.svelte.applicationShell.store === app?.svelte?.applicationShell?.store) {
        app.close();
      }
    }
    hooks.callAll(CONSTANTS.HOOKS.CLOSE_INTERFACE, this, this.merchant, this.recipient);
    return super.close(options);
  }
};
__name(_MerchantApp, "MerchantApp");
let MerchantApp = _MerchantApp;
const _TJSContextMenu = class _TJSContextMenu {
  /**
   * Creates and manages a browser wide context menu. The best way to create the context menu is to pass in the source
   * DOM event as it is processed for the location of the context menu to display. Likewise, a A11yFocusSource object
   * is generated that allows focus to be returned to the source location. You may supply a default focus target as a
   * fallback via `focusEl`.
   *
   * @param {object}      opts - Optional parameters.
   *
   * @param {string}      [opts.id] - A custom CSS ID to add to the menu. This allows CSS style targeting.
   *
   * @param {KeyboardEvent|MouseEvent}  [opts.event] - The source MouseEvent or KeyboardEvent.
   *
   * @param {number}      [opts.x] - X position override for the top / left of the menu.
   *
   * @param {number}      [opts.y] - Y position override for the top / left of the menu.
   *
   * @param {Iterable<TJSContextMenuItemData>} [opts.items] - Menu items to display.
   *
   * @param {boolean}     [opts.focusDebug] - When true the associated A11yFocusSource object will log focus target
   *        data when applied.
   *
   * @param {HTMLElement|string} [opts.focusEl] - A specific HTMLElement or selector string as the default focus
   *        target.
   *
   * @param {string}      [opts.keyCode='Enter'] - Key to select menu items.
   *
   * @param {Record<string, string>}  [opts.styles] - Optional inline styles to apply.
   *
   * @param {number}      [opts.zIndex=Number.MAX_SAFE_INTEGER - 100] - Z-index for context menu.
   *
   * @param {number}      [opts.duration] - Transition option for duration of transition.
   *
   * @param {Function}    [opts.easing] - Transition option for easing function.
   */
  static create({
    id = "",
    event,
    x,
    y,
    items,
    focusDebug = false,
    focusEl,
    keyCode = "Enter",
    styles: styles2,
    zIndex = Number.MAX_SAFE_INTEGER - 100,
    duration = 200,
    easing
  } = {}) {
    if (__privateGet(this, _contextMenu) !== void 0) {
      return;
    }
    if (!event && (typeof x !== "number" || typeof y !== "number")) {
      throw new Error(`TJSContextMenu.create error: No event or absolute X / Y position not defined.`);
    }
    if (event !== void 0 && !(event instanceof KeyboardEvent) && !(event instanceof MouseEvent)) {
      throw new TypeError(`TJSContextMenu.create error: 'event' is not a KeyboardEvent or MouseEvent.`);
    }
    const focusSource = A11yHelper.getFocusSource({ event, x, y, focusEl, debug: focusDebug });
    __privateSet(this, _contextMenu, new TJSContextMenuImpl({
      target: document.body,
      intro: true,
      props: {
        id,
        x: focusSource.x,
        y: focusSource.y,
        items: __privateMethod(this, _processItems, processItems_fn).call(this, items),
        focusSource,
        keyCode,
        styles: styles2,
        transitionOptions: { duration, easing },
        zIndex
      }
    }));
    __privateGet(this, _contextMenu).$on("close", () => {
      __privateSet(this, _contextMenu, void 0);
    });
  }
};
_contextMenu = new WeakMap();
_processItems = new WeakSet();
processItems_fn = /* @__PURE__ */ __name(function(items) {
  if (!isIterable(items)) {
    throw new TypeError(`TJSContextMenu error: 'items' is not an iterable list.`);
  }
  const tempList = items;
  const tempItems = [];
  let cntr = -1;
  for (const item of tempList) {
    cntr++;
    if (!isObject(item)) {
      throw new TypeError(`TJSContextMenu error: 'item[${cntr}]' is not an object.`);
    }
    if (typeof item.condition === "function" && !item.condition()) {
      continue;
    }
    if (typeof item.condition === "boolean" && !item.condition) {
      continue;
    }
    let type;
    if (isSvelteComponent(item.class)) {
      type = "class";
    } else if (typeof item.icon === "string") {
      type = "icon";
    } else if (typeof item.image === "string") {
      type = "image";
    } else if (typeof item.separator === "string") {
      if (item.separator !== "hr") {
        throw new Error(
          `TJSContextMenu error: 'item[${cntr}]' has unknown separator type; only 'hr' is currently supported.`
        );
      }
      type = "separator-hr";
    }
    if (type === void 0) {
      throw new TypeError(`TJSContextMenu error: Unknown type for 'item[${cntr}]'.`);
    }
    tempItems.push({ ...item, "#type": type });
  }
  return tempItems;
}, "#processItems");
/**
 * Processes menu item data for conditions and evaluating the type of menu item.
 *
 * @param {Iterable<TJSContextMenuItemData>} items - Menu item data.
 *
 * @returns {object[]} Processed menu items.
 */
__privateAdd(_TJSContextMenu, _processItems);
__name(_TJSContextMenu, "TJSContextMenu");
/**
 * Stores any active context menu.
 */
__privateAdd(_TJSContextMenu, _contextMenu, void 0);
let TJSContextMenu = _TJSContextMenu;
function isItemColliding(item, otherItem) {
  const transform = item.transform?.subscribe ? get_store_value(item.transform) : item.transform;
  const otherTransform = otherItem.transform?.subscribe ? get_store_value(otherItem.transform) : otherItem.transform;
  return item.id !== otherItem.id && transform.x + (transform.w - 1) >= otherTransform.x && transform.y + (transform.h - 1) >= otherTransform.y && transform.x <= otherTransform.x + (otherTransform.w - 1) && transform.y <= otherTransform.y + (otherTransform.h - 1);
}
__name(isItemColliding, "isItemColliding");
function getCollisions(originalItem, items) {
  return items.filter((item) => {
    return isItemColliding(originalItem, item);
  });
}
__name(getCollisions, "getCollisions");
function coordinate2position(coordinate, cellSize, gap) {
  return coordinate * cellSize + (coordinate + 1) * gap;
}
__name(coordinate2position, "coordinate2position");
function coordinate2size(coordinate, cellSize, gap) {
  return coordinate * cellSize + (coordinate - 1) * gap;
}
__name(coordinate2size, "coordinate2size");
function position2coordinate(position, cellSize, size, gap) {
  return Math.round(position / (cellSize + gap));
}
__name(position2coordinate, "position2coordinate");
function snapOnMove(left, top, transform, options, doClamp = true) {
  const { gridSize, gap, enabledCols, enabledRows } = options;
  const { w, h } = transform;
  const width = w * gridSize;
  const height = h * gridSize;
  const x = position2coordinate(left, gridSize, width, gap);
  const y = position2coordinate(top, gridSize, height, gap);
  return {
    x: doClamp ? clamp(x, 0, enabledCols - w) : x,
    y: doClamp ? clamp(y, 0, enabledRows - h) : y
  };
}
__name(snapOnMove, "snapOnMove");
function calcPosition(transform, options) {
  const { gridSize, gap } = options;
  return {
    ...transform,
    left: coordinate2position(transform.x, gridSize, gap),
    top: coordinate2position(transform.y, gridSize, gap),
    width: coordinate2size(transform.w, gridSize, gap),
    height: coordinate2size(transform.h, gridSize, gap)
  };
}
__name(calcPosition, "calcPosition");
function swapItemTransform(originalTransform, finalTransform, transform) {
  const newTransform = { ...transform };
  const shouldFlip = originalTransform.flipped !== finalTransform.flipped;
  const delta = {
    x: newTransform.x - finalTransform.x,
    y: newTransform.y - finalTransform.y
  };
  if (shouldFlip) {
    if (!originalTransform.flipped && finalTransform.flipped) {
      delta.x -= finalTransform.w;
      delta.x += newTransform.w;
      const { x, y } = delta;
      delta.x = y;
      delta.y = x * -1;
    } else if (originalTransform.flipped && !finalTransform.flipped) {
      delta.y -= finalTransform.h;
      delta.y += newTransform.h;
      const { x, y } = delta;
      delta.x = y * -1;
      delta.y = x;
    }
    const { w, h } = newTransform;
    newTransform.w = shouldFlip ? h : w;
    newTransform.h = shouldFlip ? w : h;
    newTransform.flipped = shouldFlip ? !newTransform.flipped : newTransform.flipped;
  }
  newTransform.x = originalTransform.x + delta.x;
  newTransform.y = originalTransform.y + delta.y;
  return newTransform;
}
__name(swapItemTransform, "swapItemTransform");
function isPlacementValid(item, collisions, items, options) {
  if (!collisions.length)
    return true;
  const finalTransform = foundry.utils.deepClone(get_store_value(item.transform));
  const origItemTransform = foundry.utils.deepClone(get_store_value(item.item.transform));
  const newItemPlacement = {
    id: item.id,
    transform: finalTransform
  };
  const itemWithinBounds = finalTransform.x + (finalTransform.w - 1) < options.cols && finalTransform.y + (finalTransform.h - 1) < options.rows && finalTransform.x >= 0 && finalTransform.y >= 0;
  if (!itemWithinBounds)
    return false;
  const assumedCollisionMovement = collisions.map((collision) => {
    const collisionTransform = foundry.utils.deepClone(get_store_value(collision.transform));
    return {
      id: collision.id,
      transform: swapItemTransform(origItemTransform, finalTransform, collisionTransform)
    };
  });
  if (!assumedCollisionMovement.every((entry) => {
    return entry && entry.transform.x + (entry.transform.w - 1) < options.cols && entry.transform.y + (entry.transform.h - 1) < options.rows && entry.transform.x >= 0 && entry.transform.y >= 0;
  }))
    return false;
  const itemsSansCollisions = items.filter((i) => {
    return i.id !== item.id && !assumedCollisionMovement.some((coll) => coll.id === i.id);
  }).concat([newItemPlacement]);
  return assumedCollisionMovement.every((movedBox) => {
    return !getCollisions(movedBox, itemsSansCollisions).length;
  });
}
__name(isPlacementValid, "isPlacementValid");
const { window: window_1 } = globals;
function create_if_block$p(ctx) {
  let div;
  let t;
  let if_block_anchor;
  let if_block = (
    /*collisions*/
    ctx[0].length && create_if_block_1$h(ctx)
  );
  return {
    c() {
      div = element("div");
      t = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      attr(
        div,
        "style",
        /*ghostStyle*/
        ctx[6]
      );
      attr(
        div,
        "class",
        /*collisionClass*/
        ctx[4]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      insert(target, t, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*ghostStyle*/
      64) {
        attr(
          div,
          "style",
          /*ghostStyle*/
          ctx2[6]
        );
      }
      if (dirty[0] & /*collisionClass*/
      16) {
        attr(
          div,
          "class",
          /*collisionClass*/
          ctx2[4]
        );
      }
      if (
        /*collisions*/
        ctx2[0].length
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_1$h(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block$p, "create_if_block$p");
function create_if_block_1$h(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(
        div,
        "style",
        /*style*/
        ctx[7]
      );
      attr(
        div,
        "class",
        /*itemClass*/
        ctx[5]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*style*/
      128) {
        attr(
          div,
          "style",
          /*style*/
          ctx2[7]
        );
      }
      if (dirty[0] & /*itemClass*/
      32) {
        attr(
          div,
          "class",
          /*itemClass*/
          ctx2[5]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_1$h, "create_if_block_1$h");
function create_fragment$G(ctx) {
  let div;
  let t;
  let if_block_anchor;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[27].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[26],
    null
  );
  let if_block = (
    /*active*/
    ctx[3] && create_if_block$p(ctx)
  );
  return {
    c() {
      div = element("div");
      if (default_slot)
        default_slot.c();
      t = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      attr(
        div,
        "class",
        /*classes*/
        ctx[2]
      );
      attr(
        div,
        "style",
        /*style*/
        ctx[7]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (default_slot) {
        default_slot.m(div, null);
      }
      ctx[29](div);
      insert(target, t, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            window_1,
            "keydown",
            /*keydown*/
            ctx[15]
          ),
          listen(
            div,
            "dblclick",
            /*doubleClick*/
            ctx[11]
          ),
          listen(div, "dragover", prevent_default(
            /*dragover_handler*/
            ctx[28]
          )),
          listen(
            div,
            "pointerdown",
            /*moveStart*/
            ctx[12]
          ),
          listen(
            div,
            "pointerleave",
            /*hoverLeave*/
            ctx[14]
          ),
          listen(
            div,
            "pointerover",
            /*hoverOver*/
            ctx[13]
          ),
          listen(
            div,
            "touchstart",
            /*moveStart*/
            ctx[12]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty[0] & /*$$scope*/
        67108864)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[26],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[26]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[26],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty[0] & /*classes*/
      4) {
        attr(
          div,
          "class",
          /*classes*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*style*/
      128) {
        attr(
          div,
          "style",
          /*style*/
          ctx2[7]
        );
      }
      if (
        /*active*/
        ctx2[3]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$p(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (default_slot)
        default_slot.d(detaching);
      ctx[29](null);
      if (detaching)
        detach(t);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$G, "create_fragment$G");
function instance$D($$self, $$props, $$invalidate) {
  let active2;
  let transform;
  let gridTransform;
  let ghostGridTransform;
  let style;
  let ghostStyle;
  let itemClass;
  let collisionClass;
  let $transformStore;
  let $previewTransform;
  let $activeStore;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { item } = $$props;
  let { options } = $$props;
  let { items } = $$props;
  let { gridContainer } = $$props;
  const dispatch2 = createEventDispatcher();
  let itemRef = HTMLElement;
  let dragged = false;
  const transformStore = item.transform;
  component_subscribe($$self, transformStore, (value) => $$invalidate(23, $transformStore = value));
  const previewTransform = item.ghostTransform;
  component_subscribe($$self, previewTransform, (value) => $$invalidate(24, $previewTransform = value));
  const activeStore = item.active;
  component_subscribe($$self, activeStore, (value) => $$invalidate(25, $activeStore = value));
  let classes = "";
  let splitting = false;
  let validPlacement = false;
  let collisions = [];
  let pointerOffset = { left: 0, top: 0 };
  function doubleClick(event) {
    if (event.button !== 0)
      return;
    dispatch2("itemdoubleclick", { item });
  }
  __name(doubleClick, "doubleClick");
  function moveStart(event) {
    if (event.button === 2) {
      return rightClick(event);
    }
    if (!options.canOrganize)
      return;
    if (event.button !== 0)
      return;
    if (event.pointerId) {
      itemRef.setPointerCapture(event.pointerId);
    }
    enableMoveEvents(event);
    dispatch2("itembegindrag", {
      item,
      target: itemRef,
      x: event.pageX - pointerOffset.internalLeft,
      y: event.pageY - pointerOffset.internalTop
    });
    dragged = true;
    move(event);
  }
  __name(moveStart, "moveStart");
  function splitStart(event) {
    splitting = true;
    enableMoveEvents(event);
  }
  __name(splitStart, "splitStart");
  function enableMoveEvents(event) {
    pointerOffset = {
      left: event.pageX - gridTransform.left,
      top: event.pageY - gridTransform.top,
      internalLeft: event.offsetX,
      internalTop: event.offsetY
    };
    set_store_value(previewTransform, $previewTransform = $transformStore, $previewTransform);
    window.addEventListener("pointermove", move, { passive: false });
    window.addEventListener("pointerup", moveEnd, { passive: false });
    window.addEventListener("touchmove", move, { passive: false });
    window.addEventListener("touchend", moveEnd, { passive: false });
  }
  __name(enableMoveEvents, "enableMoveEvents");
  let lastMoveEvent = false;
  function move(event) {
    if (!event && lastMoveEvent)
      event = lastMoveEvent;
    if (event)
      lastMoveEvent = event;
    if (!event)
      return;
    const { pageX, pageY } = event.type === "touchmove" ? event.changedTouches[0] : event;
    previewTransform.update((data2) => {
      const unsnappedData = calcPosition(data2, options);
      const { left, top, outOfBounds } = constrainToContainer(pageX - pointerOffset.left, pageY - pointerOffset.top, unsnappedData.width, unsnappedData.height);
      activeStore.set(!outOfBounds);
      dispatch2("itemmove", {
        x: pageX - pointerOffset.internalLeft,
        y: pageY - pointerOffset.internalTop
      });
      return {
        ...data2,
        ...snapOnMove(left, top, unsnappedData, options),
        left,
        top
      };
    });
    $$invalidate(0, collisions = getCollisions({ id: item.id, transform: previewTransform }, items));
    if (!splitting) {
      $$invalidate(20, validPlacement = isPlacementValid(
        {
          id: item.id,
          item,
          transform: previewTransform
        },
        collisions,
        items,
        options
      ));
      for (const otherItem of items) {
        if (otherItem.id === item.id)
          continue;
        const isActive = collisions.indexOf(otherItem) > -1;
        otherItem.active.set(isActive);
        if (isActive) {
          otherItem.ghostTransform.update(() => {
            return calcPosition(swapItemTransform(transform, get_store_value(previewTransform), get_store_value(otherItem.transform)), options);
          });
        }
      }
    } else {
      activeStore.set(!collisions.length);
    }
  }
  __name(move, "move");
  function constrainToContainer(left, top, width, height) {
    const parentRect = gridContainer.getBoundingClientRect();
    const relativeRect = {
      left: parentRect.left - parentRect.x,
      top: parentRect.top - parentRect.y,
      right: parentRect.right - parentRect.x,
      bottom: parentRect.bottom - parentRect.y
    };
    const outOfBounds = left < relativeRect.left && left < relativeRect.left - width / 2 || top < relativeRect.top && top < relativeRect.top - height / 2 || left + width > relativeRect.right && left + width > relativeRect.right + width / 2 || top + height > relativeRect.bottom && top + height > relativeRect.bottom + height / 2;
    if (left < relativeRect.left) {
      left = relativeRect.left;
    }
    if (top < relativeRect.top) {
      top = relativeRect.top;
    }
    if (left + width > relativeRect.right) {
      left = relativeRect.right - width;
    }
    if (top + height > relativeRect.bottom) {
      top = relativeRect.bottom - height;
    }
    return { left, top, outOfBounds };
  }
  __name(constrainToContainer, "constrainToContainer");
  function moveEnd(event) {
    window.removeEventListener("pointermove", move);
    window.removeEventListener("pointerup", moveEnd);
    window.removeEventListener("touchmove", move);
    window.removeEventListener("touchend", moveEnd);
    const origItemTransform = get_store_value(transformStore);
    const finalTransform = get_store_value(previewTransform);
    const { pageX, pageY } = event.type === "touchmove" ? event.changedTouches[0] : event;
    if (event.button === 2) {
      dispatch2("itemstopdrag", { cancelled: true });
      activeStore.set(false);
    } else {
      dispatch2("itemstopdrag", {
        item,
        outOfBounds: !active2,
        x: pageX,
        y: pageY,
        gridX: finalTransform.x,
        gridY: finalTransform.y,
        splitting
      });
    }
    dragged = false;
    if (!active2)
      return;
    for (const otherItem of items) {
      otherItem.active.set(false);
    }
    if (splitting) {
      splitting = false;
      return;
    }
    if (foundry.utils.isEmpty(finalTransform) || finalTransform.x === transform.x && finalTransform.y === transform.y && finalTransform.w === transform.w && finalTransform.h === transform.h) {
      return;
    }
    if (!validPlacement)
      return;
    $$invalidate(20, validPlacement = false);
    if (collisions.length) {
      if (item.item.areItemsSimilar(collisions[0].item) && !globalThis.keyboard.downKeys.has("ControlLeft")) {
        return collisions[0].item.merge(item.item);
      }
      for (const collision of collisions) {
        collision.transform.update((trans) => {
          return swapItemTransform(origItemTransform, finalTransform, trans);
        });
      }
    }
    transformStore.update((trans) => {
      trans.x = finalTransform.x;
      trans.y = finalTransform.y;
      trans.w = finalTransform.w;
      trans.h = finalTransform.h;
      trans.flipped = finalTransform.flipped;
      return trans;
    });
    dispatch2("itemchange", { items: collisions.concat([item]) });
  }
  __name(moveEnd, "moveEnd");
  function hoverOver() {
    const { x, y } = itemRef.getBoundingClientRect();
    dispatch2("itemhover", {
      item,
      target: itemRef,
      x: x + Math.floor(options.gridSize / 2),
      y: y + Math.floor(options.gridSize / 2)
    });
  }
  __name(hoverOver, "hoverOver");
  function hoverLeave() {
    const { x, y } = itemRef.getBoundingClientRect();
    dispatch2("itemhoverleave", {
      item,
      target: itemRef,
      x: x + Math.floor(options.gridSize / 2),
      y: y + Math.floor(options.gridSize / 2)
    });
  }
  __name(hoverLeave, "hoverLeave");
  function rightClick(event) {
    dispatch2("itemrightclick", {
      item,
      target: itemRef,
      x: event.pageX,
      y: event.pageY,
      splitStart
    });
  }
  __name(rightClick, "rightClick");
  function keydown(event) {
    if (event.key !== "r" || !active2 || !dragged || item.item.w === item.item.h)
      return;
    previewTransform.update((data2) => {
      const { w, h } = data2;
      dispatch2("itemflipped", {
        item,
        target: itemRef,
        h: w,
        w: h,
        flipped: !data2.flipped
      });
      const width = coordinate2size(h / 2, options.gridSize, options.gap);
      const height = coordinate2size(w / 2, options.gridSize, options.gap);
      pointerOffset.top -= width - height;
      pointerOffset.left -= height - width;
      return {
        ...data2,
        w: h,
        h: w,
        flipped: !data2.flipped
      };
    });
    move();
  }
  __name(keydown, "keydown");
  function dragover_handler(event) {
    bubble.call(this, $$self, event);
  }
  __name(dragover_handler, "dragover_handler");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      itemRef = $$value;
      $$invalidate(1, itemRef);
    });
  }
  __name(div_binding, "div_binding");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(16, item = $$props2.item);
    if ("options" in $$props2)
      $$invalidate(17, options = $$props2.options);
    if ("items" in $$props2)
      $$invalidate(18, items = $$props2.items);
    if ("gridContainer" in $$props2)
      $$invalidate(19, gridContainer = $$props2.gridContainer);
    if ("$$scope" in $$props2)
      $$invalidate(26, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*$activeStore*/
    33554432) {
      $$invalidate(3, active2 = $activeStore);
    }
    if ($$self.$$.dirty[0] & /*$transformStore*/
    8388608) {
      transform = $transformStore;
    }
    if ($$self.$$.dirty[0] & /*$transformStore, options*/
    8519680) {
      $$invalidate(21, gridTransform = calcPosition($transformStore, options));
    }
    if ($$self.$$.dirty[0] & /*$previewTransform, options*/
    16908288) {
      $$invalidate(22, ghostGridTransform = calcPosition(
        {
          ...snapOnMove($previewTransform.left, $previewTransform.top, $previewTransform, options, false),
          w: $previewTransform.w,
          h: $previewTransform.h
        },
        options
      ));
    }
    if ($$self.$$.dirty[0] & /*$activeStore*/
    33554432) {
      {
        if (!$activeStore)
          $$invalidate(0, collisions = []);
      }
    }
    if ($$self.$$.dirty[0] & /*classes, options, item*/
    196612) {
      {
        $$invalidate(2, classes = "");
        $$invalidate(2, classes += " " + options.hoverClass);
        $$invalidate(2, classes += options.highlightItems && item.highlight ? " " + options.highlightClass : "");
        $$invalidate(2, classes += options.highlightItems && !item.highlight ? " " + options.dimClass : "");
      }
    }
    if ($$self.$$.dirty[0] & /*gridTransform*/
    2097152) {
      $$invalidate(7, style = styleFromObject({
        "position": "absolute",
        "left": gridTransform.left + "px",
        "top": gridTransform.top + "px",
        "width": gridTransform.width + "px",
        "height": gridTransform.height + "px",
        "cursor": "move"
      }));
    }
    if ($$self.$$.dirty[0] & /*ghostGridTransform*/
    4194304) {
      $$invalidate(6, ghostStyle = styleFromObject({
        "position": "absolute",
        "left": ghostGridTransform.left + "px",
        "top": ghostGridTransform.top + "px",
        "width": ghostGridTransform.width + "px",
        "height": ghostGridTransform.height + "px",
        "opacity": "0.75",
        "z-index": "5"
      }));
    }
    if ($$self.$$.dirty[0] & /*collisions, validPlacement, options*/
    1179649) {
      $$invalidate(5, itemClass = collisions.length ? validPlacement ? options.collisionClass : options.invalidCollisionClass : options.previewClass);
    }
    if ($$self.$$.dirty[0] & /*collisions, validPlacement, options*/
    1179649) {
      $$invalidate(4, collisionClass = collisions.length ? validPlacement ? options.collisionClass : options.invalidCollisionClass : options.previewClass);
    }
  };
  return [
    collisions,
    itemRef,
    classes,
    active2,
    collisionClass,
    itemClass,
    ghostStyle,
    style,
    transformStore,
    previewTransform,
    activeStore,
    doubleClick,
    moveStart,
    hoverOver,
    hoverLeave,
    keydown,
    item,
    options,
    items,
    gridContainer,
    validPlacement,
    gridTransform,
    ghostGridTransform,
    $transformStore,
    $previewTransform,
    $activeStore,
    $$scope,
    slots,
    dragover_handler,
    div_binding
  ];
}
__name(instance$D, "instance$D");
const _GridItem = class _GridItem extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$D,
      create_fragment$G,
      safe_not_equal,
      {
        item: 16,
        options: 17,
        items: 18,
        gridContainer: 19
      },
      null,
      [-1, -1]
    );
  }
};
__name(_GridItem, "GridItem");
let GridItem = _GridItem;
const Grid_svelte_svelte_type_style_lang = "";
function get_each_context$k(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[26] = list[i];
  child_ctx[28] = i;
  return child_ctx;
}
__name(get_each_context$k, "get_each_context$k");
function get_each_context_1$a(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[26] = list[i];
  child_ctx[30] = i;
  return child_ctx;
}
__name(get_each_context_1$a, "get_each_context_1$a");
function get_each_context_2$3(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[31] = list[i];
  child_ctx[32] = list;
  child_ctx[33] = i;
  return child_ctx;
}
__name(get_each_context_2$3, "get_each_context_2$3");
const get_default_slot_changes = /* @__PURE__ */ __name((dirty) => ({ item: dirty[0] & /*items*/
4 }), "get_default_slot_changes");
const get_default_slot_context = /* @__PURE__ */ __name((ctx) => ({ item: (
  /*item*/
  ctx[31]
) }), "get_default_slot_context");
function get_if_ctx(ctx) {
  const child_ctx = ctx.slice();
  const constants_0 = calcPosition(
    /*dropGhost*/
    child_ctx[3],
    /*options*/
    child_ctx[0]
  );
  child_ctx[34] = constants_0;
  return child_ctx;
}
__name(get_if_ctx, "get_if_ctx");
function create_if_block_1$g(ctx) {
  let div;
  let div_style_value;
  let div_class_value;
  return {
    c() {
      div = element("div");
      attr(div, "style", div_style_value = `position: absolute; left:${/*dropElem*/
      ctx[34].left}px; top:${/*dropElem*/
      ctx[34].top}px;
        width: ${/*dropElem*/
      ctx[34].width}px; height: ${/*dropElem*/
      ctx[34].height}px;`);
      attr(div, "class", div_class_value = null_to_empty(
        /*options*/
        ctx[0].previewClass
      ) + " svelte-15sf5oy");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*dropGhost, options*/
      9 && div_style_value !== (div_style_value = `position: absolute; left:${/*dropElem*/
      ctx2[34].left}px; top:${/*dropElem*/
      ctx2[34].top}px;
        width: ${/*dropElem*/
      ctx2[34].width}px; height: ${/*dropElem*/
      ctx2[34].height}px;`)) {
        attr(div, "style", div_style_value);
      }
      if (dirty[0] & /*options*/
      1 && div_class_value !== (div_class_value = null_to_empty(
        /*options*/
        ctx2[0].previewClass
      ) + " svelte-15sf5oy")) {
        attr(div, "class", div_class_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_1$g, "create_if_block_1$g");
function create_default_slot$j(ctx) {
  let t;
  let current;
  const default_slot_template = (
    /*#slots*/
    ctx[19].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[24],
    get_default_slot_context
  );
  return {
    c() {
      if (default_slot)
        default_slot.c();
      t = space();
    },
    m(target, anchor) {
      if (default_slot) {
        default_slot.m(target, anchor);
      }
      insert(target, t, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty[0] & /*$$scope, items*/
        16777220)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[24],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[24]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[24],
              dirty,
              get_default_slot_changes
            ),
            get_default_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (default_slot)
        default_slot.d(detaching);
      if (detaching)
        detach(t);
    }
  };
}
__name(create_default_slot$j, "create_default_slot$j");
function create_each_block_2$3(key_1, ctx) {
  let first;
  let griditem;
  let updating_item;
  let updating_items;
  let updating_options;
  let current;
  function griditem_item_binding(value) {
    ctx[20](
      value,
      /*item*/
      ctx[31],
      /*each_value_2*/
      ctx[32],
      /*item_index*/
      ctx[33]
    );
  }
  __name(griditem_item_binding, "griditem_item_binding");
  function griditem_items_binding(value) {
    ctx[21](value);
  }
  __name(griditem_items_binding, "griditem_items_binding");
  function griditem_options_binding(value) {
    ctx[22](value);
  }
  __name(griditem_options_binding, "griditem_options_binding");
  let griditem_props = {
    gridContainer: (
      /*gridContainer*/
      ctx[1]
    ),
    $$slots: { default: [create_default_slot$j] },
    $$scope: { ctx }
  };
  if (
    /*item*/
    ctx[31] !== void 0
  ) {
    griditem_props.item = /*item*/
    ctx[31];
  }
  if (
    /*items*/
    ctx[2] !== void 0
  ) {
    griditem_props.items = /*items*/
    ctx[2];
  }
  if (
    /*options*/
    ctx[0] !== void 0
  ) {
    griditem_props.options = /*options*/
    ctx[0];
  }
  griditem = new GridItem({ props: griditem_props });
  binding_callbacks.push(() => bind(griditem, "item", griditem_item_binding));
  binding_callbacks.push(() => bind(griditem, "items", griditem_items_binding));
  binding_callbacks.push(() => bind(griditem, "options", griditem_options_binding));
  griditem.$on(
    "itemdoubleclick",
    /*itemDoubleClickEvent*/
    ctx[15]
  );
  griditem.$on(
    "itemchange",
    /*itemChangeEvent*/
    ctx[8]
  );
  griditem.$on(
    "itemhover",
    /*itemHoverEvent*/
    ctx[9]
  );
  griditem.$on(
    "itembegindrag",
    /*itemBeginDrag*/
    ctx[10]
  );
  griditem.$on(
    "itemstopdrag",
    /*itemStopDrag*/
    ctx[11]
  );
  griditem.$on(
    "itemmove",
    /*itemMove*/
    ctx[12]
  );
  griditem.$on(
    "itemhoverleave",
    /*itemHoverLeaveEvent*/
    ctx[13]
  );
  griditem.$on(
    "itemrightclick",
    /*itemRightClickEvent*/
    ctx[14]
  );
  griditem.$on(
    "itemflipped",
    /*itemFlippedEvent*/
    ctx[16]
  );
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(griditem.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(griditem, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const griditem_changes = {};
      if (dirty[0] & /*gridContainer*/
      2)
        griditem_changes.gridContainer = /*gridContainer*/
        ctx[1];
      if (dirty[0] & /*$$scope, items*/
      16777220) {
        griditem_changes.$$scope = { dirty, ctx };
      }
      if (!updating_item && dirty[0] & /*items*/
      4) {
        updating_item = true;
        griditem_changes.item = /*item*/
        ctx[31];
        add_flush_callback(() => updating_item = false);
      }
      if (!updating_items && dirty[0] & /*items*/
      4) {
        updating_items = true;
        griditem_changes.items = /*items*/
        ctx[2];
        add_flush_callback(() => updating_items = false);
      }
      if (!updating_options && dirty[0] & /*options*/
      1) {
        updating_options = true;
        griditem_changes.options = /*options*/
        ctx[0];
        add_flush_callback(() => updating_options = false);
      }
      griditem.$set(griditem_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(griditem.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(griditem.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(griditem, detaching);
    }
  };
}
__name(create_each_block_2$3, "create_each_block_2$3");
function create_if_block$o(ctx) {
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_value = Array(
    /*options*/
    ctx[0].rows
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*rowIndex*/
    ctx2[28]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$k(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$k(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "item-piles-inner-grid svelte-15sf5oy");
      attr(
        div,
        "style",
        /*backgroundGridStyle*/
        ctx[4]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*options*/
      1) {
        each_value = Array(
          /*options*/
          ctx2[0].rows
        );
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, destroy_block, create_each_block$k, null, get_each_context$k);
      }
      if (dirty[0] & /*backgroundGridStyle*/
      16) {
        attr(
          div,
          "style",
          /*backgroundGridStyle*/
          ctx2[4]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_if_block$o, "create_if_block$o");
function create_each_block_1$a(key_1, ctx) {
  let div;
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      set_style(
        div,
        "width",
        /*options*/
        ctx[0].gridSize + /*options*/
        ctx[0].gap / 2 + "px"
      );
      set_style(
        div,
        "height",
        /*options*/
        ctx[0].gridSize + /*options*/
        ctx[0].gap / 2
      );
      attr(div, "class", "svelte-15sf5oy");
      toggle_class(
        div,
        "grid-disabled",
        /*colIndex*/
        ctx[30] >= /*options*/
        ctx[0].enabledCols || /*rowIndex*/
        ctx[28] >= /*options*/
        ctx[0].enabledRows
      );
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*options*/
      1) {
        set_style(
          div,
          "width",
          /*options*/
          ctx[0].gridSize + /*options*/
          ctx[0].gap / 2 + "px"
        );
      }
      if (dirty[0] & /*options*/
      1) {
        set_style(
          div,
          "height",
          /*options*/
          ctx[0].gridSize + /*options*/
          ctx[0].gap / 2
        );
      }
      if (dirty[0] & /*options*/
      1) {
        toggle_class(
          div,
          "grid-disabled",
          /*colIndex*/
          ctx[30] >= /*options*/
          ctx[0].enabledCols || /*rowIndex*/
          ctx[28] >= /*options*/
          ctx[0].enabledRows
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_each_block_1$a, "create_each_block_1$a");
function create_each_block$k(key_1, ctx) {
  let first;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let each_value_1 = Array(
    /*options*/
    ctx[0].cols
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*colIndex*/
    ctx2[30]
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$a(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$a(key, child_ctx));
  }
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*options*/
      1) {
        each_value_1 = Array(
          /*options*/
          ctx[0].cols
        );
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_1, each_1_lookup, each_1_anchor.parentNode, destroy_block, create_each_block_1$a, each_1_anchor, get_each_context_1$a);
      }
    },
    d(detaching) {
      if (detaching)
        detach(first);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_each_block$k, "create_each_block$k");
function create_fragment$F(ctx) {
  let div1;
  let div0;
  let t0;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let div0_class_value;
  let t1;
  let current;
  let if_block0 = (
    /*dropGhost*/
    ctx[3] && /*dropGhost*/
    ctx[3]?.active && create_if_block_1$g(get_if_ctx(ctx))
  );
  let each_value_2 = (
    /*items*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[31].id
  ), "get_key");
  for (let i = 0; i < each_value_2.length; i += 1) {
    let child_ctx = get_each_context_2$3(ctx, each_value_2, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_2$3(key, child_ctx));
  }
  let if_block1 = (
    /*options*/
    ctx[0].backgroundGrid && create_if_block$o(ctx)
  );
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t1 = space();
      if (if_block1)
        if_block1.c();
      attr(div0, "class", div0_class_value = "item-piles-grid " + /*options*/
      ctx[0].class + " svelte-15sf5oy");
      attr(
        div0,
        "style",
        /*containerStyle*/
        ctx[5]
      );
      attr(div1, "class", "item-piles-grid-container svelte-15sf5oy");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      if (if_block0)
        if_block0.m(div0, null);
      append(div0, t0);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div0, null);
        }
      }
      ctx[23](div0);
      append(div1, t1);
      if (if_block1)
        if_block1.m(div1, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*dropGhost*/
        ctx2[3] && /*dropGhost*/
        ctx2[3]?.active
      ) {
        if (if_block0) {
          if_block0.p(get_if_ctx(ctx2), dirty);
        } else {
          if_block0 = create_if_block_1$g(get_if_ctx(ctx2));
          if_block0.c();
          if_block0.m(div0, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty[0] & /*gridContainer, items, options, itemDoubleClickEvent, itemChangeEvent, itemHoverEvent, itemBeginDrag, itemStopDrag, itemMove, itemHoverLeaveEvent, itemRightClickEvent, itemFlippedEvent, $$scope*/
      16908039) {
        each_value_2 = /*items*/
        ctx2[2];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_2, each_1_lookup, div0, outro_and_destroy_block, create_each_block_2$3, null, get_each_context_2$3);
        check_outros();
      }
      if (!current || dirty[0] & /*options*/
      1 && div0_class_value !== (div0_class_value = "item-piles-grid " + /*options*/
      ctx2[0].class + " svelte-15sf5oy")) {
        attr(div0, "class", div0_class_value);
      }
      if (!current || dirty[0] & /*containerStyle*/
      32) {
        attr(
          div0,
          "style",
          /*containerStyle*/
          ctx2[5]
        );
      }
      if (
        /*options*/
        ctx2[0].backgroundGrid
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block$o(ctx2);
          if_block1.c();
          if_block1.m(div1, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_2.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      if (if_block0)
        if_block0.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[23](null);
      if (if_block1)
        if_block1.d();
    }
  };
}
__name(create_fragment$F, "create_fragment$F");
function instance$C($$self, $$props, $$invalidate) {
  let containerStyle;
  let $containerHeight;
  let $containerWidth;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { gridContainer = HTMLDivElement } = $$props;
  let { items = [] } = $$props;
  let { dropGhost = false } = $$props;
  let { options = {
    cols: null,
    rows: null,
    enabledCols: null,
    enabledRows: null,
    gap: 10,
    gridSize: 50,
    canOrganize: false,
    backgroundGrid: false,
    class: "",
    activeClass: "",
    previewClass: "",
    collisionClass: "",
    invalidCollisionClass: "",
    hoverClass: "",
    highlightClass: "",
    highlightItems: false
  } } = $$props;
  let containerHeight = writable$1(0);
  component_subscribe($$self, containerHeight, (value) => $$invalidate(17, $containerHeight = value));
  let containerWidth = writable$1(0);
  component_subscribe($$self, containerWidth, (value) => $$invalidate(18, $containerWidth = value));
  const dispatch2 = createEventDispatcher();
  function itemChangeEvent(event) {
    dispatch2("change", { ...event.detail });
  }
  __name(itemChangeEvent, "itemChangeEvent");
  function itemHoverEvent(event) {
    dispatch2("hover", { ...event.detail });
  }
  __name(itemHoverEvent, "itemHoverEvent");
  function itemBeginDrag(event) {
    dispatch2("itembegindrag", { ...event.detail });
  }
  __name(itemBeginDrag, "itemBeginDrag");
  function itemStopDrag(event) {
    dispatch2("itemstopdrag", { ...event.detail });
  }
  __name(itemStopDrag, "itemStopDrag");
  function itemMove(event) {
    dispatch2("itemmove", { ...event.detail });
  }
  __name(itemMove, "itemMove");
  function itemHoverLeaveEvent(event) {
    dispatch2("leave", { ...event.detail });
  }
  __name(itemHoverLeaveEvent, "itemHoverLeaveEvent");
  function itemRightClickEvent(event) {
    dispatch2("rightclick", { ...event.detail });
  }
  __name(itemRightClickEvent, "itemRightClickEvent");
  function itemDoubleClickEvent(event) {
    dispatch2("doubleclick", { ...event.detail });
  }
  __name(itemDoubleClickEvent, "itemDoubleClickEvent");
  function itemFlippedEvent(event) {
    dispatch2("itemflipped", { ...event.detail });
  }
  __name(itemFlippedEvent, "itemFlippedEvent");
  let backgroundGridStyle = "";
  function griditem_item_binding(value, item, each_value_2, item_index) {
    each_value_2[item_index] = value;
    $$invalidate(2, items);
  }
  __name(griditem_item_binding, "griditem_item_binding");
  function griditem_items_binding(value) {
    items = value;
    $$invalidate(2, items);
  }
  __name(griditem_items_binding, "griditem_items_binding");
  function griditem_options_binding(value) {
    options = value;
    $$invalidate(0, options);
  }
  __name(griditem_options_binding, "griditem_options_binding");
  function div0_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      gridContainer = $$value;
      $$invalidate(1, gridContainer);
    });
  }
  __name(div0_binding, "div0_binding");
  $$self.$$set = ($$props2) => {
    if ("gridContainer" in $$props2)
      $$invalidate(1, gridContainer = $$props2.gridContainer);
    if ("items" in $$props2)
      $$invalidate(2, items = $$props2.items);
    if ("dropGhost" in $$props2)
      $$invalidate(3, dropGhost = $$props2.dropGhost);
    if ("options" in $$props2)
      $$invalidate(0, options = $$props2.options);
    if ("$$scope" in $$props2)
      $$invalidate(24, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*options*/
    1) {
      set_store_value(containerWidth, $containerWidth = options.cols * (options.gridSize + options.gap) + options.gap, $containerWidth);
    }
    if ($$self.$$.dirty[0] & /*options*/
    1) {
      set_store_value(containerHeight, $containerHeight = options.rows * (options.gridSize + options.gap) + options.gap, $containerHeight);
    }
    if ($$self.$$.dirty[0] & /*$containerWidth, $containerHeight*/
    393216) {
      $$invalidate(5, containerStyle = styleFromObject({
        "width": $containerWidth + "px",
        "height": $containerHeight + "px"
      }));
    }
    if ($$self.$$.dirty[0] & /*options*/
    1) {
      $$invalidate(4, backgroundGridStyle = styleFromObject({
        "grid-template-columns": `repeat(${options.cols}, ${options.gridSize + options.gap / 2}px)`,
        "grid-template-rows": `repeat(${options.rows}, ${options.gridSize + options.gap / 2}px)`,
        "gap": `${options.gap / 2}px`,
        "top": `${options.gap / 2}px`
      }));
    }
  };
  return [
    options,
    gridContainer,
    items,
    dropGhost,
    backgroundGridStyle,
    containerStyle,
    containerHeight,
    containerWidth,
    itemChangeEvent,
    itemHoverEvent,
    itemBeginDrag,
    itemStopDrag,
    itemMove,
    itemHoverLeaveEvent,
    itemRightClickEvent,
    itemDoubleClickEvent,
    itemFlippedEvent,
    $containerHeight,
    $containerWidth,
    slots,
    griditem_item_binding,
    griditem_items_binding,
    griditem_options_binding,
    div0_binding,
    $$scope
  ];
}
__name(instance$C, "instance$C");
const _Grid = class _Grid extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$C,
      create_fragment$F,
      safe_not_equal,
      {
        gridContainer: 1,
        items: 2,
        dropGhost: 3,
        options: 0
      },
      null,
      [-1, -1]
    );
  }
};
__name(_Grid, "Grid");
let Grid = _Grid;
const VaultItemEntry_svelte_svelte_type_style_lang = "";
function create_if_block_2$a(ctx) {
  let div;
  let img_1;
  let img_1_src_value;
  return {
    c() {
      div = element("div");
      img_1 = element("img");
      attr(img_1, "class", "grid-item-image svelte-1yp67rp");
      if (!src_url_equal(img_1.src, img_1_src_value = /*displayImage*/
      ctx[2]))
        attr(img_1, "src", img_1_src_value);
      attr(div, "class", "grid-item-image-container svelte-1yp67rp");
      attr(
        div,
        "style",
        /*containerStyle*/
        ctx[0]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, img_1);
    },
    p(ctx2, dirty) {
      if (dirty & /*displayImage*/
      4 && !src_url_equal(img_1.src, img_1_src_value = /*displayImage*/
      ctx2[2])) {
        attr(img_1, "src", img_1_src_value);
      }
      if (dirty & /*containerStyle*/
      1) {
        attr(
          div,
          "style",
          /*containerStyle*/
          ctx2[0]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_2$a, "create_if_block_2$a");
function create_if_block_1$f(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "grid-item-ghost svelte-1yp67rp");
      attr(
        div,
        "style",
        /*styling*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*styling*/
      8) {
        attr(
          div,
          "style",
          /*styling*/
          ctx2[3]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_1$f, "create_if_block_1$f");
function create_if_block$n(ctx) {
  let span;
  let t;
  return {
    c() {
      span = element("span");
      t = text(
        /*$quantity*/
        ctx[5]
      );
      attr(span, "class", "grid-item-quantity svelte-1yp67rp");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantity*/
      32)
        set_data(
          t,
          /*$quantity*/
          ctx2[5]
        );
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_if_block$n, "create_if_block$n");
function create_fragment$E(ctx) {
  let div;
  let t0;
  let t1;
  let if_block0 = (
    /*displayImage*/
    ctx[2] && create_if_block_2$a(ctx)
  );
  let if_block1 = (
    /*styling*/
    ctx[3] && create_if_block_1$f(ctx)
  );
  let if_block2 = (
    /*canStack*/
    ctx[12] && /*$quantity*/
    ctx[5] > 1 && create_if_block$n(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      if (if_block1)
        if_block1.c();
      t1 = space();
      if (if_block2)
        if_block2.c();
      attr(div, "class", "grid-item svelte-1yp67rp");
      attr(
        div,
        "data-fast-tooltip",
        /*$name*/
        ctx[4]
      );
      attr(div, "data-fast-tooltip-activation-speed", "0");
      attr(div, "data-fast-tooltip-deactivation-speed", "0");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t0);
      if (if_block1)
        if_block1.m(div, null);
      append(div, t1);
      if (if_block2)
        if_block2.m(div, null);
      ctx[22](div);
    },
    p(ctx2, [dirty]) {
      if (
        /*displayImage*/
        ctx2[2]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_2$a(ctx2);
          if_block0.c();
          if_block0.m(div, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*styling*/
        ctx2[3]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_1$f(ctx2);
          if_block1.c();
          if_block1.m(div, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (
        /*canStack*/
        ctx2[12] && /*$quantity*/
        ctx2[5] > 1
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block$n(ctx2);
          if_block2.c();
          if_block2.m(div, null);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (dirty & /*$name*/
      16) {
        attr(
          div,
          "data-fast-tooltip",
          /*$name*/
          ctx2[4]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      ctx[22](null);
    }
  };
}
__name(create_fragment$E, "create_fragment$E");
function instance$B($$self, $$props, $$invalidate) {
  let gridData;
  let styling;
  let displayImage;
  let $doc;
  let $transform;
  let $flagData;
  let $img;
  let $style;
  let $gridDataStore;
  let $name;
  let $quantity;
  let { entry } = $$props;
  const store = getContext("store");
  const gridDataStore = store.gridData;
  component_subscribe($$self, gridDataStore, (value) => $$invalidate(21, $gridDataStore = value));
  const item = entry.item;
  const doc = item.itemDocument;
  component_subscribe($$self, doc, (value) => $$invalidate(16, $doc = value));
  const name = item.name;
  component_subscribe($$self, name, (value) => $$invalidate(4, $name = value));
  const img = item.img;
  component_subscribe($$self, img, (value) => $$invalidate(19, $img = value));
  const flagData = item.itemFlagData;
  component_subscribe($$self, flagData, (value) => $$invalidate(18, $flagData = value));
  const quantity = item.quantity;
  component_subscribe($$self, quantity, (value) => $$invalidate(5, $quantity = value));
  const canStack = item.canStack;
  const style = item.style;
  component_subscribe($$self, style, (value) => $$invalidate(20, $style = value));
  const transform = entry.transform;
  component_subscribe($$self, transform, (value) => $$invalidate(17, $transform = value));
  let containerStyle = "";
  function imageChanged(flagData2, transform2) {
    if (!flagData2.vaultImageFlipped) {
      getImageDimensions(transform2);
    } else {
      $$invalidate(0, containerStyle = "");
    }
  }
  __name(imageChanged, "imageChanged");
  function getImageDimensions(transform2) {
    let { w, h, flipped } = transform2;
    const width = coordinate2size(!flipped ? w : h, gridData.gridSize, gridData.gap);
    const height = coordinate2size(!flipped ? h : w, gridData.gridSize, gridData.gap);
    $$invalidate(0, containerStyle = `transform: rotate(${flipped ? "90deg" : "0deg"}); min-width: ${width}px; max-width: ${width}px; min-height: ${height}px; max-height: ${height}px;`);
  }
  __name(getImageDimensions, "getImageDimensions");
  let element2 = false;
  function callRenderedHook() {
    if (!element2)
      return;
    Hooks.callAll(CONSTANTS.HOOKS.RENDER_VAULT_GRID_ITEM, element2, item.item);
  }
  __name(callRenderedHook, "callRenderedHook");
  onMount(() => {
    callRenderedHook();
  });
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      element2 = $$value;
      $$invalidate(1, element2);
    });
  }
  __name(div_binding, "div_binding");
  $$self.$$set = ($$props2) => {
    if ("entry" in $$props2)
      $$invalidate(15, entry = $$props2.entry);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$gridDataStore*/
    2097152) {
      gridData = $gridDataStore;
    }
    if ($$self.$$.dirty & /*$style*/
    1048576) {
      $$invalidate(3, styling = styleFromObject($style));
    }
    if ($$self.$$.dirty & /*$flagData, $img*/
    786432) {
      $$invalidate(2, displayImage = ($flagData.flipped ? $flagData.vaultImageFlipped || $flagData.vaultImage : $flagData.vaultImage) || $img);
    }
    if ($$self.$$.dirty & /*$flagData, $transform*/
    393216) {
      imageChanged($flagData, $transform);
    }
    if ($$self.$$.dirty & /*$doc*/
    65536) {
      {
        callRenderedHook();
      }
    }
  };
  return [
    containerStyle,
    element2,
    displayImage,
    styling,
    $name,
    $quantity,
    gridDataStore,
    doc,
    name,
    img,
    flagData,
    quantity,
    canStack,
    style,
    transform,
    entry,
    $doc,
    $transform,
    $flagData,
    $img,
    $style,
    $gridDataStore,
    div_binding
  ];
}
__name(instance$B, "instance$B");
const _VaultItemEntry = class _VaultItemEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$B, create_fragment$E, safe_not_equal, { entry: 15 });
  }
};
__name(_VaultItemEntry, "VaultItemEntry");
let VaultItemEntry = _VaultItemEntry;
const _VaultStore = class _VaultStore extends ItemPileStore {
  constructor(...args) {
    super(...args);
    this.gridData = writable$1({});
    this.gridItems = writable$1([]);
    this.validGridItems = writable$1([]);
    this.canDepositCurrency = writable$1(false);
    this.canWithdrawCurrency = writable$1(false);
    this.logSearch = writable$1("");
    this.vaultLog = writable$1([]);
    this.visibleLogItems = writable$1(18);
    this.highlightedGridItems = writable$1([]);
    this.vaultExpanderItems = writable$1([]);
    this.dragPosition = writable$1({ x: 0, y: 0, w: 1, h: 1, active: false, flipped: false });
    this.mainContainer = false;
  }
  get searchDelay() {
    return 50;
  }
  get ItemClass() {
    return VaultItem;
  }
  setupStores(reset = false) {
    super.setupStores(reset);
    this.gridData.set({});
    this.gridItems.set([]);
    this.validGridItems.set([]);
    this.logSearch.set("");
    this.vaultLog.set([]);
    this.visibleLogItems.set(18);
    this.highlightedGridItems.set([]);
    this.vaultExpanderItems.set([]);
    this.dragPosition.set({ x: 0, y: 0, w: 1, h: 1, active: false, flipped: false });
    this.refreshGridDebounce = foundry.utils.debounce(() => {
      this.refreshGrid();
    }, this.searchDelay);
  }
  setupSubscriptions() {
    super.setupSubscriptions();
    this.subscribeTo(this.pileData, () => {
      this.refreshAppSize();
      this.refreshGridDebounce();
      this.processLogEntries();
    });
    this.subscribeTo(this.document, () => {
      const { data: data2 } = this.document.updateOptions;
      if (hasProperty(data2, CONSTANTS.FLAGS.LOG)) {
        this.processLogEntries();
      }
    });
    this.subscribeTo(this.logSearch, this.filterLogEntries.bind(this));
    this.refreshGrid();
    this.processLogEntries();
  }
  processLogEntries() {
    const pileData = get_store_value(this.pileData);
    const logEntries = getActorLog(this.actor);
    logEntries.map((log) => {
      let instigator = log.actor || "Unknown character";
      if (pileData.vaultLogType === "user_actor") {
        instigator = game.i18n.format("ITEM-PILES.Vault.LogUserActor", {
          actor_name: log.actor || "Unknown character",
          user_name: game.users.get(log.user)?.name ?? "unknown user"
        });
      } else if (pileData.vaultLogType === "user") {
        instigator = game.users.get(log.user)?.name ?? "unknown user";
      }
      const quantity = Math.abs(log.qty) > 1 ? game.i18n.format("ITEM-PILES.Vault.LogQuantity", { quantity: Math.abs(log.qty) }) : "";
      if (!log.action) {
        log.action = log.qty > 0 ? "deposited" : "withdrew";
      }
      const action = log.action === "withdrew" || log.action === "deposited" ? game.i18n.localize("ITEM-PILES.Vault." + (log.action.slice(0, 1).toUpperCase() + log.action.slice(1))) : log.action;
      log.text = game.i18n.format("ITEM-PILES.Vault.LogEntry", {
        instigator,
        action: `<span>${action}</span>`,
        quantity,
        item_name: `<strong>${log.name}</strong>`
      });
      log.visible = true;
    });
    this.vaultLog.set(logEntries);
    this.filterLogEntries();
  }
  filterLogEntries() {
    const search = get_store_value(this.logSearch).toLowerCase();
    const regex = new RegExp(search, "g");
    this.vaultLog.update((logs) => {
      for (let log of logs) {
        log.visible = log.text.toLowerCase().search(regex) !== -1;
      }
      return logs;
    });
  }
  refreshFreeSpaces() {
    const pileData = get_store_value(this.pileData);
    this.gridData.update(() => {
      const access = getVaultAccess(this.actor, {
        flagData: pileData,
        hasRecipient: !!this.recipient
      });
      return {
        ...getVaultGridData(this.actor, { flagData: pileData }),
        ...access,
        canEditCurrencies: game.user.isGM,
        fullAccess: game.user.isGM || Object.values(access).every(Boolean),
        gridSize: 40,
        gap: 4
      };
    });
  }
  canItemsFitWithout(itemToCompare) {
    const pileData = get_store_value(this.pileData);
    const items = get_store_value(this.validGridItems);
    const vaultExpanders = get_store_value(this.vaultExpanderItems);
    const expansions = vaultExpanders.reduce((acc, item) => {
      if (item === itemToCompare)
        return acc;
      acc.cols += get_store_value(item.itemFlagData).addsCols * get_store_value(item.quantity);
      acc.rows += get_store_value(item.itemFlagData).addsRows * get_store_value(item.quantity);
      return acc;
    }, {
      cols: pileData.baseExpansionCols ?? 0,
      rows: pileData.baseExpansionRows ?? 0
    });
    const enabledCols = Math.min(pileData.cols, expansions.cols);
    const enabledRows = Math.min(pileData.rows, expansions.rows);
    const enabledSpaces = enabledCols * enabledRows;
    return enabledSpaces - items.length;
  }
  updateGrid(items) {
    if (!items.length)
      return;
    const itemsToUpdate = items.map((item) => {
      const transform = get_store_value(item.transform);
      return {
        _id: item.id,
        [CONSTANTS.FLAGS.ITEM + ".x"]: transform.x,
        [CONSTANTS.FLAGS.ITEM + ".y"]: transform.y,
        [CONSTANTS.FLAGS.ITEM + ".flipped"]: transform.flipped
      };
    });
    debug("itemsToUpdate", itemsToUpdate);
    const actorUuid = getUuid(this.actor);
    if (this.actor.isOwner) {
      return PrivateAPI._commitActorChanges(actorUuid, {
        itemsToUpdate
      });
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.COMMIT_ACTOR_CHANGES, actorUuid, {
      itemsToUpdate
    });
  }
  refreshItems() {
    super.refreshItems();
    const pileData = get_store_value(this.pileData);
    this.validGridItems.set(get_store_value(this.allItems).filter((entry) => {
      const itemFlagData = get_store_value(entry.itemFlagData);
      return (!pileData.vaultExpansion || !itemFlagData.vaultExpander) && !entry.isCurrency;
    }));
    this.highlightedGridItems.set(get_store_value(this.items).filter((entry) => {
      const itemFlagData = get_store_value(entry.itemFlagData);
      return !pileData.vaultExpansion || !itemFlagData.vaultExpander;
    }).map((item) => item.id));
    this.vaultExpanderItems.set(get_store_value(this.allItems).filter((entry) => {
      const itemFlagData = get_store_value(entry.itemFlagData);
      return !pileData.vaultExpansion || itemFlagData.vaultExpander;
    }));
    this.refreshGridDebounce();
  }
  createItem(...args) {
    super.createItem(...args);
    this.refreshGrid();
  }
  deleteItem(...args) {
    super.deleteItem(...args);
    this.refreshGrid();
  }
  refreshGrid() {
    this.refreshFreeSpaces();
    this.gridItems.set(this.placeItemsOnGrid());
  }
  placeItemsOnGrid() {
    const search = get_store_value(this.search);
    const highlightedItems = get_store_value(this.highlightedGridItems);
    const gridData = get_store_value(this.gridData);
    const allItems = [...get_store_value(this.validGridItems)];
    const existingItems = [];
    const grid = Array.from(Array(gridData.enabledCols).keys()).map((_, x) => {
      return Array.from(Array(gridData.enabledRows).keys()).map((_2, y) => {
        const item = allItems.find((item2) => {
          return item2.x === x && item2.y === y;
        });
        if (item) {
          allItems.splice(allItems.indexOf(item), 1);
          existingItems.push({
            id: item.id,
            active: item.active,
            transform: item.transform,
            ghostTransform: item.ghostTransform,
            highlight: search && highlightedItems.includes(item.id),
            item
          });
        }
        return item?.id ?? null;
      });
    });
    debug("grid", grid);
    debug("existingItems", existingItems);
    debug("allItems", allItems);
    const itemsToUpdate = allItems.map((item) => {
      let freeCells = [];
      for (let x = 0; x < gridData.enabledCols; x++) {
        for (let y = 0; y < gridData.enabledRows; y++) {
          if (grid[x][y])
            continue;
          freeCells.push({ x, y });
        }
      }
      const position = getNewItemsVaultPosition(item.item, { ...gridData, grid, freeCells });
      if (!position)
        return false;
      const itemFlagData = get_store_value(item.itemFlagData);
      let { width, height } = getVaultItemDimensions(item.item, itemFlagData);
      for (let w = 0; w < width; w++) {
        const x = Math.max(0, Math.min(position.x + w, gridData.enabledCols - 1));
        for (let h = 0; h < height; h++) {
          const y = Math.max(0, Math.min(position.y + h, gridData.enabledRows - 1));
          grid[x][y] = item.id;
        }
      }
      item.transform.update((trans) => {
        trans.x = position.x;
        trans.y = position.y;
        trans.flipped = position.flipped;
        return trans;
      });
      return {
        id: item.id,
        active: item.active,
        transform: item.transform,
        ghostTransform: item.ghostTransform,
        highlight: search && highlightedItems.includes(item.id),
        item
      };
    }).filter(Boolean);
    this.updateGrid(itemsToUpdate);
    return itemsToUpdate.concat(existingItems);
  }
  refreshAppSize() {
    if (!this.mainContainer)
      return;
    const oldHeight = this.mainContainer.getBoundingClientRect().height;
    setTimeout(() => {
      const newHeight = this.mainContainer.getBoundingClientRect().height - oldHeight;
      this.application.position.stores.height.update((height) => {
        return height + newHeight;
      });
    }, 10);
  }
  async onDropData(data2, event, isExpander) {
    let validPosition = get_store_value(this.dragPosition);
    this.dragPosition.set({ x: 0, y: 0, w: 1, h: 1, flipped: false, active: false });
    if (data2.type === "Actor" && game.user.isGM) {
      const newRecipient = data2.uuid ? await fromUuid(data2.uuid) : game.actors.get(data2.id);
      this.refreshAppSize();
      this.updateRecipient(newRecipient);
      this.refreshFreeSpaces();
      return;
    }
    if (data2.type !== "Item") {
      custom_warning(`You can't drop documents of type "${data2.type}" into this Item Piles vault!`, true);
      return false;
    }
    const item = await Item.implementation.fromDropData(data2);
    const itemData = item.toObject();
    if (!itemData) {
      console.error(data2);
      throw custom_error("Something went wrong when dropping this item!");
    }
    const source = (data2.uuid ? fromUuidSync(data2.uuid) : false)?.parent ?? false;
    const target = this.actor;
    if (source === target) {
      custom_warning(`You can't drop items into the vault that originate from the vault!`, true);
      return false;
    }
    if (!source && !game.user.isGM) {
      custom_warning(`Only GMs can drop items from the sidebar!`, true);
      return false;
    }
    const vaultExpander = getProperty(itemData, CONSTANTS.FLAGS.ITEM + ".vaultExpander");
    if (isExpander && !vaultExpander) {
      custom_warning(game.i18n.localize("ITEM-PILES.Warnings.VaultItemNotExpander"), true);
      return false;
    }
    const similarItem = this.getSimilarItem(itemData);
    if (!vaultExpander) {
      if (!similarItem || !canItemStack(item, this.actor)) {
        validPosition = canItemFitInVault(itemData, this.actor, { position: validPosition });
        if (!validPosition) {
          custom_warning(game.i18n.localize("ITEM-PILES.Warnings.VaultFull"), true);
          return false;
        }
      }
    }
    foundry.utils.setProperty(itemData, CONSTANTS.FLAGS.ITEM + ".x", validPosition.x);
    foundry.utils.setProperty(itemData, CONSTANTS.FLAGS.ITEM + ".y", validPosition.y);
    foundry.utils.setProperty(itemData, CONSTANTS.FLAGS.ITEM + ".flipped", validPosition.flipped);
    return PrivateAPI._depositWithdrawItem({
      source,
      target,
      itemData: {
        item: itemData
      },
      gridPosition: validPosition
    });
  }
  async sortItemsOnGrid(event) {
    const mergeItems = event.ctrlKey;
    if (mergeItems) {
      const doMerge = await TJSDialog.confirm({
        title: "Item Piles",
        content: {
          class: CustomDialog,
          props: {
            header: game.i18n.localize("ITEM-PILES.Dialogs.SortMergeVaultItems.Title"),
            content: game.i18n.localize("ITEM-PILES.Dialogs.SortMergeVaultItems.Content")
          }
        },
        modal: true
      });
      if (!doMerge)
        return;
    }
    const gridItems = get_store_value(this.gridItems).map((item) => item.item).sort((a, b) => {
      return b.size - a.size;
    }).map((item) => item.item);
    const result = fitItemsIntoVault(gridItems, this.actor, { existingItems: [], mergeItems });
    if (!result)
      return custom_warning("ITEM-PILES.Warnings.CantSortVault", true);
    const { updates, deletions } = result;
    const itemUpdates = updates.map((item) => ({
      _id: item._id,
      [game.itempiles.API.ITEM_QUANTITY_ATTRIBUTE]: getItemQuantity(item),
      [CONSTANTS.FLAGS.ITEM]: cleanItemFlagData(getItemFlagData(item))
    }));
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.COMMIT_ACTOR_CHANGES, this.actor.uuid, {
      itemsToUpdate: itemUpdates,
      itemsToDelete: deletions
    });
  }
};
__name(_VaultStore, "VaultStore");
let VaultStore = _VaultStore;
const _VaultItem = class _VaultItem extends PileItem {
  setupStores(...args) {
    super.setupStores(...args);
    this.transform = writable$1({
      x: 0,
      y: 0,
      w: 1,
      h: 1,
      flipped: false
    });
    this.ghostTransform = writable$1({
      x: 0,
      y: 0,
      w: 1,
      h: 1,
      flipped: false
    });
    this.active = writable$1(false);
    this.x = 0;
    this.y = 0;
    this.w = 1;
    this.h = 1;
    this.flipped = false;
    this.size = 1;
    this.style = writable$1({});
  }
  setupSubscriptions() {
    super.setupSubscriptions();
    let setup = false;
    this.subscribeTo(this.itemDocument, () => {
      let rarityColor = get_store_value(this.rarityColor);
      if (rarityColor) {
        this.style.set({ "box-shadow": `inset 0px 0px 7px 0px ${rarityColor}` });
      } else {
        this.style.set(SYSTEMS.DATA?.VAULT_STYLES ? SYSTEMS.DATA?.VAULT_STYLES.filter((style) => {
          return getProperty(this.item, style.path) === style.value;
        }).reduce((acc, style) => {
          return foundry.utils.mergeObject(acc, style.styling);
        }, {}) : {});
      }
    });
    this.subscribeTo(this.itemFlagData, (data2) => {
      if (setup) {
        debug("itemFlagData", data2);
      }
      const { width, height } = getVaultItemDimensions(this.item, data2);
      this.transform.set({
        x: data2.x,
        y: data2.y,
        w: width,
        h: height,
        flipped: data2.flipped ?? false
      });
      this.size = Math.max(width, height);
    });
    this.subscribeTo(this.transform, (transform) => {
      if (setup) {
        debug("transform", transform);
      }
      this.x = transform.x;
      this.y = transform.y;
      this.w = transform.w;
      this.h = transform.h;
      this.flipped = transform.flipped;
    });
    this.subscribeTo(this.quantity, () => {
      const itemFlagData = get_store_value(this.itemFlagData);
      if (!itemFlagData.vaultExpander)
        return;
      this.store.refreshFreeSpaces();
      this.store.refreshGridDebounce();
    });
    setup = true;
  }
  async take() {
    const pileData = get_store_value(this.store.pileData);
    const itemFlagData = get_store_value(this.itemFlagData);
    if (pileData.vaultExpansion && itemFlagData.vaultExpander) {
      const slotsLeft = this.store.canItemsFitWithout(this);
      if (slotsLeft < 0) {
        return TJSDialog.prompt({
          title: "Item Piles",
          content: {
            class: CustomDialog,
            props: {
              header: game.i18n.localize("ITEM-PILES.Dialogs.CantRemoveVaultExpander.Title"),
              content: game.i18n.format("ITEM-PILES.Dialogs.CantRemoveVaultExpander.Content", {
                num_items: Math.abs(slotsLeft)
              })
            }
          },
          modal: true
        });
      }
    }
    let quantity = get_store_value(this.quantity);
    if (quantity > 1) {
      quantity = await DropItemDialog.show(this.item, this.store.actor, {
        localizationTitle: "WithdrawItem"
      });
    }
    return game.itempiles.API.transferItems(this.store.actor, this.store.recipient, [{
      _id: this.id,
      quantity
    }], { interactionId: this.store.interactionId });
  }
  async split(x, y, flipped) {
    let quantity = await DropItemDialog.show(this.item, this.store.actor, {
      localizationTitle: "SplitItem",
      quantityAdjustment: -1
    });
    await game.itempiles.API.removeItems(this.store.actor, [{
      _id: this.id,
      quantity
    }], { interactionId: this.store.interactionId });
    const itemData = this.item.toObject();
    const flags = getItemFlagData(this.item);
    itemData._id = randomID();
    setProperty(flags, "x", x);
    setProperty(flags, "y", y);
    setProperty(flags, "flipped", flipped);
    setProperty(itemData, "flags", flags);
    await game.itempiles.API.addItems(this.store.actor, [{
      item: itemData,
      quantity
    }], { interactionId: this.store.interactionId, skipVaultLogging: true });
  }
  async merge(itemToMerge) {
    const itemDelta = await game.itempiles.API.removeItems(this.store.actor, [{
      _id: itemToMerge.id
    }], {
      interactionId: this.store.interactionId,
      skipVaultLogging: true
    });
    return game.itempiles.API.addItems(this.store.actor, [{
      id: this.id,
      quantity: Math.abs(itemDelta[0].quantity)
    }], {
      interactionId: this.store.interactionId,
      skipVaultLogging: true
    });
  }
  areItemsSimilar(itemToCompare) {
    return !areItemsDifferent(this.item, itemToCompare.item) && canItemStack(itemToCompare.item, this.store.actor);
  }
};
__name(_VaultItem, "VaultItem");
let VaultItem = _VaultItem;
const VaultExpanderEntry_svelte_svelte_type_style_lang = "";
function create_if_block_1$e(ctx) {
  let span;
  let t0;
  let t1;
  let t2;
  return {
    c() {
      span = element("span");
      t0 = text("(x");
      t1 = text(
        /*$quantity*/
        ctx[4]
      );
      t2 = text(")");
      attr(span, "class", "item-piles-small-text");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t0);
      append(span, t1);
      append(span, t2);
    },
    p(ctx2, dirty) {
      if (dirty & /*$quantity*/
      16)
        set_data(
          t1,
          /*$quantity*/
          ctx2[4]
        );
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_if_block_1$e, "create_if_block_1$e");
function create_else_block$a(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = `${localize("Remove")}`;
      attr(button, "class", "item-piles-item-take-button");
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[13]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$a, "create_else_block$a");
function create_if_block$m(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = `${localize("ITEM-PILES.Inspect.Take")}`;
      attr(button, "class", "item-piles-item-take-button");
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$m, "create_if_block$m");
function create_fragment$D(ctx) {
  let div3;
  let div0;
  let img_1;
  let img_1_src_value;
  let t0;
  let div2;
  let div1;
  let p;
  let t1;
  let t2;
  let t3;
  let span;
  let t4_value = (
    /*$itemFlagData*/
    (ctx[5].addsCols ? localize("ITEM-PILES.Vault.ExpandsCols", { cols: (
      /*$itemFlagData*/
      ctx[5].addsCols
    ) }) : "") + /*$itemFlagData*/
    (ctx[5].addsCols && /*$itemFlagData*/
    ctx[5].addsRows ? ", " : "") + /*$itemFlagData*/
    (ctx[5].addsRows ? localize("ITEM-PILES.Vault.ExpandsRows", { rows: (
      /*$itemFlagData*/
      ctx[5].addsRows
    ) }) : "")
  );
  let t4;
  let t5;
  let if_block0 = !/*$editQuantities*/
  ctx[3] && /*item*/
  ctx[0].canStack && create_if_block_1$e(ctx);
  function select_block_type(ctx2, dirty) {
    if (!/*$editQuantities*/
    ctx2[3])
      return create_if_block$m;
    return create_else_block$a;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block1 = current_block_type(ctx);
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      img_1 = element("img");
      t0 = space();
      div2 = element("div");
      div1 = element("div");
      p = element("p");
      t1 = text(
        /*$name*/
        ctx[2]
      );
      t2 = space();
      if (if_block0)
        if_block0.c();
      t3 = space();
      span = element("span");
      t4 = text(t4_value);
      t5 = space();
      if_block1.c();
      attr(img_1, "class", "item-piles-img");
      if (!src_url_equal(img_1.src, img_1_src_value = /*$img*/
      ctx[1]))
        attr(img_1, "src", img_1_src_value);
      attr(div0, "class", "item-piles-img-container");
      attr(span, "class", "item-piles-small-text");
      attr(div1, "class", "item-piles-name-container");
      attr(div2, "class", "item-piles-name svelte-1djj85e");
      attr(div3, "class", "item-piles-flexrow item-piles-item-row item-piles-even-color svelte-1djj85e");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, img_1);
      append(div3, t0);
      append(div3, div2);
      append(div2, div1);
      append(div1, p);
      append(p, t1);
      append(div1, t2);
      if (if_block0)
        if_block0.m(div1, null);
      append(div1, t3);
      append(div1, span);
      append(span, t4);
      append(div3, t5);
      if_block1.m(div3, null);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*$img*/
      2 && !src_url_equal(img_1.src, img_1_src_value = /*$img*/
      ctx2[1])) {
        attr(img_1, "src", img_1_src_value);
      }
      if (dirty & /*$name*/
      4)
        set_data(
          t1,
          /*$name*/
          ctx2[2]
        );
      if (!/*$editQuantities*/
      ctx2[3] && /*item*/
      ctx2[0].canStack) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_1$e(ctx2);
          if_block0.c();
          if_block0.m(div1, t3);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty & /*$itemFlagData*/
      32 && t4_value !== (t4_value = /*$itemFlagData*/
      (ctx2[5].addsCols ? localize("ITEM-PILES.Vault.ExpandsCols", { cols: (
        /*$itemFlagData*/
        ctx2[5].addsCols
      ) }) : "") + /*$itemFlagData*/
      (ctx2[5].addsCols && /*$itemFlagData*/
      ctx2[5].addsRows ? ", " : "") + /*$itemFlagData*/
      (ctx2[5].addsRows ? localize("ITEM-PILES.Vault.ExpandsRows", { rows: (
        /*$itemFlagData*/
        ctx2[5].addsRows
      ) }) : "")))
        set_data(t4, t4_value);
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block1) {
        if_block1.p(ctx2, dirty);
      } else {
        if_block1.d(1);
        if_block1 = current_block_type(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div3, null);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div3);
      if (if_block0)
        if_block0.d();
      if_block1.d();
    }
  };
}
__name(create_fragment$D, "create_fragment$D");
function instance$A($$self, $$props, $$invalidate) {
  let $img;
  let $name;
  let $editQuantities;
  let $quantity;
  let $itemFlagData;
  let { store } = $$props;
  let { item } = $$props;
  const name = item.name;
  component_subscribe($$self, name, (value) => $$invalidate(2, $name = value));
  const img = item.img;
  component_subscribe($$self, img, (value) => $$invalidate(1, $img = value));
  const quantity = item.quantity;
  component_subscribe($$self, quantity, (value) => $$invalidate(4, $quantity = value));
  const itemFlagData = item.itemFlagData;
  component_subscribe($$self, itemFlagData, (value) => $$invalidate(5, $itemFlagData = value));
  store.pileData;
  const editQuantities = store.editQuantities;
  component_subscribe($$self, editQuantities, (value) => $$invalidate(3, $editQuantities = value));
  const click_handler = /* @__PURE__ */ __name(() => {
    item.take();
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    item.remove();
  }, "click_handler_1");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(11, store = $$props2.store);
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
  };
  return [
    item,
    $img,
    $name,
    $editQuantities,
    $quantity,
    $itemFlagData,
    name,
    img,
    quantity,
    itemFlagData,
    editQuantities,
    store,
    click_handler,
    click_handler_1
  ];
}
__name(instance$A, "instance$A");
const _VaultExpanderEntry = class _VaultExpanderEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$A, create_fragment$D, safe_not_equal, { store: 11, item: 0 });
  }
};
__name(_VaultExpanderEntry, "VaultExpanderEntry");
let VaultExpanderEntry = _VaultExpanderEntry;
const FloatingElementImpl_svelte_svelte_type_style_lang = "";
function create_fragment$C(ctx) {
  let div;
  let switch_instance;
  let current;
  const switch_instance_spread_levels = [
    /*componentData*/
    ctx[3]
  ];
  var switch_value = (
    /*component*/
    ctx[2]
  );
  function switch_props(ctx2) {
    let switch_instance_props = {};
    for (let i = 0; i < switch_instance_spread_levels.length; i += 1) {
      switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]);
    }
    return { props: switch_instance_props };
  }
  __name(switch_props, "switch_props");
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  return {
    c() {
      div = element("div");
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      attr(div, "class", "item-piles-floting-element svelte-nb4ghy");
      attr(
        div,
        "style",
        /*elementStyle*/
        ctx[4]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (switch_instance)
        mount_component(switch_instance, div, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      const switch_instance_changes = dirty & /*componentData*/
      8 ? get_spread_update(switch_instance_spread_levels, [get_spread_object(
        /*componentData*/
        ctx2[3]
      )]) : {};
      if (dirty & /*component*/
      4 && switch_value !== (switch_value = /*component*/
      ctx2[2])) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, div, null);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
      if (!current || dirty & /*elementStyle*/
      16) {
        attr(
          div,
          "style",
          /*elementStyle*/
          ctx2[4]
        );
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (switch_instance)
        destroy_component(switch_instance);
    }
  };
}
__name(create_fragment$C, "create_fragment$C");
function instance$z($$self, $$props, $$invalidate) {
  let elementStyle;
  let $style, $$unsubscribe_style = noop, $$subscribe_style = /* @__PURE__ */ __name(() => ($$unsubscribe_style(), $$unsubscribe_style = subscribe(style, ($$value) => $$invalidate(7, $style = $$value)), style), "$$subscribe_style");
  let $position, $$unsubscribe_position = noop, $$subscribe_position = /* @__PURE__ */ __name(() => ($$unsubscribe_position(), $$unsubscribe_position = subscribe(position, ($$value) => $$invalidate(8, $position = $$value)), position), "$$subscribe_position");
  $$self.$$.on_destroy.push(() => $$unsubscribe_style());
  $$self.$$.on_destroy.push(() => $$unsubscribe_position());
  let { position } = $$props;
  $$subscribe_position();
  let { zIndex } = $$props;
  let { style } = $$props;
  $$subscribe_style();
  let { context } = $$props;
  let { component } = $$props;
  let { componentData } = $$props;
  for (const [key, ctx] of Object.entries(context)) {
    setContext(key, ctx);
  }
  $$self.$$set = ($$props2) => {
    if ("position" in $$props2)
      $$subscribe_position($$invalidate(0, position = $$props2.position));
    if ("zIndex" in $$props2)
      $$invalidate(5, zIndex = $$props2.zIndex);
    if ("style" in $$props2)
      $$subscribe_style($$invalidate(1, style = $$props2.style));
    if ("context" in $$props2)
      $$invalidate(6, context = $$props2.context);
    if ("component" in $$props2)
      $$invalidate(2, component = $$props2.component);
    if ("componentData" in $$props2)
      $$invalidate(3, componentData = $$props2.componentData);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$position, zIndex, $style*/
    416) {
      $$invalidate(4, elementStyle = styleFromObject({
        "left": $position.x + "px",
        "top": $position.y + "px",
        "z-index": zIndex,
        ...$style
      }));
    }
  };
  return [
    position,
    style,
    component,
    componentData,
    elementStyle,
    zIndex,
    context,
    $style,
    $position
  ];
}
__name(instance$z, "instance$z");
const _FloatingElementImpl = class _FloatingElementImpl extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$z, create_fragment$C, safe_not_equal, {
      position: 0,
      zIndex: 5,
      style: 1,
      context: 6,
      component: 2,
      componentData: 3
    });
  }
};
__name(_FloatingElementImpl, "FloatingElementImpl");
let FloatingElementImpl = _FloatingElementImpl;
const _FloatingElement = class _FloatingElement {
  static create({ id, x, y, zIndex = Number.MAX_SAFE_INTEGER - 100, style = {}, context = {}, component, componentData } = {}) {
    if (this.element)
      return this.element;
    this.positionStore.set({ x, y });
    this.styleStore.set(style);
    this.id = id;
    this.element = new FloatingElementImpl({
      target: document.body,
      props: {
        position: this.positionStore,
        style: this.styleStore,
        zIndex,
        component,
        componentData,
        context
      }
    });
  }
  static destroy() {
    this.element.$destroy();
    this.element = void 0;
    this.id = void 0;
    this.positionStore.set(false);
    this.styleStore.set({});
  }
};
__name(_FloatingElement, "FloatingElement");
__publicField(_FloatingElement, "id");
__publicField(_FloatingElement, "element");
__publicField(_FloatingElement, "positionStore", writable$1(false));
__publicField(_FloatingElement, "styleStore", writable$1({}));
let FloatingElement = _FloatingElement;
const vaultShell_svelte_svelte_type_style_lang = "";
function get_each_context$j(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[68] = list[i];
  child_ctx[70] = i;
  return child_ctx;
}
__name(get_each_context$j, "get_each_context$j");
function get_each_context_1$9(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[71] = list[i];
  child_ctx[72] = list;
  child_ctx[73] = i;
  return child_ctx;
}
__name(get_each_context_1$9, "get_each_context_1$9");
function create_if_block_11$1(ctx) {
  let tabs;
  let updating_activeTab;
  let current;
  function tabs_activeTab_binding(value) {
    ctx[46](value);
  }
  __name(tabs_activeTab_binding, "tabs_activeTab_binding");
  let tabs_props = {
    tabs: [
      {
        value: "vault",
        label: "ITEM-PILES.Vault.VaultTab",
        icon: "fas fa-vault"
      },
      {
        value: "expanders",
        label: "ITEM-PILES.Vault.ExpandersTab",
        icon: "fas fa-maximize",
        hidden: !/*pileData*/
        ctx[5].vaultExpansion || !/*gridData*/
        ctx[4].fullAccess
      },
      {
        value: "log",
        label: "ITEM-PILES.Vault.LogTab",
        icon: "fas fa-note-sticky",
        hidden: !/*pileData*/
        ctx[5].logVaultActions || !/*gridData*/
        ctx[4].fullAccess
      }
    ],
    style: "flex: 0 1 auto; margin-bottom: 0.5rem; padding-bottom: 0.5rem;"
  };
  if (
    /*$activeTab*/
    ctx[2] !== void 0
  ) {
    tabs_props.activeTab = /*$activeTab*/
    ctx[2];
  }
  tabs = new Tabs({ props: tabs_props });
  binding_callbacks.push(() => bind(tabs, "activeTab", tabs_activeTab_binding));
  return {
    c() {
      create_component(tabs.$$.fragment);
    },
    m(target, anchor) {
      mount_component(tabs, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const tabs_changes = {};
      if (dirty[0] & /*pileData, gridData*/
      48)
        tabs_changes.tabs = [
          {
            value: "vault",
            label: "ITEM-PILES.Vault.VaultTab",
            icon: "fas fa-vault"
          },
          {
            value: "expanders",
            label: "ITEM-PILES.Vault.ExpandersTab",
            icon: "fas fa-maximize",
            hidden: !/*pileData*/
            ctx2[5].vaultExpansion || !/*gridData*/
            ctx2[4].fullAccess
          },
          {
            value: "log",
            label: "ITEM-PILES.Vault.LogTab",
            icon: "fas fa-note-sticky",
            hidden: !/*pileData*/
            ctx2[5].logVaultActions || !/*gridData*/
            ctx2[4].fullAccess
          }
        ];
      if (!updating_activeTab && dirty[0] & /*$activeTab*/
      4) {
        updating_activeTab = true;
        tabs_changes.activeTab = /*$activeTab*/
        ctx2[2];
        add_flush_callback(() => updating_activeTab = false);
      }
      tabs.$set(tabs_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tabs.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tabs.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(tabs, detaching);
    }
  };
}
__name(create_if_block_11$1, "create_if_block_11$1");
function create_if_block_4$8(ctx) {
  let div0;
  let label;
  let t1;
  let input;
  let t2;
  let dropzone;
  let t3;
  let t4;
  let div1;
  let t5;
  let currencylist;
  let current;
  let mounted;
  let dispose;
  dropzone = new DropZone({
    props: {
      callback: (
        /*func*/
        ctx[51]
      ),
      overCallback: (
        /*onDragOverEvent*/
        ctx[28]
      ),
      leaveCallback: (
        /*onDragLeave*/
        ctx[29]
      ),
      style: "display: flex; flex: 1; justify-content: center; align-items: center;",
      $$slots: { default: [create_default_slot_3] },
      $$scope: { ctx }
    }
  });
  let if_block0 = (
    /*$recipientDocument*/
    ctx[9]?.name && create_if_block_7$3(ctx)
  );
  let if_block1 = (
    /*gridData*/
    ctx[4].canOrganize && create_if_block_6$4(ctx)
  );
  currencylist = new CurrencyList$1({
    props: {
      currencies: (
        /*currencies*/
        ctx[16]
      ),
      options: {
        abbreviations: false,
        imgSize: 18,
        abbreviateNumbers: true
      },
      style: "align-items: center;",
      $$slots: { default: [create_default_slot_2] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      div0 = element("div");
      label = element("label");
      label.textContent = "Search:";
      t1 = space();
      input = element("input");
      t2 = space();
      create_component(dropzone.$$.fragment);
      t3 = space();
      if (if_block0)
        if_block0.c();
      t4 = space();
      div1 = element("div");
      if (if_block1)
        if_block1.c();
      t5 = space();
      create_component(currencylist.$$.fragment);
      set_style(label, "flex", "0 1 auto");
      set_style(label, "margin-right", "5px");
      attr(input, "type", "text");
      attr(div0, "class", "form-group item-piles-flexrow item-piles-bottom-divider");
      set_style(div0, "margin", "0.25rem 0");
      set_style(div0, "align-items", "center");
      set_style(div0, "flex", "0 1 auto");
      attr(div1, "class", "item-piles-flexrow");
      set_style(div1, "margin-top", "0.25rem");
      set_style(div1, "flex", "0 1 auto");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, label);
      append(div0, t1);
      append(div0, input);
      set_input_value(
        input,
        /*$searchStore*/
        ctx[6]
      );
      insert(target, t2, anchor);
      mount_component(dropzone, target, anchor);
      insert(target, t3, anchor);
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t4, anchor);
      insert(target, div1, anchor);
      if (if_block1)
        if_block1.m(div1, null);
      append(div1, t5);
      mount_component(currencylist, div1, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler*/
          ctx[47]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$searchStore*/
      64 && input.value !== /*$searchStore*/
      ctx2[6]) {
        set_input_value(
          input,
          /*$searchStore*/
          ctx2[6]
        );
      }
      const dropzone_changes = {};
      if (dirty[0] & /*store*/
      2)
        dropzone_changes.callback = /*func*/
        ctx2[51];
      if (dirty[0] & /*gridData, $searchStore, $dragPositionStore, $gridItems, element, store*/
      474 | dirty[2] & /*$$scope*/
      4096) {
        dropzone_changes.$$scope = { dirty, ctx: ctx2 };
      }
      dropzone.$set(dropzone_changes);
      if (
        /*$recipientDocument*/
        ctx2[9]?.name
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_7$3(ctx2);
          if_block0.c();
          if_block0.m(t4.parentNode, t4);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*gridData*/
        ctx2[4].canOrganize
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_6$4(ctx2);
          if_block1.c();
          if_block1.m(div1, t5);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      const currencylist_changes = {};
      if (dirty[0] & /*store, gridData*/
      18 | dirty[2] & /*$$scope*/
      4096) {
        currencylist_changes.$$scope = { dirty, ctx: ctx2 };
      }
      currencylist.$set(currencylist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dropzone.$$.fragment, local);
      transition_in(currencylist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropzone.$$.fragment, local);
      transition_out(currencylist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t2);
      destroy_component(dropzone, detaching);
      if (detaching)
        detach(t3);
      if (if_block0)
        if_block0.d(detaching);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(div1);
      if (if_block1)
        if_block1.d();
      destroy_component(currencylist);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$8, "create_if_block_4$8");
function create_default_slot_4(ctx) {
  let vaultitementry;
  let current;
  vaultitementry = new VaultItemEntry({ props: { entry: (
    /*item*/
    ctx[71]
  ) } });
  return {
    c() {
      create_component(vaultitementry.$$.fragment);
    },
    m(target, anchor) {
      mount_component(vaultitementry, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const vaultitementry_changes = {};
      if (dirty[2] & /*item*/
      512)
        vaultitementry_changes.entry = /*item*/
        ctx2[71];
      vaultitementry.$set(vaultitementry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(vaultitementry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(vaultitementry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(vaultitementry, detaching);
    }
  };
}
__name(create_default_slot_4, "create_default_slot_4");
function create_default_slot_3(ctx) {
  let grid;
  let updating_items;
  let updating_gridContainer;
  let current;
  function grid_items_binding(value) {
    ctx[48](value);
  }
  __name(grid_items_binding, "grid_items_binding");
  function grid_gridContainer_binding(value) {
    ctx[49](value);
  }
  __name(grid_gridContainer_binding, "grid_gridContainer_binding");
  let grid_props = {
    options: {
      .../*gridData*/
      ctx[4],
      class: "item-piles-grid-background",
      activeClass: "item-piles-grid-item-active",
      previewClass: "item-piles-grid-item-preview",
      collisionClass: "item-piles-grid-item-collision",
      invalidCollisionClass: "item-piles-grid-item-invalid-collision",
      hoverClass: "item-piles-grid-item-hover",
      highlightClass: "item-piles-grid-item-highlight",
      invalidPlacementClass: "item-piles-grid-item-invalid",
      dimClass: "item-piles-grid-item-dim",
      backgroundGrid: true,
      highlightItems: !!/*$searchStore*/
      ctx[6]
    },
    dropGhost: (
      /*$dragPositionStore*/
      ctx[8]
    ),
    $$slots: {
      default: [
        create_default_slot_4,
        ({ item }) => ({ 71: item }),
        ({ item }) => [0, 0, item ? 512 : 0]
      ]
    },
    $$scope: { ctx }
  };
  if (
    /*$gridItems*/
    ctx[7] !== void 0
  ) {
    grid_props.items = /*$gridItems*/
    ctx[7];
  }
  if (
    /*element*/
    ctx[3] !== void 0
  ) {
    grid_props.gridContainer = /*element*/
    ctx[3];
  }
  grid = new Grid({ props: grid_props });
  binding_callbacks.push(() => bind(grid, "items", grid_items_binding));
  binding_callbacks.push(() => bind(grid, "gridContainer", grid_gridContainer_binding));
  grid.$on(
    "change",
    /*change_handler*/
    ctx[50]
  );
  grid.$on(
    "itembegindrag",
    /*itemBeginDrag*/
    ctx[32]
  );
  grid.$on(
    "itemstopdrag",
    /*itemStopDrag*/
    ctx[33]
  );
  grid.$on(
    "itemmove",
    /*itemMove*/
    ctx[34]
  );
  grid.$on(
    "rightclick",
    /*rightClickItem*/
    ctx[31]
  );
  grid.$on(
    "doubleclick",
    /*doubleClickItem*/
    ctx[30]
  );
  grid.$on(
    "itemflipped",
    /*itemFlipped*/
    ctx[35]
  );
  return {
    c() {
      create_component(grid.$$.fragment);
    },
    m(target, anchor) {
      mount_component(grid, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const grid_changes = {};
      if (dirty[0] & /*gridData, $searchStore*/
      80)
        grid_changes.options = {
          .../*gridData*/
          ctx2[4],
          class: "item-piles-grid-background",
          activeClass: "item-piles-grid-item-active",
          previewClass: "item-piles-grid-item-preview",
          collisionClass: "item-piles-grid-item-collision",
          invalidCollisionClass: "item-piles-grid-item-invalid-collision",
          hoverClass: "item-piles-grid-item-hover",
          highlightClass: "item-piles-grid-item-highlight",
          invalidPlacementClass: "item-piles-grid-item-invalid",
          dimClass: "item-piles-grid-item-dim",
          backgroundGrid: true,
          highlightItems: !!/*$searchStore*/
          ctx2[6]
        };
      if (dirty[0] & /*$dragPositionStore*/
      256)
        grid_changes.dropGhost = /*$dragPositionStore*/
        ctx2[8];
      if (dirty[2] & /*$$scope, item*/
      4608) {
        grid_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_items && dirty[0] & /*$gridItems*/
      128) {
        updating_items = true;
        grid_changes.items = /*$gridItems*/
        ctx2[7];
        add_flush_callback(() => updating_items = false);
      }
      if (!updating_gridContainer && dirty[0] & /*element*/
      8) {
        updating_gridContainer = true;
        grid_changes.gridContainer = /*element*/
        ctx2[3];
        add_flush_callback(() => updating_gridContainer = false);
      }
      grid.$set(grid_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(grid.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(grid.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(grid, detaching);
    }
  };
}
__name(create_default_slot_3, "create_default_slot_3");
function create_if_block_7$3(ctx) {
  let div;
  let span;
  let a;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Vault.ViewingAs", {
    actor_name: (
      /*$recipientDocument*/
      ctx[9].name
    )
  }) + "";
  let t1;
  let t2;
  let mounted;
  let dispose;
  let if_block = (
    /*gridData*/
    (ctx[4].canDepositCurrencies || /*gridData*/
    ctx[4].canWithdrawCurrencies) && create_if_block_8$1(ctx)
  );
  return {
    c() {
      div = element("div");
      span = element("span");
      a = element("a");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      t2 = space();
      if (if_block)
        if_block.c();
      attr(i, "class", "fa-solid fa-suitcase");
      attr(div, "class", "item-piles-flexrow item-piles-top-divider");
      set_style(div, "flex", "0 1 auto");
      set_style(div, "align-items", "center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      append(span, a);
      append(a, i);
      append(a, t0);
      append(a, t1);
      append(div, t2);
      if (if_block)
        if_block.m(div, null);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[52]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$recipientDocument*/
      512 && t1_value !== (t1_value = localize("ITEM-PILES.Vault.ViewingAs", {
        actor_name: (
          /*$recipientDocument*/
          ctx2[9].name
        )
      }) + ""))
        set_data(t1, t1_value);
      if (
        /*gridData*/
        ctx2[4].canDepositCurrencies || /*gridData*/
        ctx2[4].canWithdrawCurrencies
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_8$1(ctx2);
          if_block.c();
          if_block.m(div, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_7$3, "create_if_block_7$3");
function create_if_block_8$1(ctx) {
  let div;
  let t;
  let if_block0 = (
    /*gridData*/
    ctx[4].canWithdrawCurrencies && create_if_block_10$1(ctx)
  );
  let if_block1 = (
    /*gridData*/
    ctx[4].canDepositCurrencies && create_if_block_9$1(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t = space();
      if (if_block1)
        if_block1.c();
      set_style(div, "flex", "0 1 auto");
      set_style(div, "justify-self", "flex-end");
      set_style(div, "display", "flex");
      set_style(div, "justify-content", "flex-end");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t);
      if (if_block1)
        if_block1.m(div, null);
    },
    p(ctx2, dirty) {
      if (
        /*gridData*/
        ctx2[4].canWithdrawCurrencies
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_10$1(ctx2);
          if_block0.c();
          if_block0.m(div, t);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*gridData*/
        ctx2[4].canDepositCurrencies
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_9$1(ctx2);
          if_block1.c();
          if_block1.m(div, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
    }
  };
}
__name(create_if_block_8$1, "create_if_block_8$1");
function create_if_block_10$1(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = `${localize("ITEM-PILES.Vault.Withdraw")}`;
      attr(button, "type", "button");
      attr(button, "class", "item-piles-small-button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[53]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_10$1, "create_if_block_10$1");
function create_if_block_9$1(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = `${localize("ITEM-PILES.Vault.Deposit")}`;
      attr(button, "type", "button");
      attr(button, "class", "item-piles-small-button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_2*/
          ctx[54]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_9$1, "create_if_block_9$1");
function create_if_block_6$4(ctx) {
  let div;
  let button;
  let t_value = localize("ITEM-PILES.Vault.SortItems") + "";
  let t;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      button = element("button");
      t = text(t_value);
      attr(button, "type", "button");
      attr(button, "class", "item-piles-small-button");
      attr(button, "data-tooltip", localize("ITEM-PILES.Vault.SortItemsTooltip"));
      set_style(div, "flex", "0 1 auto");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button);
      append(button, t);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_3*/
          ctx[55]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_6$4, "create_if_block_6$4");
function create_if_block_5$5(ctx) {
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.innerHTML = `<i class="fas fa-cog"></i>`;
      set_style(a, "order", "100");
      set_style(a, "display", "flex");
      set_style(a, "flex", "0");
      set_style(a, "margin-left", "0.25rem");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler_4*/
          ctx[56]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_5$5, "create_if_block_5$5");
function create_default_slot_2(ctx) {
  let if_block_anchor;
  let if_block = (
    /*gridData*/
    ctx[4].canEditCurrencies && create_if_block_5$5(ctx)
  );
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (
        /*gridData*/
        ctx2[4].canEditCurrencies
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_5$5(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_default_slot_2, "create_default_slot_2");
function create_if_block_2$9(ctx) {
  let dropzone;
  let current;
  dropzone = new DropZone({
    props: {
      callback: (
        /*func_1*/
        ctx[58]
      ),
      style: "display: flex; flex-direction: column; flex:1;",
      $$slots: { default: [create_default_slot_1$1] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(dropzone.$$.fragment);
    },
    m(target, anchor) {
      mount_component(dropzone, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const dropzone_changes = {};
      if (dirty[0] & /*store*/
      2)
        dropzone_changes.callback = /*func_1*/
        ctx2[58];
      if (dirty[0] & /*$vaultExpanderItems, store, gridData*/
      1042 | dirty[2] & /*$$scope*/
      4096) {
        dropzone_changes.$$scope = { dirty, ctx: ctx2 };
      }
      dropzone.$set(dropzone_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dropzone.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropzone.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(dropzone, detaching);
    }
  };
}
__name(create_if_block_2$9, "create_if_block_2$9");
function create_each_block_1$9(key_1, ctx) {
  let first;
  let vaultexpanderentry;
  let updating_item;
  let current;
  function vaultexpanderentry_item_binding(value) {
    ctx[57](
      value,
      /*item*/
      ctx[71],
      /*each_value_1*/
      ctx[72],
      /*item_index*/
      ctx[73]
    );
  }
  __name(vaultexpanderentry_item_binding, "vaultexpanderentry_item_binding");
  let vaultexpanderentry_props = { store: (
    /*store*/
    ctx[1]
  ) };
  if (
    /*item*/
    ctx[71] !== void 0
  ) {
    vaultexpanderentry_props.item = /*item*/
    ctx[71];
  }
  vaultexpanderentry = new VaultExpanderEntry({ props: vaultexpanderentry_props });
  binding_callbacks.push(() => bind(vaultexpanderentry, "item", vaultexpanderentry_item_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(vaultexpanderentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(vaultexpanderentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const vaultexpanderentry_changes = {};
      if (dirty[0] & /*store*/
      2)
        vaultexpanderentry_changes.store = /*store*/
        ctx[1];
      if (!updating_item && dirty[0] & /*$vaultExpanderItems*/
      1024) {
        updating_item = true;
        vaultexpanderentry_changes.item = /*item*/
        ctx[71];
        add_flush_callback(() => updating_item = false);
      }
      vaultexpanderentry.$set(vaultexpanderentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(vaultexpanderentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(vaultexpanderentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(vaultexpanderentry, detaching);
    }
  };
}
__name(create_each_block_1$9, "create_each_block_1$9");
function create_if_block_3$8(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.innerHTML = `<i>Drag and drop items to expand spaces</i>`;
      set_style(div, "flex", "1 0 auto");
      set_style(div, "display", "flex");
      set_style(div, "align-items", "center");
      set_style(div, "place-content", "center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_3$8, "create_if_block_3$8");
function create_default_slot_1$1(ctx) {
  let div0;
  let raw_value = localize(
    "ITEM-PILES.Vault." + /*gridData*/
    (ctx[4].totalSpaces === /*gridData*/
    ctx[4].enabledSpaces ? "CapacityFull" : (
      /*gridData*/
      ctx[4].enabledSpaces ? "CapacityLeft" : "NeedsCapacity"
    )),
    {
      total_capacity: `<strong>${/*gridData*/
      ctx[4].totalSpaces}</strong>`,
      capacity: `<strong>${/*gridData*/
      ctx[4].enabledSpaces}</strong>`
    }
  ) + "";
  let t0;
  let div1;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t1;
  let if_block_anchor;
  let current;
  let each_value_1 = (
    /*$vaultExpanderItems*/
    ctx[10]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[71].id
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$9(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$9(key, child_ctx));
  }
  let if_block = !/*$vaultExpanderItems*/
  ctx[10].length && create_if_block_3$8();
  return {
    c() {
      div0 = element("div");
      t0 = space();
      div1 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t1 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      set_style(div0, "text-align", "center");
      attr(div0, "class", "item-piles-bottom-divider");
      attr(div1, "class", "item-piles-items-list");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      div0.innerHTML = raw_value;
      insert(target, t0, anchor);
      insert(target, div1, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div1, null);
        }
      }
      insert(target, t1, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if ((!current || dirty[0] & /*gridData*/
      16) && raw_value !== (raw_value = localize(
        "ITEM-PILES.Vault." + /*gridData*/
        (ctx2[4].totalSpaces === /*gridData*/
        ctx2[4].enabledSpaces ? "CapacityFull" : (
          /*gridData*/
          ctx2[4].enabledSpaces ? "CapacityLeft" : "NeedsCapacity"
        )),
        {
          total_capacity: `<strong>${/*gridData*/
          ctx2[4].totalSpaces}</strong>`,
          capacity: `<strong>${/*gridData*/
          ctx2[4].enabledSpaces}</strong>`
        }
      ) + ""))
        div0.innerHTML = raw_value;
      if (dirty[0] & /*store, $vaultExpanderItems*/
      1026) {
        each_value_1 = /*$vaultExpanderItems*/
        ctx2[10];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_1, each_1_lookup, div1, outro_and_destroy_block, create_each_block_1$9, null, get_each_context_1$9);
        check_outros();
      }
      if (!/*$vaultExpanderItems*/
      ctx2[10].length) {
        if (if_block)
          ;
        else {
          if_block = create_if_block_3$8();
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(div1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if (detaching)
        detach(t1);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_default_slot_1$1, "create_default_slot_1$1");
function create_if_block$l(ctx) {
  let div0;
  let label;
  let t1;
  let input;
  let t2;
  let div1;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t3;
  let mounted;
  let dispose;
  let each_value = (
    /*$vaultLog*/
    ctx[13].slice(
      0,
      /*$visibleLogItems*/
      ctx[14]
    ).filter(func_2)
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[70]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$j(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$j(key, child_ctx));
  }
  let if_block = (
    /*$vaultLog*/
    ctx[13].length > /*$visibleLogItems*/
    ctx[14] && create_if_block_1$d(ctx)
  );
  return {
    c() {
      div0 = element("div");
      label = element("label");
      label.textContent = "Log search:";
      t1 = space();
      input = element("input");
      t2 = space();
      div1 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t3 = space();
      if (if_block)
        if_block.c();
      set_style(label, "flex", "0 1 auto");
      set_style(label, "margin-right", "5px");
      attr(input, "type", "text");
      attr(div0, "class", "form-group item-piles-flexrow item-piles-bottom-divider");
      set_style(div0, "margin", "0.25rem 0");
      set_style(div0, "align-items", "center");
      set_style(div0, "flex", "0 1 auto");
      attr(div1, "class", "item-piles-vault-log");
      set_style(
        div1,
        "max-height",
        /*$applicationHeight*/
        ctx[12] - 130 + "px"
      );
      set_style(div1, "overflow-y", "scroll");
      set_style(div1, "font-size", "0.75rem");
      set_style(div1, "padding-right", "0.5rem");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, label);
      append(div0, t1);
      append(div0, input);
      set_input_value(
        input,
        /*$logSearchStore*/
        ctx[11]
      );
      insert(target, t2, anchor);
      insert(target, div1, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div1, null);
        }
      }
      append(div1, t3);
      if (if_block)
        if_block.m(div1, null);
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler_1*/
          ctx[59]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$logSearchStore*/
      2048 && input.value !== /*$logSearchStore*/
      ctx2[11]) {
        set_input_value(
          input,
          /*$logSearchStore*/
          ctx2[11]
        );
      }
      if (dirty[0] & /*$vaultLog, $visibleLogItems*/
      24576) {
        each_value = /*$vaultLog*/
        ctx2[13].slice(
          0,
          /*$visibleLogItems*/
          ctx2[14]
        ).filter(func_2);
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div1, destroy_block, create_each_block$j, t3, get_each_context$j);
      }
      if (
        /*$vaultLog*/
        ctx2[13].length > /*$visibleLogItems*/
        ctx2[14]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_1$d(ctx2);
          if_block.c();
          if_block.m(div1, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty[0] & /*$applicationHeight*/
      4096) {
        set_style(
          div1,
          "max-height",
          /*$applicationHeight*/
          ctx2[12] - 130 + "px"
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t2);
      if (detaching)
        detach(div1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$l, "create_if_block$l");
function create_each_block$j(key_1, ctx) {
  let div;
  let html_tag;
  let raw_value = (
    /*log*/
    ctx[68].text + ""
  );
  let t0;
  let t1_value = timeSince(
    /*log*/
    ctx[68].date
  ) + "";
  let t1;
  let t2;
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      html_tag = new HtmlTag(false);
      t0 = text(" - ");
      t1 = text(t1_value);
      t2 = text(" ago");
      html_tag.a = t0;
      toggle_class(
        div,
        "item-piles-log-deposit",
        /*log*/
        ctx[68].action === "deposited" || !/*log*/
        ctx[68].action && /*log*/
        ctx[68].qty > 0
      );
      toggle_class(
        div,
        "item-piles-log-withdrawal",
        /*log*/
        ctx[68].action === "withdrew" || !/*log*/
        ctx[68].action && /*log*/
        ctx[68].qty < 0
      );
      toggle_class(
        div,
        "item-piles-log-other",
        /*log*/
        ctx[68].action && /*log*/
        ctx[68].action !== "deposited" && /*log*/
        ctx[68].action !== "withdrew"
      );
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      html_tag.m(raw_value, div);
      append(div, t0);
      append(div, t1);
      append(div, t2);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*$vaultLog, $visibleLogItems*/
      24576 && raw_value !== (raw_value = /*log*/
      ctx[68].text + ""))
        html_tag.p(raw_value);
      if (dirty[0] & /*$vaultLog, $visibleLogItems*/
      24576 && t1_value !== (t1_value = timeSince(
        /*log*/
        ctx[68].date
      ) + ""))
        set_data(t1, t1_value);
      if (dirty[0] & /*$vaultLog, $visibleLogItems*/
      24576) {
        toggle_class(
          div,
          "item-piles-log-deposit",
          /*log*/
          ctx[68].action === "deposited" || !/*log*/
          ctx[68].action && /*log*/
          ctx[68].qty > 0
        );
      }
      if (dirty[0] & /*$vaultLog, $visibleLogItems*/
      24576) {
        toggle_class(
          div,
          "item-piles-log-withdrawal",
          /*log*/
          ctx[68].action === "withdrew" || !/*log*/
          ctx[68].action && /*log*/
          ctx[68].qty < 0
        );
      }
      if (dirty[0] & /*$vaultLog, $visibleLogItems*/
      24576) {
        toggle_class(
          div,
          "item-piles-log-other",
          /*log*/
          ctx[68].action && /*log*/
          ctx[68].action !== "deposited" && /*log*/
          ctx[68].action !== "withdrew"
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_each_block$j, "create_each_block$j");
function create_if_block_1$d(ctx) {
  let div;
  let a;
  let i;
  let t0;
  let t1;
  let t2;
  let t3_value = (
    /*$vaultLog*/
    ctx[13].length + ""
  );
  let t3;
  let t4;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      a = element("a");
      i = element("i");
      t0 = text("Load more transactions (");
      t1 = text(
        /*$visibleLogItems*/
        ctx[14]
      );
      t2 = text("\r\n							/ ");
      t3 = text(t3_value);
      t4 = text(")...");
      attr(div, "class", "item-piles-top-divider");
      set_style(div, "text-align", "center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, a);
      append(a, i);
      append(i, t0);
      append(i, t1);
      append(i, t2);
      append(i, t3);
      append(i, t4);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler_5*/
          ctx[60]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$visibleLogItems*/
      16384)
        set_data(
          t1,
          /*$visibleLogItems*/
          ctx2[14]
        );
      if (dirty[0] & /*$vaultLog*/
      8192 && t3_value !== (t3_value = /*$vaultLog*/
      ctx2[13].length + ""))
        set_data(t3, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$d, "create_if_block_1$d");
function create_default_slot$i(ctx) {
  let main;
  let t0;
  let t1;
  let t2;
  let main_intro;
  let current;
  let if_block0 = (
    /*gridData*/
    ctx[4].fullAccess && /*pileData*/
    (ctx[5].vaultExpansion || /*pileData*/
    ctx[5].logVaultActions) && create_if_block_11$1(ctx)
  );
  let if_block1 = (
    /*$activeTab*/
    ctx[2] === "vault" && create_if_block_4$8(ctx)
  );
  let if_block2 = (
    /*$activeTab*/
    ctx[2] === "expanders" && create_if_block_2$9(ctx)
  );
  let if_block3 = (
    /*$activeTab*/
    ctx[2] === "log" && create_if_block$l(ctx)
  );
  return {
    c() {
      main = element("main");
      if (if_block0)
        if_block0.c();
      t0 = space();
      if (if_block1)
        if_block1.c();
      t1 = space();
      if (if_block2)
        if_block2.c();
      t2 = space();
      if (if_block3)
        if_block3.c();
      attr(main, "class", "item-piles-flexcol svelte-1ebevu2");
    },
    m(target, anchor) {
      insert(target, main, anchor);
      if (if_block0)
        if_block0.m(main, null);
      append(main, t0);
      if (if_block1)
        if_block1.m(main, null);
      append(main, t1);
      if (if_block2)
        if_block2.m(main, null);
      append(main, t2);
      if (if_block3)
        if_block3.m(main, null);
      ctx[61](main);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*gridData*/
        ctx2[4].fullAccess && /*pileData*/
        (ctx2[5].vaultExpansion || /*pileData*/
        ctx2[5].logVaultActions)
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*gridData, pileData*/
          48) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_11$1(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(main, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*$activeTab*/
        ctx2[2] === "vault"
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*$activeTab*/
          4) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_4$8(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(main, t1);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*$activeTab*/
        ctx2[2] === "expanders"
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty[0] & /*$activeTab*/
          4) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_2$9(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(main, t2);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (
        /*$activeTab*/
        ctx2[2] === "log"
      ) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
        } else {
          if_block3 = create_if_block$l(ctx2);
          if_block3.c();
          if_block3.m(main, null);
        }
      } else if (if_block3) {
        if_block3.d(1);
        if_block3 = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      if (!main_intro) {
        add_render_callback(() => {
          main_intro = create_in_transition(main, fade, { duration: 500 });
          main_intro.start();
        });
      }
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(main);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      if (if_block3)
        if_block3.d();
      ctx[61](null);
    }
  };
}
__name(create_default_slot$i, "create_default_slot$i");
function create_fragment$B(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  let mounted;
  let dispose;
  function applicationshell_elementRoot_binding(value) {
    ctx[62](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$i] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
      if (!mounted) {
        dispose = listen(
          window,
          "keydown",
          /*keydown*/
          ctx[39]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*store, $applicationHeight, $visibleLogItems, $vaultLog, $logSearchStore, $activeTab, $vaultExpanderItems, gridData, $recipientDocument, $searchStore, $dragPositionStore, $gridItems, element, pileData*/
      32766 | dirty[2] & /*$$scope*/
      4096) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$B, "create_fragment$B");
const func_2 = /* @__PURE__ */ __name((log) => log.visible, "func_2");
function instance$y($$self, $$props, $$invalidate) {
  let pileData;
  let gridData;
  let $applicationWidth;
  let $activeTab;
  let $floatingElementPositionStore;
  let $gridDataStore;
  let $pileDataStore;
  let $searchStore;
  let $gridItems;
  let $dragPositionStore;
  let $recipientDocument;
  let $vaultExpanderItems;
  let $logSearchStore;
  let $applicationHeight;
  let $vaultLog;
  let $visibleLogItems;
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let { actor } = $$props;
  let { recipient } = $$props;
  let { store = VaultStore.make(application, actor, recipient) } = $$props;
  setContext("store", store);
  const currencies = store.allCurrencies;
  const pileDataStore = store.pileData;
  component_subscribe($$self, pileDataStore, (value) => $$invalidate(45, $pileDataStore = value));
  const gridDataStore = store.gridData;
  component_subscribe($$self, gridDataStore, (value) => $$invalidate(44, $gridDataStore = value));
  const gridItems = store.gridItems;
  component_subscribe($$self, gridItems, (value) => $$invalidate(7, $gridItems = value));
  const vaultExpanderItems = store.vaultExpanderItems;
  component_subscribe($$self, vaultExpanderItems, (value) => $$invalidate(10, $vaultExpanderItems = value));
  const searchStore = store.search;
  component_subscribe($$self, searchStore, (value) => $$invalidate(6, $searchStore = value));
  const logSearchStore = store.logSearch;
  component_subscribe($$self, logSearchStore, (value) => $$invalidate(11, $logSearchStore = value));
  const vaultLog = store.vaultLog;
  component_subscribe($$self, vaultLog, (value) => $$invalidate(13, $vaultLog = value));
  const visibleLogItems = store.visibleLogItems;
  component_subscribe($$self, visibleLogItems, (value) => $$invalidate(14, $visibleLogItems = value));
  const recipientDocument = store.recipientDocument;
  component_subscribe($$self, recipientDocument, (value) => $$invalidate(9, $recipientDocument = value));
  const dragPositionStore = store.dragPosition;
  component_subscribe($$self, dragPositionStore, (value) => $$invalidate(8, $dragPositionStore = value));
  const floatingElementPositionStore = FloatingElement.positionStore;
  component_subscribe($$self, floatingElementPositionStore, (value) => $$invalidate(43, $floatingElementPositionStore = value));
  let element2;
  function onDragOverEvent(event) {
    onDragOver(event.clientX, event.clientY, true);
  }
  __name(onDragOverEvent, "onDragOverEvent");
  async function onDragOver(clientX, clientY, offset2 = false) {
    const rect = element2.getBoundingClientRect();
    if (FloatingElement.id === application.id || !isCoordinateWithinPosition(clientX, clientY, rect)) {
      return onDragLeave();
    }
    dragPositionStore.update((data2) => {
      const x = clientX - rect.left - (offset2 ? gridData.gridSize * data2.w / 2 : gridData.gridSize / 2);
      const y = clientY - rect.top - (offset2 ? gridData.gridSize * data2.w / 2 : gridData.gridSize / 2);
      return {
        ...data2,
        ...snapOnMove(x, y, { w: data2.w, h: data2.h }, { ...gridData }),
        active: true
      };
    });
  }
  __name(onDragOver, "onDragOver");
  async function onDragLeave() {
    dragPositionStore.update((data2) => {
      return { ...data2, active: false };
    });
  }
  __name(onDragLeave, "onDragLeave");
  const dragHookId = Hooks.on(CONSTANTS.HOOKS.DRAG_DOCUMENT, async (dropData) => {
    if (dropData.type !== "Item")
      return;
    const item = await Item.implementation.fromDropData(dropData);
    const flags = getItemFlagData(item);
    const { width, height } = getVaultItemDimensions(item, flags);
    dragPositionStore.update((data2) => {
      return {
        ...data2,
        w: width,
        h: height,
        flipped: flags.flipped
      };
    });
  });
  const dropHookId = Hooks.on(CONSTANTS.HOOKS.DROP_DOCUMENT, () => {
    dragPositionStore.update((data2) => {
      return { ...data2, w: 1, h: 1, flipped: false };
    });
  });
  onDestroy(() => {
    store.onDestroy();
    Hooks.off(CONSTANTS.HOOKS.DRAG_DOCUMENT, dragHookId);
    Hooks.off(CONSTANTS.HOOKS.DROP_DOCUMENT, dropHookId);
  });
  function doubleClickItem(event) {
    if (!gridData.canWithdrawItems)
      return;
    event.detail.item.item.take();
  }
  __name(doubleClickItem, "doubleClickItem");
  function rightClickItem(event) {
    setTimeout(() => {
      const contextMenu = [];
      if (gridData.canWithdrawItems) {
        contextMenu.push({
          icon: "fas fa-hand",
          label: "Take",
          onPress: () => {
            event.detail.item.item.take();
          }
        });
      }
      const quantity = get_store_value(event.detail.item.item.quantity);
      const freeSpacesAfterSplit = gridData.freeSpaces;
      if ((gridData.canDepositItems || game.user.isGM) && event.detail.item.item.canStack && quantity > 1 && freeSpacesAfterSplit) {
        contextMenu.push({
          icon: "fas fa-object-ungroup",
          label: "Split",
          onPress: () => {
            beginSplitItem(event);
          }
        });
      }
      if (pileData.canInspectItems || game.user.isGM) {
        contextMenu.push({
          icon: "fas fa-eye",
          label: "Inspect",
          onPress: () => {
            event.detail.item.item.preview();
          }
        });
      }
      Hooks.call(CONSTANTS.HOOKS.PILE.PRE_RIGHT_CLICK_ITEM, event.detail.item.item.item, contextMenu, actor, store.recipient);
      if (!contextMenu.length)
        return;
      TJSContextMenu.create({
        x: event.detail.x,
        y: event.detail.y,
        zIndex: 1e12,
        transitionOptions: { duration: 0 },
        items: contextMenu
      });
    });
  }
  __name(rightClickItem, "rightClickItem");
  function beginSplitItem(event) {
    const { item, splitStart, x, y } = event.detail;
    const { w, h } = item.item;
    FloatingElement.create({
      id: application.id,
      x,
      y,
      style: {
        width: coordinate2size(w, gridData.gridSize, gridData.gap) + "px",
        height: coordinate2size(h, gridData.gridSize, gridData.gap) + "px",
        opacity: 0.7
      },
      component: VaultItemEntry,
      componentData: { entry: item },
      context: { store }
    });
    splitStart({
      pageX: x,
      pageY: y,
      offsetX: Math.floor(gridData.gridSize * w / 2),
      offsetY: Math.floor(gridData.gridSize * h / 2)
    });
  }
  __name(beginSplitItem, "beginSplitItem");
  function itemBeginDrag(event) {
    const { x, y, item } = event.detail;
    const { w, h } = item.item;
    FloatingElement.create({
      id: application.id,
      x,
      y,
      style: {
        width: coordinate2size(w, gridData.gridSize, gridData.gap) + "px",
        height: coordinate2size(h, gridData.gridSize, gridData.gap) + "px",
        opacity: 0.7
      },
      component: VaultItemEntry,
      componentData: { entry: item },
      context: { store }
    });
    Hooks.callAll(CONSTANTS.HOOKS.DRAG_DOCUMENT, { type: "Item", uuid: item.item.item.uuid });
  }
  __name(itemBeginDrag, "itemBeginDrag");
  function itemStopDrag(event) {
    if (!FloatingElement.id)
      return;
    FloatingElement.destroy();
    if (event.detail.cancelled)
      return;
    const { item, outOfBounds, x, y, gridX, gridY, splitting } = event.detail;
    if (splitting) {
      if (outOfBounds)
        return;
      item.item.split(gridX, gridY);
      return;
    }
    if (!outOfBounds)
      return;
    const hitApps = Object.values(ui.windows).sort((a, b) => b.position.zIndex - a.position.zIndex).filter((app) => isCoordinateWithinPosition(x, y, app.element[0].getBoundingClientRect()));
    let dropData = { type: "Item", uuid: item.item.item.uuid };
    if (hitApps.length) {
      if (hitApps[0] === application)
        return;
      if (hitApps[0].actor) {
        dropData.target = hitApps[0].actor;
      }
      if (hitApps[0].onDropData) {
        return hitApps[0].onDropData(dropData);
      }
      if (hitApps[0]._handleDroppedEntry) {
        return hitApps[0]._handleDroppedEntry(document.elementFromPoint(x, y), dropData);
      }
    }
    const position = getCanvasMouse().getLocalPosition(canvas.app.stage);
    dropData.x = position.x;
    dropData.y = position.y;
    Hooks.call("dropCanvasData", canvas, dropData);
  }
  __name(itemStopDrag, "itemStopDrag");
  function itemMove(event) {
    if (!FloatingElement.id)
      return;
    const { x, y } = event.detail;
    FloatingElement.positionStore.set({ x, y });
  }
  __name(itemMove, "itemMove");
  function itemFlipped(event) {
    if (!FloatingElement.id)
      return;
    const item = event.detail.item.item;
    const { flipped } = event.detail;
    const rotation = item.flipped ? flipped ? "0deg" : "-90deg" : flipped ? "90deg" : "0deg";
    FloatingElement.styleStore.update((style) => {
      return foundry.utils.mergeObject(style, {
        "transform": `rotate(${rotation})`,
        "transition": "transform 150ms"
      });
    });
  }
  __name(itemFlipped, "itemFlipped");
  let activeTab = writable$1("vault");
  component_subscribe($$self, activeTab, (value) => $$invalidate(2, $activeTab = value));
  const applicationHeight = application.position.stores.height;
  component_subscribe($$self, applicationHeight, (value) => $$invalidate(12, $applicationHeight = value));
  const applicationWidth = application.position.stores.width;
  component_subscribe($$self, applicationWidth, (value) => $$invalidate(42, $applicationWidth = value));
  const defaultWidth = get_store_value(application.position.stores.width);
  function keydown(event) {
    if (event.key !== "r")
      return;
    dragPositionStore.update((data2) => {
      const { w, h } = data2;
      if (data2.active && w !== h) {
        data2.w = h;
        data2.h = w;
        data2.flipped = !data2.flipped;
      }
      return data2;
    });
  }
  __name(keydown, "keydown");
  function tabs_activeTab_binding(value) {
    $activeTab = value;
    activeTab.set($activeTab);
  }
  __name(tabs_activeTab_binding, "tabs_activeTab_binding");
  function input_input_handler() {
    $searchStore = this.value;
    searchStore.set($searchStore);
  }
  __name(input_input_handler, "input_input_handler");
  function grid_items_binding(value) {
    $gridItems = value;
    gridItems.set($gridItems);
  }
  __name(grid_items_binding, "grid_items_binding");
  function grid_gridContainer_binding(value) {
    element2 = value;
    $$invalidate(3, element2);
  }
  __name(grid_gridContainer_binding, "grid_gridContainer_binding");
  const change_handler = /* @__PURE__ */ __name((event) => store.updateGrid(event.detail.items), "change_handler");
  const func2 = /* @__PURE__ */ __name((data2) => store.onDropData(data2), "func");
  const click_handler = /* @__PURE__ */ __name(() => {
    const [appPosition, actorPosition] = getApplicationPositions(application, store.recipient.sheet);
    application.position.stores.left.set(appPosition.left);
    application.position.stores.top.set(appPosition.top);
    store.recipient.sheet.render(true, actorPosition);
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => store.withdrawCurrency(), "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => store.depositCurrency(), "click_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name((event) => store.sortItemsOnGrid(event), "click_handler_3");
  const click_handler_4 = /* @__PURE__ */ __name(() => store.addCurrency(), "click_handler_4");
  function vaultexpanderentry_item_binding(value, item, each_value_1, item_index) {
    each_value_1[item_index] = value;
    vaultExpanderItems.set($vaultExpanderItems);
  }
  __name(vaultexpanderentry_item_binding, "vaultexpanderentry_item_binding");
  const func_12 = /* @__PURE__ */ __name((data2, event) => {
    store.onDropData(data2, event, true);
  }, "func_1");
  function input_input_handler_1() {
    $logSearchStore = this.value;
    logSearchStore.set($logSearchStore);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  const click_handler_52 = /* @__PURE__ */ __name(() => {
    set_store_value(visibleLogItems, $visibleLogItems += 20, $visibleLogItems);
  }, "click_handler_5");
  function main_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      store.mainContainer = $$value;
      $$invalidate(1, store);
    });
  }
  __name(main_binding, "main_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("actor" in $$props2)
      $$invalidate(40, actor = $$props2.actor);
    if ("recipient" in $$props2)
      $$invalidate(41, recipient = $$props2.recipient);
    if ("store" in $$props2)
      $$invalidate(1, store = $$props2.store);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[1] & /*$pileDataStore*/
    16384) {
      $$invalidate(5, pileData = $pileDataStore);
    }
    if ($$self.$$.dirty[1] & /*$gridDataStore*/
    8192) {
      $$invalidate(4, gridData = $gridDataStore);
    }
    if ($$self.$$.dirty[1] & /*$floatingElementPositionStore*/
    4096) {
      {
        if ($floatingElementPositionStore) {
          onDragOver($floatingElementPositionStore?.x + 20, $floatingElementPositionStore?.y + 20);
        } else {
          onDragLeave();
        }
      }
    }
    if ($$self.$$.dirty[0] & /*$activeTab*/
    4 | $$self.$$.dirty[1] & /*$applicationWidth*/
    2048) {
      {
        if ($activeTab === "vault" && $applicationWidth) {
          application.position.stores.width.set(defaultWidth);
        }
      }
    }
  };
  return [
    elementRoot,
    store,
    $activeTab,
    element2,
    gridData,
    pileData,
    $searchStore,
    $gridItems,
    $dragPositionStore,
    $recipientDocument,
    $vaultExpanderItems,
    $logSearchStore,
    $applicationHeight,
    $vaultLog,
    $visibleLogItems,
    application,
    currencies,
    pileDataStore,
    gridDataStore,
    gridItems,
    vaultExpanderItems,
    searchStore,
    logSearchStore,
    vaultLog,
    visibleLogItems,
    recipientDocument,
    dragPositionStore,
    floatingElementPositionStore,
    onDragOverEvent,
    onDragLeave,
    doubleClickItem,
    rightClickItem,
    itemBeginDrag,
    itemStopDrag,
    itemMove,
    itemFlipped,
    activeTab,
    applicationHeight,
    applicationWidth,
    keydown,
    actor,
    recipient,
    $applicationWidth,
    $floatingElementPositionStore,
    $gridDataStore,
    $pileDataStore,
    tabs_activeTab_binding,
    input_input_handler,
    grid_items_binding,
    grid_gridContainer_binding,
    change_handler,
    func2,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_32,
    click_handler_4,
    vaultexpanderentry_item_binding,
    func_12,
    input_input_handler_1,
    click_handler_52,
    main_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$y, "instance$y");
const _Vault_shell = class _Vault_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$y,
      create_fragment$B,
      safe_not_equal,
      {
        elementRoot: 0,
        actor: 40,
        recipient: 41,
        store: 1
      },
      null,
      [-1, -1, -1]
    );
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get actor() {
    return this.$$.ctx[40];
  }
  set actor(actor) {
    this.$$set({ actor });
    flush();
  }
  get recipient() {
    return this.$$.ctx[41];
  }
  set recipient(recipient) {
    this.$$set({ recipient });
    flush();
  }
  get store() {
    return this.$$.ctx[1];
  }
  set store(store) {
    this.$$set({ store });
    flush();
  }
};
__name(_Vault_shell, "Vault_shell");
let Vault_shell = _Vault_shell;
const _VaultApp = class _VaultApp extends SvelteApplication {
  /**
   *
   * @param actor
   * @param recipient
   * @param options
   * @param dialogData
   */
  constructor(actor, recipient, options = {}, dialogData = {}) {
    super({
      id: `item-pile-vault-${actor?.token?.id ?? actor.id}-${randomID()}`,
      title: actor.name,
      svelte: {
        class: Vault_shell,
        target: document.body,
        props: {
          actor,
          recipient
        }
      },
      zIndex: 100,
      ...options
    }, dialogData);
    this.actor = actor;
    this.recipient = recipient;
    hooks.callAll(CONSTANTS.HOOKS.OPEN_INTERFACE, this, actor, recipient, options, dialogData);
  }
  onDropData(data2) {
    return this.store.onDropData(data2);
  }
  /** @inheritdoc */
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      closeOnSubmit: false,
      classes: ["app", "window-app", "sheet", "item-pile-vault", "item-piles", "item-piles-app"],
      minWidth: 300,
      minHeight: 300,
      resizable: false
    });
  }
  get store() {
    return this.svelte.applicationShell.store;
  }
  static getActiveApps(id = "") {
    return getActiveApps(`item-pile-vault-${id}`);
  }
  static async show(source, recipient = false, options = {}, dialogData = {}) {
    source = getActor(source);
    recipient = getActor(recipient);
    const result = hooks.call(CONSTANTS.HOOKS.PRE_OPEN_INTERFACE, source, recipient, options, dialogData);
    if (result === false)
      return;
    const access = getVaultAccess(source, { hasRecipient: !!recipient });
    if (!access.canView) {
      ui.notifications.error(game.i18n.format(recipient ? "ITEM-PILES.Errors.NoVaultAccessActor" : "ITEM-PILES.Errors.NoVaultAccess", {
        actor_name: recipient?.name ?? ""
      }));
      return;
    }
    const apps = this.getActiveApps(source?.token?.uuid ?? source.uuid);
    if (apps.length) {
      for (let app of apps) {
        app.render(false, { focus: true });
      }
      return;
    }
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(source, recipient, options, dialogData).render(true, { focus: true });
    });
  }
  async close(options) {
    const result = hooks.call(CONSTANTS.HOOKS.PRE_CLOSE_INTERFACE, this, this.actor, this.recipient, options);
    if (result === false)
      return;
    hooks.callAll(CONSTANTS.HOOKS.CLOSE_INTERFACE, this, this.actor, this.recipient, options);
    return super.close(options);
  }
  /* -------------------------------------------- */
  /** @override */
  _getHeaderButtons() {
    let buttons = super._getHeaderButtons();
    const canConfigure = game.user.isGM;
    if (canConfigure) {
      buttons = [
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.Inspect.OpenSheet" : "",
          class: "item-piles-open-actor-sheet",
          icon: "fas fa-user",
          onclick: () => {
            this.actor.sheet.render(true, { focus: true, bypassItemPiles: true });
          }
        },
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.ContextMenu.ShowToPlayers" : "",
          class: "item-piles-show-to-players",
          icon: "fas fa-eye",
          onclick: async (event) => {
            const activeUsers = Array.from(game.users).filter((u) => u.active && u !== game.user).map((u) => u.id);
            if (!activeUsers.length) {
              return custom_warning(game.i18n.localize("ITEM-PILES.Warnings.NoPlayersActive"), true);
            }
            const users = event.altKey ? activeUsers : await UserSelectDialog.show({ excludeSelf: true });
            if (!users || !users.length)
              return;
            custom_notify(game.i18n.format("ITEM-PILES.Notifications.ShownToPlayers", { actor_name: this.actor.name }));
            return game.itempiles.API.renderItemPileInterface(this.actor, {
              userIds: users,
              useDefaultCharacter: true
            });
          }
        },
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.HUD.Configure" : "",
          class: "item-piles-configure-pile",
          icon: "fas fa-box-open",
          onclick: () => {
            ItemPileConfig.show(this.actor);
          }
        }
      ].concat(buttons);
    }
    return buttons;
  }
};
__name(_VaultApp, "VaultApp");
let VaultApp = _VaultApp;
const CurrencyList_svelte_svelte_type_style_lang = "";
function get_each_context$i(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[17] = list[i];
  child_ctx[18] = list;
  child_ctx[19] = i;
  return child_ctx;
}
__name(get_each_context$i, "get_each_context$i");
function create_if_block_6$3(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = "Primary";
      set_style(div, "justify-content", "flex-start");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_6$3, "create_if_block_6$3");
function create_if_block_5$4(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = "Exchange";
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_5$4, "create_if_block_5$4");
function create_if_block_4$7(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = "Drop to add";
      attr(div, "class", "drop-to-add svelte-1q2f0bu");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_4$7, "create_if_block_4$7");
function create_if_block_3$7(ctx) {
  let div1;
  let div0;
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      div0.textContent = "Drop an item or click the plus button to get started!";
      attr(div0, "class", "full-span svelte-1q2f0bu");
      toggle_class(
        div0,
        "invisible",
        /*isHovering*/
        ctx[1]
      );
      attr(div1, "class", "item-piles-sortable-list-columns svelte-1q2f0bu");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
    },
    p(ctx2, dirty) {
      if (dirty & /*isHovering*/
      2) {
        toggle_class(
          div0,
          "invisible",
          /*isHovering*/
          ctx2[1]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div1);
    }
  };
}
__name(create_if_block_3$7, "create_if_block_3$7");
function create_if_block_2$8(ctx) {
  let div;
  let input;
  let input_checked_value;
  let mounted;
  let dispose;
  function change_handler() {
    return (
      /*change_handler*/
      ctx[8](
        /*index*/
        ctx[19]
      )
    );
  }
  __name(change_handler, "change_handler");
  return {
    c() {
      div = element("div");
      input = element("input");
      attr(input, "type", "checkbox");
      input.checked = input_checked_value = /*item*/
      ctx[17].primary;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      if (!mounted) {
        dispose = listen(input, "change", change_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*currencies*/
      8 && input_checked_value !== (input_checked_value = /*item*/
      ctx[17].primary)) {
        input.checked = input_checked_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_2$8, "create_if_block_2$8");
function create_if_block_1$c(ctx) {
  let div;
  let input;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx[10].call(
      input,
      /*each_value*/
      ctx[18],
      /*index*/
      ctx[19]
    );
  }
  __name(input_input_handler, "input_input_handler");
  return {
    c() {
      div = element("div");
      input = element("input");
      attr(input, "type", "number");
      attr(input, "step", "0.000000001");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*item*/
        ctx[17].exchangeRate
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*currencies*/
      8 && to_number(input.value) !== /*item*/
      ctx[17].exchangeRate) {
        set_input_value(
          input,
          /*item*/
          ctx[17].exchangeRate
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$c, "create_if_block_1$c");
function create_else_block$9(ctx) {
  let button;
  let mounted;
  let dispose;
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[14](
        /*index*/
        ctx[19]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    c() {
      button = element("button");
      button.innerHTML = `<i class="fas fa-eye"></i> View item`;
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(button, "click", click_handler_1);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$9, "create_else_block$9");
function create_if_block$k(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler_1() {
    ctx[13].call(
      input,
      /*each_value*/
      ctx[18],
      /*index*/
      ctx[19]
    );
  }
  __name(input_input_handler_1, "input_input_handler_1");
  return {
    c() {
      input = element("input");
      attr(input, "type", "text");
      attr(input, "placeholder", "system.attributes.hp.value");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*item*/
        ctx[17].data.path
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler_1);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*currencies*/
      8 && input.value !== /*item*/
      ctx[17].data.path) {
        set_input_value(
          input,
          /*item*/
          ctx[17].data.path
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$k, "create_if_block$k");
function create_each_block$i(key_1, ctx) {
  let div5;
  let t0;
  let div0;
  let input0;
  let t1;
  let t2;
  let div1;
  let input1;
  let t3;
  let div2;
  let filepicker;
  let updating_value;
  let t4;
  let div3;
  let t5;
  let div4;
  let button;
  let t6;
  let applyStyles_action;
  let current;
  let mounted;
  let dispose;
  let if_block0 = !/*store*/
  ctx[0].secondary && create_if_block_2$8(ctx);
  function input0_input_handler() {
    ctx[9].call(
      input0,
      /*each_value*/
      ctx[18],
      /*index*/
      ctx[19]
    );
  }
  __name(input0_input_handler, "input0_input_handler");
  let if_block1 = !/*store*/
  ctx[0].secondary && create_if_block_1$c(ctx);
  function input1_input_handler() {
    ctx[11].call(
      input1,
      /*each_value*/
      ctx[18],
      /*index*/
      ctx[19]
    );
  }
  __name(input1_input_handler, "input1_input_handler");
  function filepicker_value_binding(value) {
    ctx[12](
      value,
      /*item*/
      ctx[17]
    );
  }
  __name(filepicker_value_binding, "filepicker_value_binding");
  let filepicker_props = {
    type: "imagevideo",
    showImage: true,
    showInput: false
  };
  if (
    /*item*/
    ctx[17].img !== void 0
  ) {
    filepicker_props.value = /*item*/
    ctx[17].img;
  }
  filepicker = new FilePicker_1({ props: filepicker_props });
  binding_callbacks.push(() => bind(filepicker, "value", filepicker_value_binding));
  function select_block_type(ctx2, dirty) {
    if (
      /*item*/
      ctx2[17].type === "attribute"
    )
      return create_if_block$k;
    return create_else_block$9;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block2 = current_block_type(ctx);
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx[15](
        /*index*/
        ctx[19]
      )
    );
  }
  __name(click_handler_2, "click_handler_2");
  return {
    key: key_1,
    first: null,
    c() {
      div5 = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      div0 = element("div");
      input0 = element("input");
      t1 = space();
      if (if_block1)
        if_block1.c();
      t2 = space();
      div1 = element("div");
      input1 = element("input");
      t3 = space();
      div2 = element("div");
      create_component(filepicker.$$.fragment);
      t4 = space();
      div3 = element("div");
      if_block2.c();
      t5 = space();
      div4 = element("div");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      t6 = space();
      attr(input0, "type", "text");
      attr(input1, "type", "text");
      attr(button, "type", "button");
      attr(button, "class", "delete-button");
      attr(div5, "class", "item-piles-sortable-list-columns");
      this.first = div5;
    },
    m(target, anchor) {
      insert(target, div5, anchor);
      if (if_block0)
        if_block0.m(div5, null);
      append(div5, t0);
      append(div5, div0);
      append(div0, input0);
      set_input_value(
        input0,
        /*item*/
        ctx[17].name
      );
      append(div5, t1);
      if (if_block1)
        if_block1.m(div5, null);
      append(div5, t2);
      append(div5, div1);
      append(div1, input1);
      set_input_value(
        input1,
        /*item*/
        ctx[17].abbreviation
      );
      append(div5, t3);
      append(div5, div2);
      mount_component(filepicker, div2, null);
      append(div5, t4);
      append(div5, div3);
      if_block2.m(div3, null);
      append(div5, t5);
      append(div5, div4);
      append(div4, button);
      append(div5, t6);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input0, "input", input0_input_handler),
          listen(input1, "input", input1_input_handler),
          listen(button, "click", click_handler_2),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            div5,
            /*style*/
            ctx[2]
          ))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (!/*store*/
      ctx[0].secondary) {
        if (if_block0) {
          if_block0.p(ctx, dirty);
        } else {
          if_block0 = create_if_block_2$8(ctx);
          if_block0.c();
          if_block0.m(div5, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty & /*currencies*/
      8 && input0.value !== /*item*/
      ctx[17].name) {
        set_input_value(
          input0,
          /*item*/
          ctx[17].name
        );
      }
      if (!/*store*/
      ctx[0].secondary) {
        if (if_block1) {
          if_block1.p(ctx, dirty);
        } else {
          if_block1 = create_if_block_1$c(ctx);
          if_block1.c();
          if_block1.m(div5, t2);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty & /*currencies*/
      8 && input1.value !== /*item*/
      ctx[17].abbreviation) {
        set_input_value(
          input1,
          /*item*/
          ctx[17].abbreviation
        );
      }
      const filepicker_changes = {};
      if (!updating_value && dirty & /*currencies*/
      8) {
        updating_value = true;
        filepicker_changes.value = /*item*/
        ctx[17].img;
        add_flush_callback(() => updating_value = false);
      }
      filepicker.$set(filepicker_changes);
      if (current_block_type === (current_block_type = select_block_type(ctx)) && if_block2) {
        if_block2.p(ctx, dirty);
      } else {
        if_block2.d(1);
        if_block2 = current_block_type(ctx);
        if (if_block2) {
          if_block2.c();
          if_block2.m(div3, null);
        }
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*style*/
      4)
        applyStyles_action.update.call(
          null,
          /*style*/
          ctx[2]
        );
    },
    i(local) {
      if (current)
        return;
      transition_in(filepicker.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filepicker.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div5);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      destroy_component(filepicker);
      if_block2.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$i, "create_each_block$i");
function create_default_slot$h(ctx) {
  let div5;
  let t0;
  let div0;
  let t2;
  let t3;
  let div1;
  let t5;
  let div2;
  let t7;
  let div3;
  let t9;
  let div4;
  let a;
  let applyStyles_action;
  let t10;
  let div6;
  let t11;
  let t12;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let current;
  let mounted;
  let dispose;
  let if_block0 = !/*store*/
  ctx[0].secondary && create_if_block_6$3();
  let if_block1 = !/*store*/
  ctx[0].secondary && create_if_block_5$4();
  let if_block2 = (
    /*isHovering*/
    ctx[1] && create_if_block_4$7()
  );
  let if_block3 = !/*currencies*/
  ctx[3].length && create_if_block_3$7(ctx);
  let each_value = (
    /*currencies*/
    ctx[3]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[17].id
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$i(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$i(key, child_ctx));
  }
  return {
    c() {
      div5 = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      div0 = element("div");
      div0.textContent = "Name";
      t2 = space();
      if (if_block1)
        if_block1.c();
      t3 = space();
      div1 = element("div");
      div1.textContent = "Short";
      t5 = space();
      div2 = element("div");
      div2.textContent = "Icon";
      t7 = space();
      div3 = element("div");
      div3.textContent = "Data";
      t9 = space();
      div4 = element("div");
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus"></i>`;
      t10 = space();
      div6 = element("div");
      if (if_block2)
        if_block2.c();
      t11 = space();
      if (if_block3)
        if_block3.c();
      t12 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div5, "class", "item-piles-sortable-list-columns header");
      attr(div6, "class", "table-container svelte-1q2f0bu");
    },
    m(target, anchor) {
      insert(target, div5, anchor);
      if (if_block0)
        if_block0.m(div5, null);
      append(div5, t0);
      append(div5, div0);
      append(div5, t2);
      if (if_block1)
        if_block1.m(div5, null);
      append(div5, t3);
      append(div5, div1);
      append(div5, t5);
      append(div5, div2);
      append(div5, t7);
      append(div5, div3);
      append(div5, t9);
      append(div5, div4);
      append(div4, a);
      insert(target, t10, anchor);
      insert(target, div6, anchor);
      if (if_block2)
        if_block2.m(div6, null);
      append(div6, t11);
      if (if_block3)
        if_block3.m(div6, null);
      append(div6, t12);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div6, null);
        }
      }
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*click_handler*/
            ctx[7]
          ),
          action_destroyer(applyStyles_action = applyStyles.call(
            null,
            div5,
            /*style*/
            ctx[2]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!/*store*/
      ctx2[0].secondary) {
        if (if_block0)
          ;
        else {
          if_block0 = create_if_block_6$3();
          if_block0.c();
          if_block0.m(div5, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (!/*store*/
      ctx2[0].secondary) {
        if (if_block1)
          ;
        else {
          if_block1 = create_if_block_5$4();
          if_block1.c();
          if_block1.m(div5, t3);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (applyStyles_action && is_function(applyStyles_action.update) && dirty & /*style*/
      4)
        applyStyles_action.update.call(
          null,
          /*style*/
          ctx2[2]
        );
      if (
        /*isHovering*/
        ctx2[1]
      ) {
        if (if_block2)
          ;
        else {
          if_block2 = create_if_block_4$7();
          if_block2.c();
          if_block2.m(div6, t11);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (!/*currencies*/
      ctx2[3].length) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
        } else {
          if_block3 = create_if_block_3$7(ctx2);
          if_block3.c();
          if_block3.m(div6, t12);
        }
      } else if (if_block3) {
        if_block3.d(1);
        if_block3 = null;
      }
      if (dirty & /*style, store, currencies*/
      13) {
        each_value = /*currencies*/
        ctx2[3];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div6, outro_and_destroy_block, create_each_block$i, null, get_each_context$i);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div5);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (detaching)
        detach(t10);
      if (detaching)
        detach(div6);
      if (if_block2)
        if_block2.d();
      if (if_block3)
        if_block3.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$h, "create_default_slot$h");
function create_fragment$A(ctx) {
  let dropzone;
  let updating_isHovering;
  let current;
  function dropzone_isHovering_binding(value) {
    ctx[16](value);
  }
  __name(dropzone_isHovering_binding, "dropzone_isHovering_binding");
  let dropzone_props = {
    callback: (
      /*dropData*/
      ctx[5]
    ),
    $$slots: { default: [create_default_slot$h] },
    $$scope: { ctx }
  };
  if (
    /*isHovering*/
    ctx[1] !== void 0
  ) {
    dropzone_props.isHovering = /*isHovering*/
    ctx[1];
  }
  dropzone = new DropZone({ props: dropzone_props });
  binding_callbacks.push(() => bind(dropzone, "isHovering", dropzone_isHovering_binding));
  return {
    c() {
      create_component(dropzone.$$.fragment);
    },
    m(target, anchor) {
      mount_component(dropzone, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const dropzone_changes = {};
      if (dirty & /*$$scope, currencies, style, store, isHovering*/
      1048591) {
        dropzone_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_isHovering && dirty & /*isHovering*/
      2) {
        updating_isHovering = true;
        dropzone_changes.isHovering = /*isHovering*/
        ctx2[1];
        add_flush_callback(() => updating_isHovering = false);
      }
      dropzone.$set(dropzone_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dropzone.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropzone.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(dropzone, detaching);
    }
  };
}
__name(create_fragment$A, "create_fragment$A");
function instance$x($$self, $$props, $$invalidate) {
  let currencies;
  let style;
  let $currenciesStore;
  let { store } = $$props;
  const currenciesStore = store.currencies;
  component_subscribe($$self, currenciesStore, (value) => $$invalidate(6, $currenciesStore = value));
  let isHovering = false;
  async function dropData(data2) {
    if (!data2.type) {
      throw custom_error("Something went wrong when dropping this item!");
    }
    if (data2.type !== "Item") {
      throw custom_error("You must drop an item, not " + data2.type.toLowerCase() + "!");
    }
    store.addItem(data2);
  }
  __name(dropData, "dropData");
  const click_handler = /* @__PURE__ */ __name(() => store.addAttribute(), "click_handler");
  const change_handler = /* @__PURE__ */ __name((index2) => store.setPrimary(index2), "change_handler");
  function input0_input_handler(each_value, index2) {
    each_value[index2].name = this.value;
    $$invalidate(3, currencies), $$invalidate(6, $currenciesStore);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input_input_handler(each_value, index2) {
    each_value[index2].exchangeRate = to_number(this.value);
    $$invalidate(3, currencies), $$invalidate(6, $currenciesStore);
  }
  __name(input_input_handler, "input_input_handler");
  function input1_input_handler(each_value, index2) {
    each_value[index2].abbreviation = this.value;
    $$invalidate(3, currencies), $$invalidate(6, $currenciesStore);
  }
  __name(input1_input_handler, "input1_input_handler");
  function filepicker_value_binding(value, item) {
    if ($$self.$$.not_equal(item.img, value)) {
      item.img = value;
      $$invalidate(3, currencies), $$invalidate(6, $currenciesStore);
    }
  }
  __name(filepicker_value_binding, "filepicker_value_binding");
  function input_input_handler_1(each_value, index2) {
    each_value[index2].data.path = this.value;
    $$invalidate(3, currencies), $$invalidate(6, $currenciesStore);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  const click_handler_1 = /* @__PURE__ */ __name((index2) => store.editItem(index2), "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name((index2) => store.removeEntry(index2), "click_handler_2");
  function dropzone_isHovering_binding(value) {
    isHovering = value;
    $$invalidate(1, isHovering);
  }
  __name(dropzone_isHovering_binding, "dropzone_isHovering_binding");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(0, store = $$props2.store);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$currenciesStore*/
    64) {
      $$invalidate(3, currencies = $currenciesStore);
    }
    if ($$self.$$.dirty & /*$currenciesStore, store*/
    65) {
      {
        store.sortCurrencies();
      }
    }
    if ($$self.$$.dirty & /*store*/
    1) {
      $$invalidate(2, style = {
        "grid-template-columns": `${store.secondary ? "" : "28px"} 1.25fr ${store.secondary ? "" : "60px"} 0.5fr 60px 1fr 28px`
      });
    }
  };
  return [
    store,
    isHovering,
    style,
    currencies,
    currenciesStore,
    dropData,
    $currenciesStore,
    click_handler,
    change_handler,
    input0_input_handler,
    input_input_handler,
    input1_input_handler,
    filepicker_value_binding,
    input_input_handler_1,
    click_handler_1,
    click_handler_2,
    dropzone_isHovering_binding
  ];
}
__name(instance$x, "instance$x");
const _CurrencyList = class _CurrencyList extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$x, create_fragment$A, safe_not_equal, { store: 0 });
  }
};
__name(_CurrencyList, "CurrencyList");
let CurrencyList = _CurrencyList;
const _CurrencyStore = class _CurrencyStore {
  constructor(data2, secondary = false) {
    this.secondary = secondary;
    this.currencies = writable$1(data2.map((entry, index2) => {
      return {
        ...entry,
        index: index2,
        id: entry.data?.path ?? entry.data?._id ?? randomID()
      };
    }));
  }
  setPrimary(index2) {
    if (this.secondary)
      return;
    this.currencies.update((currencies) => {
      currencies.forEach((entry, entryIndex) => {
        entry.primary = entryIndex === index2;
      });
      return currencies;
    });
  }
  sortCurrencies() {
    if (this.secondary)
      return;
    this.currencies.update((currencies) => {
      currencies.sort((a, b) => {
        return b.exchangeRate - a.exchangeRate;
      });
      return currencies;
    });
  }
  addAttribute() {
    this.currencies.update((currencies) => {
      currencies.push(foundry.utils.mergeObject({
        type: "attribute",
        name: "New Attribute",
        img: "",
        abbreviation: "{#}N",
        data: {
          path: ""
        }
      }, this.secondary ? {} : {
        primary: !currencies.length,
        exchangeRate: 1
      }));
      return currencies;
    });
  }
  async addItem(data2) {
    let uuid = false;
    if (data2.pack) {
      uuid = "Compendium" + data2.pack + "." + data2.id;
    }
    let item = await Item.implementation.fromDropData(data2);
    let itemData = item.toObject();
    if (!itemData) {
      console.error(data2);
      throw custom_error("Something went wrong when dropping this item!");
    }
    if (!uuid) {
      uuid = (await findOrCreateItemInCompendium(itemData)).uuid;
    }
    this.currencies.update((currencies) => {
      const itemCurrencies = currencies.map((entry) => entry.data?.item ?? {});
      const foundItem = findSimilarItem(itemCurrencies, itemData);
      if (foundItem) {
        const index2 = itemCurrencies.indexOf(foundItem);
        currencies[index2].data = {
          uuid
        };
        custom_notify(`Updated item data for ${localize(currencies[index2].name)} (item name ${itemData.name})`);
      } else {
        currencies.push(foundry.utils.mergeObject({
          id: randomID(),
          type: "item",
          name: itemData.name,
          img: itemData.img,
          abbreviation: "{#} " + itemData.name,
          data: {
            uuid
          }
        }, this.secondary ? {} : {
          primary: !currencies.length,
          exchangeRate: 1
        }));
      }
      return currencies;
    });
  }
  async editItem(index2) {
    const currencies = get_store_value(this.currencies);
    const data2 = currencies[index2].data;
    let item;
    if (data2.uuid) {
      item = await fromUuid(data2.uuid);
    } else {
      let itemData = data2.item;
      if (itemData._id)
        delete itemData._id;
      if (itemData.ownership)
        delete itemData.ownership;
      const items = Array.from(game.items);
      item = findSimilarItem(items, itemData);
      if (!item) {
        setProperty(itemData, CONSTANTS.FLAGS.TEMPORARY_ITEM, true);
        item = await Item.implementation.create(itemData);
        custom_notify(`An item has been created for ${item.name} - drag and drop it into the list to update the stored item data`);
      }
    }
    item.sheet.render(true);
  }
  removeEntry(index2) {
    this.currencies.update((currencies) => {
      currencies.splice(index2, 1);
      return currencies;
    });
  }
  export() {
    return get_store_value(this.currencies);
  }
};
__name(_CurrencyStore, "CurrencyStore");
let CurrencyStore = _CurrencyStore;
const currenciesEditorShell_svelte_svelte_type_style_lang = "";
function create_default_slot$g(ctx) {
  let form_1;
  let p0;
  let t0_value = localize(`ITEM-PILES.Applications.${/*secondary*/
  ctx[1] ? "Secondary" : ""}CurrenciesEditor.Explanation`) + "";
  let t0;
  let t1;
  let p1;
  let t3;
  let p2;
  let t5;
  let currencylist;
  let t6;
  let footer;
  let button0;
  let i0;
  let t7;
  let t8_value = localize("Save") + "";
  let t8;
  let t9;
  let button1;
  let i1;
  let t10;
  let t11_value = localize("Cancel") + "";
  let t11;
  let current;
  let mounted;
  let dispose;
  currencylist = new CurrencyList({ props: { store: (
    /*store*/
    ctx[5]
  ) } });
  return {
    c() {
      form_1 = element("form");
      p0 = element("p");
      t0 = text(t0_value);
      t1 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.CurrenciesEditor.ExplanationSmallAttributes")}`;
      t3 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.CurrenciesEditor.ExplanationSmallItems")}`;
      t5 = space();
      create_component(currencylist.$$.fragment);
      t6 = space();
      footer = element("footer");
      button0 = element("button");
      i0 = element("i");
      t7 = space();
      t8 = text(t8_value);
      t9 = space();
      button1 = element("button");
      i1 = element("i");
      t10 = space();
      t11 = text(t11_value);
      attr(p1, "class", "small svelte-19gcezu");
      attr(p2, "class", "small item-piles-bottom-divider svelte-19gcezu");
      attr(i0, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i1, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(footer, "class", "svelte-19gcezu");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "svelte-19gcezu");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p0);
      append(p0, t0);
      append(form_1, t1);
      append(form_1, p1);
      append(form_1, t3);
      append(form_1, p2);
      append(form_1, t5);
      mount_component(currencylist, form_1, null);
      append(form_1, t6);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i0);
      append(button0, t7);
      append(button0, t8);
      append(footer, t9);
      append(footer, button1);
      append(button1, i1);
      append(button1, t10);
      append(button1, t11);
      ctx[9](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[2],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[8],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[6]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if ((!current || dirty & /*secondary*/
      2) && t0_value !== (t0_value = localize(`ITEM-PILES.Applications.${/*secondary*/
      ctx2[1] ? "Secondary" : ""}CurrenciesEditor.Explanation`) + ""))
        set_data(t0, t0_value);
    },
    i(local) {
      if (current)
        return;
      transition_in(currencylist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(currencylist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      destroy_component(currencylist);
      ctx[9](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$g, "create_default_slot$g");
function create_fragment$z(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[10](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$g] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, secondary*/
      2058) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$z, "create_fragment$z");
function instance$w($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { data: data2 } = $$props;
  let { secondary = false } = $$props;
  let { elementRoot } = $$props;
  const store = new CurrencyStore(data2 || getSetting(SETTINGS$1.CURRENCIES), secondary);
  let form;
  async function updateSettings() {
    application.options.resolve(store.export());
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(3, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(7, data2 = $$props2.data);
    if ("secondary" in $$props2)
      $$invalidate(1, secondary = $$props2.secondary);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  return [
    elementRoot,
    secondary,
    requestSubmit,
    form,
    application,
    store,
    updateSettings,
    data2,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$w, "instance$w");
const _Currencies_editor_shell = class _Currencies_editor_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$w, create_fragment$z, safe_not_equal, {
      data: 7,
      secondary: 1,
      elementRoot: 0,
      requestSubmit: 2
    });
  }
  get data() {
    return this.$$.ctx[7];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get secondary() {
    return this.$$.ctx[1];
  }
  set secondary(secondary) {
    this.$$set({ secondary });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[2];
  }
};
__name(_Currencies_editor_shell, "Currencies_editor_shell");
let Currencies_editor_shell = _Currencies_editor_shell;
const _Editor = class _Editor extends SvelteApplication {
  constructor(data2, options, dialogOptions) {
    super({
      svelte: {
        props: {
          data: data2
        }
      },
      ...options
    }, dialogOptions);
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 400,
      height: "auto",
      classes: ["item-piles-app"],
      close: () => this.options.resolve(null),
      svelte: {
        target: document.body
      }
    });
  }
  static async show(data2, options = {}, dialogOptions = {}) {
    const app = options?.id ? getActiveApps(options?.id, true) : false;
    if (app)
      return app.render(false, { focus: true });
    return new Promise((resolve) => {
      options.resolve = resolve;
      return new this(data2, options, dialogOptions).render(true, { focus: true });
    });
  }
};
__name(_Editor, "Editor");
let Editor = _Editor;
const _CurrenciesEditor = class _CurrenciesEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Applications.CurrenciesEditor.Title"),
      width: 630,
      svelte: {
        class: Currencies_editor_shell
      }
    });
  }
};
__name(_CurrenciesEditor, "CurrenciesEditor");
let CurrenciesEditor = _CurrenciesEditor;
const _SecondaryCurrenciesEditor = class _SecondaryCurrenciesEditor extends CurrenciesEditor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Applications.SecondaryCurrenciesEditor.Title"),
      svelte: {
        props: {
          secondary: true
        }
      }
    });
  }
};
__name(_SecondaryCurrenciesEditor, "SecondaryCurrenciesEditor");
let SecondaryCurrenciesEditor = _SecondaryCurrenciesEditor;
const itemFiltersEditor_svelte_svelte_type_style_lang = "";
function get_each_context$h(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[15] = list[i].path;
  child_ctx[16] = list[i].filters;
  child_ctx[17] = list;
  child_ctx[18] = i;
  return child_ctx;
}
__name(get_each_context$h, "get_each_context$h");
function create_each_block$h(key_1, ctx) {
  let tr;
  let td0;
  let input0;
  let t0;
  let td1;
  let input1;
  let t1;
  let td2;
  let button;
  let t2;
  let mounted;
  let dispose;
  function input0_input_handler() {
    ctx[10].call(
      input0,
      /*each_value*/
      ctx[17],
      /*index*/
      ctx[18]
    );
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler() {
    ctx[11].call(
      input1,
      /*each_value*/
      ctx[17],
      /*index*/
      ctx[18]
    );
  }
  __name(input1_input_handler, "input1_input_handler");
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      input0 = element("input");
      t0 = space();
      td1 = element("td");
      input1 = element("input");
      t1 = space();
      td2 = element("td");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      t2 = space();
      attr(input0, "type", "text");
      input0.required = true;
      attr(input0, "placeholder", "type");
      attr(input1, "type", "text");
      input1.required = true;
      attr(input1, "placeholder", "class, spell, feat");
      attr(button, "type", "button");
      attr(button, "class", "svelte-19toc95");
      attr(td2, "class", "custom-small svelte-19toc95");
      attr(tr, "class", "svelte-19toc95");
      this.first = tr;
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, input0);
      set_input_value(
        input0,
        /*path*/
        ctx[15]
      );
      append(tr, t0);
      append(tr, td1);
      append(td1, input1);
      set_input_value(
        input1,
        /*filters*/
        ctx[16]
      );
      append(tr, t1);
      append(tr, td2);
      append(td2, button);
      append(tr, t2);
      if (!mounted) {
        dispose = [
          listen(input0, "input", input0_input_handler),
          listen(input1, "input", input1_input_handler),
          listen(button, "click", function() {
            if (is_function(
              /*remove*/
              ctx[7](
                /*index*/
                ctx[18]
              )
            ))
              ctx[7](
                /*index*/
                ctx[18]
              ).apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$itemFilters*/
      8 && input0.value !== /*path*/
      ctx[15]) {
        set_input_value(
          input0,
          /*path*/
          ctx[15]
        );
      }
      if (dirty & /*$itemFilters*/
      8 && input1.value !== /*filters*/
      ctx[16]) {
        set_input_value(
          input1,
          /*filters*/
          ctx[16]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$h, "create_each_block$h");
function create_default_slot$f(ctx) {
  let form_1;
  let p;
  let t1;
  let table;
  let tr;
  let th0;
  let t3;
  let th1;
  let t5;
  let th2;
  let a;
  let t6;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t7;
  let footer;
  let button0;
  let i1;
  let t8;
  let t9_value = localize("Save") + "";
  let t9;
  let t10;
  let button1;
  let i2;
  let t11;
  let t12_value = localize("Cancel") + "";
  let t12;
  let mounted;
  let dispose;
  let each_value = (
    /*$itemFilters*/
    ctx[3]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[18]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$h(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$h(key, child_ctx));
  }
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.FilterEditor.Explanation")}`;
      t1 = space();
      table = element("table");
      tr = element("tr");
      th0 = element("th");
      th0.textContent = `${localize("ITEM-PILES.Applications.FilterEditor.Path")}`;
      t3 = space();
      th1 = element("th");
      th1.textContent = `${localize("ITEM-PILES.Applications.FilterEditor.Filters")}`;
      t5 = space();
      th2 = element("th");
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus"></i>`;
      t6 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t7 = space();
      footer = element("footer");
      button0 = element("button");
      i1 = element("i");
      t8 = space();
      t9 = text(t9_value);
      t10 = space();
      button1 = element("button");
      i2 = element("i");
      t11 = space();
      t12 = text(t12_value);
      attr(a, "class", "item-piles-clickable svelte-19toc95");
      attr(th2, "class", "custom-small svelte-19toc95");
      attr(tr, "class", "svelte-19toc95");
      attr(table, "class", "svelte-19toc95");
      attr(i1, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i2, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(form_1, t1);
      append(form_1, table);
      append(table, tr);
      append(tr, th0);
      append(tr, t3);
      append(tr, th1);
      append(tr, t5);
      append(tr, th2);
      append(th2, a);
      append(table, t6);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(table, null);
        }
      }
      append(form_1, t7);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i1);
      append(button0, t8);
      append(button0, t9);
      append(footer, t10);
      append(footer, button1);
      append(button1, i2);
      append(button1, t11);
      append(button1, t12);
      ctx[13](form_1);
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*add*/
            ctx[6]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[12],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[8]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*remove, $itemFilters*/
      136) {
        each_value = /*$itemFilters*/
        ctx2[3];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, table, destroy_block, create_each_block$h, null, get_each_context$h);
      }
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[13](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$f, "create_default_slot$f");
function create_fragment$y(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[14](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$f] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $itemFilters*/
      524300) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$y, "create_fragment$y");
function instance$v($$self, $$props, $$invalidate) {
  let $itemFilters;
  const { application } = getContext("#external");
  let { data: data2 } = $$props;
  let { elementRoot } = $$props;
  let form;
  const itemFilters = writable$1(data2 ? data2 : getSetting(SETTINGS$1.ITEM_FILTERS));
  component_subscribe($$self, itemFilters, (value) => $$invalidate(3, $itemFilters = value));
  function add() {
    itemFilters.update((val) => {
      val.push({ path: "", filters: "" });
      return val;
    });
  }
  __name(add, "add");
  function remove(index2) {
    itemFilters.update((val) => {
      val.splice(index2, 1);
      return val;
    });
  }
  __name(remove, "remove");
  async function updateSettings() {
    application.options.resolve(get_store_value(itemFilters));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function input0_input_handler(each_value, index2) {
    each_value[index2].path = this.value;
    itemFilters.set($itemFilters);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler(each_value, index2) {
    each_value[index2].filters = this.value;
    itemFilters.set($itemFilters);
  }
  __name(input1_input_handler, "input1_input_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(9, data2 = $$props2.data);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  return [
    elementRoot,
    requestSubmit,
    form,
    $itemFilters,
    application,
    itemFilters,
    add,
    remove,
    updateSettings,
    data2,
    input0_input_handler,
    input1_input_handler,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$v, "instance$v");
const _Item_filters_editor = class _Item_filters_editor extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$v, create_fragment$y, safe_not_equal, {
      data: 9,
      elementRoot: 0,
      requestSubmit: 1
    });
  }
  get data() {
    return this.$$.ctx[9];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Item_filters_editor, "Item_filters_editor");
let Item_filters_editor = _Item_filters_editor;
const _ItemFiltersEditor = class _ItemFiltersEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: "ITEM-PILES.Applications.FilterEditor.Title",
      svelte: {
        class: Item_filters_editor
      }
    });
  }
};
__name(_ItemFiltersEditor, "ItemFiltersEditor");
let ItemFiltersEditor = _ItemFiltersEditor;
function create_if_block$j(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.innerHTML = `<i class="fas fa-exclamation"></i>`;
      set_style(div, "flex", "0 1 auto");
      set_style(div, "margin-right", "1rem");
      attr(div, "class", "blob");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block$j, "create_if_block$j");
function create_fragment$x(ctx) {
  let div0;
  let label0;
  let span0;
  let t1;
  let p0;
  let t3;
  let span2;
  let t4;
  let span1;
  let input0;
  let t5;
  let div1;
  let label1;
  let span3;
  let t7;
  let p1;
  let t9;
  let input1;
  let t10;
  let div2;
  let label2;
  let span4;
  let t12;
  let p2;
  let t14;
  let input2;
  let t15;
  let div3;
  let label3;
  let span5;
  let t17;
  let p3;
  let t19;
  let input3;
  let t20;
  let div4;
  let label4;
  let span6;
  let t22;
  let p4;
  let t24;
  let div5;
  let macroselector;
  let updating_macro;
  let t25;
  let div6;
  let label5;
  let span7;
  let t27;
  let p5;
  let t29;
  let select0;
  let option0;
  let option1;
  let option2;
  let t36;
  let div8;
  let label6;
  let span8;
  let t38;
  let p6;
  let t40;
  let div7;
  let t41;
  let select1;
  let option3;
  let option4;
  let option5;
  let option6;
  let t49;
  let div9;
  let label7;
  let span9;
  let t51;
  let p7;
  let t53;
  let div10;
  let button0;
  let t55;
  let div11;
  let label8;
  let span10;
  let t57;
  let p8;
  let t59;
  let input4;
  let t60;
  let div12;
  let button1;
  let t61_value = localize("ITEM-PILES.Applications.ItemPileConfig.Main.ConfigureOverrideCurrencies") + "";
  let t61;
  let button1_disabled_value;
  let t62;
  let div13;
  let label9;
  let span11;
  let t64;
  let p9;
  let t66;
  let input5;
  let t67;
  let div14;
  let button2;
  let t68_value = localize("ITEM-PILES.Applications.ItemPileConfig.Main.ConfigureOverrideSecondaryCurrencies") + "";
  let t68;
  let button2_disabled_value;
  let t69;
  let div15;
  let label10;
  let span12;
  let t71;
  let p10;
  let t73;
  let input6;
  let t74;
  let div16;
  let button3;
  let t75_value = localize("ITEM-PILES.Applications.ItemPileConfig.Main.ConfigureOverrideItemFilters") + "";
  let t75;
  let button3_disabled_value;
  let current;
  let mounted;
  let dispose;
  let if_block = !/*$pileEnabled*/
  ctx[5] && create_if_block$j();
  function macroselector_macro_binding(value) {
    ctx[19](value);
  }
  __name(macroselector_macro_binding, "macroselector_macro_binding");
  let macroselector_props = {};
  if (
    /*pileData*/
    ctx[0].macro !== void 0
  ) {
    macroselector_props.macro = /*pileData*/
    ctx[0].macro;
  }
  macroselector = new MacroSelector({ props: macroselector_props });
  binding_callbacks.push(() => bind(macroselector, "macro", macroselector_macro_binding));
  return {
    c() {
      div0 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.EnabledPile")}`;
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.EnabledPileExplanation")}`;
      t3 = space();
      span2 = element("span");
      if (if_block)
        if_block.c();
      t4 = space();
      span1 = element("span");
      input0 = element("input");
      t5 = space();
      div1 = element("div");
      label1 = element("label");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.Distance")}`;
      t7 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.GridUnits")}`;
      t9 = space();
      input1 = element("input");
      t10 = space();
      div2 = element("div");
      label2 = element("label");
      span4 = element("span");
      span4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.InspectItems")}`;
      t12 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.InspectItemsExplanation")}`;
      t14 = space();
      input2 = element("input");
      t15 = space();
      div3 = element("div");
      label3 = element("label");
      span5 = element("span");
      span5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.DisplayItemTypes")}`;
      t17 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.DisplayItemTypesExplanation")}`;
      t19 = space();
      input3 = element("input");
      t20 = space();
      div4 = element("div");
      label4 = element("label");
      span6 = element("span");
      span6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.Macro")}`;
      t22 = space();
      p4 = element("p");
      p4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.MacroExplanation")}`;
      t24 = space();
      div5 = element("div");
      create_component(macroselector.$$.fragment);
      t25 = space();
      div6 = element("div");
      label5 = element("label");
      span7 = element("span");
      span7.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.DeleteWhenEmpty")}`;
      t27 = space();
      p5 = element("p");
      p5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.DeleteWhenEmptyExplanation")}`;
      t29 = space();
      select0 = element("select");
      option0 = element("option");
      option0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.DeleteWhenEmptyDefault")}
			(${localize(
        /*deleteWhenEmptySetting*/
        ctx[6]
      )})
		`;
      option1 = element("option");
      option1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.DeleteWhenEmptyYes")}`;
      option2 = element("option");
      option2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.DeleteWhenEmptyNo")}`;
      t36 = space();
      div8 = element("div");
      label6 = element("label");
      span8 = element("span");
      span8.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.CanStackItems")}`;
      t38 = space();
      p6 = element("p");
      p6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.CanStackItemsExplanation")}`;
      t40 = space();
      div7 = element("div");
      t41 = space();
      select1 = element("select");
      option3 = element("option");
      option3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.CanStackItemsYes")} 
		`;
      option4 = element("option");
      option4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.CanStackItemsNo")} 
		`;
      option5 = element("option");
      option5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.CanStackItemsYesAlways")} 
		`;
      option6 = element("option");
      option6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.CanStackItemsNoAlways")}`;
      t49 = space();
      div9 = element("div");
      label7 = element("label");
      span9 = element("span");
      span9.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.EditDescription")}`;
      t51 = space();
      p7 = element("p");
      p7.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.EditDescriptionExplanation")}`;
      t53 = space();
      div10 = element("div");
      button0 = element("button");
      button0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.EditDescription")}`;
      t55 = space();
      div11 = element("div");
      label8 = element("label");
      span10 = element("span");
      span10.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.OverrideCurrencies")}`;
      t57 = space();
      p8 = element("p");
      p8.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.OverrideCurrenciesExplanation")}`;
      t59 = space();
      input4 = element("input");
      t60 = space();
      div12 = element("div");
      button1 = element("button");
      t61 = text(t61_value);
      t62 = space();
      div13 = element("div");
      label9 = element("label");
      span11 = element("span");
      span11.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.OverrideSecondaryCurrencies")}`;
      t64 = space();
      p9 = element("p");
      p9.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.OverrideSecondaryCurrenciesExplanation")}`;
      t66 = space();
      input5 = element("input");
      t67 = space();
      div14 = element("div");
      button2 = element("button");
      t68 = text(t68_value);
      t69 = space();
      div15 = element("div");
      label10 = element("label");
      span12 = element("span");
      span12.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.OverrideItemFilters")}`;
      t71 = space();
      p10 = element("p");
      p10.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Main.OverrideItemFiltersExplanation")}`;
      t73 = space();
      input6 = element("input");
      t74 = space();
      div16 = element("div");
      button3 = element("button");
      t75 = text(t75_value);
      attr(input0, "type", "checkbox");
      set_style(span1, "flex", "0 1 auto");
      attr(span2, "class", "item-piles-flexrow");
      set_style(span2, "max-width", "100px");
      set_style(span2, "justify-content", "flex-end");
      set_style(span2, "align-items", "center");
      attr(div0, "class", "form-group");
      set_style(label1, "flex", "4");
      attr(input1, "placeholder", "Infinity");
      set_style(input1, "flex", "4");
      attr(input1, "type", "number");
      attr(div1, "class", "form-group");
      attr(input2, "type", "checkbox");
      attr(div2, "class", "form-group");
      attr(input3, "type", "checkbox");
      attr(div3, "class", "form-group");
      set_style(label4, "flex", "4");
      attr(div4, "class", "form-group");
      attr(div5, "class", "form-group");
      set_style(label5, "flex", "4");
      option0.__value = "default";
      option0.value = option0.__value;
      option1.__value = true;
      option1.value = option1.__value;
      option2.__value = false;
      option2.value = option2.__value;
      set_style(select0, "flex", "4");
      if (
        /*pileData*/
        ctx[0].deleteWhenEmpty === void 0
      )
        add_render_callback(() => (
          /*select0_change_handler*/
          ctx[20].call(select0)
        ));
      attr(div6, "class", "form-group");
      attr(div7, "class", "break");
      option3.__value = "yes";
      option3.value = option3.__value;
      option4.__value = "no";
      option4.value = option4.__value;
      option5.__value = "alwaysyes";
      option5.value = option5.__value;
      option6.__value = "alwaysno";
      option6.value = option6.__value;
      set_style(select1, "flex", "4");
      if (
        /*pileData*/
        ctx[0].canStackItems === void 0
      )
        add_render_callback(() => (
          /*select1_change_handler*/
          ctx[21].call(select1)
        ));
      attr(div8, "class", "form-group");
      set_style(label7, "flex", "4");
      attr(div9, "class", "form-group");
      set_style(button0, "flex", "4");
      attr(button0, "type", "button");
      attr(div10, "class", "form-group");
      set_style(label8, "flex", "4");
      attr(input4, "type", "checkbox");
      attr(div11, "class", "form-group");
      button1.disabled = button1_disabled_value = !/*$hasOverrideCurrencies*/
      ctx[4];
      set_style(button1, "flex", "4");
      attr(button1, "type", "button");
      attr(div12, "class", "form-group");
      set_style(label9, "flex", "4");
      attr(input5, "type", "checkbox");
      attr(div13, "class", "form-group");
      button2.disabled = button2_disabled_value = !/*$hasOverrideSecondaryCurrencies*/
      ctx[3];
      set_style(button2, "flex", "4");
      attr(button2, "type", "button");
      attr(div14, "class", "form-group");
      set_style(label10, "flex", "4");
      attr(input6, "type", "checkbox");
      attr(div15, "class", "form-group");
      button3.disabled = button3_disabled_value = !/*$hasOverrideItemFilters*/
      ctx[2];
      set_style(button3, "flex", "4");
      attr(button3, "type", "button");
      attr(div16, "class", "form-group");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, label0);
      append(label0, span0);
      append(label0, t1);
      append(label0, p0);
      append(div0, t3);
      append(div0, span2);
      if (if_block)
        if_block.m(span2, null);
      append(span2, t4);
      append(span2, span1);
      append(span1, input0);
      input0.checked = /*$pileEnabled*/
      ctx[5];
      insert(target, t5, anchor);
      insert(target, div1, anchor);
      append(div1, label1);
      append(label1, span3);
      append(label1, t7);
      append(label1, p1);
      append(div1, t9);
      append(div1, input1);
      set_input_value(
        input1,
        /*pileData*/
        ctx[0].distance
      );
      insert(target, t10, anchor);
      insert(target, div2, anchor);
      append(div2, label2);
      append(label2, span4);
      append(label2, t12);
      append(label2, p2);
      append(div2, t14);
      append(div2, input2);
      input2.checked = /*pileData*/
      ctx[0].canInspectItems;
      insert(target, t15, anchor);
      insert(target, div3, anchor);
      append(div3, label3);
      append(label3, span5);
      append(label3, t17);
      append(label3, p3);
      append(div3, t19);
      append(div3, input3);
      input3.checked = /*pileData*/
      ctx[0].displayItemTypes;
      insert(target, t20, anchor);
      insert(target, div4, anchor);
      append(div4, label4);
      append(label4, span6);
      append(label4, t22);
      append(label4, p4);
      insert(target, t24, anchor);
      insert(target, div5, anchor);
      mount_component(macroselector, div5, null);
      insert(target, t25, anchor);
      insert(target, div6, anchor);
      append(div6, label5);
      append(label5, span7);
      append(label5, t27);
      append(label5, p5);
      append(div6, t29);
      append(div6, select0);
      append(select0, option0);
      append(select0, option1);
      append(select0, option2);
      select_option(
        select0,
        /*pileData*/
        ctx[0].deleteWhenEmpty,
        true
      );
      insert(target, t36, anchor);
      insert(target, div8, anchor);
      append(div8, label6);
      append(label6, span8);
      append(label6, t38);
      append(label6, p6);
      append(div8, t40);
      append(div8, div7);
      append(div8, t41);
      append(div8, select1);
      append(select1, option3);
      append(select1, option4);
      append(select1, option5);
      append(select1, option6);
      select_option(
        select1,
        /*pileData*/
        ctx[0].canStackItems,
        true
      );
      insert(target, t49, anchor);
      insert(target, div9, anchor);
      append(div9, label7);
      append(label7, span9);
      append(label7, t51);
      append(label7, p7);
      insert(target, t53, anchor);
      insert(target, div10, anchor);
      append(div10, button0);
      insert(target, t55, anchor);
      insert(target, div11, anchor);
      append(div11, label8);
      append(label8, span10);
      append(label8, t57);
      append(label8, p8);
      append(div11, t59);
      append(div11, input4);
      input4.checked = /*$hasOverrideCurrencies*/
      ctx[4];
      insert(target, t60, anchor);
      insert(target, div12, anchor);
      append(div12, button1);
      append(button1, t61);
      insert(target, t62, anchor);
      insert(target, div13, anchor);
      append(div13, label9);
      append(label9, span11);
      append(label9, t64);
      append(label9, p9);
      append(div13, t66);
      append(div13, input5);
      input5.checked = /*$hasOverrideSecondaryCurrencies*/
      ctx[3];
      insert(target, t67, anchor);
      insert(target, div14, anchor);
      append(div14, button2);
      append(button2, t68);
      insert(target, t69, anchor);
      insert(target, div15, anchor);
      append(div15, label10);
      append(label10, span12);
      append(label10, t71);
      append(label10, p10);
      append(div15, t73);
      append(div15, input6);
      input6.checked = /*$hasOverrideItemFilters*/
      ctx[2];
      insert(target, t74, anchor);
      insert(target, div16, anchor);
      append(div16, button3);
      append(button3, t75);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler*/
            ctx[15]
          ),
          listen(
            input1,
            "input",
            /*input1_input_handler*/
            ctx[16]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler*/
            ctx[17]
          ),
          listen(
            input3,
            "change",
            /*input3_change_handler*/
            ctx[18]
          ),
          listen(
            select0,
            "change",
            /*select0_change_handler*/
            ctx[20]
          ),
          listen(
            select1,
            "change",
            /*select1_change_handler*/
            ctx[21]
          ),
          listen(
            button0,
            "click",
            /*click_handler*/
            ctx[22]
          ),
          listen(
            input4,
            "change",
            /*input4_change_handler*/
            ctx[23]
          ),
          listen(
            button1,
            "click",
            /*click_handler_1*/
            ctx[24]
          ),
          listen(
            input5,
            "change",
            /*input5_change_handler*/
            ctx[25]
          ),
          listen(
            button2,
            "click",
            /*click_handler_2*/
            ctx[26]
          ),
          listen(
            input6,
            "change",
            /*input6_change_handler*/
            ctx[27]
          ),
          listen(
            button3,
            "click",
            /*click_handler_3*/
            ctx[28]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (!/*$pileEnabled*/
      ctx2[5]) {
        if (if_block)
          ;
        else {
          if_block = create_if_block$j();
          if_block.c();
          if_block.m(span2, t4);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*$pileEnabled*/
      32) {
        input0.checked = /*$pileEnabled*/
        ctx2[5];
      }
      if (dirty & /*pileData*/
      1 && to_number(input1.value) !== /*pileData*/
      ctx2[0].distance) {
        set_input_value(
          input1,
          /*pileData*/
          ctx2[0].distance
        );
      }
      if (dirty & /*pileData*/
      1) {
        input2.checked = /*pileData*/
        ctx2[0].canInspectItems;
      }
      if (dirty & /*pileData*/
      1) {
        input3.checked = /*pileData*/
        ctx2[0].displayItemTypes;
      }
      const macroselector_changes = {};
      if (!updating_macro && dirty & /*pileData*/
      1) {
        updating_macro = true;
        macroselector_changes.macro = /*pileData*/
        ctx2[0].macro;
        add_flush_callback(() => updating_macro = false);
      }
      macroselector.$set(macroselector_changes);
      if (dirty & /*pileData*/
      1) {
        select_option(
          select0,
          /*pileData*/
          ctx2[0].deleteWhenEmpty
        );
      }
      if (dirty & /*pileData*/
      1) {
        select_option(
          select1,
          /*pileData*/
          ctx2[0].canStackItems
        );
      }
      if (dirty & /*$hasOverrideCurrencies*/
      16) {
        input4.checked = /*$hasOverrideCurrencies*/
        ctx2[4];
      }
      if (!current || dirty & /*$hasOverrideCurrencies*/
      16 && button1_disabled_value !== (button1_disabled_value = !/*$hasOverrideCurrencies*/
      ctx2[4])) {
        button1.disabled = button1_disabled_value;
      }
      if (dirty & /*$hasOverrideSecondaryCurrencies*/
      8) {
        input5.checked = /*$hasOverrideSecondaryCurrencies*/
        ctx2[3];
      }
      if (!current || dirty & /*$hasOverrideSecondaryCurrencies*/
      8 && button2_disabled_value !== (button2_disabled_value = !/*$hasOverrideSecondaryCurrencies*/
      ctx2[3])) {
        button2.disabled = button2_disabled_value;
      }
      if (dirty & /*$hasOverrideItemFilters*/
      4) {
        input6.checked = /*$hasOverrideItemFilters*/
        ctx2[2];
      }
      if (!current || dirty & /*$hasOverrideItemFilters*/
      4 && button3_disabled_value !== (button3_disabled_value = !/*$hasOverrideItemFilters*/
      ctx2[2])) {
        button3.disabled = button3_disabled_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(macroselector.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(macroselector.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (if_block)
        if_block.d();
      if (detaching)
        detach(t5);
      if (detaching)
        detach(div1);
      if (detaching)
        detach(t10);
      if (detaching)
        detach(div2);
      if (detaching)
        detach(t15);
      if (detaching)
        detach(div3);
      if (detaching)
        detach(t20);
      if (detaching)
        detach(div4);
      if (detaching)
        detach(t24);
      if (detaching)
        detach(div5);
      destroy_component(macroselector);
      if (detaching)
        detach(t25);
      if (detaching)
        detach(div6);
      if (detaching)
        detach(t36);
      if (detaching)
        detach(div8);
      if (detaching)
        detach(t49);
      if (detaching)
        detach(div9);
      if (detaching)
        detach(t53);
      if (detaching)
        detach(div10);
      if (detaching)
        detach(t55);
      if (detaching)
        detach(div11);
      if (detaching)
        detach(t60);
      if (detaching)
        detach(div12);
      if (detaching)
        detach(t62);
      if (detaching)
        detach(div13);
      if (detaching)
        detach(t67);
      if (detaching)
        detach(div14);
      if (detaching)
        detach(t69);
      if (detaching)
        detach(div15);
      if (detaching)
        detach(t74);
      if (detaching)
        detach(div16);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$x, "create_fragment$x");
function instance$u($$self, $$props, $$invalidate) {
  let $hasOverrideItemFilters;
  let $hasOverrideSecondaryCurrencies;
  let $hasOverrideCurrencies;
  let $pileEnabled, $$unsubscribe_pileEnabled = noop, $$subscribe_pileEnabled = /* @__PURE__ */ __name(() => ($$unsubscribe_pileEnabled(), $$unsubscribe_pileEnabled = subscribe(pileEnabled, ($$value) => $$invalidate(5, $pileEnabled = $$value)), pileEnabled), "$$subscribe_pileEnabled");
  $$self.$$.on_destroy.push(() => $$unsubscribe_pileEnabled());
  let { pileActor } = $$props;
  let { pileData } = $$props;
  let { pileEnabled } = $$props;
  $$subscribe_pileEnabled();
  const deleteWhenEmptySetting = localize(getSetting(SETTINGS$1.DELETE_EMPTY_PILES) ? "Yes" : "No");
  let hasOverrideCurrencies = writable$1(typeof pileData?.overrideCurrencies === "object");
  component_subscribe($$self, hasOverrideCurrencies, (value) => $$invalidate(4, $hasOverrideCurrencies = value));
  let hasOverrideSecondaryCurrencies = writable$1(typeof pileData?.overrideSecondaryCurrencies === "object");
  component_subscribe($$self, hasOverrideSecondaryCurrencies, (value) => $$invalidate(3, $hasOverrideSecondaryCurrencies = value));
  let hasOverrideItemFilters = writable$1(typeof pileData?.overrideItemFilters === "object");
  component_subscribe($$self, hasOverrideItemFilters, (value) => $$invalidate(2, $hasOverrideItemFilters = value));
  async function showCurrenciesEditor() {
    $$invalidate(0, pileData.overrideCurrencies = pileData?.overrideCurrencies || foundry.utils.deepClone(game.itempiles.API.CURRENCIES), pileData);
    return CurrenciesEditor.show(
      pileData.overrideCurrencies,
      {
        id: `currencies-item-pile-config-${pileActor.id}`
      },
      {
        title: game.i18n.format("ITEM-PILES.Applications.CurrenciesEditor.TitleActor", { actor_name: pileActor.name })
      }
    ).then((result) => {
      $$invalidate(0, pileData.overrideCurrencies = result, pileData);
    });
  }
  __name(showCurrenciesEditor, "showCurrenciesEditor");
  async function showSecondaryCurrenciesEditor() {
    $$invalidate(0, pileData.overrideSecondaryCurrencies = pileData?.overrideSecondaryCurrencies || foundry.utils.deepClone(game.itempiles.API.SECONDARY_CURRENCIES), pileData);
    return SecondaryCurrenciesEditor.show(
      pileData.overrideSecondaryCurrencies,
      {
        id: `secondary-currencies-item-pile-config-${pileActor.id}`
      },
      {
        title: game.i18n.format("ITEM-PILES.Applications.SecondaryCurrenciesEditor.TitleActor", { actor_name: pileActor.name })
      }
    ).then((result) => {
      $$invalidate(0, pileData.overrideSecondaryCurrencies = result, pileData);
    });
  }
  __name(showSecondaryCurrenciesEditor, "showSecondaryCurrenciesEditor");
  async function showItemFiltersEditor() {
    $$invalidate(0, pileData.overrideItemFilters = pileData?.overrideItemFilters || foundry.utils.deepClone(game.itempiles.API.ITEM_FILTERS), pileData);
    return ItemFiltersEditor.show(
      pileData.overrideItemFilters,
      {
        id: `item-filters-item-pile-config-${pileActor.id}`
      },
      {
        title: game.i18n.format("ITEM-PILES.Applications.FilterEditor.TitleActor", { actor_name: pileActor.name })
      }
    ).then((result) => {
      $$invalidate(0, pileData.overrideItemFilters = result, pileData);
    });
  }
  __name(showItemFiltersEditor, "showItemFiltersEditor");
  async function showDescriptionDialog() {
    return TextEditorDialog.show(pileData.description, {
      id: "item-pile-text-editor-" + pileActor.id
    }).then((result) => {
      $$invalidate(0, pileData.description = result || "", pileData);
    });
  }
  __name(showDescriptionDialog, "showDescriptionDialog");
  function input0_change_handler() {
    $pileEnabled = this.checked;
    pileEnabled.set($pileEnabled);
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_input_handler() {
    pileData.distance = to_number(this.value);
    $$invalidate(0, pileData), $$invalidate(4, $hasOverrideCurrencies), $$invalidate(3, $hasOverrideSecondaryCurrencies), $$invalidate(2, $hasOverrideItemFilters);
  }
  __name(input1_input_handler, "input1_input_handler");
  function input2_change_handler() {
    pileData.canInspectItems = this.checked;
    $$invalidate(0, pileData), $$invalidate(4, $hasOverrideCurrencies), $$invalidate(3, $hasOverrideSecondaryCurrencies), $$invalidate(2, $hasOverrideItemFilters);
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler() {
    pileData.displayItemTypes = this.checked;
    $$invalidate(0, pileData), $$invalidate(4, $hasOverrideCurrencies), $$invalidate(3, $hasOverrideSecondaryCurrencies), $$invalidate(2, $hasOverrideItemFilters);
  }
  __name(input3_change_handler, "input3_change_handler");
  function macroselector_macro_binding(value) {
    if ($$self.$$.not_equal(pileData.macro, value)) {
      pileData.macro = value;
      $$invalidate(0, pileData), $$invalidate(4, $hasOverrideCurrencies), $$invalidate(3, $hasOverrideSecondaryCurrencies), $$invalidate(2, $hasOverrideItemFilters);
    }
  }
  __name(macroselector_macro_binding, "macroselector_macro_binding");
  function select0_change_handler() {
    pileData.deleteWhenEmpty = select_value(this);
    $$invalidate(0, pileData), $$invalidate(4, $hasOverrideCurrencies), $$invalidate(3, $hasOverrideSecondaryCurrencies), $$invalidate(2, $hasOverrideItemFilters);
  }
  __name(select0_change_handler, "select0_change_handler");
  function select1_change_handler() {
    pileData.canStackItems = select_value(this);
    $$invalidate(0, pileData), $$invalidate(4, $hasOverrideCurrencies), $$invalidate(3, $hasOverrideSecondaryCurrencies), $$invalidate(2, $hasOverrideItemFilters);
  }
  __name(select1_change_handler, "select1_change_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    showDescriptionDialog();
  }, "click_handler");
  function input4_change_handler() {
    $hasOverrideCurrencies = this.checked;
    hasOverrideCurrencies.set($hasOverrideCurrencies);
  }
  __name(input4_change_handler, "input4_change_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    showCurrenciesEditor();
  }, "click_handler_1");
  function input5_change_handler() {
    $hasOverrideSecondaryCurrencies = this.checked;
    hasOverrideSecondaryCurrencies.set($hasOverrideSecondaryCurrencies);
  }
  __name(input5_change_handler, "input5_change_handler");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    showSecondaryCurrenciesEditor();
  }, "click_handler_2");
  function input6_change_handler() {
    $hasOverrideItemFilters = this.checked;
    hasOverrideItemFilters.set($hasOverrideItemFilters);
  }
  __name(input6_change_handler, "input6_change_handler");
  const click_handler_32 = /* @__PURE__ */ __name(() => {
    showItemFiltersEditor();
  }, "click_handler_3");
  $$self.$$set = ($$props2) => {
    if ("pileActor" in $$props2)
      $$invalidate(14, pileActor = $$props2.pileActor);
    if ("pileData" in $$props2)
      $$invalidate(0, pileData = $$props2.pileData);
    if ("pileEnabled" in $$props2)
      $$subscribe_pileEnabled($$invalidate(1, pileEnabled = $$props2.pileEnabled));
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$hasOverrideCurrencies*/
    16) {
      {
        if (!$hasOverrideCurrencies) {
          $$invalidate(0, pileData.overrideCurrencies = false, pileData);
        }
      }
    }
    if ($$self.$$.dirty & /*$hasOverrideSecondaryCurrencies*/
    8) {
      {
        if (!$hasOverrideSecondaryCurrencies) {
          $$invalidate(0, pileData.overrideSecondaryCurrencies = false, pileData);
        }
      }
    }
    if ($$self.$$.dirty & /*$hasOverrideItemFilters*/
    4) {
      {
        if (!$hasOverrideItemFilters) {
          $$invalidate(0, pileData.overrideItemFilters = false, pileData);
        }
      }
    }
  };
  return [
    pileData,
    pileEnabled,
    $hasOverrideItemFilters,
    $hasOverrideSecondaryCurrencies,
    $hasOverrideCurrencies,
    $pileEnabled,
    deleteWhenEmptySetting,
    hasOverrideCurrencies,
    hasOverrideSecondaryCurrencies,
    hasOverrideItemFilters,
    showCurrenciesEditor,
    showSecondaryCurrenciesEditor,
    showItemFiltersEditor,
    showDescriptionDialog,
    pileActor,
    input0_change_handler,
    input1_input_handler,
    input2_change_handler,
    input3_change_handler,
    macroselector_macro_binding,
    select0_change_handler,
    select1_change_handler,
    click_handler,
    input4_change_handler,
    click_handler_1,
    input5_change_handler,
    click_handler_2,
    input6_change_handler,
    click_handler_32
  ];
}
__name(instance$u, "instance$u");
const _Main = class _Main extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$u, create_fragment$x, safe_not_equal, {
      pileActor: 14,
      pileData: 0,
      pileEnabled: 1
    });
  }
};
__name(_Main, "Main");
let Main = _Main;
const itemTypePriceModifiersEditor_svelte_svelte_type_style_lang = "";
function get_each_context$g(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[20] = list[i];
  child_ctx[21] = list;
  child_ctx[22] = i;
  return child_ctx;
}
__name(get_each_context$g, "get_each_context$g");
function get_each_context_1$8(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[23] = list[i];
  return child_ctx;
}
__name(get_each_context_1$8, "get_each_context_1$8");
function get_each_context_2$2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[26] = list[i][0];
  child_ctx[27] = list[i][1];
  return child_ctx;
}
__name(get_each_context_2$2, "get_each_context_2$2");
function create_each_block_2$2(key_1, ctx) {
  let option;
  let t0_value = localize(
    /*label*/
    ctx[27]
  ) + "";
  let t0;
  let t1;
  let option_selected_value;
  let option_disabled_value;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t0 = text(t0_value);
      t1 = space();
      option.__value = /*itemType*/
      ctx[26];
      option.value = option.__value;
      option.selected = option_selected_value = /*priceData*/
      ctx[20].type === /*itemType*/
      ctx[26];
      option.disabled = option_disabled_value = /*itemType*/
      ctx[26] !== /*priceData*/
      ctx[20].type && !/*unusedTypes*/
      ctx[4].includes(
        /*itemType*/
        ctx[26]
      );
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$itemTypePriceModifiers*/
      4 && option_selected_value !== (option_selected_value = /*priceData*/
      ctx[20].type === /*itemType*/
      ctx[26])) {
        option.selected = option_selected_value;
      }
      if (dirty & /*$itemTypePriceModifiers, unusedTypes*/
      20 && option_disabled_value !== (option_disabled_value = /*itemType*/
      ctx[26] !== /*priceData*/
      ctx[20].type && !/*unusedTypes*/
      ctx[4].includes(
        /*itemType*/
        ctx[26]
      ))) {
        option.disabled = option_disabled_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_2$2, "create_each_block_2$2");
function create_if_block$i(ctx) {
  let optgroup;
  let each_value_1 = (
    /*currentCustomCategories*/
    ctx[8]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_1$8(get_each_context_1$8(ctx, each_value_1, i));
  }
  return {
    c() {
      optgroup = element("optgroup");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(optgroup, "label", "Custom Categories");
    },
    m(target, anchor) {
      insert(target, optgroup, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(optgroup, null);
        }
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*$itemTypePriceModifiers, currentCustomCategories, unusedTypes*/
      276) {
        each_value_1 = /*currentCustomCategories*/
        ctx2[8];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1$8(ctx2, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_1$8(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(optgroup, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
    },
    d(detaching) {
      if (detaching)
        detach(optgroup);
      destroy_each(each_blocks, detaching);
    }
  };
}
__name(create_if_block$i, "create_if_block$i");
function create_each_block_1$8(ctx) {
  let option;
  let t0_value = (
    /*customCategory*/
    ctx[23] + ""
  );
  let t0;
  let t1;
  let option_selected_value;
  let option_disabled_value;
  return {
    c() {
      option = element("option");
      t0 = text(t0_value);
      t1 = space();
      option.__value = "custom";
      option.value = option.__value;
      option.selected = option_selected_value = /*priceData*/
      ctx[20].type === "custom" && /*customCategory*/
      ctx[23].toLowerCase() === /*priceData*/
      ctx[20].category.toLowerCase();
      option.disabled = option_disabled_value = /*customCategory*/
      ctx[23].toLowerCase() !== /*priceData*/
      ctx[20].category.toLowerCase() && !/*unusedTypes*/
      ctx[4].includes(
        /*customCategory*/
        ctx[23].toLowerCase()
      );
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p(ctx2, dirty) {
      if (dirty & /*$itemTypePriceModifiers*/
      4 && option_selected_value !== (option_selected_value = /*priceData*/
      ctx2[20].type === "custom" && /*customCategory*/
      ctx2[23].toLowerCase() === /*priceData*/
      ctx2[20].category.toLowerCase())) {
        option.selected = option_selected_value;
      }
      if (dirty & /*$itemTypePriceModifiers, unusedTypes*/
      20 && option_disabled_value !== (option_disabled_value = /*customCategory*/
      ctx2[23].toLowerCase() !== /*priceData*/
      ctx2[20].category.toLowerCase() && !/*unusedTypes*/
      ctx2[4].includes(
        /*customCategory*/
        ctx2[23].toLowerCase()
      ))) {
        option.disabled = option_disabled_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_1$8, "create_each_block_1$8");
function create_each_block$g(key_1, ctx) {
  let tr;
  let td0;
  let div0;
  let input;
  let t0;
  let td1;
  let div1;
  let select;
  let optgroup;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t1;
  let td2;
  let div2;
  let sliderinput0;
  let updating_value;
  let t2;
  let td3;
  let div3;
  let sliderinput1;
  let updating_value_1;
  let t3;
  let td4;
  let button;
  let t4;
  let current;
  let mounted;
  let dispose;
  function input_change_handler() {
    ctx[13].call(
      input,
      /*each_value*/
      ctx[21],
      /*index*/
      ctx[22]
    );
  }
  __name(input_change_handler, "input_change_handler");
  let each_value_2 = (
    /*systemTypes*/
    ctx[7]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*itemType*/
    ctx2[26]
  ), "get_key");
  for (let i = 0; i < each_value_2.length; i += 1) {
    let child_ctx = get_each_context_2$2(ctx, each_value_2, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_2$2(key, child_ctx));
  }
  let if_block = (
    /*currentCustomCategories*/
    ctx[8].length && create_if_block$i(ctx)
  );
  function change_handler(...args) {
    return (
      /*change_handler*/
      ctx[14](
        /*priceData*/
        ctx[20],
        /*each_value*/
        ctx[21],
        /*index*/
        ctx[22],
        ...args
      )
    );
  }
  __name(change_handler, "change_handler");
  function sliderinput0_value_binding(value) {
    ctx[15](
      value,
      /*priceData*/
      ctx[20]
    );
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  let sliderinput0_props = { style: "flex:4;" };
  if (
    /*priceData*/
    ctx[20].buyPriceModifier !== void 0
  ) {
    sliderinput0_props.value = /*priceData*/
    ctx[20].buyPriceModifier;
  }
  sliderinput0 = new SliderInput({ props: sliderinput0_props });
  binding_callbacks.push(() => bind(sliderinput0, "value", sliderinput0_value_binding));
  function sliderinput1_value_binding(value) {
    ctx[16](
      value,
      /*priceData*/
      ctx[20]
    );
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  let sliderinput1_props = { style: "flex:4;" };
  if (
    /*priceData*/
    ctx[20].sellPriceModifier !== void 0
  ) {
    sliderinput1_props.value = /*priceData*/
    ctx[20].sellPriceModifier;
  }
  sliderinput1 = new SliderInput({ props: sliderinput1_props });
  binding_callbacks.push(() => bind(sliderinput1, "value", sliderinput1_value_binding));
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      div0 = element("div");
      input = element("input");
      t0 = space();
      td1 = element("td");
      div1 = element("div");
      select = element("select");
      optgroup = element("optgroup");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      if (if_block)
        if_block.c();
      t1 = space();
      td2 = element("td");
      div2 = element("div");
      create_component(sliderinput0.$$.fragment);
      t2 = space();
      td3 = element("td");
      div3 = element("div");
      create_component(sliderinput1.$$.fragment);
      t3 = space();
      td4 = element("td");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      t4 = space();
      attr(input, "type", "checkbox");
      attr(div0, "class", "form-group");
      attr(optgroup, "label", "System Types");
      attr(div1, "class", "form-group");
      attr(div2, "class", "item-piles-flexrow");
      set_style(div2, "margin", "0 0.25rem");
      attr(div3, "class", "item-piles-flexrow");
      set_style(div3, "margin", "0 0.25rem");
      attr(button, "type", "button");
      attr(button, "class", "svelte-a1mqx5");
      attr(td4, "class", "small");
      attr(tr, "class", "svelte-a1mqx5");
      this.first = tr;
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, div0);
      append(div0, input);
      input.checked = /*priceData*/
      ctx[20].override;
      append(tr, t0);
      append(tr, td1);
      append(td1, div1);
      append(div1, select);
      append(select, optgroup);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(optgroup, null);
        }
      }
      if (if_block)
        if_block.m(select, null);
      append(tr, t1);
      append(tr, td2);
      append(td2, div2);
      mount_component(sliderinput0, div2, null);
      append(tr, t2);
      append(tr, td3);
      append(td3, div3);
      mount_component(sliderinput1, div3, null);
      append(tr, t3);
      append(tr, td4);
      append(td4, button);
      append(tr, t4);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input, "change", input_change_handler),
          listen(select, "change", change_handler),
          listen(button, "click", function() {
            if (is_function(
              /*remove*/
              ctx[10](
                /*index*/
                ctx[22]
              )
            ))
              ctx[10](
                /*index*/
                ctx[22]
              ).apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$itemTypePriceModifiers*/
      4) {
        input.checked = /*priceData*/
        ctx[20].override;
      }
      if (dirty & /*systemTypes, $itemTypePriceModifiers, unusedTypes, localize*/
      148) {
        each_value_2 = /*systemTypes*/
        ctx[7];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_2, each_1_lookup, optgroup, destroy_block, create_each_block_2$2, null, get_each_context_2$2);
      }
      if (
        /*currentCustomCategories*/
        ctx[8].length
      )
        if_block.p(ctx, dirty);
      const sliderinput0_changes = {};
      if (!updating_value && dirty & /*$itemTypePriceModifiers*/
      4) {
        updating_value = true;
        sliderinput0_changes.value = /*priceData*/
        ctx[20].buyPriceModifier;
        add_flush_callback(() => updating_value = false);
      }
      sliderinput0.$set(sliderinput0_changes);
      const sliderinput1_changes = {};
      if (!updating_value_1 && dirty & /*$itemTypePriceModifiers*/
      4) {
        updating_value_1 = true;
        sliderinput1_changes.value = /*priceData*/
        ctx[20].sellPriceModifier;
        add_flush_callback(() => updating_value_1 = false);
      }
      sliderinput1.$set(sliderinput1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sliderinput0.$$.fragment, local);
      transition_in(sliderinput1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sliderinput0.$$.fragment, local);
      transition_out(sliderinput1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if (if_block)
        if_block.d();
      destroy_component(sliderinput0);
      destroy_component(sliderinput1);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$g, "create_each_block$g");
function create_default_slot$e(ctx) {
  let form_1;
  let p;
  let t1;
  let div;
  let table;
  let tr;
  let th0;
  let t3;
  let th1;
  let t5;
  let th2;
  let t7;
  let th3;
  let t9;
  let th4;
  let span;
  let t10;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t11;
  let footer;
  let button0;
  let i1;
  let t12;
  let t13_value = localize("Save") + "";
  let t13;
  let t14;
  let button1;
  let i2;
  let t15;
  let t16_value = localize("Cancel") + "";
  let t16;
  let current;
  let mounted;
  let dispose;
  let each_value = (
    /*$itemTypePriceModifiers*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[22]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$g(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$g(key, child_ctx));
  }
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.ItemTypePriceModifiersEditor.Explanation")}`;
      t1 = space();
      div = element("div");
      table = element("table");
      tr = element("tr");
      th0 = element("th");
      th0.textContent = `${localize("ITEM-PILES.Applications.ItemTypePriceModifiersEditor.Override")}`;
      t3 = space();
      th1 = element("th");
      th1.textContent = `${localize("ITEM-PILES.Applications.ItemTypePriceModifiersEditor.ItemType")}`;
      t5 = space();
      th2 = element("th");
      th2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.BuyPriceModifier")}`;
      t7 = space();
      th3 = element("th");
      th3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.SellPriceModifier")}`;
      t9 = space();
      th4 = element("th");
      span = element("span");
      span.innerHTML = `<i class="fas fa-plus"></i>`;
      t10 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t11 = space();
      footer = element("footer");
      button0 = element("button");
      i1 = element("i");
      t12 = space();
      t13 = text(t13_value);
      t14 = space();
      button1 = element("button");
      i2 = element("i");
      t15 = space();
      t16 = text(t16_value);
      set_style(th0, "width", "5%");
      set_style(th1, "width", "20%");
      set_style(th2, "width", "35%");
      set_style(th3, "width", "35%");
      toggle_class(
        span,
        "item-piles-clickable-link",
        /*unusedTypes*/
        ctx[4].length
      );
      set_style(th4, "width", "5%");
      attr(tr, "class", "svelte-a1mqx5");
      attr(table, "class", "svelte-a1mqx5");
      attr(i1, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i2, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(form_1, t1);
      append(form_1, div);
      append(div, table);
      append(table, tr);
      append(tr, th0);
      append(tr, t3);
      append(tr, th1);
      append(tr, t5);
      append(tr, th2);
      append(tr, t7);
      append(tr, th3);
      append(tr, t9);
      append(tr, th4);
      append(th4, span);
      append(table, t10);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(table, null);
        }
      }
      append(form_1, t11);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i1);
      append(button0, t12);
      append(button0, t13);
      append(footer, t14);
      append(footer, button1);
      append(button1, i2);
      append(button1, t15);
      append(button1, t16);
      ctx[18](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            span,
            "click",
            /*add*/
            ctx[9]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[17],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[11]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty & /*unusedTypes*/
      16) {
        toggle_class(
          span,
          "item-piles-clickable-link",
          /*unusedTypes*/
          ctx2[4].length
        );
      }
      if (dirty & /*remove, $itemTypePriceModifiers, currentCustomCategories, unusedTypes, systemTypes, localize*/
      1428) {
        each_value = /*$itemTypePriceModifiers*/
        ctx2[2];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, table, outro_and_destroy_block, create_each_block$g, null, get_each_context$g);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[18](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$e, "create_default_slot$e");
function create_fragment$w(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[19](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$e] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $itemTypePriceModifiers, unusedTypes*/
      1073741852) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$w, "create_fragment$w");
function instance$t($$self, $$props, $$invalidate) {
  let $itemTypePriceModifiers;
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let { data: data2 = [] } = $$props;
  const itemTypePriceModifiers = writable$1(data2);
  component_subscribe($$self, itemTypePriceModifiers, (value) => $$invalidate(2, $itemTypePriceModifiers = value));
  let form;
  let unusedTypes;
  let systemTypes = Object.entries(CONFIG.Item.typeLabels);
  let currentCustomCategories = Array.from(new Set(getSetting(SETTINGS$1.CUSTOM_ITEM_CATEGORIES)));
  function add() {
    if (!unusedTypes.length)
      return;
    itemTypePriceModifiers.update((val) => {
      val.push({
        type: unusedTypes[0],
        category: "",
        override: false,
        buyPriceModifier: 1,
        sellPriceModifier: 0.5
      });
      return val;
    });
  }
  __name(add, "add");
  function remove(index2) {
    itemTypePriceModifiers.update((val) => {
      val.splice(index2, 1);
      return val;
    });
  }
  __name(remove, "remove");
  async function updateSettings() {
    application.options.resolve?.(get_store_value(itemTypePriceModifiers));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function input_change_handler(each_value, index2) {
    each_value[index2].override = this.checked;
    itemTypePriceModifiers.set($itemTypePriceModifiers);
  }
  __name(input_change_handler, "input_change_handler");
  const change_handler = /* @__PURE__ */ __name((priceData, each_value, index2, e) => {
    set_store_value(itemTypePriceModifiers, each_value[index2].type = e.target.value, $itemTypePriceModifiers);
    set_store_value(
      itemTypePriceModifiers,
      each_value[index2].category = e.target.value === "custom" ? e.target.options[e.target.selectedIndex].text.toLowerCase() : "",
      $itemTypePriceModifiers
    );
  }, "change_handler");
  function sliderinput0_value_binding(value, priceData) {
    if ($$self.$$.not_equal(priceData.buyPriceModifier, value)) {
      priceData.buyPriceModifier = value;
      itemTypePriceModifiers.set($itemTypePriceModifiers);
    }
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  function sliderinput1_value_binding(value, priceData) {
    if ($$self.$$.not_equal(priceData.sellPriceModifier, value)) {
      priceData.sellPriceModifier = value;
      itemTypePriceModifiers.set($itemTypePriceModifiers);
    }
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(3, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("data" in $$props2)
      $$invalidate(12, data2 = $$props2.data);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$itemTypePriceModifiers*/
    4) {
      {
        const allTypes = systemTypes.map(([type]) => type).concat(currentCustomCategories).map((type) => type.toLowerCase());
        $$invalidate(4, unusedTypes = allTypes.filter((type) => {
          return !$itemTypePriceModifiers.some((priceData) => priceData.type === type || priceData.type === "custom" && priceData.category === type);
        }));
      }
    }
  };
  return [
    elementRoot,
    requestSubmit,
    $itemTypePriceModifiers,
    form,
    unusedTypes,
    application,
    itemTypePriceModifiers,
    systemTypes,
    currentCustomCategories,
    add,
    remove,
    updateSettings,
    data2,
    input_change_handler,
    change_handler,
    sliderinput0_value_binding,
    sliderinput1_value_binding,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$t, "instance$t");
const _Item_type_price_modifiers_editor = class _Item_type_price_modifiers_editor extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$t, create_fragment$w, safe_not_equal, {
      elementRoot: 0,
      data: 12,
      requestSubmit: 1
    });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get data() {
    return this.$$.ctx[12];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Item_type_price_modifiers_editor, "Item_type_price_modifiers_editor");
let Item_type_price_modifiers_editor = _Item_type_price_modifiers_editor;
const _ItemTypePriceModifiersEditor = class _ItemTypePriceModifiersEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Applications.ItemTypePriceModifiersEditor.Title"),
      width: 600,
      svelte: {
        class: Item_type_price_modifiers_editor
      }
    });
  }
};
__name(_ItemTypePriceModifiersEditor, "ItemTypePriceModifiersEditor");
let ItemTypePriceModifiersEditor = _ItemTypePriceModifiersEditor;
const priceModifiersEditorShell_svelte_svelte_type_style_lang = "";
function get_each_context$f(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[16] = list[i];
  child_ctx[17] = list;
  child_ctx[18] = i;
  return child_ctx;
}
__name(get_each_context$f, "get_each_context$f");
function create_if_block$h(ctx) {
  let table;
  let tr;
  let th0;
  let t1;
  let th1;
  let t3;
  let th2;
  let t5;
  let th3;
  let t7;
  let th4;
  let t8;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let current;
  let each_value = (
    /*$priceModifiers*/
    ctx[3]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[18]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$f(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$f(key, child_ctx));
  }
  return {
    c() {
      table = element("table");
      tr = element("tr");
      th0 = element("th");
      th0.textContent = `${localize("ITEM-PILES.Applications.PriceModifiersEditor.Override")}`;
      t1 = space();
      th1 = element("th");
      th1.textContent = `${localize("ITEM-PILES.Applications.PriceModifiersEditor.Actor")}`;
      t3 = space();
      th2 = element("th");
      th2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.BuyPriceModifier")}`;
      t5 = space();
      th3 = element("th");
      th3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.SellPriceModifier")}`;
      t7 = space();
      th4 = element("th");
      t8 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      set_style(th0, "width", "5%");
      set_style(th1, "width", "25%");
      set_style(th2, "width", "35%");
      set_style(th3, "width", "35%");
      set_style(th4, "width", "5%");
      attr(tr, "class", "svelte-xx5053");
      attr(table, "class", "svelte-xx5053");
    },
    m(target, anchor) {
      insert(target, table, anchor);
      append(table, tr);
      append(tr, th0);
      append(tr, t1);
      append(tr, th1);
      append(tr, t3);
      append(tr, th2);
      append(tr, t5);
      append(tr, th3);
      append(tr, t7);
      append(tr, th4);
      append(table, t8);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(table, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*remove, $priceModifiers*/
      72) {
        each_value = /*$priceModifiers*/
        ctx2[3];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, table, outro_and_destroy_block, create_each_block$f, null, get_each_context$f);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(table);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_if_block$h, "create_if_block$h");
function create_each_block$f(key_1, ctx) {
  let tr;
  let td0;
  let div0;
  let input;
  let t0;
  let td1;
  let a;
  let t1_value = (
    /*priceData*/
    ctx[16].actor.name + ""
  );
  let t1;
  let t2;
  let td2;
  let div1;
  let sliderinput0;
  let updating_value;
  let t3;
  let td3;
  let div2;
  let sliderinput1;
  let updating_value_1;
  let t4;
  let td4;
  let button;
  let t5;
  let current;
  let mounted;
  let dispose;
  function input_change_handler() {
    ctx[10].call(
      input,
      /*each_value*/
      ctx[17],
      /*index*/
      ctx[18]
    );
  }
  __name(input_change_handler, "input_change_handler");
  function sliderinput0_value_binding(value) {
    ctx[11](
      value,
      /*priceData*/
      ctx[16]
    );
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  let sliderinput0_props = {};
  if (
    /*priceData*/
    ctx[16].buyPriceModifier !== void 0
  ) {
    sliderinput0_props.value = /*priceData*/
    ctx[16].buyPriceModifier;
  }
  sliderinput0 = new SliderInput({ props: sliderinput0_props });
  binding_callbacks.push(() => bind(sliderinput0, "value", sliderinput0_value_binding));
  function sliderinput1_value_binding(value) {
    ctx[12](
      value,
      /*priceData*/
      ctx[16]
    );
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  let sliderinput1_props = {};
  if (
    /*priceData*/
    ctx[16].sellPriceModifier !== void 0
  ) {
    sliderinput1_props.value = /*priceData*/
    ctx[16].sellPriceModifier;
  }
  sliderinput1 = new SliderInput({ props: sliderinput1_props });
  binding_callbacks.push(() => bind(sliderinput1, "value", sliderinput1_value_binding));
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      div0 = element("div");
      input = element("input");
      t0 = space();
      td1 = element("td");
      a = element("a");
      t1 = text(t1_value);
      t2 = space();
      td2 = element("td");
      div1 = element("div");
      create_component(sliderinput0.$$.fragment);
      t3 = space();
      td3 = element("td");
      div2 = element("div");
      create_component(sliderinput1.$$.fragment);
      t4 = space();
      td4 = element("td");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      t5 = space();
      attr(input, "type", "checkbox");
      attr(div0, "class", "form-group");
      attr(a, "class", "item-piles-actor-name-clickable svelte-xx5053");
      attr(div1, "class", "item-piles-flexrow");
      set_style(div1, "margin", "0 0.25rem");
      attr(div2, "class", "item-piles-flexrow");
      set_style(div2, "margin", "0 0.25rem");
      attr(button, "type", "button");
      attr(button, "class", "svelte-xx5053");
      attr(td4, "class", "small svelte-xx5053");
      attr(tr, "class", "svelte-xx5053");
      this.first = tr;
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, div0);
      append(div0, input);
      input.checked = /*priceData*/
      ctx[16].override;
      append(tr, t0);
      append(tr, td1);
      append(td1, a);
      append(a, t1);
      append(tr, t2);
      append(tr, td2);
      append(td2, div1);
      mount_component(sliderinput0, div1, null);
      append(tr, t3);
      append(tr, td3);
      append(td3, div2);
      mount_component(sliderinput1, div2, null);
      append(tr, t4);
      append(tr, td4);
      append(td4, button);
      append(tr, t5);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input, "change", input_change_handler),
          listen(a, "click", function() {
            if (is_function(
              /*priceData*/
              ctx[16].actor.sheet.render(true, { bypassItemPiles: true })
            ))
              ctx[16].actor.sheet.render(true, { bypassItemPiles: true }).apply(this, arguments);
          }),
          listen(button, "click", function() {
            if (is_function(
              /*remove*/
              ctx[6](
                /*index*/
                ctx[18]
              )
            ))
              ctx[6](
                /*index*/
                ctx[18]
              ).apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$priceModifiers*/
      8) {
        input.checked = /*priceData*/
        ctx[16].override;
      }
      if ((!current || dirty & /*$priceModifiers*/
      8) && t1_value !== (t1_value = /*priceData*/
      ctx[16].actor.name + ""))
        set_data(t1, t1_value);
      const sliderinput0_changes = {};
      if (!updating_value && dirty & /*$priceModifiers*/
      8) {
        updating_value = true;
        sliderinput0_changes.value = /*priceData*/
        ctx[16].buyPriceModifier;
        add_flush_callback(() => updating_value = false);
      }
      sliderinput0.$set(sliderinput0_changes);
      const sliderinput1_changes = {};
      if (!updating_value_1 && dirty & /*$priceModifiers*/
      8) {
        updating_value_1 = true;
        sliderinput1_changes.value = /*priceData*/
        ctx[16].sellPriceModifier;
        add_flush_callback(() => updating_value_1 = false);
      }
      sliderinput1.$set(sliderinput1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sliderinput0.$$.fragment, local);
      transition_in(sliderinput1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sliderinput0.$$.fragment, local);
      transition_out(sliderinput1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      destroy_component(sliderinput0);
      destroy_component(sliderinput1);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$f, "create_each_block$f");
function create_default_slot$d(ctx) {
  let form_1;
  let p0;
  let t1;
  let div;
  let t2;
  let p1;
  let t4;
  let footer;
  let button0;
  let i0;
  let t5;
  let t6_value = localize("Save") + "";
  let t6;
  let t7;
  let button1;
  let i1;
  let t8;
  let t9_value = localize("Cancel") + "";
  let t9;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*$priceModifiers*/
    ctx[3].length && create_if_block$h(ctx)
  );
  return {
    c() {
      form_1 = element("form");
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.PriceModifiersEditor.Explanation")}`;
      t1 = space();
      div = element("div");
      if (if_block)
        if_block.c();
      t2 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.PriceModifiersEditor.DragDrop")}`;
      t4 = space();
      footer = element("footer");
      button0 = element("button");
      i0 = element("i");
      t5 = space();
      t6 = text(t6_value);
      t7 = space();
      button1 = element("button");
      i1 = element("i");
      t8 = space();
      t9 = text(t9_value);
      attr(p1, "class", "item-piles-text-center");
      attr(div, "class", "svelte-xx5053");
      toggle_class(div, "border-highlight", !/*$priceModifiers*/
      ctx[3].length);
      attr(i0, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i1, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p0);
      append(form_1, t1);
      append(form_1, div);
      if (if_block)
        if_block.m(div, null);
      append(div, t2);
      append(div, p1);
      append(form_1, t4);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i0);
      append(button0, t5);
      append(button0, t6);
      append(footer, t7);
      append(footer, button1);
      append(button1, i1);
      append(button1, t8);
      append(button1, t9);
      ctx[14](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(div, "dragover", preventDefault$1),
          listen(div, "dragstart", preventDefault$1),
          listen(
            div,
            "drop",
            /*dropData*/
            ctx[8]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[13],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[7]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*$priceModifiers*/
        ctx2[3].length
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*$priceModifiers*/
          8) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$h(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div, t2);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty & /*$priceModifiers*/
      8) {
        toggle_class(div, "border-highlight", !/*$priceModifiers*/
        ctx2[3].length);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      if (if_block)
        if_block.d();
      ctx[14](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$d, "create_default_slot$d");
function create_fragment$v(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[15](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$d] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $priceModifiers*/
      524300) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$v, "create_fragment$v");
function preventDefault$1(event) {
  event.preventDefault();
}
__name(preventDefault$1, "preventDefault$1");
function instance$s($$self, $$props, $$invalidate) {
  let $priceModifiers;
  const { application } = getContext("#external");
  let form;
  let { data: data2 } = $$props;
  let { elementRoot } = $$props;
  const priceModifiers = writable$1(data2.map((data3) => {
    data3.actor = globalThis.fromUuidSync(data3.actorUuid);
    if (!data3.actor)
      return false;
    return data3;
  }).filter(Boolean));
  component_subscribe($$self, priceModifiers, (value) => $$invalidate(3, $priceModifiers = value));
  function remove(index2) {
    priceModifiers.update((val) => {
      val.splice(index2, 1);
      return val;
    });
  }
  __name(remove, "remove");
  async function updateSettings() {
    let result = get_store_value(priceModifiers);
    result.forEach((data3) => {
      data3.actorUuid = getUuid(data3.actor);
    });
    application.options.resolve?.(result);
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  async function dropData(event) {
    event.preventDefault();
    let data3;
    try {
      data3 = JSON.parse(event.dataTransfer.getData("text/plain"));
    } catch (err) {
      return false;
    }
    if (data3.type !== "Actor")
      return;
    const actor = getSourceActorFromDropData(data3);
    if (!actor)
      return;
    priceModifiers.update((val) => {
      if (val.find((data4) => data4.actor === actor))
        return val;
      val.push({
        override: false,
        actor,
        buyPriceModifier: 1,
        sellPriceModifier: 0.5
      });
      return val;
    });
  }
  __name(dropData, "dropData");
  function input_change_handler(each_value, index2) {
    each_value[index2].override = this.checked;
    priceModifiers.set($priceModifiers);
  }
  __name(input_change_handler, "input_change_handler");
  function sliderinput0_value_binding(value, priceData) {
    if ($$self.$$.not_equal(priceData.buyPriceModifier, value)) {
      priceData.buyPriceModifier = value;
      priceModifiers.set($priceModifiers);
    }
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  function sliderinput1_value_binding(value, priceData) {
    if ($$self.$$.not_equal(priceData.sellPriceModifier, value)) {
      priceData.sellPriceModifier = value;
      priceModifiers.set($priceModifiers);
    }
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(9, data2 = $$props2.data);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  return [
    elementRoot,
    requestSubmit,
    form,
    $priceModifiers,
    application,
    priceModifiers,
    remove,
    updateSettings,
    dropData,
    data2,
    input_change_handler,
    sliderinput0_value_binding,
    sliderinput1_value_binding,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$s, "instance$s");
const _Price_modifiers_editor_shell = class _Price_modifiers_editor_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$s, create_fragment$v, safe_not_equal, {
      data: 9,
      elementRoot: 0,
      requestSubmit: 1
    });
  }
  get data() {
    return this.$$.ctx[9];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Price_modifiers_editor_shell, "Price_modifiers_editor_shell");
let Price_modifiers_editor_shell = _Price_modifiers_editor_shell;
const _PriceModifiersEditor = class _PriceModifiersEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Applications.PriceModifiersEditor.Title"),
      width: 600,
      svelte: {
        class: Price_modifiers_editor_shell
      }
    });
  }
};
__name(_PriceModifiersEditor, "PriceModifiersEditor");
let PriceModifiersEditor = _PriceModifiersEditor;
function get_each_context$e(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
__name(get_each_context$e, "get_each_context$e");
function create_each_block$e(ctx) {
  let option;
  let t_value = (
    /*suggestion*/
    ctx[8] + ""
  );
  let t;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*suggestion*/
      ctx[8];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*suggestions*/
      4 && t_value !== (t_value = /*suggestion*/
      ctx2[8] + ""))
        set_data(t, t_value);
      if (dirty & /*suggestions*/
      4 && option_value_value !== (option_value_value = /*suggestion*/
      ctx2[8])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$e, "create_each_block$e");
function create_fragment$u(ctx) {
  let input;
  let t;
  let datalist;
  let mounted;
  let dispose;
  let each_value = (
    /*suggestions*/
    ctx[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$e(get_each_context$e(ctx, each_value, i));
  }
  return {
    c() {
      input = element("input");
      t = space();
      datalist = element("datalist");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(
        input,
        "list",
        /*id*/
        ctx[3]
      );
      input.required = /*required*/
      ctx[1];
      attr(input, "type", "text");
      attr(
        datalist,
        "id",
        /*id*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*value*/
        ctx[0]
      );
      insert(target, t, anchor);
      insert(target, datalist, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(datalist, null);
        }
      }
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler*/
          ctx[5]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*required*/
      2) {
        input.required = /*required*/
        ctx2[1];
      }
      if (dirty & /*value*/
      1 && input.value !== /*value*/
      ctx2[0]) {
        set_input_value(
          input,
          /*value*/
          ctx2[0]
        );
      }
      if (dirty & /*suggestions*/
      4) {
        each_value = /*suggestions*/
        ctx2[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$e(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block$e(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(datalist, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(input);
      if (detaching)
        detach(t);
      if (detaching)
        detach(datalist);
      destroy_each(each_blocks, detaching);
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$u, "create_fragment$u");
function instance$r($$self, $$props, $$invalidate) {
  let { value = "" } = $$props;
  let { templateType } = $$props;
  let { required = false } = $$props;
  const id = "property-list-" + randomID();
  const templates = foundry.utils.deepClone(game.system.template[templateType]);
  const templateObject = {
    name: "",
    type: "",
    system: templates.types.map((type) => {
      let obj = templates[type];
      if (obj["templates"]) {
        for (const template of obj["templates"]) {
          obj = foundry.utils.mergeObject(obj, templates["templates"][template]);
        }
        delete obj["templates"];
      }
      return obj;
    }).reduce(
      (acc, obj) => {
        return foundry.utils.mergeObject(acc, obj);
      },
      {}
    )
  };
  let suggestions = [];
  function input_input_handler() {
    value = this.value;
    $$invalidate(0, value);
  }
  __name(input_input_handler, "input_input_handler");
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(0, value = $$props2.value);
    if ("templateType" in $$props2)
      $$invalidate(4, templateType = $$props2.templateType);
    if ("required" in $$props2)
      $$invalidate(1, required = $$props2.required);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*value*/
    1) {
      {
        let trimmedValue = value.trim();
        let options = getProperty(templateObject, trimmedValue);
        if (!options) {
          trimmedValue = trimmedValue.split(".").slice(0, -1).join(".");
          options = getProperty(templateObject, trimmedValue);
        }
        $$invalidate(2, suggestions = options ? Object.keys(options).map((t) => trimmedValue + "." + t).sort() : Object.keys(templateObject));
      }
    }
  };
  return [value, required, suggestions, id, templateType, input_input_handler];
}
__name(instance$r, "instance$r");
const _PropertyPathInput = class _PropertyPathInput extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$r, create_fragment$u, safe_not_equal, { value: 0, templateType: 4, required: 1 });
  }
};
__name(_PropertyPathInput, "PropertyPathInput");
let PropertyPathInput = _PropertyPathInput;
const stringListEditor_svelte_svelte_type_style_lang = "";
function get_each_context_1$7(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[18] = list[i];
  child_ctx[21] = list;
  child_ctx[20] = i;
  return child_ctx;
}
__name(get_each_context_1$7, "get_each_context_1$7");
function get_each_context$d(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[17] = list[i][0];
  child_ctx[18] = list[i][1];
  child_ctx[19] = list;
  child_ctx[20] = i;
  return child_ctx;
}
__name(get_each_context$d, "get_each_context$d");
function create_if_block_2$7(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize(
        /*application*/
        ctx[4].options.content
      )}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_2$7, "create_if_block_2$7");
function create_if_block_1$b(ctx) {
  let th;
  return {
    c() {
      th = element("th");
      th.textContent = `${localize(
        /*application*/
        ctx[4].options?.columnKey
      )}`;
    },
    m(target, anchor) {
      insert(target, th, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(th);
    }
  };
}
__name(create_if_block_1$b, "create_if_block_1$b");
function create_else_block$8(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let each_value_1 = (
    /*$stringListStore*/
    ctx[3]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[20]
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$7(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$7(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*remove, $stringListStore*/
      264) {
        each_value_1 = /*$stringListStore*/
        ctx2[3];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_1, each_1_lookup, each_1_anchor.parentNode, destroy_block, create_each_block_1$7, each_1_anchor, get_each_context_1$7);
      }
    },
    d(detaching) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_else_block$8, "create_else_block$8");
function create_if_block$g(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let each_value = (
    /*$stringListStore*/
    ctx[3]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[20]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$d(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$d(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*remove, $stringListStore*/
      264) {
        each_value = /*$stringListStore*/
        ctx2[3];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, each_1_anchor.parentNode, destroy_block, create_each_block$d, each_1_anchor, get_each_context$d);
      }
    },
    d(detaching) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block$g, "create_if_block$g");
function create_each_block_1$7(key_1, ctx) {
  let tr;
  let td0;
  let input;
  let t0;
  let td1;
  let button;
  let t1;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx[13].call(
      input,
      /*each_value_1*/
      ctx[21],
      /*index*/
      ctx[20]
    );
  }
  __name(input_input_handler, "input_input_handler");
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      input = element("input");
      t0 = space();
      td1 = element("td");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      t1 = space();
      attr(input, "type", "text");
      input.required = true;
      attr(button, "type", "button");
      attr(button, "class", "svelte-vd7iuf");
      attr(td1, "class", "small svelte-vd7iuf");
      attr(tr, "class", "svelte-vd7iuf");
      this.first = tr;
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, input);
      set_input_value(
        input,
        /*path*/
        ctx[18]
      );
      append(tr, t0);
      append(tr, td1);
      append(td1, button);
      append(tr, t1);
      if (!mounted) {
        dispose = [
          listen(input, "input", input_input_handler),
          listen(button, "click", function() {
            if (is_function(
              /*remove*/
              ctx[8](
                /*index*/
                ctx[20]
              )
            ))
              ctx[8](
                /*index*/
                ctx[20]
              ).apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$stringListStore*/
      8 && input.value !== /*path*/
      ctx[18]) {
        set_input_value(
          input,
          /*path*/
          ctx[18]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_1$7, "create_each_block_1$7");
function create_each_block$d(key_1, ctx) {
  let tr;
  let td0;
  let input0;
  let t0;
  let td1;
  let input1;
  let t1;
  let td2;
  let button;
  let t2;
  let mounted;
  let dispose;
  function input0_input_handler() {
    ctx[11].call(
      input0,
      /*each_value*/
      ctx[19],
      /*index*/
      ctx[20]
    );
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler() {
    ctx[12].call(
      input1,
      /*each_value*/
      ctx[19],
      /*index*/
      ctx[20]
    );
  }
  __name(input1_input_handler, "input1_input_handler");
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      input0 = element("input");
      t0 = space();
      td1 = element("td");
      input1 = element("input");
      t1 = space();
      td2 = element("td");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      t2 = space();
      attr(input0, "type", "text");
      input0.required = true;
      attr(input1, "type", "text");
      attr(button, "type", "button");
      attr(button, "class", "svelte-vd7iuf");
      attr(td2, "class", "small svelte-vd7iuf");
      attr(tr, "class", "svelte-vd7iuf");
      this.first = tr;
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, input0);
      set_input_value(
        input0,
        /*key*/
        ctx[17]
      );
      append(tr, t0);
      append(tr, td1);
      append(td1, input1);
      set_input_value(
        input1,
        /*path*/
        ctx[18]
      );
      append(tr, t1);
      append(tr, td2);
      append(td2, button);
      append(tr, t2);
      if (!mounted) {
        dispose = [
          listen(input0, "input", input0_input_handler),
          listen(input1, "input", input1_input_handler),
          listen(button, "click", function() {
            if (is_function(
              /*remove*/
              ctx[8](
                /*index*/
                ctx[20]
              )
            ))
              ctx[8](
                /*index*/
                ctx[20]
              ).apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$stringListStore*/
      8 && input0.value !== /*key*/
      ctx[17]) {
        set_input_value(
          input0,
          /*key*/
          ctx[17]
        );
      }
      if (dirty & /*$stringListStore*/
      8 && input1.value !== /*path*/
      ctx[18]) {
        set_input_value(
          input1,
          /*path*/
          ctx[18]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$d, "create_each_block$d");
function create_default_slot$c(ctx) {
  let form_1;
  let t0;
  let table;
  let tr;
  let t1;
  let th0;
  let t3;
  let th1;
  let a;
  let t4;
  let t5;
  let footer;
  let button0;
  let i1;
  let t6;
  let t7_value = localize("Save") + "";
  let t7;
  let t8;
  let button1;
  let i2;
  let t9;
  let t10_value = localize("Cancel") + "";
  let t10;
  let mounted;
  let dispose;
  let if_block0 = (
    /*application*/
    ctx[4].options.content && create_if_block_2$7(ctx)
  );
  let if_block1 = (
    /*keyValuePair*/
    ctx[5] && create_if_block_1$b(ctx)
  );
  function select_block_type(ctx2, dirty) {
    if (
      /*keyValuePair*/
      ctx2[5]
    )
      return create_if_block$g;
    return create_else_block$8;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block2 = current_block_type(ctx);
  return {
    c() {
      form_1 = element("form");
      if (if_block0)
        if_block0.c();
      t0 = space();
      table = element("table");
      tr = element("tr");
      if (if_block1)
        if_block1.c();
      t1 = space();
      th0 = element("th");
      th0.textContent = `${localize(
        /*application*/
        ctx[4].options?.column
      )}`;
      t3 = space();
      th1 = element("th");
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus"></i>`;
      t4 = space();
      if_block2.c();
      t5 = space();
      footer = element("footer");
      button0 = element("button");
      i1 = element("i");
      t6 = space();
      t7 = text(t7_value);
      t8 = space();
      button1 = element("button");
      i2 = element("i");
      t9 = space();
      t10 = text(t10_value);
      attr(a, "class", "item-piles-clickable svelte-vd7iuf");
      attr(th1, "class", "small svelte-vd7iuf");
      attr(tr, "class", "svelte-vd7iuf");
      attr(table, "class", "svelte-vd7iuf");
      attr(i1, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i2, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      if (if_block0)
        if_block0.m(form_1, null);
      append(form_1, t0);
      append(form_1, table);
      append(table, tr);
      if (if_block1)
        if_block1.m(tr, null);
      append(tr, t1);
      append(tr, th0);
      append(tr, t3);
      append(tr, th1);
      append(th1, a);
      append(table, t4);
      if_block2.m(table, null);
      append(form_1, t5);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i1);
      append(button0, t6);
      append(button0, t7);
      append(footer, t8);
      append(footer, button1);
      append(button1, i2);
      append(button1, t9);
      append(button1, t10);
      ctx[15](form_1);
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*add*/
            ctx[7]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[14],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[9]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*application*/
        ctx2[4].options.content
      )
        if_block0.p(ctx2, dirty);
      if (
        /*keyValuePair*/
        ctx2[5]
      )
        if_block1.p(ctx2, dirty);
      if_block2.p(ctx2, dirty);
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if_block2.d();
      ctx[15](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$c, "create_default_slot$c");
function create_fragment$t(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[16](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$c] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $stringListStore*/
      4194316) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$t, "create_fragment$t");
function instance$q($$self, $$props, $$invalidate) {
  let $stringListStore;
  const { application } = getContext("#external");
  let form;
  let { elementRoot } = $$props;
  let { data: data2 } = $$props;
  const keyValuePair = application.options?.keyValuePair ?? false;
  const stringListStore = writable$1(data2);
  component_subscribe($$self, stringListStore, (value) => $$invalidate(3, $stringListStore = value));
  function add() {
    stringListStore.update((val) => {
      if (keyValuePair) {
        val.push(["", ""]);
      } else {
        val.push("");
      }
      return val;
    });
  }
  __name(add, "add");
  function remove(index2) {
    stringListStore.update((val) => {
      val.splice(index2, 1);
      return val;
    });
  }
  __name(remove, "remove");
  async function updateSettings() {
    application.options.resolve(get_store_value(stringListStore));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function input0_input_handler(each_value, index2) {
    each_value[index2][0] = this.value;
    stringListStore.set($stringListStore);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler(each_value, index2) {
    each_value[index2][1] = this.value;
    stringListStore.set($stringListStore);
  }
  __name(input1_input_handler, "input1_input_handler");
  function input_input_handler(each_value_1, index2) {
    each_value_1[index2] = this.value;
    stringListStore.set($stringListStore);
  }
  __name(input_input_handler, "input_input_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("data" in $$props2)
      $$invalidate(10, data2 = $$props2.data);
  };
  return [
    elementRoot,
    requestSubmit,
    form,
    $stringListStore,
    application,
    keyValuePair,
    stringListStore,
    add,
    remove,
    updateSettings,
    data2,
    input0_input_handler,
    input1_input_handler,
    input_input_handler,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$q, "instance$q");
const _String_list_editor = class _String_list_editor extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$q, create_fragment$t, safe_not_equal, {
      elementRoot: 0,
      data: 10,
      requestSubmit: 1
    });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get data() {
    return this.$$.ctx[10];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_String_list_editor, "String_list_editor");
let String_list_editor = _String_list_editor;
const _StringListEditor = class _StringListEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      svelte: {
        class: String_list_editor
      }
    });
  }
};
__name(_StringListEditor, "StringListEditor");
let StringListEditor = _StringListEditor;
const merchantColumnsEditorShell_svelte_svelte_type_style_lang = "";
function get_each_context$c(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[22] = list[i];
  child_ctx[23] = list;
  child_ctx[24] = i;
  return child_ctx;
}
__name(get_each_context$c, "get_each_context$c");
function create_each_block$c(ctx) {
  let div6;
  let div0;
  let input0;
  let t0;
  let div1;
  let propertypathinput;
  let updating_value;
  let t1;
  let div2;
  let input1;
  let t2;
  let div3;
  let input2;
  let t3;
  let div4;
  let input3;
  let t4;
  let div5;
  let button;
  let t5_value = localize("ITEM-PILES.Applications.MerchantColumnsEditor.ConfigureMapping") + "";
  let t5;
  let button_disabled_value;
  let t6;
  let a;
  let t7;
  let current;
  let mounted;
  let dispose;
  function input0_input_handler() {
    ctx[12].call(
      input0,
      /*each_value*/
      ctx[23],
      /*index*/
      ctx[24]
    );
  }
  __name(input0_input_handler, "input0_input_handler");
  function propertypathinput_value_binding(value) {
    ctx[13](
      value,
      /*column*/
      ctx[22]
    );
  }
  __name(propertypathinput_value_binding, "propertypathinput_value_binding");
  let propertypathinput_props = { templateType: "Item", required: true };
  if (
    /*column*/
    ctx[22].path !== void 0
  ) {
    propertypathinput_props.value = /*column*/
    ctx[22].path;
  }
  propertypathinput = new PropertyPathInput({ props: propertypathinput_props });
  binding_callbacks.push(() => bind(propertypathinput, "value", propertypathinput_value_binding));
  function input1_input_handler() {
    ctx[14].call(
      input1,
      /*each_value*/
      ctx[23],
      /*index*/
      ctx[24]
    );
  }
  __name(input1_input_handler, "input1_input_handler");
  function input2_change_handler() {
    ctx[15].call(
      input2,
      /*each_value*/
      ctx[23],
      /*index*/
      ctx[24]
    );
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler() {
    ctx[16].call(
      input3,
      /*each_value*/
      ctx[23],
      /*index*/
      ctx[24]
    );
  }
  __name(input3_change_handler, "input3_change_handler");
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[17](
        /*index*/
        ctx[24]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx[18](
        /*index*/
        ctx[24]
      )
    );
  }
  __name(click_handler_2, "click_handler_2");
  return {
    c() {
      div6 = element("div");
      div0 = element("div");
      input0 = element("input");
      t0 = space();
      div1 = element("div");
      create_component(propertypathinput.$$.fragment);
      t1 = space();
      div2 = element("div");
      input1 = element("input");
      t2 = space();
      div3 = element("div");
      input2 = element("input");
      t3 = space();
      div4 = element("div");
      input3 = element("input");
      t4 = space();
      div5 = element("div");
      button = element("button");
      t5 = text(t5_value);
      t6 = space();
      a = element("a");
      a.innerHTML = `<i class="fas fa-times"></i>`;
      t7 = space();
      attr(input0, "type", "text");
      input0.required = true;
      attr(div0, "class", "svelte-15856bi");
      attr(div1, "class", "svelte-15856bi");
      attr(input1, "type", "text");
      input1.required = true;
      attr(div2, "class", "svelte-15856bi");
      attr(input2, "type", "checkbox");
      attr(div3, "class", "svelte-15856bi");
      attr(input3, "type", "checkbox");
      attr(div4, "class", "svelte-15856bi");
      attr(button, "type", "button");
      button.disabled = button_disabled_value = !/*column*/
      ctx[22].label || !/*column*/
      ctx[22].path;
      attr(button, "class", "svelte-15856bi");
      attr(div5, "class", "svelte-15856bi");
      attr(a, "class", "item-piles-clickable-red");
      set_style(a, "margin-right", "0.5rem");
      set_style(a, "text-align", "center");
      attr(div6, "class", "item-piles-grid-row-wrapper svelte-15856bi");
    },
    m(target, anchor) {
      insert(target, div6, anchor);
      append(div6, div0);
      append(div0, input0);
      set_input_value(
        input0,
        /*column*/
        ctx[22].label
      );
      append(div6, t0);
      append(div6, div1);
      mount_component(propertypathinput, div1, null);
      append(div6, t1);
      append(div6, div2);
      append(div2, input1);
      set_input_value(
        input1,
        /*column*/
        ctx[22].formatting
      );
      append(div6, t2);
      append(div6, div3);
      append(div3, input2);
      input2.checked = /*column*/
      ctx[22].buying;
      append(div6, t3);
      append(div6, div4);
      append(div4, input3);
      input3.checked = /*column*/
      ctx[22].selling;
      append(div6, t4);
      append(div6, div5);
      append(div5, button);
      append(button, t5);
      append(div6, t6);
      append(div6, a);
      append(div6, t7);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input0, "input", input0_input_handler),
          listen(input1, "input", input1_input_handler),
          listen(input2, "change", input2_change_handler),
          listen(input3, "change", input3_change_handler),
          listen(button, "click", click_handler_1),
          listen(a, "click", click_handler_2)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$merchantColumns*/
      8 && input0.value !== /*column*/
      ctx[22].label) {
        set_input_value(
          input0,
          /*column*/
          ctx[22].label
        );
      }
      const propertypathinput_changes = {};
      if (!updating_value && dirty & /*$merchantColumns*/
      8) {
        updating_value = true;
        propertypathinput_changes.value = /*column*/
        ctx[22].path;
        add_flush_callback(() => updating_value = false);
      }
      propertypathinput.$set(propertypathinput_changes);
      if (dirty & /*$merchantColumns*/
      8 && input1.value !== /*column*/
      ctx[22].formatting) {
        set_input_value(
          input1,
          /*column*/
          ctx[22].formatting
        );
      }
      if (dirty & /*$merchantColumns*/
      8) {
        input2.checked = /*column*/
        ctx[22].buying;
      }
      if (dirty & /*$merchantColumns*/
      8) {
        input3.checked = /*column*/
        ctx[22].selling;
      }
      if (!current || dirty & /*$merchantColumns*/
      8 && button_disabled_value !== (button_disabled_value = !/*column*/
      ctx[22].label || !/*column*/
      ctx[22].path)) {
        button.disabled = button_disabled_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(propertypathinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(propertypathinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div6);
      destroy_component(propertypathinput);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$c, "create_each_block$c");
function create_default_slot$b(ctx) {
  let form_1;
  let p;
  let t1;
  let div7;
  let div6;
  let div0;
  let span0;
  let t3;
  let div1;
  let span1;
  let t5;
  let div2;
  let span2;
  let t7;
  let div3;
  let span3;
  let t9;
  let div4;
  let span4;
  let t11;
  let div5;
  let t12;
  let a;
  let t13;
  let t14;
  let footer;
  let button0;
  let i1;
  let t15;
  let t16_value = localize("Save") + "";
  let t16;
  let t17;
  let button1;
  let i2;
  let t18;
  let t19_value = localize("Cancel") + "";
  let t19;
  let current;
  let mounted;
  let dispose;
  let each_value = (
    /*$merchantColumns*/
    ctx[3]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$c(get_each_context$c(ctx, each_value, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  }), "out");
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.MerchantColumnsEditor.Explanation")}`;
      t1 = space();
      div7 = element("div");
      div6 = element("div");
      div0 = element("div");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.MerchantColumnsEditor.Label")}`;
      t3 = space();
      div1 = element("div");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.MerchantColumnsEditor.PropertyPath")}`;
      t5 = space();
      div2 = element("div");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.MerchantColumnsEditor.Formatting")}`;
      t7 = space();
      div3 = element("div");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Applications.MerchantColumnsEditor.Buying")}`;
      t9 = space();
      div4 = element("div");
      span4 = element("span");
      span4.textContent = `${localize("ITEM-PILES.Applications.MerchantColumnsEditor.Selling")}`;
      t11 = space();
      div5 = element("div");
      t12 = space();
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus"></i>`;
      t13 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t14 = space();
      footer = element("footer");
      button0 = element("button");
      i1 = element("i");
      t15 = space();
      t16 = text(t16_value);
      t17 = space();
      button1 = element("button");
      i2 = element("i");
      t18 = space();
      t19 = text(t19_value);
      set_style(p, "text-align", "center");
      set_style(div0, "text-align", "left");
      attr(div0, "class", "svelte-15856bi");
      attr(div1, "class", "item-piles-flexcol svelte-15856bi");
      attr(div2, "class", "item-piles-flexcol svelte-15856bi");
      attr(div3, "class", "item-piles-flexcol svelte-15856bi");
      attr(div4, "class", "item-piles-flexcol svelte-15856bi");
      attr(div5, "class", "item-piles-flexcol svelte-15856bi");
      set_style(a, "margin-right", "0.5rem");
      attr(div6, "class", "item-piles-grid-row-wrapper svelte-15856bi");
      attr(div7, "class", "form-group item-pile-column-grid item-piles-top-divider svelte-15856bi");
      attr(i1, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i2, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(footer, "class", "item-piles-top-divider");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(form_1, t1);
      append(form_1, div7);
      append(div7, div6);
      append(div6, div0);
      append(div0, span0);
      append(div6, t3);
      append(div6, div1);
      append(div1, span1);
      append(div6, t5);
      append(div6, div2);
      append(div2, span2);
      append(div6, t7);
      append(div6, div3);
      append(div3, span3);
      append(div6, t9);
      append(div6, div4);
      append(div4, span4);
      append(div6, t11);
      append(div6, div5);
      append(div6, t12);
      append(div6, a);
      append(div7, t13);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div7, null);
        }
      }
      append(form_1, t14);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i1);
      append(button0, t15);
      append(button0, t16);
      append(footer, t17);
      append(footer, button1);
      append(button1, i2);
      append(button1, t18);
      append(button1, t19);
      ctx[20](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*click_handler*/
            ctx[11]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler_3*/
            ctx[19],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[9]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*removeColumn, $merchantColumns, showMappingEditor, localize*/
      392) {
        each_value = /*$merchantColumns*/
        ctx2[3];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$c(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block$c(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div7, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      destroy_each(each_blocks, detaching);
      ctx[20](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$b, "create_default_slot$b");
function create_fragment$s(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[21](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$b] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $merchantColumns*/
      33554444) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$s, "create_fragment$s");
function instance$p($$self, $$props, $$invalidate) {
  let $merchantColumns;
  const { application } = getContext("#external");
  let form;
  let { data: data2 } = $$props;
  let { elementRoot } = $$props;
  const merchantColumns = writable$1(data2);
  component_subscribe($$self, merchantColumns, (value) => $$invalidate(3, $merchantColumns = value));
  function addColumn() {
    merchantColumns.update((value) => {
      value.push({
        label: "",
        path: "",
        formatting: "{#}",
        mapping: {},
        buying: true,
        selling: true
      });
      return value;
    });
  }
  __name(addColumn, "addColumn");
  function removeColumn(index2) {
    merchantColumns.update((value) => {
      value.splice(index2, 1);
      return value;
    });
  }
  __name(removeColumn, "removeColumn");
  async function showMappingEditor(index2) {
    const data3 = get_store_value(merchantColumns)[index2];
    return StringListEditor.show(Object.entries(data3.mapping), {
      id: `merchant-columns-mapping-editor-${data3.path}`,
      title: localize("ITEM-PILES.Applications.MerchantColumnsEditor.MappingTitle", { label: data3.label }),
      content: localize("ITEM-PILES.Applications.MerchantColumnsEditor.MappingContent"),
      keyValuePair: true
    }).then((result) => {
      merchantColumns.update((value) => {
        value[index2].mapping = Object.fromEntries(result);
        return value;
      });
    });
  }
  __name(showMappingEditor, "showMappingEditor");
  async function updateSettings() {
    application.options.resolve(get_store_value(merchantColumns));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  const click_handler = /* @__PURE__ */ __name(() => addColumn(), "click_handler");
  function input0_input_handler(each_value, index2) {
    each_value[index2].label = this.value;
    merchantColumns.set($merchantColumns);
  }
  __name(input0_input_handler, "input0_input_handler");
  function propertypathinput_value_binding(value, column) {
    if ($$self.$$.not_equal(column.path, value)) {
      column.path = value;
      merchantColumns.set($merchantColumns);
    }
  }
  __name(propertypathinput_value_binding, "propertypathinput_value_binding");
  function input1_input_handler(each_value, index2) {
    each_value[index2].formatting = this.value;
    merchantColumns.set($merchantColumns);
  }
  __name(input1_input_handler, "input1_input_handler");
  function input2_change_handler(each_value, index2) {
    each_value[index2].buying = this.checked;
    merchantColumns.set($merchantColumns);
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler(each_value, index2) {
    each_value[index2].selling = this.checked;
    merchantColumns.set($merchantColumns);
  }
  __name(input3_change_handler, "input3_change_handler");
  const click_handler_1 = /* @__PURE__ */ __name((index2) => showMappingEditor(index2), "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name((index2) => removeColumn(index2), "click_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler_3");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(10, data2 = $$props2.data);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  return [
    elementRoot,
    requestSubmit,
    form,
    $merchantColumns,
    application,
    merchantColumns,
    addColumn,
    removeColumn,
    showMappingEditor,
    updateSettings,
    data2,
    click_handler,
    input0_input_handler,
    propertypathinput_value_binding,
    input1_input_handler,
    input2_change_handler,
    input3_change_handler,
    click_handler_1,
    click_handler_2,
    click_handler_32,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$p, "instance$p");
const _Merchant_columns_editor_shell = class _Merchant_columns_editor_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$p, create_fragment$s, safe_not_equal, {
      data: 10,
      elementRoot: 0,
      requestSubmit: 1
    });
  }
  get data() {
    return this.$$.ctx[10];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Merchant_columns_editor_shell, "Merchant_columns_editor_shell");
let Merchant_columns_editor_shell = _Merchant_columns_editor_shell;
const _MerchantColumnsEditor = class _MerchantColumnsEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: "ITEM-PILES.Applications.MerchantColumnsEditor.Title",
      width: 600,
      svelte: {
        class: Merchant_columns_editor_shell
      }
    });
  }
};
__name(_MerchantColumnsEditor, "MerchantColumnsEditor");
let MerchantColumnsEditor = _MerchantColumnsEditor;
const merchant_svelte_svelte_type_style_lang = "";
function get_each_context$b(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[43] = list[i];
  child_ctx[44] = list;
  child_ctx[45] = i;
  return child_ctx;
}
__name(get_each_context$b, "get_each_context$b");
function get_each_context_1$6(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[46] = list[i];
  child_ctx[47] = list;
  child_ctx[48] = i;
  return child_ctx;
}
__name(get_each_context_1$6, "get_each_context_1$6");
function get_each_context_2$1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[43] = list[i];
  child_ctx[49] = list;
  child_ctx[45] = i;
  return child_ctx;
}
__name(get_each_context_2$1, "get_each_context_2$1");
function get_each_context_3$1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[46] = list[i];
  child_ctx[50] = list;
  child_ctx[51] = i;
  return child_ctx;
}
__name(get_each_context_3$1, "get_each_context_3$1");
function create_if_block_1$a(ctx) {
  let option;
  return {
    c() {
      option = element("option");
      option.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OpenStatusAuto")}`;
      option.__value = "auto";
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_if_block_1$a, "create_if_block_1$a");
function create_if_block$f(ctx) {
  let div2;
  let label0;
  let span0;
  let t1;
  let p0;
  let t3;
  let div0;
  let t4;
  let div1;
  let each_blocks_3 = [];
  let each0_lookup = /* @__PURE__ */ new Map();
  let t5;
  let div5;
  let label1;
  let span1;
  let t7;
  let p1;
  let t9;
  let div3;
  let t10;
  let div4;
  let each_blocks_2 = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let t11;
  let div6;
  let label2;
  let p2;
  let t13;
  let div7;
  let label3;
  let span2;
  let t15;
  let p3;
  let t17;
  let input;
  let input_disabled_value;
  let t18;
  let div10;
  let label4;
  let span3;
  let t20;
  let p4;
  let t22;
  let div8;
  let t23;
  let div9;
  let each_blocks_1 = [];
  let each2_lookup = /* @__PURE__ */ new Map();
  let t24;
  let div13;
  let label5;
  let span4;
  let t26;
  let p5;
  let t28;
  let div11;
  let t29;
  let div12;
  let each_blocks = [];
  let each3_lookup = /* @__PURE__ */ new Map();
  let mounted;
  let dispose;
  let each_value_3 = (
    /*weekdays*/
    ctx[1]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*weekday*/
    ctx2[46].id + "-weekday-close"
  ), "get_key");
  for (let i = 0; i < each_value_3.length; i += 1) {
    let child_ctx = get_each_context_3$1(ctx, each_value_3, i);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_3[i] = create_each_block_3$1(key, child_ctx));
  }
  let each_value_2 = (
    /*holidays*/
    ctx[3]
  );
  const get_key_1 = /* @__PURE__ */ __name((ctx2) => (
    /*holiday*/
    ctx2[43].name + "-" + /*index*/
    ctx2[45]
  ), "get_key_1");
  for (let i = 0; i < each_value_2.length; i += 1) {
    let child_ctx = get_each_context_2$1(ctx, each_value_2, i);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks_2[i] = create_each_block_2$1(key, child_ctx));
  }
  let each_value_1 = (
    /*refreshItemDays*/
    ctx[2]
  );
  const get_key_2 = /* @__PURE__ */ __name((ctx2) => (
    /*weekday*/
    ctx2[46].id + "-weekday-refresh"
  ), "get_key_2");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$6(ctx, each_value_1, i);
    let key = get_key_2(child_ctx);
    each2_lookup.set(key, each_blocks_1[i] = create_each_block_1$6(key, child_ctx));
  }
  let each_value = (
    /*refreshItemsHolidays*/
    ctx[4]
  );
  const get_key_3 = /* @__PURE__ */ __name((ctx2) => (
    /*holiday*/
    ctx2[43].name + "-remove-" + /*index*/
    ctx2[45]
  ), "get_key_3");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$b(ctx, each_value, i);
    let key = get_key_3(child_ctx);
    each3_lookup.set(key, each_blocks[i] = create_each_block$b(key, child_ctx));
  }
  return {
    c() {
      div2 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ClosedDays")}`;
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ClosedDaysExplanation")}`;
      t3 = space();
      div0 = element("div");
      t4 = space();
      div1 = element("div");
      for (let i = 0; i < each_blocks_3.length; i += 1) {
        each_blocks_3[i].c();
      }
      t5 = space();
      div5 = element("div");
      label1 = element("label");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ClosedHolidays")}`;
      t7 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ClosedHolidaysExplanation")}`;
      t9 = space();
      div3 = element("div");
      t10 = space();
      div4 = element("div");
      for (let i = 0; i < each_blocks_2.length; i += 1) {
        each_blocks_2[i].c();
      }
      t11 = space();
      div6 = element("div");
      label2 = element("label");
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.RefreshItemsWarning")}`;
      t13 = space();
      div7 = element("div");
      label3 = element("label");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.RefreshItemsOnOpen")}`;
      t15 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.RefreshItemsOnOpenExplanation")}`;
      t17 = space();
      input = element("input");
      t18 = space();
      div10 = element("div");
      label4 = element("label");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.RefreshItemsDays")}`;
      t20 = space();
      p4 = element("p");
      p4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.RefreshItemsDaysExplanation")}`;
      t22 = space();
      div8 = element("div");
      t23 = space();
      div9 = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t24 = space();
      div13 = element("div");
      label5 = element("label");
      span4 = element("span");
      span4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.RefreshItemsHolidays")}`;
      t26 = space();
      p5 = element("p");
      p5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.RefreshItemsHolidaysExplanation")}`;
      t28 = space();
      div11 = element("div");
      t29 = space();
      div12 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div0, "class", "break");
      attr(div1, "class", "item-piles-flexrow");
      set_style(div1, "text-align", "center");
      attr(div2, "class", "form-group svelte-4amoj2");
      toggle_class(div2, "item-piles-disabled", !/*pileData*/
      ctx[0].openTimes.enabled);
      attr(div3, "class", "break");
      set_style(div4, "display", "grid");
      set_style(div4, "grid-template-columns", "1fr 1fr");
      attr(div5, "class", "form-group svelte-4amoj2");
      toggle_class(div5, "item-piles-disabled", !/*pileData*/
      ctx[0].openTimes.enabled);
      set_style(p2, "color", "#c02609");
      attr(div6, "class", "form-group item-piles-top-divider svelte-4amoj2");
      attr(input, "type", "checkbox");
      input.disabled = input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      attr(div7, "class", "form-group svelte-4amoj2");
      toggle_class(div7, "item-piles-disabled", !/*pileData*/
      ctx[0].openTimes.enabled);
      attr(div8, "class", "break");
      attr(div9, "class", "item-piles-flexrow");
      set_style(div9, "text-align", "center");
      attr(div10, "class", "form-group svelte-4amoj2");
      toggle_class(div10, "item-piles-disabled", !/*pileData*/
      ctx[0].openTimes.enabled);
      attr(div11, "class", "break");
      set_style(div12, "display", "grid");
      set_style(div12, "grid-template-columns", "1fr 1fr");
      attr(div13, "class", "form-group svelte-4amoj2");
      toggle_class(div13, "item-piles-disabled", !/*pileData*/
      ctx[0].openTimes.enabled);
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, label0);
      append(label0, span0);
      append(label0, t1);
      append(label0, p0);
      append(div2, t3);
      append(div2, div0);
      append(div2, t4);
      append(div2, div1);
      for (let i = 0; i < each_blocks_3.length; i += 1) {
        if (each_blocks_3[i]) {
          each_blocks_3[i].m(div1, null);
        }
      }
      insert(target, t5, anchor);
      insert(target, div5, anchor);
      append(div5, label1);
      append(label1, span1);
      append(label1, t7);
      append(label1, p1);
      append(div5, t9);
      append(div5, div3);
      append(div5, t10);
      append(div5, div4);
      for (let i = 0; i < each_blocks_2.length; i += 1) {
        if (each_blocks_2[i]) {
          each_blocks_2[i].m(div4, null);
        }
      }
      insert(target, t11, anchor);
      insert(target, div6, anchor);
      append(div6, label2);
      append(label2, p2);
      insert(target, t13, anchor);
      insert(target, div7, anchor);
      append(div7, label3);
      append(label3, span2);
      append(label3, t15);
      append(label3, p3);
      append(div7, t17);
      append(div7, input);
      input.checked = /*pileData*/
      ctx[0].refreshItemsOnOpen;
      insert(target, t18, anchor);
      insert(target, div10, anchor);
      append(div10, label4);
      append(label4, span3);
      append(label4, t20);
      append(label4, p4);
      append(div10, t22);
      append(div10, div8);
      append(div10, t23);
      append(div10, div9);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div9, null);
        }
      }
      insert(target, t24, anchor);
      insert(target, div13, anchor);
      append(div13, label5);
      append(label5, span4);
      append(label5, t26);
      append(label5, p5);
      append(div13, t28);
      append(div13, div11);
      append(div13, t29);
      append(div13, div12);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div12, null);
        }
      }
      if (!mounted) {
        dispose = listen(
          input,
          "change",
          /*input_change_handler_2*/
          ctx[38]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*pileData, weekdays*/
      3) {
        each_value_3 = /*weekdays*/
        ctx2[1];
        each_blocks_3 = update_keyed_each(each_blocks_3, dirty, get_key, 1, ctx2, each_value_3, each0_lookup, div1, destroy_block, create_each_block_3$1, null, get_each_context_3$1);
      }
      if (dirty[0] & /*pileData*/
      1) {
        toggle_class(div2, "item-piles-disabled", !/*pileData*/
        ctx2[0].openTimes.enabled);
      }
      if (dirty[0] & /*holidays, pileData*/
      9) {
        each_value_2 = /*holidays*/
        ctx2[3];
        each_blocks_2 = update_keyed_each(each_blocks_2, dirty, get_key_1, 1, ctx2, each_value_2, each1_lookup, div4, destroy_block, create_each_block_2$1, null, get_each_context_2$1);
      }
      if (dirty[0] & /*pileData*/
      1) {
        toggle_class(div5, "item-piles-disabled", !/*pileData*/
        ctx2[0].openTimes.enabled);
      }
      if (dirty[0] & /*pileData*/
      1 && input_disabled_value !== (input_disabled_value = !/*pileData*/
      ctx2[0].openTimes.enabled)) {
        input.disabled = input_disabled_value;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input.checked = /*pileData*/
        ctx2[0].refreshItemsOnOpen;
      }
      if (dirty[0] & /*pileData*/
      1) {
        toggle_class(div7, "item-piles-disabled", !/*pileData*/
        ctx2[0].openTimes.enabled);
      }
      if (dirty[0] & /*pileData, refreshItemDays*/
      5) {
        each_value_1 = /*refreshItemDays*/
        ctx2[2];
        each_blocks_1 = update_keyed_each(each_blocks_1, dirty, get_key_2, 1, ctx2, each_value_1, each2_lookup, div9, destroy_block, create_each_block_1$6, null, get_each_context_1$6);
      }
      if (dirty[0] & /*pileData*/
      1) {
        toggle_class(div10, "item-piles-disabled", !/*pileData*/
        ctx2[0].openTimes.enabled);
      }
      if (dirty[0] & /*refreshItemsHolidays, pileData*/
      17) {
        each_value = /*refreshItemsHolidays*/
        ctx2[4];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_3, 1, ctx2, each_value, each3_lookup, div12, destroy_block, create_each_block$b, null, get_each_context$b);
      }
      if (dirty[0] & /*pileData*/
      1) {
        toggle_class(div13, "item-piles-disabled", !/*pileData*/
        ctx2[0].openTimes.enabled);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      for (let i = 0; i < each_blocks_3.length; i += 1) {
        each_blocks_3[i].d();
      }
      if (detaching)
        detach(t5);
      if (detaching)
        detach(div5);
      for (let i = 0; i < each_blocks_2.length; i += 1) {
        each_blocks_2[i].d();
      }
      if (detaching)
        detach(t11);
      if (detaching)
        detach(div6);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(div7);
      if (detaching)
        detach(t18);
      if (detaching)
        detach(div10);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].d();
      }
      if (detaching)
        detach(t24);
      if (detaching)
        detach(div13);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$f, "create_if_block$f");
function create_each_block_3$1(key_1, ctx) {
  let div;
  let label;
  let t0_value = (
    /*weekday*/
    ctx[46].abbreviation + ""
  );
  let t0;
  let t1;
  let input;
  let input_disabled_value;
  let t2;
  let mounted;
  let dispose;
  function input_change_handler() {
    ctx[34].call(
      input,
      /*each_value_3*/
      ctx[50],
      /*weekday_index_1*/
      ctx[51]
    );
  }
  __name(input_change_handler, "input_change_handler");
  function change_handler() {
    return (
      /*change_handler*/
      ctx[35](
        /*weekday*/
        ctx[46]
      )
    );
  }
  __name(change_handler, "change_handler");
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      label = element("label");
      t0 = text(t0_value);
      t1 = space();
      input = element("input");
      t2 = space();
      attr(input, "type", "checkbox");
      input.disabled = input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      attr(div, "class", "item-piles-flexcol");
      set_style(div, "align-items", "center");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, t0);
      append(div, t1);
      append(div, input);
      input.checked = /*weekday*/
      ctx[46].selected;
      append(div, t2);
      if (!mounted) {
        dispose = [
          listen(input, "change", input_change_handler),
          listen(input, "change", change_handler)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*weekdays*/
      2 && t0_value !== (t0_value = /*weekday*/
      ctx[46].abbreviation + ""))
        set_data(t0, t0_value);
      if (dirty[0] & /*pileData*/
      1 && input_disabled_value !== (input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled)) {
        input.disabled = input_disabled_value;
      }
      if (dirty[0] & /*weekdays*/
      2) {
        input.checked = /*weekday*/
        ctx[46].selected;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_3$1, "create_each_block_3$1");
function create_each_block_2$1(key_1, ctx) {
  let div;
  let input;
  let input_disabled_value;
  let t0;
  let label;
  let t1_value = (
    /*holiday*/
    ctx[43].name + ""
  );
  let t1;
  let t2;
  let mounted;
  let dispose;
  function input_change_handler_1() {
    ctx[36].call(
      input,
      /*each_value_2*/
      ctx[49],
      /*index*/
      ctx[45]
    );
  }
  __name(input_change_handler_1, "input_change_handler_1");
  function change_handler_1() {
    return (
      /*change_handler_1*/
      ctx[37](
        /*holiday*/
        ctx[43]
      )
    );
  }
  __name(change_handler_1, "change_handler_1");
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      input = element("input");
      t0 = space();
      label = element("label");
      t1 = text(t1_value);
      t2 = space();
      attr(input, "type", "checkbox");
      input.disabled = input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      attr(div, "class", "item-piles-flexrow");
      set_style(div, "flex", "0 1 auto");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      input.checked = /*holiday*/
      ctx[43].selected;
      append(div, t0);
      append(div, label);
      append(label, t1);
      append(div, t2);
      if (!mounted) {
        dispose = [
          listen(input, "change", input_change_handler_1),
          listen(input, "change", change_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*pileData*/
      1 && input_disabled_value !== (input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled)) {
        input.disabled = input_disabled_value;
      }
      if (dirty[0] & /*holidays*/
      8) {
        input.checked = /*holiday*/
        ctx[43].selected;
      }
      if (dirty[0] & /*holidays*/
      8 && t1_value !== (t1_value = /*holiday*/
      ctx[43].name + ""))
        set_data(t1, t1_value);
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_2$1, "create_each_block_2$1");
function create_each_block_1$6(key_1, ctx) {
  let div;
  let label;
  let t0_value = (
    /*weekday*/
    ctx[46].abbreviation + ""
  );
  let t0;
  let t1;
  let input;
  let input_disabled_value;
  let t2;
  let mounted;
  let dispose;
  function input_change_handler_3() {
    ctx[39].call(
      input,
      /*each_value_1*/
      ctx[47],
      /*weekday_index*/
      ctx[48]
    );
  }
  __name(input_change_handler_3, "input_change_handler_3");
  function change_handler_2() {
    return (
      /*change_handler_2*/
      ctx[40](
        /*weekday*/
        ctx[46]
      )
    );
  }
  __name(change_handler_2, "change_handler_2");
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      label = element("label");
      t0 = text(t0_value);
      t1 = space();
      input = element("input");
      t2 = space();
      attr(input, "type", "checkbox");
      input.disabled = input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      attr(div, "class", "item-piles-flexcol");
      set_style(div, "align-items", "center");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, t0);
      append(div, t1);
      append(div, input);
      input.checked = /*weekday*/
      ctx[46].selected;
      append(div, t2);
      if (!mounted) {
        dispose = [
          listen(input, "change", input_change_handler_3),
          listen(input, "change", change_handler_2)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*refreshItemDays*/
      4 && t0_value !== (t0_value = /*weekday*/
      ctx[46].abbreviation + ""))
        set_data(t0, t0_value);
      if (dirty[0] & /*pileData*/
      1 && input_disabled_value !== (input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled)) {
        input.disabled = input_disabled_value;
      }
      if (dirty[0] & /*refreshItemDays*/
      4) {
        input.checked = /*weekday*/
        ctx[46].selected;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_1$6, "create_each_block_1$6");
function create_each_block$b(key_1, ctx) {
  let div;
  let input;
  let input_disabled_value;
  let t0;
  let label;
  let t1_value = (
    /*holiday*/
    ctx[43].name + ""
  );
  let t1;
  let t2;
  let mounted;
  let dispose;
  function input_change_handler_4() {
    ctx[41].call(
      input,
      /*each_value*/
      ctx[44],
      /*index*/
      ctx[45]
    );
  }
  __name(input_change_handler_4, "input_change_handler_4");
  function change_handler_3() {
    return (
      /*change_handler_3*/
      ctx[42](
        /*holiday*/
        ctx[43]
      )
    );
  }
  __name(change_handler_3, "change_handler_3");
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      input = element("input");
      t0 = space();
      label = element("label");
      t1 = text(t1_value);
      t2 = space();
      attr(input, "type", "checkbox");
      input.disabled = input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      attr(div, "class", "item-piles-flexrow");
      set_style(div, "flex", "0 1 auto");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      input.checked = /*holiday*/
      ctx[43].selected;
      append(div, t0);
      append(div, label);
      append(label, t1);
      append(div, t2);
      if (!mounted) {
        dispose = [
          listen(input, "change", input_change_handler_4),
          listen(input, "change", change_handler_3)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*pileData*/
      1 && input_disabled_value !== (input_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled)) {
        input.disabled = input_disabled_value;
      }
      if (dirty[0] & /*refreshItemsHolidays*/
      16) {
        input.checked = /*holiday*/
        ctx[43].selected;
      }
      if (dirty[0] & /*refreshItemsHolidays*/
      16 && t1_value !== (t1_value = /*holiday*/
      ctx[43].name + ""))
        set_data(t1, t1_value);
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$b, "create_each_block$b");
function create_fragment$r(ctx) {
  let div1;
  let label0;
  let span0;
  let t1;
  let p0;
  let t3;
  let div0;
  let filepicker;
  let updating_value;
  let t4;
  let div2;
  let label1;
  let span1;
  let t6;
  let p1;
  let t8;
  let input0;
  let t9;
  let div3;
  let label2;
  let span2;
  let t11;
  let p2;
  let t13;
  let input1;
  let t14;
  let div4;
  let label3;
  let span3;
  let t16;
  let p3;
  let t18;
  let input2;
  let t19;
  let div6;
  let label4;
  let span4;
  let t21;
  let p4;
  let t23;
  let div5;
  let t24;
  let select0;
  let option0;
  let option1;
  let option2;
  let option3;
  let t32;
  let div7;
  let label5;
  let span5;
  let t34;
  let p5;
  let t36;
  let input3;
  let t37;
  let div8;
  let label6;
  let span6;
  let t39;
  let p6;
  let t41;
  let input4;
  let t42;
  let div9;
  let label7;
  let span7;
  let t44;
  let p7;
  let t46;
  let input5;
  let t47;
  let div10;
  let label8;
  let span8;
  let t49;
  let p8;
  let t51;
  let input6;
  let t52;
  let div11;
  let label9;
  let span9;
  let t54;
  let p9;
  let t56;
  let input7;
  let t57;
  let div12;
  let label10;
  let span10;
  let t59;
  let p10;
  let t61;
  let button0;
  let t63;
  let div13;
  let label11;
  let span11;
  let t65;
  let p11;
  let t67;
  let div14;
  let label12;
  let span12;
  let t69;
  let sliderinput0;
  let updating_value_1;
  let t70;
  let div15;
  let label13;
  let span13;
  let t72;
  let sliderinput1;
  let updating_value_2;
  let t73;
  let div17;
  let div16;
  let label14;
  let span14;
  let t75;
  let p12;
  let t77;
  let button1;
  let t79;
  let div19;
  let div18;
  let label15;
  let span15;
  let t81;
  let p13;
  let t83;
  let button2;
  let t85;
  let div21;
  let div20;
  let label16;
  let span16;
  let t87;
  let p14;
  let t89;
  let button3;
  let t91;
  let div23;
  let label17;
  let span17;
  let t93;
  let p15;
  let t95;
  let div22;
  let t96;
  let select1;
  let option4;
  let option5;
  let t101;
  let div24;
  let label18;
  let span18;
  let t103;
  let p16;
  let t105;
  let input8;
  let t106;
  let div25;
  let label19;
  let span19;
  let t108;
  let p17;
  let t110;
  let input9;
  let t111;
  let div30;
  let div27;
  let label20;
  let t113;
  let div26;
  let input10;
  let input10_disabled_value;
  let t114;
  let span20;
  let t116;
  let input11;
  let input11_disabled_value;
  let t117;
  let div29;
  let label21;
  let t119;
  let div28;
  let input12;
  let input12_disabled_value;
  let t120;
  let span21;
  let t122;
  let input13;
  let input13_disabled_value;
  let t123;
  let if_block1_anchor;
  let current;
  let mounted;
  let dispose;
  function filepicker_value_binding(value) {
    ctx[11](value);
  }
  __name(filepicker_value_binding, "filepicker_value_binding");
  let filepicker_props = {
    placeholder: "path/image.png",
    type: "imagevideo"
  };
  if (
    /*pileData*/
    ctx[0].merchantImage !== void 0
  ) {
    filepicker_props.value = /*pileData*/
    ctx[0].merchantImage;
  }
  filepicker = new FilePicker_1({ props: filepicker_props });
  binding_callbacks.push(() => bind(filepicker, "value", filepicker_value_binding));
  function sliderinput0_value_binding(value) {
    ctx[22](value);
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  let sliderinput0_props = { style: "flex:4;" };
  if (
    /*pileData*/
    ctx[0].buyPriceModifier !== void 0
  ) {
    sliderinput0_props.value = /*pileData*/
    ctx[0].buyPriceModifier;
  }
  sliderinput0 = new SliderInput({ props: sliderinput0_props });
  binding_callbacks.push(() => bind(sliderinput0, "value", sliderinput0_value_binding));
  function sliderinput1_value_binding(value) {
    ctx[23](value);
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  let sliderinput1_props = { style: "flex:4;" };
  if (
    /*pileData*/
    ctx[0].sellPriceModifier !== void 0
  ) {
    sliderinput1_props.value = /*pileData*/
    ctx[0].sellPriceModifier;
  }
  sliderinput1 = new SliderInput({ props: sliderinput1_props });
  binding_callbacks.push(() => bind(sliderinput1, "value", sliderinput1_value_binding));
  let if_block0 = (
    /*simpleCalendarActive*/
    ctx[5] && /*pileData*/
    ctx[0].openTimes.enabled && create_if_block_1$a()
  );
  let if_block1 = (
    /*simpleCalendarActive*/
    ctx[5] && create_if_block$f(ctx)
  );
  return {
    c() {
      div1 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.MerchantImage")}`;
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.MerchantImageExplanation")}`;
      t3 = space();
      div0 = element("div");
      create_component(filepicker.$$.fragment);
      t4 = space();
      div2 = element("div");
      label1 = element("label");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.InfiniteQuantity")}`;
      t6 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.InfiniteQuantityExplanation")}`;
      t8 = space();
      input0 = element("input");
      t9 = space();
      div3 = element("div");
      label2 = element("label");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.InfiniteCurrency")}`;
      t11 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.InfiniteCurrencyExplanation")}`;
      t13 = space();
      input1 = element("input");
      t14 = space();
      div4 = element("div");
      label3 = element("label");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.KeepZero")}`;
      t16 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.KeepZeroExplanation")}`;
      t18 = space();
      input2 = element("input");
      t19 = space();
      div6 = element("div");
      label4 = element("label");
      span4 = element("span");
      span4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.DisplayQuantity")}`;
      t21 = space();
      p4 = element("p");
      p4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.DisplayQuantityExplanation")}`;
      t23 = space();
      div5 = element("div");
      t24 = space();
      select0 = element("select");
      option0 = element("option");
      option0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.DisplayQuantityYes")} 
		`;
      option1 = element("option");
      option1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.DisplayQuantityNo")} 
		`;
      option2 = element("option");
      option2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.DisplayQuantityYesAlways")} 
		`;
      option3 = element("option");
      option3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.DisplayQuantityNoAlways")}`;
      t32 = space();
      div7 = element("div");
      label5 = element("label");
      span5 = element("span");
      span5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.PurchaseOnly")}`;
      t34 = space();
      p5 = element("p");
      p5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.PurchaseOnlyExplanation")}`;
      t36 = space();
      input3 = element("input");
      t37 = space();
      div8 = element("div");
      label6 = element("label");
      span6 = element("span");
      span6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideNewItems")}`;
      t39 = space();
      p6 = element("p");
      p6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideNewItemsExplanation")}`;
      t41 = space();
      input4 = element("input");
      t42 = space();
      div9 = element("div");
      label7 = element("label");
      span7 = element("span");
      span7.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideItemsWithZeroCost")}`;
      t44 = space();
      p7 = element("p");
      p7.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideItemsWithZeroCostExplanation")}`;
      t46 = space();
      input5 = element("input");
      t47 = space();
      div10 = element("div");
      label8 = element("label");
      span8 = element("span");
      span8.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OnlyAcceptBasePrice")}`;
      t49 = space();
      p8 = element("p");
      p8.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OnlyAcceptBasePriceExplanation")}`;
      t51 = space();
      input6 = element("input");
      t52 = space();
      div11 = element("div");
      label9 = element("label");
      span9 = element("span");
      span9.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.LogMerchantActivity")}`;
      t54 = space();
      p9 = element("p");
      p9.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.LogMerchantActivityExplanation")}`;
      t56 = space();
      input7 = element("input");
      t57 = space();
      div12 = element("div");
      label10 = element("label");
      span10 = element("span");
      span10.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ClearMerchantLog")}`;
      t59 = space();
      p10 = element("p");
      p10.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ClearMerchantLogExplanation")}`;
      t61 = space();
      button0 = element("button");
      button0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ClearMerchantLog")}`;
      t63 = space();
      div13 = element("div");
      label11 = element("label");
      span11 = element("span");
      span11.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.PriceModifierTitle")}`;
      t65 = space();
      p11 = element("p");
      p11.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.PriceModifierExplanation")}`;
      t67 = space();
      div14 = element("div");
      label12 = element("label");
      span12 = element("span");
      span12.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.BuyPriceModifier")}`;
      t69 = space();
      create_component(sliderinput0.$$.fragment);
      t70 = space();
      div15 = element("div");
      label13 = element("label");
      span13 = element("span");
      span13.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.SellPriceModifier")}`;
      t72 = space();
      create_component(sliderinput1.$$.fragment);
      t73 = space();
      div17 = element("div");
      div16 = element("div");
      label14 = element("label");
      span14 = element("span");
      span14.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ItemTypeModifier")}`;
      t75 = space();
      p12 = element("p");
      p12.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ItemTypeModifiersExplanation")}`;
      t77 = space();
      button1 = element("button");
      button1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ConfigureItemTypePriceModifiers")}`;
      t79 = space();
      div19 = element("div");
      div18 = element("div");
      label15 = element("label");
      span15 = element("span");
      span15.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ActorPriceModifiers")}`;
      t81 = space();
      p13 = element("p");
      p13.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ActorPriceModifiersExplanation")}`;
      t83 = space();
      button2 = element("button");
      button2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ConfigureActorPriceModifiers")}`;
      t85 = space();
      div21 = element("div");
      div20 = element("div");
      label16 = element("label");
      span16 = element("span");
      span16.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.MerchantColumns")}`;
      t87 = space();
      p14 = element("p");
      p14.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.MerchantColumnsExplanation")}`;
      t89 = space();
      button3 = element("button");
      button3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.ConfigureMerchantColumns")}`;
      t91 = space();
      div23 = element("div");
      label17 = element("label");
      span17 = element("span");
      span17.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OpenStatus")}`;
      t93 = space();
      p15 = element("p");
      p15.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OpenStatusExplanation")}`;
      t95 = space();
      div22 = element("div");
      t96 = space();
      select1 = element("select");
      option4 = element("option");
      option4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OpenStatusOpen")} 
		`;
      option5 = element("option");
      option5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OpenStatusClosed")} 
		`;
      if (if_block0)
        if_block0.c();
      t101 = space();
      div24 = element("div");
      label18 = element("label");
      span18 = element("span");
      span18.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideTokenWhenClosed")}`;
      t103 = space();
      p16 = element("p");
      p16.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.HideTokenWhenClosedExplanation")}`;
      t105 = space();
      input8 = element("input");
      t106 = space();
      div25 = element("div");
      label19 = element("label");
      span19 = element("span");
      span19.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OpenTimes")}`;
      t108 = space();
      p17 = element("p");
      p17.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Merchant.OpenTimesExplanation")}`;
      t110 = space();
      input9 = element("input");
      t111 = space();
      div30 = element("div");
      div27 = element("div");
      label20 = element("label");
      label20.textContent = "Open Time:";
      t113 = space();
      div26 = element("div");
      input10 = element("input");
      t114 = space();
      span20 = element("span");
      span20.textContent = ":";
      t116 = space();
      input11 = element("input");
      t117 = space();
      div29 = element("div");
      label21 = element("label");
      label21.textContent = "Close Time:";
      t119 = space();
      div28 = element("div");
      input12 = element("input");
      t120 = space();
      span21 = element("span");
      span21.textContent = ":";
      t122 = space();
      input13 = element("input");
      t123 = space();
      if (if_block1)
        if_block1.c();
      if_block1_anchor = empty();
      attr(div0, "class", "form-fields");
      attr(div1, "class", "form-group svelte-4amoj2");
      attr(input0, "type", "checkbox");
      attr(div2, "class", "form-group svelte-4amoj2");
      attr(input1, "type", "checkbox");
      attr(div3, "class", "form-group svelte-4amoj2");
      attr(input2, "type", "checkbox");
      attr(div4, "class", "form-group svelte-4amoj2");
      attr(div5, "class", "break");
      option0.__value = "yes";
      option0.value = option0.__value;
      option1.__value = "no";
      option1.value = option1.__value;
      option2.__value = "alwaysyes";
      option2.value = option2.__value;
      option3.__value = "alwaysno";
      option3.value = option3.__value;
      set_style(select0, "flex", "4");
      if (
        /*pileData*/
        ctx[0].displayQuantity === void 0
      )
        add_render_callback(() => (
          /*select0_change_handler*/
          ctx[15].call(select0)
        ));
      attr(div6, "class", "form-group svelte-4amoj2");
      attr(input3, "type", "checkbox");
      attr(div7, "class", "form-group svelte-4amoj2");
      attr(input4, "type", "checkbox");
      attr(div8, "class", "form-group svelte-4amoj2");
      attr(input5, "type", "checkbox");
      attr(div9, "class", "form-group svelte-4amoj2");
      attr(input6, "type", "checkbox");
      attr(div10, "class", "form-group svelte-4amoj2");
      attr(input7, "type", "checkbox");
      attr(div11, "class", "form-group svelte-4amoj2");
      set_style(label10, "flex", "4");
      set_style(button0, "flex", "2");
      attr(button0, "type", "button");
      attr(div12, "class", "form-group svelte-4amoj2");
      set_style(label11, "flex", "3");
      attr(div13, "class", "form-group slider-group svelte-4amoj2");
      set_style(label12, "flex", "3");
      attr(div14, "class", "form-group slider-group svelte-4amoj2");
      set_style(label13, "flex", "3");
      attr(div15, "class", "form-group slider-group svelte-4amoj2");
      attr(button1, "type", "button");
      attr(div16, "class", "item-piles-flexcol");
      attr(div17, "class", "form-group svelte-4amoj2");
      attr(button2, "type", "button");
      attr(div18, "class", "item-piles-flexcol");
      attr(div19, "class", "form-group svelte-4amoj2");
      attr(button3, "type", "button");
      attr(div20, "class", "item-piles-flexcol");
      attr(div21, "class", "form-group svelte-4amoj2");
      attr(div22, "class", "break");
      option4.__value = "open";
      option4.value = option4.__value;
      option5.__value = "closed";
      option5.value = option5.__value;
      set_style(select1, "flex", "4");
      if (
        /*pileData*/
        ctx[0].openTimes.status === void 0
      )
        add_render_callback(() => (
          /*select1_change_handler*/
          ctx[27].call(select1)
        ));
      attr(div23, "class", "form-group svelte-4amoj2");
      attr(input8, "type", "checkbox");
      attr(div24, "class", "form-group svelte-4amoj2");
      attr(input9, "type", "checkbox");
      attr(div25, "class", "form-group svelte-4amoj2");
      attr(label20, "class", "item-piles-text-center");
      input10.disabled = input10_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      set_style(input10, "text-align", "right");
      attr(input10, "type", "number");
      set_style(span20, "flex", "0");
      set_style(span20, "line-height", "1.7");
      set_style(span20, "margin", "0 0.25rem");
      input11.disabled = input11_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      attr(input11, "type", "number");
      attr(div26, "class", "item-piles-flexrow");
      attr(div27, "class", "item-piles-flexcol");
      set_style(div27, "margin-right", "1rem");
      attr(label21, "class", "item-piles-text-center");
      input12.disabled = input12_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      set_style(input12, "text-align", "right");
      attr(input12, "type", "number");
      set_style(span21, "flex", "0");
      set_style(span21, "line-height", "1.7");
      set_style(span21, "margin", "0 0.25rem");
      input13.disabled = input13_disabled_value = !/*pileData*/
      ctx[0].openTimes.enabled;
      attr(input13, "type", "number");
      attr(div28, "class", "item-piles-flexrow");
      attr(div29, "class", "item-piles-flexcol");
      attr(div30, "class", "form-group svelte-4amoj2");
      toggle_class(div30, "item-piles-disabled", !/*pileData*/
      ctx[0].openTimes.enabled);
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, label0);
      append(label0, span0);
      append(label0, t1);
      append(label0, p0);
      append(div1, t3);
      append(div1, div0);
      mount_component(filepicker, div0, null);
      insert(target, t4, anchor);
      insert(target, div2, anchor);
      append(div2, label1);
      append(label1, span1);
      append(label1, t6);
      append(label1, p1);
      append(div2, t8);
      append(div2, input0);
      input0.checked = /*pileData*/
      ctx[0].infiniteQuantity;
      insert(target, t9, anchor);
      insert(target, div3, anchor);
      append(div3, label2);
      append(label2, span2);
      append(label2, t11);
      append(label2, p2);
      append(div3, t13);
      append(div3, input1);
      input1.checked = /*pileData*/
      ctx[0].infiniteCurrencies;
      insert(target, t14, anchor);
      insert(target, div4, anchor);
      append(div4, label3);
      append(label3, span3);
      append(label3, t16);
      append(label3, p3);
      append(div4, t18);
      append(div4, input2);
      input2.checked = /*pileData*/
      ctx[0].keepZeroQuantity;
      insert(target, t19, anchor);
      insert(target, div6, anchor);
      append(div6, label4);
      append(label4, span4);
      append(label4, t21);
      append(label4, p4);
      append(div6, t23);
      append(div6, div5);
      append(div6, t24);
      append(div6, select0);
      append(select0, option0);
      append(select0, option1);
      append(select0, option2);
      append(select0, option3);
      select_option(
        select0,
        /*pileData*/
        ctx[0].displayQuantity,
        true
      );
      insert(target, t32, anchor);
      insert(target, div7, anchor);
      append(div7, label5);
      append(label5, span5);
      append(label5, t34);
      append(label5, p5);
      append(div7, t36);
      append(div7, input3);
      input3.checked = /*pileData*/
      ctx[0].purchaseOnly;
      insert(target, t37, anchor);
      insert(target, div8, anchor);
      append(div8, label6);
      append(label6, span6);
      append(label6, t39);
      append(label6, p6);
      append(div8, t41);
      append(div8, input4);
      input4.checked = /*pileData*/
      ctx[0].hideNewItems;
      insert(target, t42, anchor);
      insert(target, div9, anchor);
      append(div9, label7);
      append(label7, span7);
      append(label7, t44);
      append(label7, p7);
      append(div9, t46);
      append(div9, input5);
      input5.checked = /*pileData*/
      ctx[0].hideItemsWithZeroCost;
      insert(target, t47, anchor);
      insert(target, div10, anchor);
      append(div10, label8);
      append(label8, span8);
      append(label8, t49);
      append(label8, p8);
      append(div10, t51);
      append(div10, input6);
      input6.checked = /*pileData*/
      ctx[0].onlyAcceptBasePrice;
      insert(target, t52, anchor);
      insert(target, div11, anchor);
      append(div11, label9);
      append(label9, span9);
      append(label9, t54);
      append(label9, p9);
      append(div11, t56);
      append(div11, input7);
      input7.checked = /*pileData*/
      ctx[0].logMerchantActivity;
      insert(target, t57, anchor);
      insert(target, div12, anchor);
      append(div12, label10);
      append(label10, span10);
      append(label10, t59);
      append(label10, p10);
      append(div12, t61);
      append(div12, button0);
      insert(target, t63, anchor);
      insert(target, div13, anchor);
      append(div13, label11);
      append(label11, span11);
      append(label11, t65);
      append(label11, p11);
      insert(target, t67, anchor);
      insert(target, div14, anchor);
      append(div14, label12);
      append(label12, span12);
      append(div14, t69);
      mount_component(sliderinput0, div14, null);
      insert(target, t70, anchor);
      insert(target, div15, anchor);
      append(div15, label13);
      append(label13, span13);
      append(div15, t72);
      mount_component(sliderinput1, div15, null);
      insert(target, t73, anchor);
      insert(target, div17, anchor);
      append(div17, div16);
      append(div16, label14);
      append(label14, span14);
      append(label14, t75);
      append(label14, p12);
      append(div16, t77);
      append(div16, button1);
      insert(target, t79, anchor);
      insert(target, div19, anchor);
      append(div19, div18);
      append(div18, label15);
      append(label15, span15);
      append(label15, t81);
      append(label15, p13);
      append(div18, t83);
      append(div18, button2);
      insert(target, t85, anchor);
      insert(target, div21, anchor);
      append(div21, div20);
      append(div20, label16);
      append(label16, span16);
      append(label16, t87);
      append(label16, p14);
      append(div20, t89);
      append(div20, button3);
      insert(target, t91, anchor);
      insert(target, div23, anchor);
      append(div23, label17);
      append(label17, span17);
      append(label17, t93);
      append(label17, p15);
      append(div23, t95);
      append(div23, div22);
      append(div23, t96);
      append(div23, select1);
      append(select1, option4);
      append(select1, option5);
      if (if_block0)
        if_block0.m(select1, null);
      select_option(
        select1,
        /*pileData*/
        ctx[0].openTimes.status,
        true
      );
      insert(target, t101, anchor);
      insert(target, div24, anchor);
      append(div24, label18);
      append(label18, span18);
      append(label18, t103);
      append(label18, p16);
      append(div24, t105);
      append(div24, input8);
      input8.checked = /*pileData*/
      ctx[0].openTimes.hideTokenWhenClosed;
      insert(target, t106, anchor);
      insert(target, div25, anchor);
      append(div25, label19);
      append(label19, span19);
      append(label19, t108);
      append(label19, p17);
      append(div25, t110);
      append(div25, input9);
      input9.checked = /*pileData*/
      ctx[0].openTimes.enabled;
      insert(target, t111, anchor);
      insert(target, div30, anchor);
      append(div30, div27);
      append(div27, label20);
      append(div27, t113);
      append(div27, div26);
      append(div26, input10);
      set_input_value(
        input10,
        /*pileData*/
        ctx[0].openTimes.open.hour
      );
      append(div26, t114);
      append(div26, span20);
      append(div26, t116);
      append(div26, input11);
      set_input_value(
        input11,
        /*pileData*/
        ctx[0].openTimes.open.minute
      );
      append(div30, t117);
      append(div30, div29);
      append(div29, label21);
      append(div29, t119);
      append(div29, div28);
      append(div28, input12);
      set_input_value(
        input12,
        /*pileData*/
        ctx[0].openTimes.close.hour
      );
      append(div28, t120);
      append(div28, span21);
      append(div28, t122);
      append(div28, input13);
      set_input_value(
        input13,
        /*pileData*/
        ctx[0].openTimes.close.minute
      );
      insert(target, t123, anchor);
      if (if_block1)
        if_block1.m(target, anchor);
      insert(target, if_block1_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler*/
            ctx[12]
          ),
          listen(
            input1,
            "change",
            /*input1_change_handler*/
            ctx[13]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler*/
            ctx[14]
          ),
          listen(
            select0,
            "change",
            /*select0_change_handler*/
            ctx[15]
          ),
          listen(
            input3,
            "change",
            /*input3_change_handler*/
            ctx[16]
          ),
          listen(
            input4,
            "change",
            /*input4_change_handler*/
            ctx[17]
          ),
          listen(
            input5,
            "change",
            /*input5_change_handler*/
            ctx[18]
          ),
          listen(
            input6,
            "change",
            /*input6_change_handler*/
            ctx[19]
          ),
          listen(
            input7,
            "change",
            /*input7_change_handler*/
            ctx[20]
          ),
          listen(
            button0,
            "click",
            /*click_handler*/
            ctx[21]
          ),
          listen(
            button1,
            "click",
            /*click_handler_1*/
            ctx[24]
          ),
          listen(
            button2,
            "click",
            /*click_handler_2*/
            ctx[25]
          ),
          listen(
            button3,
            "click",
            /*click_handler_3*/
            ctx[26]
          ),
          listen(
            select1,
            "change",
            /*select1_change_handler*/
            ctx[27]
          ),
          listen(
            input8,
            "change",
            /*input8_change_handler*/
            ctx[28]
          ),
          listen(
            input9,
            "change",
            /*input9_change_handler*/
            ctx[29]
          ),
          listen(
            input10,
            "input",
            /*input10_input_handler*/
            ctx[30]
          ),
          listen(
            input11,
            "input",
            /*input11_input_handler*/
            ctx[31]
          ),
          listen(
            input12,
            "input",
            /*input12_input_handler*/
            ctx[32]
          ),
          listen(
            input13,
            "input",
            /*input13_input_handler*/
            ctx[33]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const filepicker_changes = {};
      if (!updating_value && dirty[0] & /*pileData*/
      1) {
        updating_value = true;
        filepicker_changes.value = /*pileData*/
        ctx2[0].merchantImage;
        add_flush_callback(() => updating_value = false);
      }
      filepicker.$set(filepicker_changes);
      if (dirty[0] & /*pileData*/
      1) {
        input0.checked = /*pileData*/
        ctx2[0].infiniteQuantity;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input1.checked = /*pileData*/
        ctx2[0].infiniteCurrencies;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input2.checked = /*pileData*/
        ctx2[0].keepZeroQuantity;
      }
      if (dirty[0] & /*pileData*/
      1) {
        select_option(
          select0,
          /*pileData*/
          ctx2[0].displayQuantity
        );
      }
      if (dirty[0] & /*pileData*/
      1) {
        input3.checked = /*pileData*/
        ctx2[0].purchaseOnly;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input4.checked = /*pileData*/
        ctx2[0].hideNewItems;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input5.checked = /*pileData*/
        ctx2[0].hideItemsWithZeroCost;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input6.checked = /*pileData*/
        ctx2[0].onlyAcceptBasePrice;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input7.checked = /*pileData*/
        ctx2[0].logMerchantActivity;
      }
      const sliderinput0_changes = {};
      if (!updating_value_1 && dirty[0] & /*pileData*/
      1) {
        updating_value_1 = true;
        sliderinput0_changes.value = /*pileData*/
        ctx2[0].buyPriceModifier;
        add_flush_callback(() => updating_value_1 = false);
      }
      sliderinput0.$set(sliderinput0_changes);
      const sliderinput1_changes = {};
      if (!updating_value_2 && dirty[0] & /*pileData*/
      1) {
        updating_value_2 = true;
        sliderinput1_changes.value = /*pileData*/
        ctx2[0].sellPriceModifier;
        add_flush_callback(() => updating_value_2 = false);
      }
      sliderinput1.$set(sliderinput1_changes);
      if (
        /*simpleCalendarActive*/
        ctx2[5] && /*pileData*/
        ctx2[0].openTimes.enabled
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_1$a();
          if_block0.c();
          if_block0.m(select1, null);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty[0] & /*pileData*/
      1) {
        select_option(
          select1,
          /*pileData*/
          ctx2[0].openTimes.status
        );
      }
      if (dirty[0] & /*pileData*/
      1) {
        input8.checked = /*pileData*/
        ctx2[0].openTimes.hideTokenWhenClosed;
      }
      if (dirty[0] & /*pileData*/
      1) {
        input9.checked = /*pileData*/
        ctx2[0].openTimes.enabled;
      }
      if (!current || dirty[0] & /*pileData*/
      1 && input10_disabled_value !== (input10_disabled_value = !/*pileData*/
      ctx2[0].openTimes.enabled)) {
        input10.disabled = input10_disabled_value;
      }
      if (dirty[0] & /*pileData*/
      1 && to_number(input10.value) !== /*pileData*/
      ctx2[0].openTimes.open.hour) {
        set_input_value(
          input10,
          /*pileData*/
          ctx2[0].openTimes.open.hour
        );
      }
      if (!current || dirty[0] & /*pileData*/
      1 && input11_disabled_value !== (input11_disabled_value = !/*pileData*/
      ctx2[0].openTimes.enabled)) {
        input11.disabled = input11_disabled_value;
      }
      if (dirty[0] & /*pileData*/
      1 && to_number(input11.value) !== /*pileData*/
      ctx2[0].openTimes.open.minute) {
        set_input_value(
          input11,
          /*pileData*/
          ctx2[0].openTimes.open.minute
        );
      }
      if (!current || dirty[0] & /*pileData*/
      1 && input12_disabled_value !== (input12_disabled_value = !/*pileData*/
      ctx2[0].openTimes.enabled)) {
        input12.disabled = input12_disabled_value;
      }
      if (dirty[0] & /*pileData*/
      1 && to_number(input12.value) !== /*pileData*/
      ctx2[0].openTimes.close.hour) {
        set_input_value(
          input12,
          /*pileData*/
          ctx2[0].openTimes.close.hour
        );
      }
      if (!current || dirty[0] & /*pileData*/
      1 && input13_disabled_value !== (input13_disabled_value = !/*pileData*/
      ctx2[0].openTimes.enabled)) {
        input13.disabled = input13_disabled_value;
      }
      if (dirty[0] & /*pileData*/
      1 && to_number(input13.value) !== /*pileData*/
      ctx2[0].openTimes.close.minute) {
        set_input_value(
          input13,
          /*pileData*/
          ctx2[0].openTimes.close.minute
        );
      }
      if (!current || dirty[0] & /*pileData*/
      1) {
        toggle_class(div30, "item-piles-disabled", !/*pileData*/
        ctx2[0].openTimes.enabled);
      }
      if (
        /*simpleCalendarActive*/
        ctx2[5]
      )
        if_block1.p(ctx2, dirty);
    },
    i(local) {
      if (current)
        return;
      transition_in(filepicker.$$.fragment, local);
      transition_in(sliderinput0.$$.fragment, local);
      transition_in(sliderinput1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filepicker.$$.fragment, local);
      transition_out(sliderinput0.$$.fragment, local);
      transition_out(sliderinput1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      destroy_component(filepicker);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(div2);
      if (detaching)
        detach(t9);
      if (detaching)
        detach(div3);
      if (detaching)
        detach(t14);
      if (detaching)
        detach(div4);
      if (detaching)
        detach(t19);
      if (detaching)
        detach(div6);
      if (detaching)
        detach(t32);
      if (detaching)
        detach(div7);
      if (detaching)
        detach(t37);
      if (detaching)
        detach(div8);
      if (detaching)
        detach(t42);
      if (detaching)
        detach(div9);
      if (detaching)
        detach(t47);
      if (detaching)
        detach(div10);
      if (detaching)
        detach(t52);
      if (detaching)
        detach(div11);
      if (detaching)
        detach(t57);
      if (detaching)
        detach(div12);
      if (detaching)
        detach(t63);
      if (detaching)
        detach(div13);
      if (detaching)
        detach(t67);
      if (detaching)
        detach(div14);
      destroy_component(sliderinput0);
      if (detaching)
        detach(t70);
      if (detaching)
        detach(div15);
      destroy_component(sliderinput1);
      if (detaching)
        detach(t73);
      if (detaching)
        detach(div17);
      if (detaching)
        detach(t79);
      if (detaching)
        detach(div19);
      if (detaching)
        detach(t85);
      if (detaching)
        detach(div21);
      if (detaching)
        detach(t91);
      if (detaching)
        detach(div23);
      if (if_block0)
        if_block0.d();
      if (detaching)
        detach(t101);
      if (detaching)
        detach(div24);
      if (detaching)
        detach(t106);
      if (detaching)
        detach(div25);
      if (detaching)
        detach(t111);
      if (detaching)
        detach(div30);
      if (detaching)
        detach(t123);
      if (if_block1)
        if_block1.d(detaching);
      if (detaching)
        detach(if_block1_anchor);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$r, "create_fragment$r");
function instance$o($$self, $$props, $$invalidate) {
  let { pileData } = $$props;
  let { pileActor } = $$props;
  const simpleCalendarActive = game.modules.get("foundryvtt-simple-calendar")?.active;
  const weekdays = (simpleCalendarActive ? window.SimpleCalendar.api.getAllWeekdays() : []).map((weekday) => {
    weekday.selected = pileData.closedDays.includes(weekday.name);
    return weekday;
  });
  const refreshItemDays = (simpleCalendarActive ? window.SimpleCalendar.api.getAllWeekdays() : []).map((weekday) => {
    weekday.selected = pileData.refreshItemsDays.includes(weekday.name);
    return weekday;
  });
  pileData.closedDays = pileData.closedDays.filter((closedWeekday) => {
    return weekdays.some((weekday) => weekday.name === closedWeekday);
  });
  const holidays = (simpleCalendarActive ? window.SimpleCalendar.api.getCurrentCalendar().noteCategories : []).map((holiday) => {
    return {
      name: holiday.name,
      selected: pileData.closedHolidays.includes(holiday.name)
    };
  });
  pileData.closedHolidays = pileData.closedHolidays.filter((closedHoliday) => {
    return holidays.some((holiday) => holiday.name === closedHoliday);
  });
  const refreshItemsHolidays = (simpleCalendarActive ? window.SimpleCalendar.api.getCurrentCalendar().noteCategories : []).map((holiday) => {
    return {
      name: holiday.name,
      selected: pileData.refreshItemsHolidays.includes(holiday.name)
    };
  });
  pileData.refreshItemsHolidays = pileData.refreshItemsHolidays.filter((refreshItemsHoliday) => {
    return refreshItemsHolidays.some((holiday) => holiday.name === refreshItemsHoliday);
  });
  async function showItemTypePriceModifiers() {
    const data2 = pileData.itemTypePriceModifiers || [];
    return ItemTypePriceModifiersEditor.show(
      data2,
      {
        id: `item-type-price-modifier-item-pile-config-${pileActor.id}`
      },
      {
        title: localize("ITEM-PILES.Applications.ItemTypePriceModifiersEditor.TitleActor", { actor_name: pileActor.name })
      }
    ).then((result) => {
      $$invalidate(0, pileData.itemTypePriceModifiers = result || [], pileData);
    });
  }
  __name(showItemTypePriceModifiers, "showItemTypePriceModifiers");
  async function showActorPriceModifiers() {
    const data2 = pileData.actorPriceModifiers || [];
    return PriceModifiersEditor.show(
      data2,
      {
        id: `price-modifier-item-pile-config-${pileActor.id}`
      },
      {
        title: localize("ITEM-PILES.Applications.PriceModifiersEditor.TitleActor", { actor_name: pileActor.name })
      }
    ).then((result) => {
      $$invalidate(0, pileData.actorPriceModifiers = result || [], pileData);
      pileData.actorPriceModifiers.forEach((modifier) => {
        if (modifier.actor) {
          delete modifier["actor"];
        }
      });
    });
  }
  __name(showActorPriceModifiers, "showActorPriceModifiers");
  async function showMerchantColumns() {
    const data2 = pileData.merchantColumns || [];
    return MerchantColumnsEditor.show(
      data2,
      {
        id: `merchant-columns-item-pile-config-${pileActor.id}`
      },
      {
        title: localize("ITEM-PILES.Applications.MerchantColumnsEditor.TitleActor", { actor_name: pileActor.name })
      }
    ).then((result) => {
      $$invalidate(0, pileData.merchantColumns = result || [], pileData);
    });
  }
  __name(showMerchantColumns, "showMerchantColumns");
  async function clearLog() {
    const doThing = await TJSDialog.confirm({
      id: `sharing-dialog-item-pile-config-${pileActor.id}`,
      title: "Item Piles - " + localize("ITEM-PILES.Dialogs.ClearMerchantLog.Title"),
      content: {
        class: CustomDialog,
        props: {
          header: localize("ITEM-PILES.Dialogs.ClearMerchantLog.Title"),
          content: localize("ITEM-PILES.Dialogs.ClearMerchantLog.Content", { actor_name: pileActor.name })
        }
      },
      modal: true
    });
    if (!doThing)
      return;
    return clearActorLog(pileActor);
  }
  __name(clearLog, "clearLog");
  function filepicker_value_binding(value) {
    if ($$self.$$.not_equal(pileData.merchantImage, value)) {
      pileData.merchantImage = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker_value_binding, "filepicker_value_binding");
  function input0_change_handler() {
    pileData.infiniteQuantity = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_change_handler() {
    pileData.infiniteCurrencies = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input1_change_handler, "input1_change_handler");
  function input2_change_handler() {
    pileData.keepZeroQuantity = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input2_change_handler, "input2_change_handler");
  function select0_change_handler() {
    pileData.displayQuantity = select_value(this);
    $$invalidate(0, pileData);
  }
  __name(select0_change_handler, "select0_change_handler");
  function input3_change_handler() {
    pileData.purchaseOnly = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input3_change_handler, "input3_change_handler");
  function input4_change_handler() {
    pileData.hideNewItems = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input4_change_handler, "input4_change_handler");
  function input5_change_handler() {
    pileData.hideItemsWithZeroCost = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input5_change_handler, "input5_change_handler");
  function input6_change_handler() {
    pileData.onlyAcceptBasePrice = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input6_change_handler, "input6_change_handler");
  function input7_change_handler() {
    pileData.logMerchantActivity = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input7_change_handler, "input7_change_handler");
  const click_handler = /* @__PURE__ */ __name(() => clearLog(), "click_handler");
  function sliderinput0_value_binding(value) {
    if ($$self.$$.not_equal(pileData.buyPriceModifier, value)) {
      pileData.buyPriceModifier = value;
      $$invalidate(0, pileData);
    }
  }
  __name(sliderinput0_value_binding, "sliderinput0_value_binding");
  function sliderinput1_value_binding(value) {
    if ($$self.$$.not_equal(pileData.sellPriceModifier, value)) {
      pileData.sellPriceModifier = value;
      $$invalidate(0, pileData);
    }
  }
  __name(sliderinput1_value_binding, "sliderinput1_value_binding");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    showItemTypePriceModifiers();
  }, "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    showActorPriceModifiers();
  }, "click_handler_2");
  const click_handler_32 = /* @__PURE__ */ __name(() => {
    showMerchantColumns();
  }, "click_handler_3");
  function select1_change_handler() {
    pileData.openTimes.status = select_value(this);
    $$invalidate(0, pileData);
  }
  __name(select1_change_handler, "select1_change_handler");
  function input8_change_handler() {
    pileData.openTimes.hideTokenWhenClosed = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input8_change_handler, "input8_change_handler");
  function input9_change_handler() {
    pileData.openTimes.enabled = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input9_change_handler, "input9_change_handler");
  function input10_input_handler() {
    pileData.openTimes.open.hour = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input10_input_handler, "input10_input_handler");
  function input11_input_handler() {
    pileData.openTimes.open.minute = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input11_input_handler, "input11_input_handler");
  function input12_input_handler() {
    pileData.openTimes.close.hour = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input12_input_handler, "input12_input_handler");
  function input13_input_handler() {
    pileData.openTimes.close.minute = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input13_input_handler, "input13_input_handler");
  function input_change_handler(each_value_3, weekday_index_1) {
    each_value_3[weekday_index_1].selected = this.checked;
    $$invalidate(1, weekdays);
  }
  __name(input_change_handler, "input_change_handler");
  const change_handler = /* @__PURE__ */ __name((weekday) => {
    let weekdaySet = new Set(pileData.closedDays);
    if (weekday.selected) {
      weekdaySet.add(weekday.name);
    } else {
      weekdaySet.delete(weekday.name);
    }
    $$invalidate(0, pileData.closedDays = Array.from(weekdaySet), pileData);
  }, "change_handler");
  function input_change_handler_1(each_value_2, index2) {
    each_value_2[index2].selected = this.checked;
    $$invalidate(3, holidays);
  }
  __name(input_change_handler_1, "input_change_handler_1");
  const change_handler_1 = /* @__PURE__ */ __name((holiday) => {
    let holidaySet = new Set(pileData.closedHolidays);
    if (holiday.selected) {
      holidaySet.add(holiday.name);
    } else {
      holidaySet.delete(holiday.name);
    }
    $$invalidate(0, pileData.closedHolidays = Array.from(holidaySet), pileData);
  }, "change_handler_1");
  function input_change_handler_2() {
    pileData.refreshItemsOnOpen = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input_change_handler_2, "input_change_handler_2");
  function input_change_handler_3(each_value_1, weekday_index) {
    each_value_1[weekday_index].selected = this.checked;
    $$invalidate(2, refreshItemDays);
  }
  __name(input_change_handler_3, "input_change_handler_3");
  const change_handler_2 = /* @__PURE__ */ __name((weekday) => {
    let weekdaySet = new Set(pileData.refreshItemsDays);
    if (weekday.selected) {
      weekdaySet.add(weekday.name);
    } else {
      weekdaySet.delete(weekday.name);
    }
    $$invalidate(0, pileData.refreshItemsDays = Array.from(weekdaySet), pileData);
  }, "change_handler_2");
  function input_change_handler_4(each_value, index2) {
    each_value[index2].selected = this.checked;
    $$invalidate(4, refreshItemsHolidays);
  }
  __name(input_change_handler_4, "input_change_handler_4");
  const change_handler_3 = /* @__PURE__ */ __name((holiday) => {
    let holidaySet = new Set(pileData.refreshItemsHolidays);
    if (holiday.selected) {
      holidaySet.add(holiday.name);
    } else {
      holidaySet.delete(holiday.name);
    }
    $$invalidate(0, pileData.refreshItemsHolidays = Array.from(holidaySet), pileData);
  }, "change_handler_3");
  $$self.$$set = ($$props2) => {
    if ("pileData" in $$props2)
      $$invalidate(0, pileData = $$props2.pileData);
    if ("pileActor" in $$props2)
      $$invalidate(10, pileActor = $$props2.pileActor);
  };
  return [
    pileData,
    weekdays,
    refreshItemDays,
    holidays,
    refreshItemsHolidays,
    simpleCalendarActive,
    showItemTypePriceModifiers,
    showActorPriceModifiers,
    showMerchantColumns,
    clearLog,
    pileActor,
    filepicker_value_binding,
    input0_change_handler,
    input1_change_handler,
    input2_change_handler,
    select0_change_handler,
    input3_change_handler,
    input4_change_handler,
    input5_change_handler,
    input6_change_handler,
    input7_change_handler,
    click_handler,
    sliderinput0_value_binding,
    sliderinput1_value_binding,
    click_handler_1,
    click_handler_2,
    click_handler_32,
    select1_change_handler,
    input8_change_handler,
    input9_change_handler,
    input10_input_handler,
    input11_input_handler,
    input12_input_handler,
    input13_input_handler,
    input_change_handler,
    change_handler,
    input_change_handler_1,
    change_handler_1,
    input_change_handler_2,
    input_change_handler_3,
    change_handler_2,
    input_change_handler_4,
    change_handler_3
  ];
}
__name(instance$o, "instance$o");
const _Merchant = class _Merchant extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$o, create_fragment$r, safe_not_equal, { pileData: 0, pileActor: 10 }, null, [-1, -1]);
  }
};
__name(_Merchant, "Merchant");
let Merchant = _Merchant;
function create_fragment$q(ctx) {
  let div0;
  let label0;
  let span0;
  let t1;
  let p0;
  let t3;
  let input0;
  let t4;
  let div4;
  let div1;
  let label1;
  let span1;
  let t6;
  let p1;
  let t8;
  let input1;
  let t9;
  let div2;
  let label2;
  let span2;
  let t11;
  let input2;
  let t12;
  let div3;
  let label3;
  let span3;
  let t14;
  let input3;
  let input3_disabled_value;
  let t15;
  let input4;
  let input4_disabled_value;
  let mounted;
  let dispose;
  return {
    c() {
      div0 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.SingleItem.DisplayOne")}`;
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.SingleItem.DisplayOneExplanation")}`;
      t3 = space();
      input0 = element("input");
      t4 = space();
      div4 = element("div");
      div1 = element("div");
      label1 = element("label");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.SingleItem.ItemName")}`;
      t6 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.SingleItem.ItemNameExplanation")}`;
      t8 = space();
      input1 = element("input");
      t9 = space();
      div2 = element("div");
      label2 = element("label");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.SingleItem.OverrideScale")}`;
      t11 = space();
      input2 = element("input");
      t12 = space();
      div3 = element("div");
      label3 = element("label");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.SingleItem.Scale")}`;
      t14 = space();
      input3 = element("input");
      t15 = space();
      input4 = element("input");
      attr(input0, "type", "checkbox");
      attr(div0, "class", "form-group");
      attr(input1, "type", "checkbox");
      attr(div1, "class", "form-group");
      attr(input2, "type", "checkbox");
      attr(div2, "class", "form-group");
      set_style(label3, "flex", "3");
      attr(input3, "class", "item-piles-scaleRange");
      input3.disabled = input3_disabled_value = !/*pileData*/
      ctx[0].overrideSingleItemScale;
      attr(input3, "max", "3");
      attr(input3, "min", "0.2");
      attr(input3, "step", "0.01");
      set_style(input3, "flex", "3");
      attr(input3, "type", "range");
      attr(input4, "class", "item-piles-scaleInput");
      input4.disabled = input4_disabled_value = !/*pileData*/
      ctx[0].overrideSingleItemScale;
      attr(input4, "step", "0.01");
      set_style(input4, "flex", "0.5");
      set_style(input4, "margin-left", "1rem");
      attr(input4, "type", "number");
      attr(div3, "class", "form-group");
      toggle_class(div3, "item-piles-disabled", !/*pileData*/
      ctx[0].overrideSingleItemScale);
      attr(div4, "class", "item-pile-display-one-settings");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, label0);
      append(label0, span0);
      append(label0, t1);
      append(label0, p0);
      append(div0, t3);
      append(div0, input0);
      input0.checked = /*pileData*/
      ctx[0].displayOne;
      insert(target, t4, anchor);
      insert(target, div4, anchor);
      append(div4, div1);
      append(div1, label1);
      append(label1, span1);
      append(label1, t6);
      append(label1, p1);
      append(div1, t8);
      append(div1, input1);
      input1.checked = /*pileData*/
      ctx[0].showItemName;
      append(div4, t9);
      append(div4, div2);
      append(div2, label2);
      append(label2, span2);
      append(div2, t11);
      append(div2, input2);
      input2.checked = /*pileData*/
      ctx[0].overrideSingleItemScale;
      append(div4, t12);
      append(div4, div3);
      append(div3, label3);
      append(label3, span3);
      append(div3, t14);
      append(div3, input3);
      set_input_value(
        input3,
        /*pileData*/
        ctx[0].singleItemScale
      );
      append(div3, t15);
      append(div3, input4);
      set_input_value(
        input4,
        /*pileData*/
        ctx[0].singleItemScale
      );
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler*/
            ctx[1]
          ),
          listen(
            input1,
            "change",
            /*input1_change_handler*/
            ctx[2]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler*/
            ctx[3]
          ),
          listen(
            input3,
            "change",
            /*input3_change_input_handler*/
            ctx[4]
          ),
          listen(
            input3,
            "input",
            /*input3_change_input_handler*/
            ctx[4]
          ),
          listen(
            input4,
            "input",
            /*input4_input_handler*/
            ctx[5]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*pileData*/
      1) {
        input0.checked = /*pileData*/
        ctx2[0].displayOne;
      }
      if (dirty & /*pileData*/
      1) {
        input1.checked = /*pileData*/
        ctx2[0].showItemName;
      }
      if (dirty & /*pileData*/
      1) {
        input2.checked = /*pileData*/
        ctx2[0].overrideSingleItemScale;
      }
      if (dirty & /*pileData*/
      1 && input3_disabled_value !== (input3_disabled_value = !/*pileData*/
      ctx2[0].overrideSingleItemScale)) {
        input3.disabled = input3_disabled_value;
      }
      if (dirty & /*pileData*/
      1) {
        set_input_value(
          input3,
          /*pileData*/
          ctx2[0].singleItemScale
        );
      }
      if (dirty & /*pileData*/
      1 && input4_disabled_value !== (input4_disabled_value = !/*pileData*/
      ctx2[0].overrideSingleItemScale)) {
        input4.disabled = input4_disabled_value;
      }
      if (dirty & /*pileData*/
      1 && to_number(input4.value) !== /*pileData*/
      ctx2[0].singleItemScale) {
        set_input_value(
          input4,
          /*pileData*/
          ctx2[0].singleItemScale
        );
      }
      if (dirty & /*pileData*/
      1) {
        toggle_class(div3, "item-piles-disabled", !/*pileData*/
        ctx2[0].overrideSingleItemScale);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(div4);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$q, "create_fragment$q");
function instance$n($$self, $$props, $$invalidate) {
  let { pileData } = $$props;
  function input0_change_handler() {
    pileData.displayOne = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_change_handler() {
    pileData.showItemName = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input1_change_handler, "input1_change_handler");
  function input2_change_handler() {
    pileData.overrideSingleItemScale = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_input_handler() {
    pileData.singleItemScale = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input3_change_input_handler, "input3_change_input_handler");
  function input4_input_handler() {
    pileData.singleItemScale = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input4_input_handler, "input4_input_handler");
  $$self.$$set = ($$props2) => {
    if ("pileData" in $$props2)
      $$invalidate(0, pileData = $$props2.pileData);
  };
  return [
    pileData,
    input0_change_handler,
    input1_change_handler,
    input2_change_handler,
    input3_change_input_handler,
    input4_input_handler
  ];
}
__name(instance$n, "instance$n");
const _Itempile = class _Itempile extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$n, create_fragment$q, safe_not_equal, { pileData: 0 });
  }
};
__name(_Itempile, "Itempile");
let Itempile = _Itempile;
function create_fragment$p(ctx) {
  let div0;
  let label0;
  let t1;
  let input0;
  let t2;
  let div1;
  let label1;
  let t4;
  let input1;
  let t5;
  let div3;
  let label2;
  let t7;
  let div2;
  let filepicker0;
  let updating_value;
  let t8;
  let div5;
  let label3;
  let t10;
  let div4;
  let filepicker1;
  let updating_value_1;
  let t11;
  let div7;
  let label4;
  let t13;
  let div6;
  let filepicker2;
  let updating_value_2;
  let t14;
  let div9;
  let label5;
  let t16;
  let div8;
  let filepicker3;
  let updating_value_3;
  let t17;
  let div11;
  let label6;
  let t19;
  let div10;
  let filepicker4;
  let updating_value_4;
  let t20;
  let div13;
  let label7;
  let t22;
  let div12;
  let filepicker5;
  let updating_value_5;
  let t23;
  let div15;
  let label8;
  let t25;
  let div14;
  let filepicker6;
  let updating_value_6;
  let current;
  let mounted;
  let dispose;
  function filepicker0_value_binding(value) {
    ctx[3](value);
  }
  __name(filepicker0_value_binding, "filepicker0_value_binding");
  let filepicker0_props = {
    placeholder: "path/image.png",
    type: "imagevideo"
  };
  if (
    /*pileData*/
    ctx[0].closedImage !== void 0
  ) {
    filepicker0_props.value = /*pileData*/
    ctx[0].closedImage;
  }
  filepicker0 = new FilePicker_1({ props: filepicker0_props });
  binding_callbacks.push(() => bind(filepicker0, "value", filepicker0_value_binding));
  function filepicker1_value_binding(value) {
    ctx[4](value);
  }
  __name(filepicker1_value_binding, "filepicker1_value_binding");
  let filepicker1_props = {
    placeholder: "path/image.png",
    type: "imagevideo"
  };
  if (
    /*pileData*/
    ctx[0].openedImage !== void 0
  ) {
    filepicker1_props.value = /*pileData*/
    ctx[0].openedImage;
  }
  filepicker1 = new FilePicker_1({ props: filepicker1_props });
  binding_callbacks.push(() => bind(filepicker1, "value", filepicker1_value_binding));
  function filepicker2_value_binding(value) {
    ctx[5](value);
  }
  __name(filepicker2_value_binding, "filepicker2_value_binding");
  let filepicker2_props = {
    placeholder: "path/image.png",
    type: "imagevideo"
  };
  if (
    /*pileData*/
    ctx[0].emptyImage !== void 0
  ) {
    filepicker2_props.value = /*pileData*/
    ctx[0].emptyImage;
  }
  filepicker2 = new FilePicker_1({ props: filepicker2_props });
  binding_callbacks.push(() => bind(filepicker2, "value", filepicker2_value_binding));
  function filepicker3_value_binding(value) {
    ctx[6](value);
  }
  __name(filepicker3_value_binding, "filepicker3_value_binding");
  let filepicker3_props = {
    placeholder: "path/image.png",
    type: "imagevideo"
  };
  if (
    /*pileData*/
    ctx[0].lockedImage !== void 0
  ) {
    filepicker3_props.value = /*pileData*/
    ctx[0].lockedImage;
  }
  filepicker3 = new FilePicker_1({ props: filepicker3_props });
  binding_callbacks.push(() => bind(filepicker3, "value", filepicker3_value_binding));
  function filepicker4_value_binding(value) {
    ctx[7](value);
  }
  __name(filepicker4_value_binding, "filepicker4_value_binding");
  let filepicker4_props = {
    placeholder: "path/sound.wav",
    type: "audio"
  };
  if (
    /*pileData*/
    ctx[0].closeSound !== void 0
  ) {
    filepicker4_props.value = /*pileData*/
    ctx[0].closeSound;
  }
  filepicker4 = new FilePicker_1({ props: filepicker4_props });
  binding_callbacks.push(() => bind(filepicker4, "value", filepicker4_value_binding));
  function filepicker5_value_binding(value) {
    ctx[8](value);
  }
  __name(filepicker5_value_binding, "filepicker5_value_binding");
  let filepicker5_props = {
    placeholder: "path/sound.wav",
    type: "audio"
  };
  if (
    /*pileData*/
    ctx[0].openSound !== void 0
  ) {
    filepicker5_props.value = /*pileData*/
    ctx[0].openSound;
  }
  filepicker5 = new FilePicker_1({ props: filepicker5_props });
  binding_callbacks.push(() => bind(filepicker5, "value", filepicker5_value_binding));
  function filepicker6_value_binding(value) {
    ctx[9](value);
  }
  __name(filepicker6_value_binding, "filepicker6_value_binding");
  let filepicker6_props = {
    placeholder: "path/sound.wav",
    type: "audio"
  };
  if (
    /*pileData*/
    ctx[0].lockedSound !== void 0
  ) {
    filepicker6_props.value = /*pileData*/
    ctx[0].lockedSound;
  }
  filepicker6 = new FilePicker_1({ props: filepicker6_props });
  binding_callbacks.push(() => bind(filepicker6, "value", filepicker6_value_binding));
  return {
    c() {
      div0 = element("div");
      label0 = element("label");
      label0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.Closed")}`;
      t1 = space();
      input0 = element("input");
      t2 = space();
      div1 = element("div");
      label1 = element("label");
      label1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.Locked")}`;
      t4 = space();
      input1 = element("input");
      t5 = space();
      div3 = element("div");
      label2 = element("label");
      label2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.ClosedImagePath")}`;
      t7 = space();
      div2 = element("div");
      create_component(filepicker0.$$.fragment);
      t8 = space();
      div5 = element("div");
      label3 = element("label");
      label3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.OpenedImagePath")}`;
      t10 = space();
      div4 = element("div");
      create_component(filepicker1.$$.fragment);
      t11 = space();
      div7 = element("div");
      label4 = element("label");
      label4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.EmptyImagePath")}`;
      t13 = space();
      div6 = element("div");
      create_component(filepicker2.$$.fragment);
      t14 = space();
      div9 = element("div");
      label5 = element("label");
      label5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.LockedImagePath")}`;
      t16 = space();
      div8 = element("div");
      create_component(filepicker3.$$.fragment);
      t17 = space();
      div11 = element("div");
      label6 = element("label");
      label6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.CloseSoundPath")}`;
      t19 = space();
      div10 = element("div");
      create_component(filepicker4.$$.fragment);
      t20 = space();
      div13 = element("div");
      label7 = element("label");
      label7.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.OpenSoundPath")}`;
      t22 = space();
      div12 = element("div");
      create_component(filepicker5.$$.fragment);
      t23 = space();
      div15 = element("div");
      label8 = element("label");
      label8.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Container.LockedSoundPath")}`;
      t25 = space();
      div14 = element("div");
      create_component(filepicker6.$$.fragment);
      attr(input0, "type", "checkbox");
      attr(div0, "class", "form-group");
      attr(input1, "type", "checkbox");
      attr(div1, "class", "form-group");
      attr(div2, "class", "form-fields");
      attr(div3, "class", "form-group");
      attr(div4, "class", "form-fields");
      attr(div5, "class", "form-group");
      attr(div6, "class", "form-fields");
      attr(div7, "class", "form-group");
      attr(div8, "class", "form-fields");
      attr(div9, "class", "form-group");
      attr(div10, "class", "form-fields");
      attr(div11, "class", "form-group");
      attr(div12, "class", "form-fields");
      attr(div13, "class", "form-group");
      attr(div14, "class", "form-fields");
      attr(div15, "class", "form-group");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, label0);
      append(div0, t1);
      append(div0, input0);
      input0.checked = /*pileData*/
      ctx[0].closed;
      insert(target, t2, anchor);
      insert(target, div1, anchor);
      append(div1, label1);
      append(div1, t4);
      append(div1, input1);
      input1.checked = /*pileData*/
      ctx[0].locked;
      insert(target, t5, anchor);
      insert(target, div3, anchor);
      append(div3, label2);
      append(div3, t7);
      append(div3, div2);
      mount_component(filepicker0, div2, null);
      insert(target, t8, anchor);
      insert(target, div5, anchor);
      append(div5, label3);
      append(div5, t10);
      append(div5, div4);
      mount_component(filepicker1, div4, null);
      insert(target, t11, anchor);
      insert(target, div7, anchor);
      append(div7, label4);
      append(div7, t13);
      append(div7, div6);
      mount_component(filepicker2, div6, null);
      insert(target, t14, anchor);
      insert(target, div9, anchor);
      append(div9, label5);
      append(div9, t16);
      append(div9, div8);
      mount_component(filepicker3, div8, null);
      insert(target, t17, anchor);
      insert(target, div11, anchor);
      append(div11, label6);
      append(div11, t19);
      append(div11, div10);
      mount_component(filepicker4, div10, null);
      insert(target, t20, anchor);
      insert(target, div13, anchor);
      append(div13, label7);
      append(div13, t22);
      append(div13, div12);
      mount_component(filepicker5, div12, null);
      insert(target, t23, anchor);
      insert(target, div15, anchor);
      append(div15, label8);
      append(div15, t25);
      append(div15, div14);
      mount_component(filepicker6, div14, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler*/
            ctx[1]
          ),
          listen(
            input1,
            "change",
            /*input1_change_handler*/
            ctx[2]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*pileData*/
      1) {
        input0.checked = /*pileData*/
        ctx2[0].closed;
      }
      if (dirty & /*pileData*/
      1) {
        input1.checked = /*pileData*/
        ctx2[0].locked;
      }
      const filepicker0_changes = {};
      if (!updating_value && dirty & /*pileData*/
      1) {
        updating_value = true;
        filepicker0_changes.value = /*pileData*/
        ctx2[0].closedImage;
        add_flush_callback(() => updating_value = false);
      }
      filepicker0.$set(filepicker0_changes);
      const filepicker1_changes = {};
      if (!updating_value_1 && dirty & /*pileData*/
      1) {
        updating_value_1 = true;
        filepicker1_changes.value = /*pileData*/
        ctx2[0].openedImage;
        add_flush_callback(() => updating_value_1 = false);
      }
      filepicker1.$set(filepicker1_changes);
      const filepicker2_changes = {};
      if (!updating_value_2 && dirty & /*pileData*/
      1) {
        updating_value_2 = true;
        filepicker2_changes.value = /*pileData*/
        ctx2[0].emptyImage;
        add_flush_callback(() => updating_value_2 = false);
      }
      filepicker2.$set(filepicker2_changes);
      const filepicker3_changes = {};
      if (!updating_value_3 && dirty & /*pileData*/
      1) {
        updating_value_3 = true;
        filepicker3_changes.value = /*pileData*/
        ctx2[0].lockedImage;
        add_flush_callback(() => updating_value_3 = false);
      }
      filepicker3.$set(filepicker3_changes);
      const filepicker4_changes = {};
      if (!updating_value_4 && dirty & /*pileData*/
      1) {
        updating_value_4 = true;
        filepicker4_changes.value = /*pileData*/
        ctx2[0].closeSound;
        add_flush_callback(() => updating_value_4 = false);
      }
      filepicker4.$set(filepicker4_changes);
      const filepicker5_changes = {};
      if (!updating_value_5 && dirty & /*pileData*/
      1) {
        updating_value_5 = true;
        filepicker5_changes.value = /*pileData*/
        ctx2[0].openSound;
        add_flush_callback(() => updating_value_5 = false);
      }
      filepicker5.$set(filepicker5_changes);
      const filepicker6_changes = {};
      if (!updating_value_6 && dirty & /*pileData*/
      1) {
        updating_value_6 = true;
        filepicker6_changes.value = /*pileData*/
        ctx2[0].lockedSound;
        add_flush_callback(() => updating_value_6 = false);
      }
      filepicker6.$set(filepicker6_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(filepicker0.$$.fragment, local);
      transition_in(filepicker1.$$.fragment, local);
      transition_in(filepicker2.$$.fragment, local);
      transition_in(filepicker3.$$.fragment, local);
      transition_in(filepicker4.$$.fragment, local);
      transition_in(filepicker5.$$.fragment, local);
      transition_in(filepicker6.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filepicker0.$$.fragment, local);
      transition_out(filepicker1.$$.fragment, local);
      transition_out(filepicker2.$$.fragment, local);
      transition_out(filepicker3.$$.fragment, local);
      transition_out(filepicker4.$$.fragment, local);
      transition_out(filepicker5.$$.fragment, local);
      transition_out(filepicker6.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t2);
      if (detaching)
        detach(div1);
      if (detaching)
        detach(t5);
      if (detaching)
        detach(div3);
      destroy_component(filepicker0);
      if (detaching)
        detach(t8);
      if (detaching)
        detach(div5);
      destroy_component(filepicker1);
      if (detaching)
        detach(t11);
      if (detaching)
        detach(div7);
      destroy_component(filepicker2);
      if (detaching)
        detach(t14);
      if (detaching)
        detach(div9);
      destroy_component(filepicker3);
      if (detaching)
        detach(t17);
      if (detaching)
        detach(div11);
      destroy_component(filepicker4);
      if (detaching)
        detach(t20);
      if (detaching)
        detach(div13);
      destroy_component(filepicker5);
      if (detaching)
        detach(t23);
      if (detaching)
        detach(div15);
      destroy_component(filepicker6);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$p, "create_fragment$p");
function instance$m($$self, $$props, $$invalidate) {
  let { pileData } = $$props;
  function input0_change_handler() {
    pileData.closed = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_change_handler() {
    pileData.locked = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input1_change_handler, "input1_change_handler");
  function filepicker0_value_binding(value) {
    if ($$self.$$.not_equal(pileData.closedImage, value)) {
      pileData.closedImage = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker0_value_binding, "filepicker0_value_binding");
  function filepicker1_value_binding(value) {
    if ($$self.$$.not_equal(pileData.openedImage, value)) {
      pileData.openedImage = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker1_value_binding, "filepicker1_value_binding");
  function filepicker2_value_binding(value) {
    if ($$self.$$.not_equal(pileData.emptyImage, value)) {
      pileData.emptyImage = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker2_value_binding, "filepicker2_value_binding");
  function filepicker3_value_binding(value) {
    if ($$self.$$.not_equal(pileData.lockedImage, value)) {
      pileData.lockedImage = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker3_value_binding, "filepicker3_value_binding");
  function filepicker4_value_binding(value) {
    if ($$self.$$.not_equal(pileData.closeSound, value)) {
      pileData.closeSound = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker4_value_binding, "filepicker4_value_binding");
  function filepicker5_value_binding(value) {
    if ($$self.$$.not_equal(pileData.openSound, value)) {
      pileData.openSound = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker5_value_binding, "filepicker5_value_binding");
  function filepicker6_value_binding(value) {
    if ($$self.$$.not_equal(pileData.lockedSound, value)) {
      pileData.lockedSound = value;
      $$invalidate(0, pileData);
    }
  }
  __name(filepicker6_value_binding, "filepicker6_value_binding");
  $$self.$$set = ($$props2) => {
    if ("pileData" in $$props2)
      $$invalidate(0, pileData = $$props2.pileData);
  };
  return [
    pileData,
    input0_change_handler,
    input1_change_handler,
    filepicker0_value_binding,
    filepicker1_value_binding,
    filepicker2_value_binding,
    filepicker3_value_binding,
    filepicker4_value_binding,
    filepicker5_value_binding,
    filepicker6_value_binding
  ];
}
__name(instance$m, "instance$m");
const _Container = class _Container extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$m, create_fragment$p, safe_not_equal, { pileData: 0 });
  }
};
__name(_Container, "Container");
let Container = _Container;
function create_fragment$o(ctx) {
  let details;
  let summary;
  let t1;
  let div0;
  let label0;
  let span0;
  let t3;
  let p0;
  let t5;
  let input0;
  let t6;
  let div1;
  let label1;
  let span1;
  let t8;
  let p1;
  let t10;
  let input1;
  let t11;
  let div2;
  let label2;
  let span2;
  let t13;
  let p2;
  let t15;
  let input2;
  let t16;
  let div3;
  let label3;
  let span3;
  let t18;
  let p3;
  let t20;
  let input3;
  let t21;
  let div4;
  let label4;
  let span4;
  let t23;
  let p4;
  let t25;
  let input4;
  let t26;
  let div5;
  let label5;
  let span5;
  let t28;
  let p5;
  let t30;
  let div6;
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      details = element("details");
      summary = element("summary");
      summary.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.Title")}`;
      t1 = space();
      div0 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.ShareItemsEnabled")}`;
      t3 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.ShareItemsEnabledExplanation")}`;
      t5 = space();
      input0 = element("input");
      t6 = space();
      div1 = element("div");
      label1 = element("label");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.ShareCurrenciesEnabled")}`;
      t8 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.ShareCurrenciesEnabledExplanation")}`;
      t10 = space();
      input1 = element("input");
      t11 = space();
      div2 = element("div");
      label2 = element("label");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.TakeAllEnabled")}`;
      t13 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.TakeAllEnabledExplanation")}`;
      t15 = space();
      input2 = element("input");
      t16 = space();
      div3 = element("div");
      label3 = element("label");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.SplitAllEnabled")}`;
      t18 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.SplitAllEnabledExplanation")}`;
      t20 = space();
      input3 = element("input");
      t21 = space();
      div4 = element("div");
      label4 = element("label");
      span4 = element("span");
      span4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.InactivePlayers")}`;
      t23 = space();
      p4 = element("p");
      p4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.InactivePlayersExplanation")}`;
      t25 = space();
      input4 = element("input");
      t26 = space();
      div5 = element("div");
      label5 = element("label");
      span5 = element("span");
      span5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.ResetSharingData")}`;
      t28 = space();
      p5 = element("p");
      p5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.ResetSharingDataExplanation")}`;
      t30 = space();
      div6 = element("div");
      button = element("button");
      button.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Sharing.ResetSharingData")}`;
      attr(input0, "type", "checkbox");
      attr(div0, "class", "form-group");
      attr(input1, "type", "checkbox");
      attr(div1, "class", "form-group");
      attr(input2, "type", "checkbox");
      attr(div2, "class", "form-group");
      attr(input3, "type", "checkbox");
      attr(div3, "class", "form-group");
      attr(input4, "type", "checkbox");
      attr(div4, "class", "form-group");
      set_style(label5, "flex", "4");
      attr(div5, "class", "form-group");
      attr(button, "class", "item-piles-config-reset-sharing-data");
      set_style(button, "flex", "4");
      attr(button, "type", "button");
      attr(div6, "class", "form-group");
      attr(details, "class", "item-piles-collapsible item-piles-clickable");
    },
    m(target, anchor) {
      insert(target, details, anchor);
      append(details, summary);
      append(details, t1);
      append(details, div0);
      append(div0, label0);
      append(label0, span0);
      append(label0, t3);
      append(label0, p0);
      append(div0, t5);
      append(div0, input0);
      input0.checked = /*pileData*/
      ctx[0].shareItemsEnabled;
      append(details, t6);
      append(details, div1);
      append(div1, label1);
      append(label1, span1);
      append(label1, t8);
      append(label1, p1);
      append(div1, t10);
      append(div1, input1);
      input1.checked = /*pileData*/
      ctx[0].shareCurrenciesEnabled;
      append(details, t11);
      append(details, div2);
      append(div2, label2);
      append(label2, span2);
      append(label2, t13);
      append(label2, p2);
      append(div2, t15);
      append(div2, input2);
      input2.checked = /*pileData*/
      ctx[0].takeAllEnabled;
      append(details, t16);
      append(details, div3);
      append(div3, label3);
      append(label3, span3);
      append(label3, t18);
      append(label3, p3);
      append(div3, t20);
      append(div3, input3);
      input3.checked = /*pileData*/
      ctx[0].splitAllEnabled;
      append(details, t21);
      append(details, div4);
      append(div4, label4);
      append(label4, span4);
      append(label4, t23);
      append(label4, p4);
      append(div4, t25);
      append(div4, input4);
      input4.checked = /*pileData*/
      ctx[0].activePlayers;
      append(details, t26);
      append(details, div5);
      append(div5, label5);
      append(label5, span5);
      append(label5, t28);
      append(label5, p5);
      append(details, t30);
      append(details, div6);
      append(div6, button);
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "change",
            /*input0_change_handler*/
            ctx[3]
          ),
          listen(
            input1,
            "change",
            /*input1_change_handler*/
            ctx[4]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler*/
            ctx[5]
          ),
          listen(
            input3,
            "change",
            /*input3_change_handler*/
            ctx[6]
          ),
          listen(
            input4,
            "change",
            /*input4_change_handler*/
            ctx[7]
          ),
          listen(
            button,
            "click",
            /*click_handler*/
            ctx[8]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*pileData*/
      1) {
        input0.checked = /*pileData*/
        ctx2[0].shareItemsEnabled;
      }
      if (dirty & /*pileData*/
      1) {
        input1.checked = /*pileData*/
        ctx2[0].shareCurrenciesEnabled;
      }
      if (dirty & /*pileData*/
      1) {
        input2.checked = /*pileData*/
        ctx2[0].takeAllEnabled;
      }
      if (dirty & /*pileData*/
      1) {
        input3.checked = /*pileData*/
        ctx2[0].splitAllEnabled;
      }
      if (dirty & /*pileData*/
      1) {
        input4.checked = /*pileData*/
        ctx2[0].activePlayers;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(details);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$o, "create_fragment$o");
function instance$l($$self, $$props, $$invalidate) {
  let { pileData } = $$props;
  let { pileActor } = $$props;
  async function resetSharingData() {
    const doThing = await TJSDialog.confirm({
      id: `sharing-dialog-item-pile-config-${pileActor.id}`,
      title: "Item Piles - " + game.i18n.localize("ITEM-PILES.Dialogs.ResetSharingData.Title"),
      content: {
        class: CustomDialog,
        props: {
          header: game.i18n.localize("ITEM-PILES.Dialogs.ResetSharingData.Title"),
          content: game.i18n.localize("ITEM-PILES.Dialogs.ResetSharingData.Content")
        }
      },
      buttons: {
        yes: {
          icon: '<i class="fas fa-check"></i>',
          label: game.i18n.localize("ITEM-PILES.Dialogs.ResetSharingData.Confirm")
        }
      },
      modal: true
    });
    if (!doThing)
      return;
    return clearItemPileSharingData(pileActor);
  }
  __name(resetSharingData, "resetSharingData");
  function input0_change_handler() {
    pileData.shareItemsEnabled = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_change_handler() {
    pileData.shareCurrenciesEnabled = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input1_change_handler, "input1_change_handler");
  function input2_change_handler() {
    pileData.takeAllEnabled = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler() {
    pileData.splitAllEnabled = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input3_change_handler, "input3_change_handler");
  function input4_change_handler() {
    pileData.activePlayers = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input4_change_handler, "input4_change_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    resetSharingData();
  }, "click_handler");
  $$self.$$set = ($$props2) => {
    if ("pileData" in $$props2)
      $$invalidate(0, pileData = $$props2.pileData);
    if ("pileActor" in $$props2)
      $$invalidate(2, pileActor = $$props2.pileActor);
  };
  return [
    pileData,
    resetSharingData,
    pileActor,
    input0_change_handler,
    input1_change_handler,
    input2_change_handler,
    input3_change_handler,
    input4_change_handler,
    click_handler
  ];
}
__name(instance$l, "instance$l");
const _Sharing = class _Sharing extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$l, create_fragment$o, safe_not_equal, { pileData: 0, pileActor: 2 });
  }
};
__name(_Sharing, "Sharing");
let Sharing = _Sharing;
const vaultAccessEditorShell_svelte_svelte_type_style_lang = "";
function get_each_context$a(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[27] = list[i];
  child_ctx[28] = list;
  child_ctx[29] = i;
  return child_ctx;
}
__name(get_each_context$a, "get_each_context$a");
function get_each_context_1$5(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[30] = list[i];
  return child_ctx;
}
__name(get_each_context_1$5, "get_each_context_1$5");
function create_if_block$e(ctx) {
  let option;
  let t_value = (
    /*document*/
    ctx[30].document.name + ""
  );
  let t;
  return {
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = /*document*/
      ctx[30].uuid;
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_if_block$e, "create_if_block$e");
function create_each_block_1$5(key_1, ctx) {
  let first;
  let show_if = (
    /*access*/
    ctx[27].uuid === /*document*/
    ctx[30].uuid || /*validUuids*/
    ctx[4].has(
      /*document*/
      ctx[30].uuid
    )
  );
  let if_block_anchor;
  let if_block = show_if && create_if_block$e(ctx);
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*$vaultAccessStore, validUuids*/
      20)
        show_if = /*access*/
        ctx[27].uuid === /*document*/
        ctx[30].uuid || /*validUuids*/
        ctx[4].has(
          /*document*/
          ctx[30].uuid
        );
      if (show_if) {
        if (if_block) {
          if_block.p(ctx, dirty);
        } else {
          if_block = create_if_block$e(ctx);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(first);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block_1$5, "create_each_block_1$5");
function create_each_block$a(key_1, ctx) {
  let div5;
  let div0;
  let select;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t0;
  let div1;
  let input0;
  let t1;
  let div2;
  let input1;
  let t2;
  let div3;
  let input2;
  let t3;
  let input3;
  let t4;
  let div4;
  let input4;
  let t5;
  let input5;
  let t6;
  let a;
  let t7;
  let mounted;
  let dispose;
  let each_value_1 = (
    /*validDocs*/
    ctx[7]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*document*/
    ctx2[30].uuid
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1$5(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1$5(key, child_ctx));
  }
  function select_change_handler() {
    ctx[14].call(
      select,
      /*each_value*/
      ctx[28],
      /*index*/
      ctx[29]
    );
  }
  __name(select_change_handler, "select_change_handler");
  function input0_change_handler() {
    ctx[15].call(
      input0,
      /*each_value*/
      ctx[28],
      /*index*/
      ctx[29]
    );
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_change_handler() {
    ctx[16].call(
      input1,
      /*each_value*/
      ctx[28],
      /*index*/
      ctx[29]
    );
  }
  __name(input1_change_handler, "input1_change_handler");
  function input2_change_handler() {
    ctx[17].call(
      input2,
      /*each_value*/
      ctx[28],
      /*index*/
      ctx[29]
    );
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler() {
    ctx[18].call(
      input3,
      /*each_value*/
      ctx[28],
      /*index*/
      ctx[29]
    );
  }
  __name(input3_change_handler, "input3_change_handler");
  function input4_change_handler() {
    ctx[19].call(
      input4,
      /*each_value*/
      ctx[28],
      /*index*/
      ctx[29]
    );
  }
  __name(input4_change_handler, "input4_change_handler");
  function input5_change_handler() {
    ctx[20].call(
      input5,
      /*each_value*/
      ctx[28],
      /*index*/
      ctx[29]
    );
  }
  __name(input5_change_handler, "input5_change_handler");
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[21](
        /*index*/
        ctx[29]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    key: key_1,
    first: null,
    c() {
      div5 = element("div");
      div0 = element("div");
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t0 = space();
      div1 = element("div");
      input0 = element("input");
      t1 = space();
      div2 = element("div");
      input1 = element("input");
      t2 = space();
      div3 = element("div");
      input2 = element("input");
      t3 = space();
      input3 = element("input");
      t4 = space();
      div4 = element("div");
      input4 = element("input");
      t5 = space();
      input5 = element("input");
      t6 = space();
      a = element("a");
      a.innerHTML = `<i class="fas fa-times"></i>`;
      t7 = space();
      attr(select, "class", "svelte-ewjfl4");
      if (
        /*access*/
        ctx[27].uuid === void 0
      )
        add_render_callback(select_change_handler);
      attr(div0, "class", "svelte-ewjfl4");
      attr(input0, "type", "checkbox");
      set_style(div1, "text-align", "center");
      attr(div1, "class", "svelte-ewjfl4");
      attr(input1, "type", "checkbox");
      set_style(div2, "text-align", "center");
      attr(div2, "class", "svelte-ewjfl4");
      attr(input2, "type", "checkbox");
      attr(input3, "type", "checkbox");
      set_style(div3, "text-align", "center");
      attr(div3, "class", "svelte-ewjfl4");
      attr(input4, "type", "checkbox");
      attr(input5, "type", "checkbox");
      set_style(div4, "text-align", "center");
      attr(div4, "class", "svelte-ewjfl4");
      attr(a, "class", "item-piles-clickable-red");
      set_style(a, "margin-right", "0.5rem");
      attr(div5, "class", "item-piles-grid-row-wrapper svelte-ewjfl4");
      this.first = div5;
    },
    m(target, anchor) {
      insert(target, div5, anchor);
      append(div5, div0);
      append(div0, select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*access*/
        ctx[27].uuid,
        true
      );
      append(div5, t0);
      append(div5, div1);
      append(div1, input0);
      input0.checked = /*access*/
      ctx[27].view;
      append(div5, t1);
      append(div5, div2);
      append(div2, input1);
      input1.checked = /*access*/
      ctx[27].organize;
      append(div5, t2);
      append(div5, div3);
      append(div3, input2);
      input2.checked = /*access*/
      ctx[27].items.withdraw;
      append(div3, t3);
      append(div3, input3);
      input3.checked = /*access*/
      ctx[27].items.deposit;
      append(div5, t4);
      append(div5, div4);
      append(div4, input4);
      input4.checked = /*access*/
      ctx[27].currencies.withdraw;
      append(div4, t5);
      append(div4, input5);
      input5.checked = /*access*/
      ctx[27].currencies.deposit;
      append(div5, t6);
      append(div5, a);
      append(div5, t7);
      if (!mounted) {
        dispose = [
          listen(select, "change", select_change_handler),
          listen(input0, "change", input0_change_handler),
          listen(input1, "change", input1_change_handler),
          listen(input2, "change", input2_change_handler),
          listen(input3, "change", input3_change_handler),
          listen(input4, "change", input4_change_handler),
          listen(input5, "change", input5_change_handler),
          listen(a, "click", click_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty[0] & /*validDocs, $vaultAccessStore, validUuids*/
      148) {
        each_value_1 = /*validDocs*/
        ctx[7];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_1, each_1_lookup, select, destroy_block, create_each_block_1$5, null, get_each_context_1$5);
      }
      if (dirty[0] & /*$vaultAccessStore, validDocs*/
      132) {
        select_option(
          select,
          /*access*/
          ctx[27].uuid
        );
      }
      if (dirty[0] & /*$vaultAccessStore, validDocs*/
      132) {
        input0.checked = /*access*/
        ctx[27].view;
      }
      if (dirty[0] & /*$vaultAccessStore, validDocs*/
      132) {
        input1.checked = /*access*/
        ctx[27].organize;
      }
      if (dirty[0] & /*$vaultAccessStore, validDocs*/
      132) {
        input2.checked = /*access*/
        ctx[27].items.withdraw;
      }
      if (dirty[0] & /*$vaultAccessStore, validDocs*/
      132) {
        input3.checked = /*access*/
        ctx[27].items.deposit;
      }
      if (dirty[0] & /*$vaultAccessStore, validDocs*/
      132) {
        input4.checked = /*access*/
        ctx[27].currencies.withdraw;
      }
      if (dirty[0] & /*$vaultAccessStore, validDocs*/
      132) {
        input5.checked = /*access*/
        ctx[27].currencies.deposit;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div5);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$a, "create_each_block$a");
function create_default_slot$a(ctx) {
  let form_1;
  let p;
  let t1;
  let div8;
  let div7;
  let div0;
  let span0;
  let t3;
  let div1;
  let span1;
  let t5;
  let div2;
  let span2;
  let t7;
  let div4;
  let span3;
  let t9;
  let div3;
  let i0;
  let t11;
  let i1;
  let t13;
  let div6;
  let span4;
  let t15;
  let div5;
  let i2;
  let t17;
  let i3;
  let t19;
  let a;
  let t20;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t21;
  let footer;
  let button0;
  let i5;
  let t22;
  let t23_value = localize("Save") + "";
  let t23;
  let t24;
  let button1;
  let i6;
  let t25;
  let t26_value = localize("Cancel") + "";
  let t26;
  let mounted;
  let dispose;
  let each_value = (
    /*$vaultAccessStore*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*access*/
    ctx2[27].uuid
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$a(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$a(key, child_ctx));
  }
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.Explanation")}`;
      t1 = space();
      div8 = element("div");
      div7 = element("div");
      div0 = element("div");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.Character")}`;
      t3 = space();
      div1 = element("div");
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.View")}`;
      t5 = space();
      div2 = element("div");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.Organize")}`;
      t7 = space();
      div4 = element("div");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Items")}`;
      t9 = space();
      div3 = element("div");
      i0 = element("i");
      i0.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.Withdraw")}`;
      t11 = text(" |\r\n						");
      i1 = element("i");
      i1.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.Deposit")}`;
      t13 = space();
      div6 = element("div");
      span4 = element("span");
      span4.textContent = `${localize("ITEM-PILES.Currencies")}`;
      t15 = space();
      div5 = element("div");
      i2 = element("i");
      i2.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.Withdraw")}`;
      t17 = text(" |\r\n						");
      i3 = element("i");
      i3.textContent = `${localize("ITEM-PILES.Applications.VaultAccessEditor.Deposit")}`;
      t19 = space();
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus"></i>`;
      t20 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t21 = space();
      footer = element("footer");
      button0 = element("button");
      i5 = element("i");
      t22 = space();
      t23 = text(t23_value);
      t24 = space();
      button1 = element("button");
      i6 = element("i");
      t25 = space();
      t26 = text(t26_value);
      set_style(p, "text-align", "center");
      set_style(div0, "text-align", "left");
      attr(div0, "class", "svelte-ewjfl4");
      attr(div1, "class", "item-piles-flexcol svelte-ewjfl4");
      attr(div2, "class", "item-piles-flexcol svelte-ewjfl4");
      attr(div3, "class", "svelte-ewjfl4");
      attr(div4, "class", "item-piles-flexcol svelte-ewjfl4");
      attr(div5, "class", "svelte-ewjfl4");
      attr(div6, "class", "item-piles-flexcol svelte-ewjfl4");
      set_style(a, "margin-right", "0.5rem");
      attr(div7, "class", "item-piles-grid-row-wrapper svelte-ewjfl4");
      attr(div8, "class", "form-group item-pile-access-grid svelte-ewjfl4");
      attr(i5, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i6, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(footer, "class", "item-piles-top-divider");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(form_1, t1);
      append(form_1, div8);
      append(div8, div7);
      append(div7, div0);
      append(div0, span0);
      append(div7, t3);
      append(div7, div1);
      append(div1, span1);
      append(div7, t5);
      append(div7, div2);
      append(div2, span2);
      append(div7, t7);
      append(div7, div4);
      append(div4, span3);
      append(div4, t9);
      append(div4, div3);
      append(div3, i0);
      append(div3, t11);
      append(div3, i1);
      append(div7, t13);
      append(div7, div6);
      append(div6, span4);
      append(div6, t15);
      append(div6, div5);
      append(div5, i2);
      append(div5, t17);
      append(div5, i3);
      append(div7, t19);
      append(div7, a);
      append(div8, t20);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div8, null);
        }
      }
      append(form_1, t21);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i5);
      append(button0, t22);
      append(button0, t23);
      append(footer, t24);
      append(footer, button1);
      append(button1, i6);
      append(button1, t25);
      append(button1, t26);
      ctx[23](form_1);
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*click_handler*/
            ctx[13]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler_2*/
            ctx[22],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[10]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*removeAccess, $vaultAccessStore, validDocs, validUuids*/
      660) {
        each_value = /*$vaultAccessStore*/
        ctx2[2];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div8, destroy_block, create_each_block$a, null, get_each_context$a);
      }
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[23](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$a, "create_default_slot$a");
function create_fragment$n(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[24](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$a] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*form, $vaultAccessStore, validUuids*/
      28 | dirty[1] & /*$$scope*/
      4) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$n, "create_fragment$n");
function instance$k($$self, $$props, $$invalidate) {
  let validDocuments;
  let validUuids;
  let $vaultAccessStore;
  const { application } = getContext("#external");
  let form;
  let { data: data2 } = $$props;
  let { elementRoot } = $$props;
  const vaultAccessStore = writable$1(data2.map((access) => {
    return foundry.utils.mergeObject(
      {
        view: true,
        organize: true,
        items: { withdraw: true, deposit: true },
        currencies: { withdraw: true, deposit: true }
      },
      access
    );
  }));
  component_subscribe($$self, vaultAccessStore, (value) => $$invalidate(2, $vaultAccessStore = value));
  const validUsers = Array.from(game.users).filter((user) => !user.isGM);
  const validActors = Array.from(game.actors).filter((actor) => actor.hasPlayerOwner);
  const validDocs = validUsers.concat(validActors).map((document2) => ({ uuid: document2.uuid, document: document2 }));
  function addAccess() {
    if (!validDocuments.length)
      return;
    vaultAccessStore.update((value) => {
      value.push({
        uuid: validDocuments[0].uuid,
        document: validDocuments[0].document,
        view: true,
        organize: true,
        items: { withdraw: true, deposit: true },
        currencies: { withdraw: true, deposit: true }
      });
      return value;
    });
  }
  __name(addAccess, "addAccess");
  function removeAccess(index2) {
    vaultAccessStore.update((value) => {
      value.splice(index2, 1);
      return value;
    });
  }
  __name(removeAccess, "removeAccess");
  async function updateSettings() {
    application.options.resolve?.(get_store_value(vaultAccessStore).map((access) => {
      delete access.document;
      return access;
    }));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  const click_handler = /* @__PURE__ */ __name(() => addAccess(), "click_handler");
  function select_change_handler(each_value, index2) {
    each_value[index2].uuid = select_value(this);
    vaultAccessStore.set($vaultAccessStore);
    $$invalidate(7, validDocs);
  }
  __name(select_change_handler, "select_change_handler");
  function input0_change_handler(each_value, index2) {
    each_value[index2].view = this.checked;
    vaultAccessStore.set($vaultAccessStore);
    $$invalidate(7, validDocs);
  }
  __name(input0_change_handler, "input0_change_handler");
  function input1_change_handler(each_value, index2) {
    each_value[index2].organize = this.checked;
    vaultAccessStore.set($vaultAccessStore);
    $$invalidate(7, validDocs);
  }
  __name(input1_change_handler, "input1_change_handler");
  function input2_change_handler(each_value, index2) {
    each_value[index2].items.withdraw = this.checked;
    vaultAccessStore.set($vaultAccessStore);
    $$invalidate(7, validDocs);
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_change_handler(each_value, index2) {
    each_value[index2].items.deposit = this.checked;
    vaultAccessStore.set($vaultAccessStore);
    $$invalidate(7, validDocs);
  }
  __name(input3_change_handler, "input3_change_handler");
  function input4_change_handler(each_value, index2) {
    each_value[index2].currencies.withdraw = this.checked;
    vaultAccessStore.set($vaultAccessStore);
    $$invalidate(7, validDocs);
  }
  __name(input4_change_handler, "input4_change_handler");
  function input5_change_handler(each_value, index2) {
    each_value[index2].currencies.deposit = this.checked;
    vaultAccessStore.set($vaultAccessStore);
    $$invalidate(7, validDocs);
  }
  __name(input5_change_handler, "input5_change_handler");
  const click_handler_1 = /* @__PURE__ */ __name((index2) => removeAccess(index2), "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler_2");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(3, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(11, data2 = $$props2.data);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*$vaultAccessStore*/
    4) {
      $$invalidate(12, validDocuments = validDocs.filter((document2) => !$vaultAccessStore.some((access) => access.uuid === document2.uuid)));
    }
    if ($$self.$$.dirty[0] & /*validDocuments*/
    4096) {
      $$invalidate(4, validUuids = new Set(validDocuments.map((document2) => document2.uuid)));
    }
  };
  return [
    elementRoot,
    requestSubmit,
    $vaultAccessStore,
    form,
    validUuids,
    application,
    vaultAccessStore,
    validDocs,
    addAccess,
    removeAccess,
    updateSettings,
    data2,
    validDocuments,
    click_handler,
    select_change_handler,
    input0_change_handler,
    input1_change_handler,
    input2_change_handler,
    input3_change_handler,
    input4_change_handler,
    input5_change_handler,
    click_handler_1,
    click_handler_2,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$k, "instance$k");
const _Vault_access_editor_shell = class _Vault_access_editor_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$k,
      create_fragment$n,
      safe_not_equal,
      {
        data: 11,
        elementRoot: 0,
        requestSubmit: 1
      },
      null,
      [-1, -1]
    );
  }
  get data() {
    return this.$$.ctx[11];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Vault_access_editor_shell, "Vault_access_editor_shell");
let Vault_access_editor_shell = _Vault_access_editor_shell;
const _VaultAccessEditor = class _VaultAccessEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: "ITEM-PILES.Applications.VaultAccessEditor.Title",
      width: 600,
      svelte: {
        class: Vault_access_editor_shell
      }
    });
  }
};
__name(_VaultAccessEditor, "VaultAccessEditor");
let VaultAccessEditor = _VaultAccessEditor;
const vault_svelte_svelte_type_style_lang = "";
function create_fragment$m(ctx) {
  let div3;
  let label0;
  let span0;
  let t1;
  let p0;
  let t3;
  let div2;
  let div0;
  let i0;
  let t5;
  let i1;
  let t7;
  let div1;
  let input0;
  let t8;
  let span1;
  let t10;
  let input1;
  let t11;
  let div4;
  let label1;
  let span2;
  let t13;
  let p1;
  let t15;
  let input2;
  let t16;
  let div8;
  let label2;
  let span3;
  let t18;
  let p2;
  let t20;
  let div7;
  let div5;
  let i2;
  let t22;
  let i3;
  let t24;
  let div6;
  let input3;
  let input3_disabled_value;
  let t25;
  let span4;
  let t27;
  let input4;
  let input4_disabled_value;
  let t28;
  let div9;
  let label3;
  let span5;
  let t30;
  let p3;
  let t32;
  let input5;
  let t33;
  let div10;
  let label4;
  let span6;
  let t35;
  let p4;
  let t37;
  let button0;
  let t39;
  let div11;
  let label5;
  let span7;
  let t41;
  let p5;
  let t43;
  let input6;
  let t44;
  let div12;
  let label6;
  let span8;
  let t46;
  let p6;
  let t48;
  let button1;
  let t50;
  let div13;
  let label7;
  let span9;
  let t52;
  let p7;
  let t54;
  let div14;
  let select;
  let option0;
  let t55_value = localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LoggingFormatUserActor") + "";
  let t55;
  let t56;
  let option1;
  let t57_value = localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LoggingFormatUser") + "";
  let t57;
  let t58;
  let option2;
  let t59_value = localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LoggingFormatActor") + "";
  let t59;
  let mounted;
  let dispose;
  return {
    c() {
      div3 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Layout")}`;
      t1 = space();
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LayoutExplanation")}`;
      t3 = space();
      div2 = element("div");
      div0 = element("div");
      i0 = element("i");
      i0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Columns")}`;
      t5 = space();
      i1 = element("i");
      i1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Rows")}`;
      t7 = space();
      div1 = element("div");
      input0 = element("input");
      t8 = space();
      span1 = element("span");
      span1.textContent = "x";
      t10 = space();
      input1 = element("input");
      t11 = space();
      div4 = element("div");
      label1 = element("label");
      span2 = element("span");
      span2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.EnableExpansion")}`;
      t13 = space();
      p1 = element("p");
      p1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.EnableExpansionExplanation")}`;
      t15 = space();
      input2 = element("input");
      t16 = space();
      div8 = element("div");
      label2 = element("label");
      span3 = element("span");
      span3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.BaseExpansion")}`;
      t18 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.BaseExpansionExplanation")}`;
      t20 = space();
      div7 = element("div");
      div5 = element("div");
      i2 = element("i");
      i2.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Columns")}`;
      t22 = space();
      i3 = element("i");
      i3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Rows")}`;
      t24 = space();
      div6 = element("div");
      input3 = element("input");
      t25 = space();
      span4 = element("span");
      span4.textContent = "x";
      t27 = space();
      input4 = element("input");
      t28 = space();
      div9 = element("div");
      label3 = element("label");
      span5 = element("span");
      span5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.RestrictAccess")}`;
      t30 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.RestrictAccessExplanation")}`;
      t32 = space();
      input5 = element("input");
      t33 = space();
      div10 = element("div");
      label4 = element("label");
      span6 = element("span");
      span6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.Access")}`;
      t35 = space();
      p4 = element("p");
      p4.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.AccessExplanation")}`;
      t37 = space();
      button0 = element("button");
      button0.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.ManageAccess")}`;
      t39 = space();
      div11 = element("div");
      label5 = element("label");
      span7 = element("span");
      span7.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LogVaultAccess")}`;
      t41 = space();
      p5 = element("p");
      p5.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LogVaultAccessExplanation")}`;
      t43 = space();
      input6 = element("input");
      t44 = space();
      div12 = element("div");
      label6 = element("label");
      span8 = element("span");
      span8.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.ClearVaultLog")}`;
      t46 = space();
      p6 = element("p");
      p6.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.ClearVaultLogExplanation")}`;
      t48 = space();
      button1 = element("button");
      button1.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.ClearVaultLog")}`;
      t50 = space();
      div13 = element("div");
      label7 = element("label");
      span9 = element("span");
      span9.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LoggingFormat")}`;
      t52 = space();
      p7 = element("p");
      p7.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Vault.LoggingFormatExplanation")}`;
      t54 = space();
      div14 = element("div");
      select = element("select");
      option0 = element("option");
      t55 = text(t55_value);
      t56 = space();
      option1 = element("option");
      t57 = text(t57_value);
      t58 = space();
      option2 = element("option");
      t59 = text(t59_value);
      set_style(label0, "flex", "6");
      attr(i0, "class", "svelte-b8lxnb");
      attr(i1, "class", "svelte-b8lxnb");
      set_style(div0, "text-align", "center");
      set_style(div0, "font-size", "0.7rem");
      attr(div0, "class", "svelte-b8lxnb");
      attr(input0, "placeholder", "Enter a number...");
      set_style(input0, "text-align", "right");
      attr(input0, "type", "number");
      attr(input0, "class", "svelte-b8lxnb");
      set_style(span1, "flex", "0");
      attr(span1, "class", "svelte-b8lxnb");
      attr(input1, "placeholder", "Enter a number...");
      attr(input1, "type", "number");
      attr(input1, "class", "svelte-b8lxnb");
      set_style(div1, "align-items", "center");
      attr(div1, "class", "svelte-b8lxnb");
      attr(div2, "class", "item-piles-grid-columns svelte-b8lxnb");
      set_style(div2, "flex", "3");
      attr(div3, "class", "form-group");
      attr(input2, "type", "checkbox");
      attr(div4, "class", "form-group");
      set_style(label2, "flex", "6");
      attr(i2, "class", "svelte-b8lxnb");
      attr(i3, "class", "svelte-b8lxnb");
      set_style(div5, "text-align", "center");
      set_style(div5, "font-size", "0.7rem");
      attr(div5, "class", "svelte-b8lxnb");
      input3.disabled = input3_disabled_value = !/*pileData*/
      ctx[0].vaultExpansion;
      attr(input3, "placeholder", "Enter a number...");
      set_style(input3, "text-align", "right");
      attr(input3, "type", "number");
      attr(input3, "class", "svelte-b8lxnb");
      set_style(span4, "flex", "0");
      attr(span4, "class", "svelte-b8lxnb");
      input4.disabled = input4_disabled_value = !/*pileData*/
      ctx[0].vaultExpansion;
      attr(input4, "placeholder", "Enter a number...");
      attr(input4, "type", "number");
      attr(input4, "class", "svelte-b8lxnb");
      set_style(div6, "align-items", "center");
      attr(div6, "class", "svelte-b8lxnb");
      attr(div7, "class", "item-piles-grid-columns svelte-b8lxnb");
      set_style(div7, "flex", "3");
      attr(div8, "class", "form-group");
      attr(input5, "type", "checkbox");
      attr(div9, "class", "form-group");
      set_style(label4, "flex", "4");
      set_style(button0, "flex", "2");
      attr(button0, "type", "button");
      attr(div10, "class", "form-group");
      attr(input6, "type", "checkbox");
      attr(div11, "class", "form-group");
      set_style(label6, "flex", "4");
      set_style(button1, "flex", "2");
      attr(button1, "type", "button");
      attr(div12, "class", "form-group");
      attr(div13, "class", "form-group");
      option0.__value = CONSTANTS.VAULT_LOGGING_TYPES.USER_ACTOR;
      option0.value = option0.__value;
      option1.__value = CONSTANTS.VAULT_LOGGING_TYPES.USER;
      option1.value = option1.__value;
      option2.__value = CONSTANTS.VAULT_LOGGING_TYPES.ACTOR;
      option2.value = option2.__value;
      if (
        /*pileData*/
        ctx[0].vaultLogType === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[13].call(select)
        ));
      attr(div14, "class", "form-group");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, label0);
      append(label0, span0);
      append(label0, t1);
      append(label0, p0);
      append(div3, t3);
      append(div3, div2);
      append(div2, div0);
      append(div0, i0);
      append(div0, t5);
      append(div0, i1);
      append(div2, t7);
      append(div2, div1);
      append(div1, input0);
      set_input_value(
        input0,
        /*pileData*/
        ctx[0].cols
      );
      append(div1, t8);
      append(div1, span1);
      append(div1, t10);
      append(div1, input1);
      set_input_value(
        input1,
        /*pileData*/
        ctx[0].rows
      );
      insert(target, t11, anchor);
      insert(target, div4, anchor);
      append(div4, label1);
      append(label1, span2);
      append(label1, t13);
      append(label1, p1);
      append(div4, t15);
      append(div4, input2);
      input2.checked = /*pileData*/
      ctx[0].vaultExpansion;
      insert(target, t16, anchor);
      insert(target, div8, anchor);
      append(div8, label2);
      append(label2, span3);
      append(label2, t18);
      append(label2, p2);
      append(div8, t20);
      append(div8, div7);
      append(div7, div5);
      append(div5, i2);
      append(div5, t22);
      append(div5, i3);
      append(div7, t24);
      append(div7, div6);
      append(div6, input3);
      set_input_value(
        input3,
        /*pileData*/
        ctx[0].baseExpansionCols
      );
      append(div6, t25);
      append(div6, span4);
      append(div6, t27);
      append(div6, input4);
      set_input_value(
        input4,
        /*pileData*/
        ctx[0].baseExpansionRows
      );
      insert(target, t28, anchor);
      insert(target, div9, anchor);
      append(div9, label3);
      append(label3, span5);
      append(label3, t30);
      append(label3, p3);
      append(div9, t32);
      append(div9, input5);
      input5.checked = /*pileData*/
      ctx[0].restrictVaultAccess;
      insert(target, t33, anchor);
      insert(target, div10, anchor);
      append(div10, label4);
      append(label4, span6);
      append(label4, t35);
      append(label4, p4);
      append(div10, t37);
      append(div10, button0);
      insert(target, t39, anchor);
      insert(target, div11, anchor);
      append(div11, label5);
      append(label5, span7);
      append(label5, t41);
      append(label5, p5);
      append(div11, t43);
      append(div11, input6);
      input6.checked = /*pileData*/
      ctx[0].logVaultActions;
      insert(target, t44, anchor);
      insert(target, div12, anchor);
      append(div12, label6);
      append(label6, span8);
      append(label6, t46);
      append(label6, p6);
      append(div12, t48);
      append(div12, button1);
      insert(target, t50, anchor);
      insert(target, div13, anchor);
      append(div13, label7);
      append(label7, span9);
      append(label7, t52);
      append(label7, p7);
      insert(target, t54, anchor);
      insert(target, div14, anchor);
      append(div14, select);
      append(select, option0);
      append(option0, t55);
      append(option0, t56);
      append(select, option1);
      append(option1, t57);
      append(option1, t58);
      append(select, option2);
      append(option2, t59);
      select_option(
        select,
        /*pileData*/
        ctx[0].vaultLogType,
        true
      );
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "input",
            /*input0_input_handler*/
            ctx[4]
          ),
          listen(
            input1,
            "input",
            /*input1_input_handler*/
            ctx[5]
          ),
          listen(
            input2,
            "change",
            /*input2_change_handler*/
            ctx[6]
          ),
          listen(
            input3,
            "input",
            /*input3_input_handler*/
            ctx[7]
          ),
          listen(
            input4,
            "input",
            /*input4_input_handler*/
            ctx[8]
          ),
          listen(
            input5,
            "change",
            /*input5_change_handler*/
            ctx[9]
          ),
          listen(
            button0,
            "click",
            /*click_handler*/
            ctx[10]
          ),
          listen(
            input6,
            "change",
            /*input6_change_handler*/
            ctx[11]
          ),
          listen(
            button1,
            "click",
            /*click_handler_1*/
            ctx[12]
          ),
          listen(
            select,
            "change",
            /*select_change_handler*/
            ctx[13]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*pileData, CONSTANTS*/
      1 && to_number(input0.value) !== /*pileData*/
      ctx2[0].cols) {
        set_input_value(
          input0,
          /*pileData*/
          ctx2[0].cols
        );
      }
      if (dirty & /*pileData, CONSTANTS*/
      1 && to_number(input1.value) !== /*pileData*/
      ctx2[0].rows) {
        set_input_value(
          input1,
          /*pileData*/
          ctx2[0].rows
        );
      }
      if (dirty & /*pileData, CONSTANTS*/
      1) {
        input2.checked = /*pileData*/
        ctx2[0].vaultExpansion;
      }
      if (dirty & /*pileData, CONSTANTS*/
      1 && input3_disabled_value !== (input3_disabled_value = !/*pileData*/
      ctx2[0].vaultExpansion)) {
        input3.disabled = input3_disabled_value;
      }
      if (dirty & /*pileData, CONSTANTS*/
      1 && to_number(input3.value) !== /*pileData*/
      ctx2[0].baseExpansionCols) {
        set_input_value(
          input3,
          /*pileData*/
          ctx2[0].baseExpansionCols
        );
      }
      if (dirty & /*pileData, CONSTANTS*/
      1 && input4_disabled_value !== (input4_disabled_value = !/*pileData*/
      ctx2[0].vaultExpansion)) {
        input4.disabled = input4_disabled_value;
      }
      if (dirty & /*pileData, CONSTANTS*/
      1 && to_number(input4.value) !== /*pileData*/
      ctx2[0].baseExpansionRows) {
        set_input_value(
          input4,
          /*pileData*/
          ctx2[0].baseExpansionRows
        );
      }
      if (dirty & /*pileData, CONSTANTS*/
      1) {
        input5.checked = /*pileData*/
        ctx2[0].restrictVaultAccess;
      }
      if (dirty & /*pileData, CONSTANTS*/
      1) {
        input6.checked = /*pileData*/
        ctx2[0].logVaultActions;
      }
      if (dirty & /*pileData, CONSTANTS*/
      1) {
        select_option(
          select,
          /*pileData*/
          ctx2[0].vaultLogType
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div3);
      if (detaching)
        detach(t11);
      if (detaching)
        detach(div4);
      if (detaching)
        detach(t16);
      if (detaching)
        detach(div8);
      if (detaching)
        detach(t28);
      if (detaching)
        detach(div9);
      if (detaching)
        detach(t33);
      if (detaching)
        detach(div10);
      if (detaching)
        detach(t39);
      if (detaching)
        detach(div11);
      if (detaching)
        detach(t44);
      if (detaching)
        detach(div12);
      if (detaching)
        detach(t50);
      if (detaching)
        detach(div13);
      if (detaching)
        detach(t54);
      if (detaching)
        detach(div14);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$m, "create_fragment$m");
function instance$j($$self, $$props, $$invalidate) {
  let { pileData } = $$props;
  let { pileActor } = $$props;
  async function showVaultAccessEditor() {
    const data2 = pileData.vaultAccess || [];
    return VaultAccessEditor.show(data2, {
      id: `vault-access-editor-item-pile-config-${pileActor.id}`,
      title: localize("ITEM-PILES.Applications.VaultAccessEditor.Title", { actor_name: pileActor.name })
    }).then((result) => {
      $$invalidate(0, pileData.vaultAccess = result || [], pileData);
    });
  }
  __name(showVaultAccessEditor, "showVaultAccessEditor");
  async function clearVaultLog() {
    const doThing = await TJSDialog.confirm({
      id: `sharing-dialog-item-pile-config-${pileActor.id}`,
      title: "Item Piles - " + localize("ITEM-PILES.Dialogs.ClearVaultLog.Title"),
      content: {
        class: CustomDialog,
        props: {
          header: localize("ITEM-PILES.Dialogs.ClearVaultLog.Title"),
          content: localize("ITEM-PILES.Dialogs.ClearVaultLog.Content", { actor_name: pileActor.name })
        }
      },
      modal: true
    });
    if (!doThing)
      return;
    return clearActorLog(pileActor);
  }
  __name(clearVaultLog, "clearVaultLog");
  function input0_input_handler() {
    pileData.cols = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler() {
    pileData.rows = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input1_input_handler, "input1_input_handler");
  function input2_change_handler() {
    pileData.vaultExpansion = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input2_change_handler, "input2_change_handler");
  function input3_input_handler() {
    pileData.baseExpansionCols = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input3_input_handler, "input3_input_handler");
  function input4_input_handler() {
    pileData.baseExpansionRows = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input4_input_handler, "input4_input_handler");
  function input5_change_handler() {
    pileData.restrictVaultAccess = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input5_change_handler, "input5_change_handler");
  const click_handler = /* @__PURE__ */ __name(() => showVaultAccessEditor(), "click_handler");
  function input6_change_handler() {
    pileData.logVaultActions = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input6_change_handler, "input6_change_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => clearVaultLog(), "click_handler_1");
  function select_change_handler() {
    pileData.vaultLogType = select_value(this);
    $$invalidate(0, pileData);
  }
  __name(select_change_handler, "select_change_handler");
  $$self.$$set = ($$props2) => {
    if ("pileData" in $$props2)
      $$invalidate(0, pileData = $$props2.pileData);
    if ("pileActor" in $$props2)
      $$invalidate(3, pileActor = $$props2.pileActor);
  };
  return [
    pileData,
    showVaultAccessEditor,
    clearVaultLog,
    pileActor,
    input0_input_handler,
    input1_input_handler,
    input2_change_handler,
    input3_input_handler,
    input4_input_handler,
    input5_change_handler,
    click_handler,
    input6_change_handler,
    click_handler_1,
    select_change_handler
  ];
}
__name(instance$j, "instance$j");
const _Vault = class _Vault extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$j, create_fragment$m, safe_not_equal, { pileData: 0, pileActor: 3 });
  }
};
__name(_Vault, "Vault");
let Vault = _Vault;
const custom_svelte_svelte_type_style_lang = "";
function get_each_context$9(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[11] = list[i][0];
  child_ctx[12] = list[i][1];
  child_ctx[13] = list;
  child_ctx[14] = i;
  return child_ctx;
}
__name(get_each_context$9, "get_each_context$9");
function get_each_context_1$4(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[11] = list[i][0];
  child_ctx[15] = list[i][1];
  return child_ctx;
}
__name(get_each_context_1$4, "get_each_context_1$4");
function create_if_block_5$3(ctx) {
  let p;
  let t_value = localize(
    /*data*/
    ctx[12].label
  ) + "";
  let t;
  return {
    c() {
      p = element("p");
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*pileData*/
      1 && t_value !== (t_value = localize(
        /*data*/
        ctx2[12].label
      ) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_5$3, "create_if_block_5$3");
function create_if_block_4$6(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_change_handler() {
    ctx[9].call(
      input,
      /*key*/
      ctx[11]
    );
  }
  __name(input_change_handler, "input_change_handler");
  return {
    c() {
      input = element("input");
      attr(input, "type", "checkbox");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      input.checked = /*pileData*/
      ctx[0][
        /*key*/
        ctx[11]
      ];
      if (!mounted) {
        dispose = listen(input, "change", input_change_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*pileData, Object, CONSTANTS*/
      1) {
        input.checked = /*pileData*/
        ctx[0][
          /*key*/
          ctx[11]
        ];
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$6, "create_if_block_4$6");
function create_if_block_3$6(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler_1() {
    ctx[8].call(
      input,
      /*key*/
      ctx[11]
    );
  }
  __name(input_input_handler_1, "input_input_handler_1");
  return {
    c() {
      input = element("input");
      attr(input, "type", "number");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*pileData*/
        ctx[0][
          /*key*/
          ctx[11]
        ]
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler_1);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*pileData, Object, CONSTANTS*/
      1 && to_number(input.value) !== /*pileData*/
      ctx[0][
        /*key*/
        ctx[11]
      ]) {
        set_input_value(
          input,
          /*pileData*/
          ctx[0][
            /*key*/
            ctx[11]
          ]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$6, "create_if_block_3$6");
function create_if_block_2$6(ctx) {
  let dropzone;
  let current;
  function func2(...args) {
    return (
      /*func*/
      ctx[7](
        /*key*/
        ctx[11],
        /*data*/
        ctx[12],
        ...args
      )
    );
  }
  __name(func2, "func");
  dropzone = new DropZone({
    props: {
      callback: func2,
      $$slots: { default: [create_default_slot$9] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(dropzone.$$.fragment);
    },
    m(target, anchor) {
      mount_component(dropzone, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const dropzone_changes = {};
      if (dirty & /*pileData*/
      1)
        dropzone_changes.callback = func2;
      if (dirty & /*$$scope, pileData*/
      262145) {
        dropzone_changes.$$scope = { dirty, ctx };
      }
      dropzone.$set(dropzone_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(dropzone.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropzone.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(dropzone, detaching);
    }
  };
}
__name(create_if_block_2$6, "create_if_block_2$6");
function create_if_block$d(ctx) {
  let if_block_anchor;
  function select_block_type_1(ctx2, dirty) {
    if (
      /*data*/
      ctx2[12].options
    )
      return create_if_block_1$9;
    return create_else_block$7;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block$d, "create_if_block$d");
function create_default_slot$9(ctx) {
  let div;
  let img;
  let img_src_value;
  let t0;
  let span;
  let t1_value = (
    /*pileData*/
    (ctx[0][
      /*key*/
      ctx[11]
    ]?.data?.name ?? `Drop ${/*data*/
    ctx[12].type.prototype.constructor.name.toLowerCase()} to add`) + ""
  );
  let t1;
  let t2;
  let i;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx[5](
        /*key*/
        ctx[11]
      )
    );
  }
  __name(click_handler, "click_handler");
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[6](
        /*key*/
        ctx[11]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    c() {
      div = element("div");
      img = element("img");
      t0 = space();
      span = element("span");
      t1 = text(t1_value);
      t2 = space();
      i = element("i");
      if (!src_url_equal(img.src, img_src_value = /*pileData*/
      ctx[0][
        /*key*/
        ctx[11]
      ]?.data?.img ?? /*data*/
      ctx[12].type === Actor ? "icons/svg/cowled.svg.svg" : "icons/svg/coins.svg"))
        attr(img, "src", img_src_value);
      attr(img, "class", "drop-document-custom-image svelte-63emvi");
      attr(span, "class", "svelte-63emvi");
      toggle_class(span, "item-piles-clickable-link", !!/*pileData*/
      ctx[0][
        /*key*/
        ctx[11]
      ]?.data);
      attr(i, "class", "fas fa-times drop-item-remove item-piles-clickable-red item-piles-clickable-link svelte-63emvi");
      attr(div, "class", "drop-item svelte-63emvi");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, img);
      append(div, t0);
      append(div, span);
      append(span, t1);
      append(div, t2);
      append(div, i);
      if (!mounted) {
        dispose = [
          listen(span, "click", click_handler),
          listen(i, "click", stop_propagation(click_handler_1))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*pileData, Object, CONSTANTS*/
      1 && !src_url_equal(img.src, img_src_value = /*pileData*/
      ctx[0][
        /*key*/
        ctx[11]
      ]?.data?.img ?? /*data*/
      ctx[12].type === Actor ? "icons/svg/cowled.svg.svg" : "icons/svg/coins.svg")) {
        attr(img, "src", img_src_value);
      }
      if (dirty & /*pileData*/
      1 && t1_value !== (t1_value = /*pileData*/
      (ctx[0][
        /*key*/
        ctx[11]
      ]?.data?.name ?? `Drop ${/*data*/
      ctx[12].type.prototype.constructor.name.toLowerCase()} to add`) + ""))
        set_data(t1, t1_value);
      if (dirty & /*pileData, Object, CONSTANTS*/
      1) {
        toggle_class(span, "item-piles-clickable-link", !!/*pileData*/
        ctx[0][
          /*key*/
          ctx[11]
        ]?.data);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$9, "create_default_slot$9");
function create_else_block$7(ctx) {
  let input;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx[4].call(
      input,
      /*key*/
      ctx[11]
    );
  }
  __name(input_input_handler, "input_input_handler");
  return {
    c() {
      input = element("input");
      attr(input, "type", "text");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*pileData*/
        ctx[0][
          /*key*/
          ctx[11]
        ]
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*pileData, Object, CONSTANTS*/
      1 && input.value !== /*pileData*/
      ctx[0][
        /*key*/
        ctx[11]
      ]) {
        set_input_value(
          input,
          /*pileData*/
          ctx[0][
            /*key*/
            ctx[11]
          ]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$7, "create_else_block$7");
function create_if_block_1$9(ctx) {
  let select;
  let mounted;
  let dispose;
  let each_value_1 = Object.entries(
    /*data*/
    ctx[12].options
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_1$4(get_each_context_1$4(ctx, each_value_1, i));
  }
  function select_change_handler() {
    ctx[3].call(
      select,
      /*key*/
      ctx[11]
    );
  }
  __name(select_change_handler, "select_change_handler");
  return {
    c() {
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      if (
        /*pileData*/
        ctx[0][
          /*key*/
          ctx[11]
        ] === void 0
      )
        add_render_callback(select_change_handler);
    },
    m(target, anchor) {
      insert(target, select, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*pileData*/
        ctx[0][
          /*key*/
          ctx[11]
        ],
        true
      );
      if (!mounted) {
        dispose = listen(select, "change", select_change_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*Object, CONSTANTS, pileData, localize*/
      1) {
        each_value_1 = Object.entries(
          /*data*/
          ctx[12].options
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1$4(ctx, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_1$4(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
      if (dirty & /*pileData, Object, CONSTANTS*/
      1) {
        select_option(
          select,
          /*pileData*/
          ctx[0][
            /*key*/
            ctx[11]
          ]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(select);
      destroy_each(each_blocks, detaching);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$9, "create_if_block_1$9");
function create_each_block_1$4(ctx) {
  let option;
  let t_value = localize(
    /*value*/
    ctx[15]
  ) + "";
  let t;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*key*/
      ctx[11];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*pileData*/
      1 && t_value !== (t_value = localize(
        /*value*/
        ctx2[15]
      ) + ""))
        set_data(t, t_value);
      if (dirty & /*pileData, Object, CONSTANTS*/
      1 && option_value_value !== (option_value_value = /*key*/
      ctx2[11])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_1$4, "create_each_block_1$4");
function create_each_block$9(key_1, ctx) {
  let div;
  let label;
  let span;
  let t0_value = localize(
    /*data*/
    ctx[12].title
  ) + "";
  let t0;
  let t1;
  let t2;
  let current_block_type_index;
  let if_block1;
  let t3;
  let current;
  let if_block0 = (
    /*data*/
    ctx[12].label && create_if_block_5$3(ctx)
  );
  const if_block_creators = [create_if_block$d, create_if_block_2$6, create_if_block_3$6, create_if_block_4$6];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*data*/
      ctx2[12].type === String
    )
      return 0;
    if (
      /*data*/
      ctx2[12].type === Item || /*data*/
      ctx2[12].type === Actor
    )
      return 1;
    if (
      /*data*/
      ctx2[12].type === Number
    )
      return 2;
    if (
      /*data*/
      ctx2[12].type === Boolean
    )
      return 3;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      label = element("label");
      span = element("span");
      t0 = text(t0_value);
      t1 = space();
      if (if_block0)
        if_block0.c();
      t2 = space();
      if (if_block1)
        if_block1.c();
      t3 = space();
      set_style(label, "flex", "4");
      attr(div, "class", "form-group");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, span);
      append(span, t0);
      append(label, t1);
      if (if_block0)
        if_block0.m(label, null);
      append(div, t2);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div, null);
      }
      append(div, t3);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || dirty & /*pileData*/
      1) && t0_value !== (t0_value = localize(
        /*data*/
        ctx[12].title
      ) + ""))
        set_data(t0, t0_value);
      if (
        /*data*/
        ctx[12].label
      ) {
        if (if_block0) {
          if_block0.p(ctx, dirty);
        } else {
          if_block0 = create_if_block_5$3(ctx);
          if_block0.c();
          if_block0.m(label, null);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx, dirty);
        }
      } else {
        if (if_block1) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block1 = if_blocks[current_block_type_index];
          if (!if_block1) {
            if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
            if_block1.c();
          } else {
            if_block1.p(ctx, dirty);
          }
          transition_in(if_block1, 1);
          if_block1.m(div, t3);
        } else {
          if_block1 = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
    }
  };
}
__name(create_each_block$9, "create_each_block$9");
function create_fragment$l(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let current;
  let each_value = Object.entries(CONSTANTS.CUSTOM_PILE_TYPES[
    /*pileData*/
    ctx[0].type
  ]);
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*key*/
    ctx2[11]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$9(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$9(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (dirty & /*pileData, Object, CONSTANTS, localize, String, handleDropData, previewDocument, Actor, Item, Number, Boolean*/
      7) {
        each_value = Object.entries(CONSTANTS.CUSTOM_PILE_TYPES[
          /*pileData*/
          ctx2[0].type
        ]);
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, each_1_anchor.parentNode, outro_and_destroy_block, create_each_block$9, each_1_anchor, get_each_context$9);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_fragment$l, "create_fragment$l");
function instance$i($$self, $$props, $$invalidate) {
  let { pileData } = $$props;
  const flags = Object.entries(CONSTANTS.CUSTOM_PILE_TYPES[pileData.type]);
  for (const [key, data2] of flags) {
    if (pileData[key] === void 0) {
      pileData[key] = data2.value;
    }
  }
  async function handleDropData(dropData, key, data2) {
    if (!data2.type.implementation) {
      return;
    }
    const doc = await data2.type.implementation.fromDropData(dropData);
    $$invalidate(
      0,
      pileData[key] = {
        data: doc.toObject(),
        uuid: dropData.uuid
      },
      pileData
    );
  }
  __name(handleDropData, "handleDropData");
  async function previewDocument(key) {
    if (!pileData[key].uuid)
      return;
    const doc = fromUuidSync(pileData[key].uuid);
    if (!doc)
      return;
    doc.sheet.render(true);
  }
  __name(previewDocument, "previewDocument");
  function select_change_handler(key) {
    pileData[key] = select_value(this);
    $$invalidate(0, pileData);
  }
  __name(select_change_handler, "select_change_handler");
  function input_input_handler(key) {
    pileData[key] = this.value;
    $$invalidate(0, pileData);
  }
  __name(input_input_handler, "input_input_handler");
  const click_handler = /* @__PURE__ */ __name((key) => {
    previewDocument(key);
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name((key) => {
    delete pileData[key];
    $$invalidate(0, pileData[key] = false, pileData);
  }, "click_handler_1");
  const func2 = /* @__PURE__ */ __name((key, data2, dropData) => handleDropData(dropData, key, data2), "func");
  function input_input_handler_1(key) {
    pileData[key] = to_number(this.value);
    $$invalidate(0, pileData);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  function input_change_handler(key) {
    pileData[key] = this.checked;
    $$invalidate(0, pileData);
  }
  __name(input_change_handler, "input_change_handler");
  $$self.$$set = ($$props2) => {
    if ("pileData" in $$props2)
      $$invalidate(0, pileData = $$props2.pileData);
  };
  return [
    pileData,
    handleDropData,
    previewDocument,
    select_change_handler,
    input_input_handler,
    click_handler,
    click_handler_1,
    func2,
    input_input_handler_1,
    input_change_handler
  ];
}
__name(instance$i, "instance$i");
const _Custom = class _Custom extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$i, create_fragment$l, safe_not_equal, { pileData: 0 });
  }
};
__name(_Custom, "Custom");
let Custom = _Custom;
function get_each_context$8(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[24] = list[i];
  return child_ctx;
}
__name(get_each_context$8, "get_each_context$8");
function get_each_context_1$3(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[27] = list[i];
  return child_ctx;
}
__name(get_each_context_1$3, "get_each_context_1$3");
function create_if_block_7$2(ctx) {
  let mainsettings;
  let updating_pileData;
  let current;
  function mainsettings_pileData_binding(value) {
    ctx[13](value);
  }
  __name(mainsettings_pileData_binding, "mainsettings_pileData_binding");
  let mainsettings_props = {
    pileActor: (
      /*pileActor*/
      ctx[1]
    ),
    pileEnabled: (
      /*pileEnabled*/
      ctx[6]
    )
  };
  if (
    /*pileData*/
    ctx[3] !== void 0
  ) {
    mainsettings_props.pileData = /*pileData*/
    ctx[3];
  }
  mainsettings = new Main({ props: mainsettings_props });
  binding_callbacks.push(() => bind(mainsettings, "pileData", mainsettings_pileData_binding));
  return {
    c() {
      create_component(mainsettings.$$.fragment);
    },
    m(target, anchor) {
      mount_component(mainsettings, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const mainsettings_changes = {};
      if (dirty & /*pileActor*/
      2)
        mainsettings_changes.pileActor = /*pileActor*/
        ctx2[1];
      if (!updating_pileData && dirty & /*pileData*/
      8) {
        updating_pileData = true;
        mainsettings_changes.pileData = /*pileData*/
        ctx2[3];
        add_flush_callback(() => updating_pileData = false);
      }
      mainsettings.$set(mainsettings_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(mainsettings.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(mainsettings.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(mainsettings, detaching);
    }
  };
}
__name(create_if_block_7$2, "create_if_block_7$2");
function create_if_block$c(ctx) {
  let div;
  let label;
  let span;
  let t1;
  let p;
  let t3;
  let select;
  let each0_anchor;
  let t4;
  let hr;
  let t5;
  let show_if;
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  let mounted;
  let dispose;
  let each_value_1 = Object.values(CONSTANTS.PILE_TYPES);
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_1$3(get_each_context_1$3(ctx, each_value_1, i));
  }
  let each_value = (
    /*customTypes*/
    ctx[9]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$8(get_each_context$8(ctx, each_value, i));
  }
  const if_block_creators = [create_if_block_1$8, create_if_block_2$5, create_if_block_5$2, create_if_block_6$2];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (dirty & /*pileData*/
    8)
      show_if = null;
    if (
      /*pileData*/
      ctx2[3].type === CONSTANTS.PILE_TYPES.MERCHANT
    )
      return 0;
    if (
      /*pileData*/
      ctx2[3].type === CONSTANTS.PILE_TYPES.PILE || /*pileData*/
      ctx2[3].type === CONSTANTS.PILE_TYPES.CONTAINER
    )
      return 1;
    if (
      /*pileData*/
      ctx2[3].type === CONSTANTS.PILE_TYPES.VAULT
    )
      return 2;
    if (show_if == null)
      show_if = !!/*customTypes*/
      ctx2[9].includes(
        /*pileData*/
        ctx2[3].type
      );
    if (show_if)
      return 3;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx, -1))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    c() {
      div = element("div");
      label = element("label");
      span = element("span");
      span.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Other.Type")}`;
      t1 = space();
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.ItemPileConfig.Other.TypeExplanation")}`;
      t3 = space();
      select = element("select");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      each0_anchor = empty();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t4 = space();
      hr = element("hr");
      t5 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      set_style(label, "flex", "4");
      set_style(select, "flex", "4");
      if (
        /*pileData*/
        ctx[3].type === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[14].call(select)
        ));
      attr(div, "class", "form-group");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, span);
      append(label, t1);
      append(label, p);
      append(div, t3);
      append(div, select);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(select, null);
        }
      }
      append(select, each0_anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*pileData*/
        ctx[3].type,
        true
      );
      insert(target, t4, anchor);
      insert(target, hr, anchor);
      insert(target, t5, anchor);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = listen(
          select,
          "change",
          /*select_change_handler*/
          ctx[14]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*Object, CONSTANTS, localize*/
      0) {
        each_value_1 = Object.values(CONSTANTS.PILE_TYPES);
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1$3(ctx2, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
          } else {
            each_blocks_1[i] = create_each_block_1$3(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(select, each0_anchor);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_1.length;
      }
      if (dirty & /*customTypes, localize*/
      512) {
        each_value = /*customTypes*/
        ctx2[9];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$8(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block$8(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & /*pileData, customTypes, Object, CONSTANTS*/
      520) {
        select_option(
          select,
          /*pileData*/
          ctx2[3].type
        );
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2, dirty);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(hr);
      if (detaching)
        detach(t5);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$c, "create_if_block$c");
function create_each_block_1$3(ctx) {
  let option;
  let t0_value = localize(`ITEM-PILES.Types.${/*type*/
  ctx[27]}`) + "";
  let t0;
  let t1;
  return {
    c() {
      option = element("option");
      t0 = text(t0_value);
      t1 = space();
      option.__value = /*type*/
      ctx[27];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_1$3, "create_each_block_1$3");
function create_each_block$8(ctx) {
  let option;
  let t0_value = localize(`ITEM-PILES.Types.${/*customType*/
  ctx[24]}`) + "";
  let t0;
  let t1;
  return {
    c() {
      option = element("option");
      t0 = text(t0_value);
      t1 = space();
      option.__value = /*customType*/
      ctx[24];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$8, "create_each_block$8");
function create_if_block_6$2(ctx) {
  let customsettings;
  let updating_pileData;
  let current;
  function customsettings_pileData_binding(value) {
    ctx[20](value);
  }
  __name(customsettings_pileData_binding, "customsettings_pileData_binding");
  let customsettings_props = { pileActor: (
    /*pileActor*/
    ctx[1]
  ) };
  if (
    /*pileData*/
    ctx[3] !== void 0
  ) {
    customsettings_props.pileData = /*pileData*/
    ctx[3];
  }
  customsettings = new Custom({ props: customsettings_props });
  binding_callbacks.push(() => bind(customsettings, "pileData", customsettings_pileData_binding));
  return {
    c() {
      create_component(customsettings.$$.fragment);
    },
    m(target, anchor) {
      mount_component(customsettings, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const customsettings_changes = {};
      if (dirty & /*pileActor*/
      2)
        customsettings_changes.pileActor = /*pileActor*/
        ctx2[1];
      if (!updating_pileData && dirty & /*pileData*/
      8) {
        updating_pileData = true;
        customsettings_changes.pileData = /*pileData*/
        ctx2[3];
        add_flush_callback(() => updating_pileData = false);
      }
      customsettings.$set(customsettings_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(customsettings.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(customsettings.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(customsettings, detaching);
    }
  };
}
__name(create_if_block_6$2, "create_if_block_6$2");
function create_if_block_5$2(ctx) {
  let vaultsettings;
  let updating_pileData;
  let current;
  function vaultsettings_pileData_binding(value) {
    ctx[19](value);
  }
  __name(vaultsettings_pileData_binding, "vaultsettings_pileData_binding");
  let vaultsettings_props = { pileActor: (
    /*pileActor*/
    ctx[1]
  ) };
  if (
    /*pileData*/
    ctx[3] !== void 0
  ) {
    vaultsettings_props.pileData = /*pileData*/
    ctx[3];
  }
  vaultsettings = new Vault({ props: vaultsettings_props });
  binding_callbacks.push(() => bind(vaultsettings, "pileData", vaultsettings_pileData_binding));
  return {
    c() {
      create_component(vaultsettings.$$.fragment);
    },
    m(target, anchor) {
      mount_component(vaultsettings, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const vaultsettings_changes = {};
      if (dirty & /*pileActor*/
      2)
        vaultsettings_changes.pileActor = /*pileActor*/
        ctx2[1];
      if (!updating_pileData && dirty & /*pileData*/
      8) {
        updating_pileData = true;
        vaultsettings_changes.pileData = /*pileData*/
        ctx2[3];
        add_flush_callback(() => updating_pileData = false);
      }
      vaultsettings.$set(vaultsettings_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(vaultsettings.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(vaultsettings.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(vaultsettings, detaching);
    }
  };
}
__name(create_if_block_5$2, "create_if_block_5$2");
function create_if_block_2$5(ctx) {
  let t0;
  let t1;
  let hr;
  let t2;
  let sharingsettings;
  let updating_pileData;
  let current;
  let if_block0 = (
    /*pileData*/
    ctx[3].type === CONSTANTS.PILE_TYPES.PILE && create_if_block_4$5(ctx)
  );
  let if_block1 = (
    /*pileData*/
    ctx[3].type === CONSTANTS.PILE_TYPES.CONTAINER && create_if_block_3$5(ctx)
  );
  function sharingsettings_pileData_binding(value) {
    ctx[18](value);
  }
  __name(sharingsettings_pileData_binding, "sharingsettings_pileData_binding");
  let sharingsettings_props = { pileActor: (
    /*pileActor*/
    ctx[1]
  ) };
  if (
    /*pileData*/
    ctx[3] !== void 0
  ) {
    sharingsettings_props.pileData = /*pileData*/
    ctx[3];
  }
  sharingsettings = new Sharing({ props: sharingsettings_props });
  binding_callbacks.push(() => bind(sharingsettings, "pileData", sharingsettings_pileData_binding));
  return {
    c() {
      if (if_block0)
        if_block0.c();
      t0 = space();
      if (if_block1)
        if_block1.c();
      t1 = space();
      hr = element("hr");
      t2 = space();
      create_component(sharingsettings.$$.fragment);
    },
    m(target, anchor) {
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t0, anchor);
      if (if_block1)
        if_block1.m(target, anchor);
      insert(target, t1, anchor);
      insert(target, hr, anchor);
      insert(target, t2, anchor);
      mount_component(sharingsettings, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*pileData*/
        ctx2[3].type === CONSTANTS.PILE_TYPES.PILE
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*pileData*/
          8) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_4$5(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(t0.parentNode, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*pileData*/
        ctx2[3].type === CONSTANTS.PILE_TYPES.CONTAINER
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*pileData*/
          8) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_3$5(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(t1.parentNode, t1);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      const sharingsettings_changes = {};
      if (dirty & /*pileActor*/
      2)
        sharingsettings_changes.pileActor = /*pileActor*/
        ctx2[1];
      if (!updating_pileData && dirty & /*pileData*/
      8) {
        updating_pileData = true;
        sharingsettings_changes.pileData = /*pileData*/
        ctx2[3];
        add_flush_callback(() => updating_pileData = false);
      }
      sharingsettings.$set(sharingsettings_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(sharingsettings.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(sharingsettings.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (if_block0)
        if_block0.d(detaching);
      if (detaching)
        detach(t0);
      if (if_block1)
        if_block1.d(detaching);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(hr);
      if (detaching)
        detach(t2);
      destroy_component(sharingsettings, detaching);
    }
  };
}
__name(create_if_block_2$5, "create_if_block_2$5");
function create_if_block_1$8(ctx) {
  let merchantsettings;
  let updating_pileData;
  let current;
  function merchantsettings_pileData_binding(value) {
    ctx[15](value);
  }
  __name(merchantsettings_pileData_binding, "merchantsettings_pileData_binding");
  let merchantsettings_props = { pileActor: (
    /*pileActor*/
    ctx[1]
  ) };
  if (
    /*pileData*/
    ctx[3] !== void 0
  ) {
    merchantsettings_props.pileData = /*pileData*/
    ctx[3];
  }
  merchantsettings = new Merchant({ props: merchantsettings_props });
  binding_callbacks.push(() => bind(merchantsettings, "pileData", merchantsettings_pileData_binding));
  return {
    c() {
      create_component(merchantsettings.$$.fragment);
    },
    m(target, anchor) {
      mount_component(merchantsettings, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const merchantsettings_changes = {};
      if (dirty & /*pileActor*/
      2)
        merchantsettings_changes.pileActor = /*pileActor*/
        ctx2[1];
      if (!updating_pileData && dirty & /*pileData*/
      8) {
        updating_pileData = true;
        merchantsettings_changes.pileData = /*pileData*/
        ctx2[3];
        add_flush_callback(() => updating_pileData = false);
      }
      merchantsettings.$set(merchantsettings_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(merchantsettings.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(merchantsettings.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(merchantsettings, detaching);
    }
  };
}
__name(create_if_block_1$8, "create_if_block_1$8");
function create_if_block_4$5(ctx) {
  let itempilesettings;
  let updating_pileData;
  let current;
  function itempilesettings_pileData_binding(value) {
    ctx[16](value);
  }
  __name(itempilesettings_pileData_binding, "itempilesettings_pileData_binding");
  let itempilesettings_props = {};
  if (
    /*pileData*/
    ctx[3] !== void 0
  ) {
    itempilesettings_props.pileData = /*pileData*/
    ctx[3];
  }
  itempilesettings = new Itempile({ props: itempilesettings_props });
  binding_callbacks.push(() => bind(itempilesettings, "pileData", itempilesettings_pileData_binding));
  return {
    c() {
      create_component(itempilesettings.$$.fragment);
    },
    m(target, anchor) {
      mount_component(itempilesettings, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const itempilesettings_changes = {};
      if (!updating_pileData && dirty & /*pileData*/
      8) {
        updating_pileData = true;
        itempilesettings_changes.pileData = /*pileData*/
        ctx2[3];
        add_flush_callback(() => updating_pileData = false);
      }
      itempilesettings.$set(itempilesettings_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(itempilesettings.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(itempilesettings.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(itempilesettings, detaching);
    }
  };
}
__name(create_if_block_4$5, "create_if_block_4$5");
function create_if_block_3$5(ctx) {
  let containersettings;
  let updating_pileData;
  let current;
  function containersettings_pileData_binding(value) {
    ctx[17](value);
  }
  __name(containersettings_pileData_binding, "containersettings_pileData_binding");
  let containersettings_props = {};
  if (
    /*pileData*/
    ctx[3] !== void 0
  ) {
    containersettings_props.pileData = /*pileData*/
    ctx[3];
  }
  containersettings = new Container({ props: containersettings_props });
  binding_callbacks.push(() => bind(containersettings, "pileData", containersettings_pileData_binding));
  return {
    c() {
      create_component(containersettings.$$.fragment);
    },
    m(target, anchor) {
      mount_component(containersettings, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const containersettings_changes = {};
      if (!updating_pileData && dirty & /*pileData*/
      8) {
        updating_pileData = true;
        containersettings_changes.pileData = /*pileData*/
        ctx2[3];
        add_flush_callback(() => updating_pileData = false);
      }
      containersettings.$set(containersettings_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(containersettings.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(containersettings.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(containersettings, detaching);
    }
  };
}
__name(create_if_block_3$5, "create_if_block_3$5");
function create_default_slot$8(ctx) {
  let form_1;
  let tabs_1;
  let updating_activeTab;
  let updating_tabs;
  let t0;
  let section;
  let div;
  let t1;
  let t2;
  let footer;
  let button;
  let i;
  let t3;
  let t4_value = localize("ITEM-PILES.Applications.ItemPileConfig.Update") + "";
  let t4;
  let current;
  let mounted;
  let dispose;
  function tabs_1_activeTab_binding(value) {
    ctx[11](value);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  function tabs_1_tabs_binding(value) {
    ctx[12](value);
  }
  __name(tabs_1_tabs_binding, "tabs_1_tabs_binding");
  let tabs_1_props = {};
  if (
    /*activeTab*/
    ctx[5] !== void 0
  ) {
    tabs_1_props.activeTab = /*activeTab*/
    ctx[5];
  }
  if (
    /*tabs*/
    ctx[4] !== void 0
  ) {
    tabs_1_props.tabs = /*tabs*/
    ctx[4];
  }
  tabs_1 = new Tabs({ props: tabs_1_props });
  binding_callbacks.push(() => bind(tabs_1, "activeTab", tabs_1_activeTab_binding));
  binding_callbacks.push(() => bind(tabs_1, "tabs", tabs_1_tabs_binding));
  let if_block0 = (
    /*activeTab*/
    ctx[5] === "main" && create_if_block_7$2(ctx)
  );
  let if_block1 = (
    /*activeTab*/
    ctx[5] === "other" && create_if_block$c(ctx)
  );
  return {
    c() {
      form_1 = element("form");
      create_component(tabs_1.$$.fragment);
      t0 = space();
      section = element("section");
      div = element("div");
      if (if_block0)
        if_block0.c();
      t1 = space();
      if (if_block1)
        if_block1.c();
      t2 = space();
      footer = element("footer");
      button = element("button");
      i = element("i");
      t3 = space();
      t4 = text(t4_value);
      attr(div, "class", "tab");
      attr(section, "class", "tab-body");
      attr(i, "class", "far fa-save");
      attr(button, "type", "button");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-config-container");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      mount_component(tabs_1, form_1, null);
      append(form_1, t0);
      append(form_1, section);
      append(section, div);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t1);
      if (if_block1)
        if_block1.m(div, null);
      append(form_1, t2);
      append(form_1, footer);
      append(footer, button);
      append(button, i);
      append(button, t3);
      append(button, t4);
      ctx[21](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*requestSubmit*/
            ctx[8],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[7]
          ), { once: true })
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const tabs_1_changes = {};
      if (!updating_activeTab && dirty & /*activeTab*/
      32) {
        updating_activeTab = true;
        tabs_1_changes.activeTab = /*activeTab*/
        ctx2[5];
        add_flush_callback(() => updating_activeTab = false);
      }
      if (!updating_tabs && dirty & /*tabs*/
      16) {
        updating_tabs = true;
        tabs_1_changes.tabs = /*tabs*/
        ctx2[4];
        add_flush_callback(() => updating_tabs = false);
      }
      tabs_1.$set(tabs_1_changes);
      if (
        /*activeTab*/
        ctx2[5] === "main"
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*activeTab*/
          32) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_7$2(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div, t1);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*activeTab*/
        ctx2[5] === "other"
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*activeTab*/
          32) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block$c(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(tabs_1.$$.fragment, local);
      transition_in(if_block0);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(tabs_1.$$.fragment, local);
      transition_out(if_block0);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      destroy_component(tabs_1);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      ctx[21](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$8, "create_default_slot$8");
function create_fragment$k(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[22](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$8] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, pileActor, pileData, activeTab, tabs*/
      1073741886) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$k, "create_fragment$k");
function instance$h($$self, $$props, $$invalidate) {
  let $pileEnabled;
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let { pileActor } = $$props;
  let form;
  let pileData = getActorFlagData(pileActor);
  if (typeof pileData?.deleteWhenEmpty === "boolean") {
    pileData.deleteWhenEmpty = !!pileData?.deleteWhenEmpty;
  }
  let pileEnabled = writable$1(pileData.enabled);
  component_subscribe($$self, pileEnabled, (value) => $$invalidate(10, $pileEnabled = value));
  async function updateSettings() {
    let defaults = foundry.utils.duplicate(CONSTANTS.PILE_DEFAULTS);
    const types = [
      "closedImage",
      "emptyImage",
      "openedImage",
      "lockedImage",
      "closeSound",
      "openSound",
      "lockedSound",
      "unlockedSound"
    ];
    for (let type of types) {
      if (pileData[type].includes("*")) {
        $$invalidate(3, pileData[type + "s"] = await getFiles(pileData[type], { applyWildCard: true, softFail: true }), pileData);
        $$invalidate(3, pileData[type + "s"] = pileData[type + "s"] || [], pileData);
      }
    }
    const data2 = foundry.utils.mergeObject(defaults, pileData);
    data2.deleteWhenEmpty = {
      "default": "default",
      "true": true,
      "false": false
    }[data2.deleteWhenEmpty];
    const currentData = getActorFlagData(pileActor);
    const diff = Object.keys(foundry.utils.diffObject(currentData, foundry.utils.deepClone(data2)));
    game.itempiles.API.updateItemPile(pileActor, data2).then(async () => {
      if (diff.includes("enabled") || diff.includes("type")) {
        const promises = [];
        let apps = [];
        switch (currentData.type) {
          case CONSTANTS.PILE_TYPES.MERCHANT:
            if (MerchantApp.getActiveApp(pileActor.uuid)) {
              promises.push(MerchantApp.getActiveApp(pileActor.uuid).close());
            }
            if (MerchantApp.getActiveApp(pileActor?.token?.uuid)) {
              promises.push(MerchantApp.getActiveApp(pileActor?.token?.uuid).close());
            }
            break;
          case CONSTANTS.PILE_TYPES.VAULT:
            apps = VaultApp.getActiveApps(pileActor.uuid).concat(VaultApp.getActiveApps(pileActor?.token?.uuid));
            break;
          default:
            apps = ItemPileInventoryApp.getActiveApps(pileActor.uuid).concat(ItemPileInventoryApp.getActiveApps(pileActor?.token?.uuid));
            break;
        }
        for (let app of apps) {
          promises.push(app.close());
        }
        if (promises.length || pileActor?.sheet.rendered) {
          await Promise.allSettled(promises);
          if (data2.enabled) {
            pileActor?.sheet.close();
            game.itempiles.API.renderItemPileInterface(pileActor);
          } else if (!data2.enabled) {
            pileActor?.sheet.render(true, { bypassItemPiles: true });
          }
        }
      }
    });
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  let tabs = [];
  let activeTab = "main";
  const customTypes = Object.keys(CONSTANTS.CUSTOM_PILE_TYPES);
  function tabs_1_activeTab_binding(value) {
    activeTab = value;
    $$invalidate(5, activeTab);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  function tabs_1_tabs_binding(value) {
    tabs = value;
    $$invalidate(4, tabs), $$invalidate(10, $pileEnabled);
  }
  __name(tabs_1_tabs_binding, "tabs_1_tabs_binding");
  function mainsettings_pileData_binding(value) {
    pileData = value;
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
  }
  __name(mainsettings_pileData_binding, "mainsettings_pileData_binding");
  function select_change_handler() {
    pileData.type = select_value(this);
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
    $$invalidate(9, customTypes);
  }
  __name(select_change_handler, "select_change_handler");
  function merchantsettings_pileData_binding(value) {
    pileData = value;
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
  }
  __name(merchantsettings_pileData_binding, "merchantsettings_pileData_binding");
  function itempilesettings_pileData_binding(value) {
    pileData = value;
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
  }
  __name(itempilesettings_pileData_binding, "itempilesettings_pileData_binding");
  function containersettings_pileData_binding(value) {
    pileData = value;
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
  }
  __name(containersettings_pileData_binding, "containersettings_pileData_binding");
  function sharingsettings_pileData_binding(value) {
    pileData = value;
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
  }
  __name(sharingsettings_pileData_binding, "sharingsettings_pileData_binding");
  function vaultsettings_pileData_binding(value) {
    pileData = value;
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
  }
  __name(vaultsettings_pileData_binding, "vaultsettings_pileData_binding");
  function customsettings_pileData_binding(value) {
    pileData = value;
    $$invalidate(3, pileData), $$invalidate(10, $pileEnabled);
  }
  __name(customsettings_pileData_binding, "customsettings_pileData_binding");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("pileActor" in $$props2)
      $$invalidate(1, pileActor = $$props2.pileActor);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$pileEnabled*/
    1024) {
      $$invalidate(3, pileData.enabled = $pileEnabled, pileData);
    }
    if ($$self.$$.dirty & /*$pileEnabled*/
    1024) {
      {
        $$invalidate(4, tabs = [
          {
            value: "main",
            label: "ITEM-PILES.Applications.ItemPileConfig.Main.Title",
            highlight: !$pileEnabled
          },
          {
            value: "other",
            label: "ITEM-PILES.Applications.ItemPileConfig.Other.Title"
          }
        ]);
      }
    }
  };
  return [
    elementRoot,
    pileActor,
    form,
    pileData,
    tabs,
    activeTab,
    pileEnabled,
    updateSettings,
    requestSubmit,
    customTypes,
    $pileEnabled,
    tabs_1_activeTab_binding,
    tabs_1_tabs_binding,
    mainsettings_pileData_binding,
    select_change_handler,
    merchantsettings_pileData_binding,
    itempilesettings_pileData_binding,
    containersettings_pileData_binding,
    sharingsettings_pileData_binding,
    vaultsettings_pileData_binding,
    customsettings_pileData_binding,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$h, "instance$h");
const _Item_pile_config = class _Item_pile_config extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$h, create_fragment$k, safe_not_equal, { elementRoot: 0, pileActor: 1 });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get pileActor() {
    return this.$$.ctx[1];
  }
  set pileActor(pileActor) {
    this.$$set({ pileActor });
    flush();
  }
};
__name(_Item_pile_config, "Item_pile_config");
let Item_pile_config = _Item_pile_config;
const _ItemPileConfig = class _ItemPileConfig extends SvelteApplication {
  constructor(pileActor, options = {}) {
    super({
      id: `item-pile-config-${pileActor.id}-${randomID()}`,
      title: game.i18n.format("ITEM-PILES.Applications.ItemPileConfig.Title", { actor_name: pileActor.name }),
      svelte: {
        class: Item_pile_config,
        target: document.body,
        props: {
          pileActor
        }
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 430,
      height: 627,
      classes: ["item-piles-config", "item-piles-app"],
      resizable: true
    });
  }
  static getActiveApp(id) {
    return getActiveApps(`item-pile-config-${id}`, true);
  }
  static async show(target, options = {}, dialogData = {}) {
    const targetActor = getActor(target);
    const app = this.getActiveApp(targetActor.uuid);
    if (app)
      return app.render(false, { focus: true });
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(targetActor, options, dialogData).render(true);
    });
  }
  async close(options) {
    Object.values(ui.windows).forEach((app) => {
      if (app !== this && app.rendered && app.options?.parentApp === this) {
        app.close();
      }
    });
    return super.close(options);
  }
};
__name(_ItemPileConfig, "ItemPileConfig");
let ItemPileConfig = _ItemPileConfig;
const _ItemPileInventoryApp = class _ItemPileInventoryApp extends SvelteApplication {
  /**
   *
   * @param actor
   * @param recipient
   * @param overrides
   * @param options
   * @param dialogData
   */
  constructor(actor, recipient, options = {}, dialogData = {}) {
    super({
      id: `item-pile-inventory-${actor?.token?.id ?? actor.id}-${randomID()}`,
      title: actor.name,
      svelte: {
        class: Item_pile_inventory_shell,
        target: document.body,
        props: {
          actor,
          recipient
        }
      },
      zIndex: 100,
      ...options
    }, dialogData);
    this.actor = actor;
    this.recipient = recipient;
    hooks.callAll(CONSTANTS.HOOKS.OPEN_INTERFACE, this, actor, recipient, options, dialogData);
  }
  /** @inheritdoc */
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      closeOnSubmit: false,
      classes: ["app", "window-app", "sheet", "item-pile-inventory", "item-piles", "item-piles-app"],
      width: 550,
      height: "auto"
    });
  }
  static getActiveApps(id) {
    return getActiveApps(`item-pile-inventory-${id}`);
  }
  static async show(source, recipient = false, options = {}, dialogData = {}) {
    source = getActor(source);
    recipient = getActor(recipient);
    const result = hooks.call(CONSTANTS.HOOKS.PRE_OPEN_INTERFACE, source, recipient, options, dialogData);
    if (result === false)
      return;
    const apps = this.getActiveApps(source?.token?.uuid ?? source.uuid);
    if (apps.length) {
      for (let app of apps) {
        app.render(false, { focus: true });
      }
      return;
    }
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(source, recipient, options, dialogData).render(true, { focus: true, bypassItemPiles: true });
    });
  }
  async close(options) {
    const result = hooks.call(CONSTANTS.HOOKS.PRE_CLOSE_INTERFACE, this, this.actor, this.recipient, options);
    if (result === false)
      return;
    hooks.callAll(CONSTANTS.HOOKS.CLOSE_INTERFACE, this, this.actor, this.recipient, options);
    return super.close(options);
  }
  /* -------------------------------------------- */
  /** @override */
  _getHeaderButtons() {
    let buttons = super._getHeaderButtons();
    const newButtons = [];
    if (this.actor.isOwner) {
      newButtons.push(
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.Inspect.OpenSheet" : "",
          class: "item-piles-open-actor-sheet",
          icon: "fas fa-user",
          onclick: () => {
            this.actor.sheet.render(true, { focus: true, bypassItemPiles: true });
          }
        }
      );
    }
    if (game.user.isGM) {
      newButtons.push(
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.ContextMenu.ShowToPlayers" : "",
          class: "item-piles-show-to-players",
          icon: "fas fa-eye",
          onclick: async (event) => {
            const activeUsers = Array.from(game.users).filter((u) => u.active && u !== game.user).map((u) => u.id);
            if (!activeUsers.length) {
              return custom_warning(game.i18n.localize("ITEM-PILES.Warnings.NoPlayersActive"), true);
            }
            const users = event.altKey ? activeUsers : await UserSelectDialog.show({ excludeSelf: true });
            if (!users || !users.length)
              return;
            custom_notify(game.i18n.format("ITEM-PILES.Notifications.ShownToPlayers", { actor_name: this.actor.name }));
            return game.itempiles.API.renderItemPileInterface(this.actor, {
              userIds: users,
              useDefaultCharacter: true
            });
          }
        },
        {
          label: !getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "ITEM-PILES.HUD.Configure" : "",
          class: "item-piles-configure-pile",
          icon: "fas fa-box-open",
          onclick: () => {
            ItemPileConfig.show(this.actor);
          }
        }
      );
    }
    return newButtons.concat(buttons);
  }
};
__name(_ItemPileInventoryApp, "ItemPileInventoryApp");
let ItemPileInventoryApp = _ItemPileInventoryApp;
const receiveItemsShell_svelte_svelte_type_style_lang = "";
function create_fragment$j(ctx) {
  let div2;
  let p0;
  let t1;
  let div0;
  let img0;
  let img0_src_value;
  let t2;
  let i;
  let t3;
  let img1;
  let img1_src_value;
  let t4;
  let div1;
  let img2;
  let img2_src_value;
  let t5;
  let span;
  let t6_value = (
    /*item*/
    ctx[0].name + ""
  );
  let t6;
  let t7;
  let t8;
  let t9;
  let t10;
  let p1;
  let t11_value = localize("ITEM-PILES.Dialogs.ReceiveItem.Content", {
    source_actor_name: (
      /*sourceActor*/
      ctx[2].name
    ),
    target_actor_name: (
      /*targetActor*/
      ctx[3].name
    )
  }) + "";
  let t11;
  return {
    c() {
      div2 = element("div");
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Dialogs.ReceiveItem.Header")}`;
      t1 = space();
      div0 = element("div");
      img0 = element("img");
      t2 = space();
      i = element("i");
      t3 = space();
      img1 = element("img");
      t4 = space();
      div1 = element("div");
      img2 = element("img");
      t5 = space();
      span = element("span");
      t6 = text(t6_value);
      t7 = text(" (");
      t8 = text(
        /*quantity*/
        ctx[1]
      );
      t9 = text(")");
      t10 = space();
      p1 = element("p");
      t11 = text(t11_value);
      attr(p0, "class", "header svelte-18mobqz");
      if (!src_url_equal(img0.src, img0_src_value = /*sourceActor*/
      ctx[2].img))
        attr(img0, "src", img0_src_value);
      attr(img0, "class", "svelte-18mobqz");
      attr(i, "class", "fas fa-arrow-right");
      if (!src_url_equal(img1.src, img1_src_value = /*targetActor*/
      ctx[3].img))
        attr(img1, "src", img1_src_value);
      attr(img1, "class", "svelte-18mobqz");
      attr(div0, "class", "item-piles-give-image-container svelte-18mobqz");
      if (!src_url_equal(img2.src, img2_src_value = /*item*/
      ctx[0].img))
        attr(img2, "src", img2_src_value);
      attr(img2, "class", "svelte-18mobqz");
      attr(div1, "class", "item-piles-give-item-container svelte-18mobqz");
      attr(div2, "class", "item-piles-dialog-root svelte-18mobqz");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, p0);
      append(div2, t1);
      append(div2, div0);
      append(div0, img0);
      append(div0, t2);
      append(div0, i);
      append(div0, t3);
      append(div0, img1);
      append(div2, t4);
      append(div2, div1);
      append(div1, img2);
      append(div1, t5);
      append(div1, span);
      append(span, t6);
      append(span, t7);
      append(span, t8);
      append(span, t9);
      append(div2, t10);
      append(div2, p1);
      append(p1, t11);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*sourceActor*/
      4 && !src_url_equal(img0.src, img0_src_value = /*sourceActor*/
      ctx2[2].img)) {
        attr(img0, "src", img0_src_value);
      }
      if (dirty & /*targetActor*/
      8 && !src_url_equal(img1.src, img1_src_value = /*targetActor*/
      ctx2[3].img)) {
        attr(img1, "src", img1_src_value);
      }
      if (dirty & /*item*/
      1 && !src_url_equal(img2.src, img2_src_value = /*item*/
      ctx2[0].img)) {
        attr(img2, "src", img2_src_value);
      }
      if (dirty & /*item*/
      1 && t6_value !== (t6_value = /*item*/
      ctx2[0].name + ""))
        set_data(t6, t6_value);
      if (dirty & /*quantity*/
      2)
        set_data(
          t8,
          /*quantity*/
          ctx2[1]
        );
      if (dirty & /*sourceActor, targetActor*/
      12 && t11_value !== (t11_value = localize("ITEM-PILES.Dialogs.ReceiveItem.Content", {
        source_actor_name: (
          /*sourceActor*/
          ctx2[2].name
        ),
        target_actor_name: (
          /*targetActor*/
          ctx2[3].name
        )
      }) + ""))
        set_data(t11, t11_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div2);
    }
  };
}
__name(create_fragment$j, "create_fragment$j");
function instance$g($$self, $$props, $$invalidate) {
  let { item } = $$props;
  let { quantity } = $$props;
  let { sourceActor } = $$props;
  let { targetActor } = $$props;
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
    if ("quantity" in $$props2)
      $$invalidate(1, quantity = $$props2.quantity);
    if ("sourceActor" in $$props2)
      $$invalidate(2, sourceActor = $$props2.sourceActor);
    if ("targetActor" in $$props2)
      $$invalidate(3, targetActor = $$props2.targetActor);
  };
  return [item, quantity, sourceActor, targetActor];
}
__name(instance$g, "instance$g");
const _Receive_items_shell = class _Receive_items_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$g, create_fragment$j, safe_not_equal, {
      item: 0,
      quantity: 1,
      sourceActor: 2,
      targetActor: 3
    });
  }
};
__name(_Receive_items_shell, "Receive_items_shell");
let Receive_items_shell = _Receive_items_shell;
const preloadedFiles = /* @__PURE__ */ new Set();
const _PrivateAPI = class _PrivateAPI {
  /**
   * Initializes the API for Foundry's core hooks
   */
  static initialize() {
    hooks.on("canvasReady", this._onCanvasReady.bind(this));
    hooks.on("createItem", this._onCreateItem.bind(this));
    hooks.on("updateItem", this._onUpdateItem.bind(this));
    hooks.on("deleteItem", this._onDeleteItem.bind(this));
    hooks.on("updateActor", this._onUpdateActor.bind(this));
    hooks.on("deleteToken", this._onDeleteToken.bind(this));
    hooks.on("deleteActor", this._onDeleteActor.bind(this));
    hooks.on("preCreateToken", this._onPreCreateToken.bind(this));
    hooks.on("preUpdateToken", this._onPreUpdateToken.bind(this));
    hooks.on("createToken", this._onCreateToken.bind(this));
    hooks.on("dropCanvasData", this._dropData.bind(this));
  }
  /**
   * @private
   */
  static async _onCanvasReady(canvas2) {
    const tokens = [...canvas2.tokens.placeables].map((token) => token.document);
    for (const doc of tokens) {
      await this._preloadItemPileFiles(doc);
    }
  }
  /**
   * @private
   */
  static _onCreateItem(doc) {
    if (!doc.parent)
      return;
    ItemPileStore.notifyChanges("createItem", doc.parent, doc);
    if (!isValidItemPile(doc.parent))
      return;
    this._evaluateItemPileChange(doc.parent, {}, true);
  }
  /**
   * @private
   */
  static _onUpdateItem(doc) {
    if (!doc.parent)
      return;
    if (!isValidItemPile(doc.parent))
      return;
    this._evaluateItemPileChange(doc.parent, {}, true);
  }
  /**
   * @private
   */
  static _onDeleteItem(doc) {
    if (!doc.parent)
      return;
    ItemPileStore.notifyChanges("deleteItem", doc.parent, doc);
    if (!isValidItemPile(doc.parent))
      return;
    this._evaluateItemPileChange(doc.parent, {}, true);
  }
  /**
   * @private
   */
  static _onUpdateActor(doc, changes) {
    if (!isValidItemPile(doc))
      return;
    this._evaluateItemPileChange(doc, changes);
  }
  /**
   * @private
   */
  static _onDeleteToken(doc) {
    ItemPileStore.notifyChanges("delete", doc.actor);
    if (!isValidItemPile(doc))
      return;
    hooks.callAll(CONSTANTS.HOOKS.PILE.DELETE, doc);
  }
  /**
   * @private
   */
  static _onDeleteActor(doc) {
    ItemPileStore.notifyChanges("delete", doc);
  }
  /**
   * @private
   */
  static _onPreCreateToken(doc, data2) {
    const docData = foundry.utils.deepClone(data2);
    const sourceActor = game.actors.get(doc.actorId);
    const itemPileConfig = foundry.utils.mergeObject(
      foundry.utils.deepClone(CONSTANTS.PILE_DEFAULTS),
      foundry.utils.mergeObject(
        foundry.utils.getProperty(docData, CONSTANTS.FLAGS.PILE) ?? {},
        foundry.utils.deepClone(foundry.utils.getProperty(sourceActor, CONSTANTS.FLAGS.PILE) ?? {})
      )
    );
    if (!itemPileConfig?.enabled)
      return;
    if (!doc.isLinked) {
      docData[`${CONSTANTS.ACTOR_DELTA_PROPERTY}.flags.${CONSTANTS.MODULE_NAME}.-=sharing`] = null;
    }
    if (itemPileConfig.closedImage.includes("*")) {
      itemPileConfig.closedImage = random_array_element(itemPileConfig.closedImages);
      itemPileConfig.closedImages = [];
    }
    if (itemPileConfig.emptyImage.includes("*")) {
      itemPileConfig.emptyImage = random_array_element(itemPileConfig.emptyImages);
      itemPileConfig.emptyImages = [];
    }
    if (itemPileConfig.openedImage.includes("*")) {
      itemPileConfig.openedImage = random_array_element(itemPileConfig.openedImages);
      itemPileConfig.openedImages = [];
    }
    if (itemPileConfig.lockedImage.includes("*")) {
      itemPileConfig.lockedImage = random_array_element(itemPileConfig.lockedImages);
      itemPileConfig.lockedImages = [];
    }
    docData[CONSTANTS.FLAGS.PILE] = cleanFlagData(itemPileConfig);
    const targetItems = getActorItems(doc.actor, {
      itemFilters: itemPileConfig?.overrideItemFilters
    });
    const targetCurrencies = getActorCurrencies(doc.actor, {
      currencyList: getCurrencyList(doc.actor, itemPileConfig)
    });
    const pileData = { data: itemPileConfig, items: targetItems, currencies: targetCurrencies };
    const scale = getItemPileTokenScale(doc, pileData);
    docData["texture.src"] = getItemPileTokenImage(doc, pileData);
    docData["texture.scaleX"] = scale;
    docData["texture.scaleY"] = scale;
    docData["name"] = getItemPileName(doc, pileData);
    doc.updateSource(docData);
  }
  static _onPreUpdateToken(doc, changes) {
    if (!foundry.utils.hasProperty(changes, "actorLink"))
      return;
    if (!isValidItemPile(doc))
      return;
    const flagData = getActorFlagData(doc);
    const cleanFlagData$1 = cleanFlagData(flagData);
    changes[CONSTANTS.FLAGS.PILE] = doc.actorLink ? cleanFlagData$1 : null;
  }
  /**
   * @private
   */
  static _onCreateToken(doc) {
    if (!isValidItemPile(doc))
      return;
    const itemPileConfig = getActorFlagData(doc.actor);
    hooks.callAll(CONSTANTS.HOOKS.PILE.CREATE, doc, itemPileConfig);
    return this._preloadItemPileFiles(doc);
  }
  static async _addItems(targetUuid, items, userId, {
    removeExistingActorItems = false,
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const targetActor = getActor(targetUuid);
    const transaction = new Transaction(targetActor);
    if (removeExistingActorItems) {
      const existingItems = getActorItems(targetActor);
      await transaction.appendItemChanges(existingItems, { remove: true });
    }
    await transaction.appendItemChanges(items);
    const { itemsToUpdate, itemsToCreate } = transaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_ADD, targetActor, itemsToCreate, itemsToUpdate, interactionId);
    if (hookResult === false)
      return false;
    const { itemDeltas } = await transaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ITEM.ADD, targetUuid, itemDeltas, userId, interactionId);
    await this._executeItemPileMacro(targetUuid, {
      action: "addItems",
      target: targetUuid,
      items: itemDeltas,
      userId,
      interactionId
    });
    if (!skipVaultLogging && isItemPileVault(targetActor)) {
      await updateVaultLog(targetActor, {
        userId,
        items: itemDeltas,
        withdrawal: false
      });
    }
    return itemDeltas;
  }
  static async _removeItems(targetUuid, items, userId, { skipVaultLogging = false, interactionId = false } = {}) {
    const targetActor = getActor(targetUuid);
    const transaction = new Transaction(targetActor);
    await transaction.appendItemChanges(items, { remove: true });
    const { itemsToUpdate, itemsToDelete } = transaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_REMOVE, targetActor, itemsToUpdate, itemsToDelete, interactionId);
    if (hookResult === false)
      return false;
    const { itemDeltas } = await transaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ITEM.REMOVE, targetUuid, itemDeltas, userId, interactionId);
    await this._executeItemPileMacro(targetUuid, {
      action: "removeItems",
      target: targetUuid,
      items: itemDeltas,
      userId,
      interactionId
    });
    const shouldBeDeleted = shouldItemPileBeDeleted(targetUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(targetUuid);
    }
    if (!skipVaultLogging && isItemPileVault(targetActor)) {
      await updateVaultLog(targetActor, {
        userId,
        items: itemDeltas,
        withdrawal: true
      });
    }
    return itemDeltas;
  }
  static async _transferItems(sourceUuid, targetUuid, items, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const sourceTransaction = new Transaction(sourceActor);
    await sourceTransaction.appendItemChanges(items, { remove: true });
    const sourceUpdates = sourceTransaction.prepare();
    const targetTransaction = new Transaction(targetActor);
    await targetTransaction.appendItemChanges(sourceUpdates.itemDeltas);
    const targetUpdates = targetTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_TRANSFER, sourceActor, sourceUpdates, targetActor, targetUpdates, interactionId);
    if (hookResult === false)
      return false;
    await sourceTransaction.commit();
    const { itemDeltas } = await targetTransaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ITEM.TRANSFER, sourceUuid, targetUuid, itemDeltas, userId, interactionId);
    const macroData = {
      action: "transferItems",
      source: sourceUuid,
      target: targetUuid,
      items: itemDeltas,
      userId,
      interactionId
    };
    await this._executeItemPileMacro(sourceUuid, macroData);
    await this._executeItemPileMacro(targetUuid, macroData);
    const sourceIsItemPile = isValidItemPile(sourceActor);
    const itemPileUuid = sourceIsItemPile ? sourceUuid : targetUuid;
    const itemPile = sourceIsItemPile ? getToken(sourceUuid) : getToken(targetUuid);
    const shouldBeDeleted = shouldItemPileBeDeleted(itemPileUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(itemPileUuid);
    } else if (isItemPileLootable(itemPile)) {
      if (isItemPileEmpty(itemPile)) {
        await clearItemPileSharingData(itemPile);
      } else {
        await setItemPileSharingData(sourceUuid, targetUuid, {
          items: itemDeltas
        });
      }
    } else if (!skipVaultLogging && (isItemPileVault(sourceActor) || isItemPileVault(targetActor))) {
      const pileActor = sourceIsItemPile ? sourceActor : targetActor;
      const actorToLog = sourceIsItemPile ? targetActor : sourceActor;
      await updateVaultLog(pileActor, {
        userId,
        actor: actorToLog,
        items: itemDeltas,
        withdrawal: sourceIsItemPile
      });
    }
    return itemDeltas;
  }
  static async _transferAllItems(sourceUuid, targetUuid, userId, {
    itemFilters = false,
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const itemsToTransfer = getActorItems(sourceActor, { itemFilters }).map((item) => item.toObject());
    const sourceTransaction = new Transaction(sourceActor);
    await sourceTransaction.appendItemChanges(itemsToTransfer, { remove: true });
    const sourceUpdates = sourceTransaction.prepare();
    const targetTransaction = new Transaction(targetActor);
    await targetTransaction.appendItemChanges(sourceUpdates.itemDeltas);
    const targetUpdates = targetTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_TRANSFER_ALL, sourceActor, sourceUpdates, targetActor, targetUpdates, userId);
    if (hookResult === false)
      return false;
    await sourceTransaction.commit();
    const { itemDeltas } = await targetTransaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ITEM.TRANSFER_ALL, sourceUuid, targetUuid, itemDeltas, userId, interactionId);
    const macroData = {
      action: "transferAllItems",
      source: sourceUuid,
      target: targetUuid,
      items: itemDeltas,
      userId,
      interactionId
    };
    await this._executeItemPileMacro(sourceUuid, macroData);
    await this._executeItemPileMacro(targetUuid, macroData);
    const sourceIsItemPile = isValidItemPile(sourceActor);
    const itemPileUuid = sourceIsItemPile ? sourceUuid : targetUuid;
    const itemPile = sourceIsItemPile ? getToken(sourceUuid) : getToken(targetUuid);
    const shouldBeDeleted = shouldItemPileBeDeleted(itemPileUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(itemPileUuid);
    } else if (!skipVaultLogging && (isItemPileVault(itemPile) || isItemPileVault(targetActor))) {
      const pileActor = sourceIsItemPile ? sourceActor : targetActor;
      const actorToLog = sourceIsItemPile ? targetActor : sourceActor;
      await updateVaultLog(pileActor, {
        userId,
        actor: actorToLog,
        items: itemDeltas,
        withdrawal: sourceIsItemPile
      });
    }
    return itemDeltas;
  }
  static async _addCurrencies(targetUuid, currencies, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const targetActor = getActor(targetUuid);
    const transaction = new Transaction(targetActor);
    const currenciesToAdd = getPriceFromString(currencies).currencies.filter((currency) => currency.quantity);
    const itemsToAdd = currenciesToAdd.filter((currency) => currency.type === "item").map((currency) => ({ item: currency.data.item, quantity: currency.quantity }));
    const attributesToAdd = currenciesToAdd.filter((currency) => currency.type === "attribute").map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    await transaction.appendItemChanges(itemsToAdd, { type: "currency" });
    await transaction.appendActorChanges(attributesToAdd, { type: "currency" });
    const { actorUpdates, itemsToCreate, itemsToUpdate } = transaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.CURRENCY.PRE_ADD, targetActor, actorUpdates, itemsToCreate, itemsToUpdate, interactionId);
    if (hookResult === false)
      return false;
    const { itemDeltas, attributeDeltas } = await transaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.CURRENCY.ADD, targetUuid, itemDeltas, attributeDeltas, userId, interactionId);
    await this._executeItemPileMacro(targetUuid, {
      action: "addCurrencies",
      target: targetUuid,
      items: itemDeltas,
      attributes: attributeDeltas,
      userId,
      interactionId
    });
    if (!skipVaultLogging && isItemPileVault(targetActor)) {
      await updateVaultLog(targetActor, {
        userId,
        items: itemDeltas,
        attributes: attributeDeltas,
        withdrawal: false
      });
    }
    return { itemDeltas, attributeDeltas };
  }
  static async _removeCurrencies(targetUuid, currencies, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const targetActor = getActor(targetUuid);
    const transaction = new Transaction(targetActor);
    const priceData = getPriceFromString(currencies);
    const secondaryPrices = priceData.currencies.filter((currency) => currency.secondary && currency.quantity);
    const overallCost = priceData.overallCost;
    const paymentData = getPaymentData({
      purchaseData: [{ cost: overallCost, quantity: 1, secondaryPrices }],
      buyer: targetActor
    });
    const itemsToRemove = paymentData.finalPrices.filter((currency) => currency.type === "item" && currency.quantity).map((currency) => ({ item: currency.data.item, quantity: currency.quantity }));
    const attributesToRemove = paymentData.finalPrices.filter((currency) => currency.type === "attribute" && currency.quantity).map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    const itemsToAdd = paymentData.buyerChange.filter((currency) => currency.type === "item" && currency.quantity).map((currency) => ({ item: currency.data.item, quantity: currency.quantity }));
    const attributesToAdd = paymentData.buyerChange.filter((currency) => currency.type === "attribute" && currency.quantity).map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    await transaction.appendItemChanges(itemsToRemove, { remove: true, type: "currency" });
    await transaction.appendActorChanges(attributesToRemove, { remove: true, type: "currency" });
    await transaction.appendItemChanges(itemsToAdd, { type: "currency" });
    await transaction.appendActorChanges(attributesToAdd, { type: "currency" });
    const { actorUpdates, itemsToUpdate } = transaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.CURRENCY.PRE_REMOVE, targetActor, actorUpdates, itemsToUpdate, interactionId);
    if (hookResult === false)
      return false;
    const { itemDeltas, attributeDeltas } = await transaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.CURRENCY.REMOVE, targetUuid, itemDeltas, attributeDeltas, userId, interactionId);
    await this._executeItemPileMacro(targetUuid, {
      action: "removeCurrencies",
      target: targetUuid,
      items: itemDeltas,
      attributes: attributeDeltas,
      userId,
      interactionId
    });
    const shouldBeDeleted = shouldItemPileBeDeleted(targetUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(targetUuid);
    }
    if (!skipVaultLogging && isItemPileVault(targetActor)) {
      await updateVaultLog(targetActor, {
        userId,
        items: itemDeltas,
        attributes: attributeDeltas,
        withdrawal: true
      });
    }
    return { itemDeltas, attributeDeltas };
  }
  static async _transferCurrencies(sourceUuid, targetUuid, currencies, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const priceData = getPriceFromString(currencies);
    const overallCost = priceData.overallCost;
    const paymentData = getPaymentData({
      purchaseData: [{ cost: overallCost, quantity: 1 }],
      buyer: sourceActor
    });
    const sourceItemsToRemove = paymentData.finalPrices.filter((currency) => currency.type === "item" && currency.quantity).map((currency) => ({ item: currency.data.item, quantity: currency.quantity }));
    const sourceAttributesToRemove = paymentData.finalPrices.filter((currency) => currency.type === "attribute" && currency.quantity).map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    const sourceItemsToAdd = paymentData.buyerChange.filter((currency) => currency.type === "item" && currency.quantity).map((currency) => ({ item: currency.data.item, quantity: currency.quantity }));
    const sourceAttributesToAdd = paymentData.buyerChange.filter((currency) => currency.type === "attribute" && currency.quantity).map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    const sourceTransaction = new Transaction(sourceActor);
    await sourceTransaction.appendItemChanges(sourceItemsToRemove, { remove: true, type: "currency" });
    await sourceTransaction.appendActorChanges(sourceAttributesToRemove, { remove: true, type: "currency" });
    await sourceTransaction.appendItemChanges(sourceItemsToAdd, { type: "currency" });
    await sourceTransaction.appendActorChanges(sourceAttributesToAdd, { type: "currency" });
    const sourceUpdates = sourceTransaction.prepare();
    const targetItemsToAdd = paymentData.sellerReceive.filter((currency) => currency.type === "item").map((currency) => ({ item: currency.data.item, quantity: currency.quantity }));
    const targetAttributesToAdd = paymentData.sellerReceive.filter((currency) => currency.type === "attribute").map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    const targetTransaction = new Transaction(targetActor);
    await targetTransaction.appendItemChanges(targetItemsToAdd, { type: "currency" });
    await targetTransaction.appendActorChanges(targetAttributesToAdd, { type: "currency" });
    const targetUpdates = targetTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.CURRENCY.PRE_TRANSFER, sourceActor, sourceUpdates, targetActor, targetUpdates, interactionId);
    if (hookResult === false)
      return false;
    await sourceTransaction.commit();
    const { itemDeltas, attributeDeltas } = await targetTransaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.CURRENCY.TRANSFER, sourceUuid, targetUuid, itemDeltas, attributeDeltas, userId, interactionId);
    const macroData = {
      action: "transferCurrencies",
      source: sourceUuid,
      target: targetUuid,
      items: itemDeltas,
      attributes: attributeDeltas,
      userId,
      interactionId
    };
    await this._executeItemPileMacro(sourceUuid, macroData);
    await this._executeItemPileMacro(targetUuid, macroData);
    const sourceIsItemPile = isValidItemPile(sourceActor);
    const itemPileUuid = sourceIsItemPile ? sourceUuid : targetUuid;
    const itemPile = sourceIsItemPile ? getToken(sourceUuid) : getToken(targetUuid);
    const shouldBeDeleted = shouldItemPileBeDeleted(itemPileUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(itemPileUuid);
    } else if (isItemPileLootable(itemPile)) {
      if (isItemPileEmpty(itemPile)) {
        await clearItemPileSharingData(itemPile);
      } else {
        await setItemPileSharingData(sourceUuid, targetUuid, {
          items: itemDeltas,
          attributes: attributeDeltas
        });
      }
    } else if (!skipVaultLogging && (isItemPileVault(sourceActor) || isItemPileVault(targetActor))) {
      const sourceIsItemPile2 = isItemPileVault(sourceActor);
      const pileActor = sourceIsItemPile2 ? sourceActor : targetActor;
      const actorToLog = sourceIsItemPile2 ? targetActor : sourceActor;
      await updateVaultLog(pileActor, {
        userId,
        actor: actorToLog,
        items: itemDeltas,
        attributes: attributeDeltas,
        withdrawal: sourceIsItemPile2
      });
    }
    return { itemDeltas, attributeDeltas };
  }
  static async _transferAllCurrencies(sourceUuid, targetUuid, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const currencyList = getCurrencyList();
    const sourceCurrencyList = getActorCurrencies(sourceActor, { currencyList });
    const itemsToTransfer = sourceCurrencyList.filter((currency) => currency.type === "item").map((currency) => ({ item: currency.data.item, quantity: currency.quantity }));
    const attributesToTransfer = sourceCurrencyList.filter((currency) => currency.type === "attribute").map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    const sourceTransaction = new Transaction(sourceActor);
    await sourceTransaction.appendItemChanges(itemsToTransfer, { remove: true, type: "currency" });
    await sourceTransaction.appendActorChanges(attributesToTransfer, { remove: true, type: "currency" });
    const sourceUpdates = sourceTransaction.prepare();
    const targetTransaction = new Transaction(targetActor);
    await targetTransaction.appendItemChanges(sourceUpdates.itemDeltas);
    await targetTransaction.appendActorChanges(sourceUpdates.attributeDeltas);
    const targetUpdates = targetTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.CURRENCY.PRE_TRANSFER_ALL, sourceActor, sourceUpdates, targetActor, targetUpdates, interactionId);
    if (hookResult === false)
      return false;
    await sourceTransaction.commit();
    const { itemDeltas, attributeDeltas } = await targetTransaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.CURRENCY.TRANSFER_ALL, sourceUuid, targetUuid, itemDeltas, attributeDeltas, userId, interactionId);
    const macroData = {
      action: "transferAllCurrencies",
      source: sourceUuid,
      target: targetUuid,
      items: itemDeltas,
      attributes: attributeDeltas,
      userId,
      interactionId
    };
    await this._executeItemPileMacro(sourceUuid, macroData);
    await this._executeItemPileMacro(targetUuid, macroData);
    const sourceIsItemPile = isValidItemPile(sourceActor);
    const itemPileUuid = sourceIsItemPile ? sourceUuid : targetUuid;
    const itemPile = sourceIsItemPile ? getToken(sourceUuid) : getToken(targetUuid);
    const shouldBeDeleted = shouldItemPileBeDeleted(itemPileUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(itemPileUuid);
    } else if (!skipVaultLogging && isItemPileVault(itemPile)) {
      const pileActor = sourceIsItemPile ? sourceActor : targetActor;
      const actorToLog = sourceIsItemPile ? targetActor : sourceActor;
      await updateVaultLog(pileActor, {
        userId,
        actor: actorToLog,
        items: itemDeltas,
        attributes: attributeDeltas,
        withdrawal: sourceIsItemPile
      });
    }
    return { itemDeltas, attributeDeltas };
  }
  static async _setAttributes(targetUuid, attributes, userId, { interactionId = false } = {}) {
    const targetActor = getActor(targetUuid);
    const transaction = new Transaction(targetActor);
    await transaction.appendActorChanges(attributes, { set: true });
    const { actorUpdates } = transaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ATTRIBUTE.PRE_SET, targetActor, actorUpdates, interactionId);
    if (hookResult === false)
      return false;
    const { attributeDeltas } = await transaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ATTRIBUTE.SET, targetUuid, attributeDeltas, userId, interactionId);
    await this._executeItemPileMacro(targetUuid, {
      action: "setAttributes",
      target: targetUuid,
      attributes: attributeDeltas,
      userId,
      interactionId
    });
    return attributeDeltas;
  }
  static async _addAttributes(targetUuid, attributes, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const targetActor = getActor(targetUuid);
    const transaction = new Transaction(targetActor);
    await transaction.appendActorChanges(attributes);
    const { actorUpdates } = transaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ATTRIBUTE.PRE_ADD, targetActor, actorUpdates, interactionId);
    if (hookResult === false)
      return false;
    const { attributeDeltas } = await transaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ATTRIBUTE.ADD, targetUuid, attributeDeltas, userId, interactionId);
    await this._executeItemPileMacro(targetUuid, {
      action: "addAttributes",
      target: targetUuid,
      attributes: attributeDeltas,
      userId,
      interactionId
    });
    if (!skipVaultLogging && isItemPileVault(targetActor)) {
      await updateVaultLog(targetActor, {
        userId,
        attributes: attributeDeltas,
        withdrawal: false
      });
    }
    return attributeDeltas;
  }
  static async _removeAttributes(targetUuid, attributes, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const targetActor = getActor(targetUuid);
    const transaction = new Transaction(targetActor);
    await transaction.appendActorChanges(attributes, { remove: true });
    const { actorUpdates } = transaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ATTRIBUTE.PRE_REMOVE, targetActor, actorUpdates, interactionId);
    if (hookResult === false)
      return false;
    const { attributeDeltas } = await transaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ATTRIBUTE.REMOVE, targetUuid, attributeDeltas, userId, interactionId);
    await this._executeItemPileMacro(targetUuid, {
      action: "removeAttributes",
      target: targetUuid,
      attributes: attributeDeltas,
      userId,
      interactionId
    });
    const shouldBeDeleted = shouldItemPileBeDeleted(targetUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(targetUuid);
    }
    if (!skipVaultLogging && isItemPileVault(targetActor)) {
      await updateVaultLog(targetActor, {
        userId,
        attributes: attributeDeltas,
        withdrawal: true
      });
    }
    return attributeDeltas;
  }
  static async _transferAttributes(sourceUuid, targetUuid, attributes, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const sourceTransaction = new Transaction(sourceActor);
    await sourceTransaction.appendActorChanges(attributes, { remove: true });
    const sourceUpdates = sourceTransaction.prepare();
    const targetTransaction = new Transaction(targetActor);
    await targetTransaction.appendActorChanges(sourceUpdates.attributeDeltas);
    const targetUpdates = targetTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ATTRIBUTE.PRE_TRANSFER, sourceActor, sourceUpdates.actorUpdates, targetActor, targetUpdates.actorUpdates, interactionId);
    if (hookResult === false)
      return false;
    await sourceTransaction.commit();
    const { attributeDeltas } = await targetTransaction.commit();
    await ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.CALL_HOOK, CONSTANTS.HOOKS.ATTRIBUTE.TRANSFER, sourceUuid, targetUuid, attributeDeltas, userId, interactionId);
    const macroData = {
      action: "transferAttributes",
      source: sourceUuid,
      target: targetUuid,
      attributes: attributeDeltas,
      userId,
      interactionId
    };
    await this._executeItemPileMacro(sourceUuid, macroData);
    await this._executeItemPileMacro(targetUuid, macroData);
    const sourceIsItemPile = isValidItemPile(sourceActor);
    const itemPileUuid = sourceIsItemPile ? sourceUuid : targetUuid;
    const itemPile = sourceIsItemPile ? getToken(sourceUuid) : getToken(targetUuid);
    const shouldBeDeleted = shouldItemPileBeDeleted(itemPileUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(itemPileUuid);
    } else if (isItemPileLootable(itemPile)) {
      if (isItemPileEmpty(itemPile)) {
        await clearItemPileSharingData(itemPile);
      } else {
        await setItemPileSharingData(sourceUuid, targetUuid, {
          attributes: attributeDeltas
        });
      }
    } else if (!skipVaultLogging && (isItemPileVault(sourceActor) || isItemPileVault(targetActor))) {
      const pileActor = sourceIsItemPile ? sourceActor : targetActor;
      const actorToLog = sourceIsItemPile ? targetActor : sourceActor;
      await updateVaultLog(pileActor, {
        userId,
        actor: actorToLog,
        attributes: attributeDeltas,
        withdrawal: sourceIsItemPile
      });
    }
    return attributeDeltas;
  }
  static async _transferAllAttributes(sourceUuid, targetUuid, userId, {
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const sourceAttributes = getActorCurrencies(sourceActor).filter((entry) => entry.type === "attribute");
    const attributesToTransfer = sourceAttributes.filter((attribute) => {
      return foundry.utils.hasProperty(targetActor, attribute.data.path);
    }).map((attribute) => attribute.data.path);
    const sourceTransaction = new Transaction(sourceActor);
    await sourceTransaction.appendActorChanges(attributesToTransfer, { remove: true });
    const sourceUpdates = sourceTransaction.prepare();
    const targetTransaction = new Transaction(targetActor);
    await targetTransaction.appendActorChanges(sourceUpdates.attributeDeltas);
    const targetUpdates = targetTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ATTRIBUTE.PRE_TRANSFER_ALL, sourceActor, sourceUpdates.actorUpdates, targetActor, targetUpdates.actorUpdates, interactionId);
    if (hookResult === false)
      return false;
    await sourceTransaction.commit();
    const { attributeDeltas } = await targetTransaction.commit();
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ATTRIBUTE.TRANSFER_ALL, sourceUuid, targetUuid, attributeDeltas, userId, interactionId);
    const macroData = {
      action: "transferAllAttributes",
      source: sourceUuid,
      target: targetUuid,
      attributes: attributeDeltas,
      userId,
      interactionId
    };
    await this._executeItemPileMacro(sourceUuid, macroData);
    await this._executeItemPileMacro(targetUuid, macroData);
    const sourceIsItemPile = isValidItemPile(sourceActor);
    const itemPileUuid = sourceIsItemPile ? sourceUuid : targetUuid;
    sourceIsItemPile ? getToken(sourceUuid) : getToken(targetUuid);
    const shouldBeDeleted = shouldItemPileBeDeleted(itemPileUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(itemPileUuid);
    }
    return attributeDeltas;
  }
  static async _transferEverything(sourceUuid, targetUuid, userId, { itemFilters = false, interactionId } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const itemsToTransfer = getActorItems(sourceActor, { itemFilters }).map((item) => item.toObject());
    const sourceCurrencies = getActorCurrencies(sourceActor);
    const itemCurrenciesToTransfer = sourceCurrencies.filter((currency) => currency.type === "item").map((currency) => ({ id: currency.id, quantity: currency.quantity }));
    const attributesToTransfer = sourceCurrencies.filter((entry) => entry.type === "attribute").map((currency) => ({ path: currency.data.path, quantity: currency.quantity }));
    const sourceTransaction = new Transaction(sourceActor);
    await sourceTransaction.appendItemChanges(itemsToTransfer, { remove: true });
    await sourceTransaction.appendItemChanges(itemCurrenciesToTransfer, {
      remove: true,
      type: "currency"
    });
    await sourceTransaction.appendActorChanges(attributesToTransfer, { remove: true, type: "currency" });
    const sourceUpdates = sourceTransaction.prepare();
    const targetTransaction = new Transaction(targetActor);
    await targetTransaction.appendItemChanges(sourceUpdates.itemDeltas);
    await targetTransaction.appendActorChanges(sourceUpdates.attributeDeltas);
    const targetUpdates = targetTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.PRE_TRANSFER_EVERYTHING, sourceActor, sourceUpdates, targetActor, targetUpdates, interactionId);
    if (hookResult === false)
      return false;
    await sourceTransaction.commit();
    const { itemDeltas, attributeDeltas } = await targetTransaction.commit();
    await ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.CALL_HOOK, CONSTANTS.HOOKS.TRANSFER_EVERYTHING, sourceUuid, targetUuid, itemDeltas, attributeDeltas, userId, interactionId);
    const macroData = {
      action: "transferEverything",
      source: sourceUuid,
      target: targetUuid,
      items: itemDeltas,
      attributes: attributeDeltas,
      userId,
      interactionId
    };
    await this._executeItemPileMacro(sourceUuid, macroData);
    await this._executeItemPileMacro(targetUuid, macroData);
    const shouldBeDeleted = shouldItemPileBeDeleted(sourceUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(sourceUuid);
    }
    return {
      itemsTransferred: itemDeltas,
      attributesTransferred: attributeDeltas
    };
  }
  static async _commitActorChanges(actorUuid, {
    actorUpdates = {},
    itemsToUpdate = [],
    itemsToDelete = [],
    itemsToCreate = []
  } = {}) {
    const actor = getActor(actorUuid);
    if (!foundry.utils.isEmpty(actorUpdates)) {
      await actor.update(actorUpdates);
    }
    const createdItems = itemsToCreate.length ? await actor.createEmbeddedDocuments("Item", itemsToCreate) : [];
    if (itemsToUpdate.length)
      await actor.updateEmbeddedDocuments("Item", itemsToUpdate);
    if (itemsToDelete.length)
      await actor.deleteEmbeddedDocuments("Item", itemsToDelete);
    return createdItems.map((item) => item.toObject());
  }
  /**
   * If not given an actor, this method creates an item pile at a location, then adds an item to it.
   *
   * If a target was provided, it will just add the item to that target actor.
   *
   * If an actor was provided, it will transfer the item from the actor to the target actor.
   *
   * @param {String} userId
   * @param {String} sceneId
   * @param {String/Boolean} [sourceUuid=false]
   * @param {String/Boolean} [targetUuid=false]
   * @param {Object/Boolean} [position=false]
   * @param {Number/Boolean} [elevation=false]
   * @param {Object} [itemData=false]
   *
   * @returns {sourceUuid: string/boolean, targetUuid: string/boolean, position: object/boolean, itemsDropped: array }
   */
  static async _dropItems({
    userId,
    sceneId,
    sourceUuid = false,
    targetUuid = false,
    itemData = false,
    position = false,
    elevation = false
  } = {}) {
    let itemsDropped;
    if (sourceUuid) {
      foundry.utils.setProperty(itemData.item, game.itempiles.API.ITEM_QUANTITY_ATTRIBUTE, itemData.quantity);
      if (targetUuid) {
        itemsDropped = await this._transferItems(sourceUuid, targetUuid, [itemData.item], userId);
      } else {
        itemsDropped = (await this._removeItems(sourceUuid, [itemData.item], userId)).map((item) => {
          item.quantity = Math.abs(item.quantity);
          setItemQuantity(item.item, Math.abs(item.quantity), true);
          return item;
        });
        targetUuid = await this._createItemPile({
          sceneId,
          position,
          items: itemsDropped,
          tokenOverrides: {
            elevation: elevation || fromUuidSync(sourceUuid)?.elevation || 0
          }
        });
      }
    } else {
      if (targetUuid) {
        itemsDropped = await this._addItems(targetUuid, [itemData], userId);
      } else {
        targetUuid = await this._createItemPile({
          sceneId,
          position,
          items: [itemData],
          tokenOverrides: { elevation: elevation || 0 }
        });
      }
    }
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.ITEM.DROP, sourceUuid, targetUuid, itemsDropped, position);
    return { sourceUuid, targetUuid, position, itemsDropped };
  }
  static async _createItemPile({
    sceneId = null,
    position = false,
    actor = false,
    createActor = false,
    items = false,
    tokenOverrides = {},
    actorOverrides = {},
    itemPileFlags = {},
    folders = false
  } = {}) {
    let returns = {};
    let pileActor;
    if (createActor) {
      let pileDataDefaults = foundry.utils.deepClone(CONSTANTS.PILE_DEFAULTS);
      pileDataDefaults.enabled = true;
      if (foundry.utils.isEmpty(itemPileFlags)) {
        pileDataDefaults.deleteWhenEmpty = true;
        pileDataDefaults.displayOne = true;
        pileDataDefaults.showItemName = true;
        pileDataDefaults.overrideSingleItemScale = true;
        pileDataDefaults.singleItemScale = 0.75;
      }
      pileDataDefaults = foundry.utils.mergeObject(pileDataDefaults, itemPileFlags);
      const actorData = {
        name: actor || "New Item Pile",
        type: getSetting("actorClassType"),
        img: "icons/svg/item-bag.svg"
      };
      if (folders) {
        const folder = await createFoldersFromNames(folders);
        if (folder) {
          actorData.folder = folder.id;
        }
      }
      pileActor = await Actor.create(actorData);
      const prototypeTokenData = foundry.utils.mergeObject({
        name: "Item Pile",
        actorLink: false,
        bar1: { attribute: "" },
        vision: false,
        displayName: 50,
        [CONSTANTS.FLAGS.PILE]: pileDataDefaults,
        [CONSTANTS.FLAGS.VERSION]: getModuleVersion(),
        ...getSetting(SETTINGS$1.TOKEN_FLAG_DEFAULTS)
      }, tokenOverrides);
      const actorUpdate = foundry.utils.mergeObject({
        [CONSTANTS.FLAGS.PILE]: pileDataDefaults,
        [CONSTANTS.FLAGS.VERSION]: getModuleVersion(),
        prototypeToken: prototypeTokenData
      }, actorOverrides);
      await pileActor.update(actorUpdate);
    } else if (!actor) {
      pileActor = game.actors.get(getSetting(SETTINGS$1.DEFAULT_ITEM_PILE_ACTOR_ID));
      if (!pileActor) {
        custom_notify("A Default Item Pile has been added to your Actors list. You can configure the default look and behavior on it, or duplicate it to create different styles.");
        let pileDataDefaults = foundry.utils.deepClone(CONSTANTS.PILE_DEFAULTS);
        pileDataDefaults.enabled = true;
        if (foundry.utils.isEmpty(itemPileFlags)) {
          pileDataDefaults.deleteWhenEmpty = true;
          pileDataDefaults.displayOne = true;
          pileDataDefaults.showItemName = true;
          pileDataDefaults.overrideSingleItemScale = true;
          pileDataDefaults.singleItemScale = 0.75;
        }
        pileDataDefaults = foundry.utils.mergeObject(pileDataDefaults, itemPileFlags);
        const actorData = {
          name: "Default Item Pile",
          type: getSetting("actorClassType"),
          img: "icons/svg/item-bag.svg"
        };
        if (folders) {
          const folder = await createFoldersFromNames(folders);
          if (folder) {
            actorData.folder = folder.id;
          }
        }
        pileActor = await Actor.create(actorData);
        await pileActor.update({
          [CONSTANTS.FLAGS.PILE]: pileDataDefaults,
          [CONSTANTS.FLAGS.VERSION]: getModuleVersion(),
          prototypeToken: {
            name: "Item Pile",
            actorLink: false,
            bar1: { attribute: "" },
            vision: false,
            displayName: 50,
            [CONSTANTS.FLAGS.PILE]: pileDataDefaults,
            [CONSTANTS.FLAGS.VERSION]: getModuleVersion(),
            ...getSetting(SETTINGS$1.TOKEN_FLAG_DEFAULTS)
          }
        });
        await game.settings.set(CONSTANTS.MODULE_NAME, SETTINGS$1.DEFAULT_ITEM_PILE_ACTOR_ID, pileActor.id);
      }
    } else {
      pileActor = await fromUuid(actor);
      if (!pileActor) {
        throw custom_error("Could not find actor with UUID " + actor);
      }
    }
    if (items) {
      for (let i = 0; i < items.length; i++) {
        let itemData = items[i]?.item ?? items[i];
        itemData = await Item.implementation.create(itemData, { temporary: true });
        itemData = itemData.toObject();
        if (SYSTEMS.DATA.ITEM_TRANSFORMER) {
          itemData = await SYSTEMS.DATA.ITEM_TRANSFORMER(itemData);
        }
        items[i] = itemData;
      }
    } else {
      items = [];
    }
    items = items ? items.map((item) => {
      return item.item ?? item;
    }) : [];
    if (position && sceneId) {
      let overrideData = foundry.utils.mergeObject({
        ...position,
        ...tokenOverrides,
        ...getSetting(SETTINGS$1.TOKEN_FLAG_DEFAULTS)
      }, {});
      let pileData = getActorFlagData(pileActor);
      pileData.enabled = true;
      pileData = foundry.utils.mergeObject(pileData, itemPileFlags);
      if (!pileActor.prototypeToken.actorLink) {
        overrideData[CONSTANTS.ACTOR_DELTA_PROPERTY] = actorOverrides;
        const data2 = { data: pileData, items: [...items] };
        for (let index2 = 0; index2 < data2.items.length; index2++) {
          data2.items[index2] = await Item.implementation.create(data2.items[index2], { temporary: true });
        }
        const overrideImage = foundry.utils.getProperty(overrideData, "texture.src") ?? foundry.utils.getProperty(overrideData, "img");
        const overrideScale = foundry.utils.getProperty(overrideData, "texture.scaleX") ?? foundry.utils.getProperty(overrideData, "texture.scaleY") ?? foundry.utils.getProperty(overrideData, "scale");
        const scale = getItemPileTokenScale(pileActor, data2, overrideScale);
        overrideData = foundry.utils.mergeObject(overrideData, {
          "texture.src": getItemPileTokenImage(pileActor, data2, overrideImage),
          "texture.scaleX": scale,
          "texture.scaleY": scale,
          "name": getItemPileName(pileActor, data2, overrideData?.name)
        });
      }
      const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_CREATE, overrideData, items);
      if (hookResult === false)
        return false;
      const tokenData = await pileActor.getTokenDocument(overrideData);
      const scene = game.scenes.get(sceneId);
      const [tokenDocument] = await scene.createEmbeddedDocuments("Token", [tokenData]);
      if (items.length && !pileActor.prototypeToken.actorLink) {
        new Promise(async (resolve) => {
          await wait(250);
          await hooks.runWithout(async () => {
            await tokenDocument.actor.createEmbeddedDocuments("Item", items);
          });
          resolve();
        });
      }
      returns["tokenUuid"] = getUuid(tokenDocument);
    } else if (pileActor.prototypeToken.actorLink) {
      if (items.length && !pileActor.prototypeToken.actorLink) {
        await hooks.runWithout(async () => {
          await pileActor.createEmbeddedDocuments("Item", items);
        });
      }
    }
    returns["actorUuid"] = pileActor.uuid;
    return returns;
  }
  static async _turnTokensIntoItemPiles(targetUuids, pileSettings = {}, tokenSettings = {}) {
    const tokenUpdateGroups = {};
    const actorUpdateGroups = {};
    for (const targetUuid of targetUuids) {
      const target = fromUuidSync(targetUuid);
      let targetItemPileSettings = getActorFlagData(target);
      const defaultItemPileId = getSetting(SETTINGS$1.DEFAULT_ITEM_PILE_ACTOR_ID);
      const defaultItemPileActor = game.actors.get(defaultItemPileId);
      if (defaultItemPileActor) {
        const defaultItemPileSettings = getActorFlagData(defaultItemPileActor);
        targetItemPileSettings = foundry.utils.mergeObject(targetItemPileSettings, defaultItemPileSettings);
      }
      let specificPileSettings = foundry.utils.mergeObject(targetItemPileSettings, pileSettings);
      specificPileSettings.enabled = true;
      const targetItems = getActorItems(target, { itemFilters: specificPileSettings.overrideItemFilters });
      const targetCurrencies = getActorCurrencies(target, { currencyList: specificPileSettings.overrideCurrencies });
      const data2 = { data: specificPileSettings, items: targetItems, currencies: targetCurrencies };
      let specificTokenSettings = isFunction(tokenSettings) ? await tokenSettings(target) : foundry.utils.deepClone(tokenSettings);
      const overrideImage = foundry.utils.getProperty(specificTokenSettings, "texture.src") ?? foundry.utils.getProperty(specificTokenSettings, "img");
      const overrideScale = foundry.utils.getProperty(specificTokenSettings, "texture.scaleX") ?? foundry.utils.getProperty(specificTokenSettings, "texture.scaleY") ?? foundry.utils.getProperty(specificTokenSettings, "scale");
      const scale = getItemPileTokenScale(target, data2, overrideScale);
      specificTokenSettings = foundry.utils.mergeObject(specificTokenSettings, {
        "texture.src": getItemPileTokenImage(target, data2, overrideImage),
        "texture.scaleX": scale,
        "texture.scaleY": scale,
        "name": getItemPileName(target, data2, specificTokenSettings?.name)
      });
      const sceneId = targetUuid.split(".")[1];
      const tokenId = targetUuid.split(".")[3];
      if (!tokenUpdateGroups[sceneId]) {
        tokenUpdateGroups[sceneId] = [];
      }
      tokenUpdateGroups[sceneId].push({
        "_id": tokenId,
        ...specificTokenSettings,
        [CONSTANTS.FLAGS.PILE]: specificPileSettings
      });
      if (target.isLinked) {
        if (actorUpdateGroups[target.actor.id])
          continue;
        actorUpdateGroups[target.actor.id] = {
          "_id": target.actor.id,
          [CONSTANTS.FLAGS.PILE]: specificPileSettings
        };
      }
    }
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_TURN_INTO, tokenUpdateGroups, actorUpdateGroups);
    if (hookResult === false)
      return false;
    await Actor.updateDocuments(Object.values(actorUpdateGroups));
    for (const [sceneId, updateData] of Object.entries(tokenUpdateGroups)) {
      const scene = game.scenes.get(sceneId);
      await scene.updateEmbeddedDocuments("Token", updateData);
    }
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.PILE.TURN_INTO, tokenUpdateGroups, actorUpdateGroups);
    return targetUuids;
  }
  static async _revertTokensFromItemPiles(targetUuids, tokenSettings) {
    const actorUpdateGroups = {};
    const tokenUpdateGroups = {};
    for (const targetUuid of targetUuids) {
      let target = fromUuidSync(targetUuid);
      let specificPileSettings = getActorFlagData(target);
      specificPileSettings.enabled = false;
      const sceneId = targetUuid.split(".")[1];
      const tokenId = targetUuid.split(".")[3];
      if (!tokenUpdateGroups[sceneId]) {
        tokenUpdateGroups[sceneId] = [];
      }
      const specificTokenSettings = isFunction(tokenSettings) ? await tokenSettings(target) : foundry.utils.deepClone(tokenSettings);
      tokenUpdateGroups[sceneId].push({
        "_id": tokenId,
        ...specificTokenSettings,
        [CONSTANTS.FLAGS.PILE]: specificPileSettings
      });
      if (target.isLinked) {
        if (actorUpdateGroups[target.actor.id])
          continue;
        actorUpdateGroups[target.actor.id] = {
          "_id": target.actor.id,
          [CONSTANTS.FLAGS.PILE]: specificPileSettings
        };
      }
    }
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_REVERT_FROM, tokenUpdateGroups, actorUpdateGroups);
    if (hookResult === false)
      return false;
    await Actor.updateDocuments(Object.values(actorUpdateGroups));
    for (const [sceneId, updateData] of Object.entries(tokenUpdateGroups)) {
      const scene = game.scenes.get(sceneId);
      await scene.updateEmbeddedDocuments("Token", updateData);
    }
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.PILE.REVERT_FROM, tokenUpdateGroups, actorUpdateGroups);
    return targetUuids;
  }
  static async _updateItemPile(targetUuid, newData, { interactingTokenUuid = false, tokenSettings = false } = {}) {
    const targetActor = getActor(targetUuid);
    const interactingToken = interactingTokenUuid ? getToken(interactingTokenUuid) : false;
    const oldData = getActorFlagData(targetActor);
    const data2 = foundry.utils.mergeObject(foundry.utils.deepClone(oldData), foundry.utils.deepClone(newData));
    const diff = foundry.utils.diffObject(oldData, data2);
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_UPDATE, targetActor, data2, interactingToken, tokenSettings);
    if (hookResult === false)
      return false;
    await wait(15);
    await updateItemPileData(targetActor, data2, tokenSettings);
    if (isItemPileContainer(targetActor, data2)) {
      if (diff?.closed === true) {
        await this._executeItemPileMacro(targetUuid, {
          action: "closeItemPile",
          source: interactingTokenUuid,
          target: targetUuid
        });
      }
      if (diff?.locked === true) {
        await this._executeItemPileMacro(targetUuid, {
          action: "lockItemPile",
          source: interactingTokenUuid,
          target: targetUuid
        });
      }
      if (diff?.locked === false) {
        await this._executeItemPileMacro(targetUuid, {
          action: "unlockItemPile",
          source: interactingTokenUuid,
          target: targetUuid
        });
      }
      if (diff?.closed === false) {
        await this._executeItemPileMacro(targetUuid, {
          action: "openItemPile",
          source: interactingTokenUuid,
          target: targetUuid
        });
      }
    }
    return ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.UPDATED_PILE, targetUuid, diff, interactingTokenUuid);
  }
  static _updatedItemPile(targetUuid, diffData, interactingTokenUuid) {
    const target = getToken(targetUuid);
    const interactingToken = interactingTokenUuid ? fromUuidSync(interactingTokenUuid) : false;
    if (foundry.utils.isEmpty(diffData))
      return false;
    const data2 = getActorFlagData(target);
    hooks.callAll(CONSTANTS.HOOKS.PILE.UPDATE, target, diffData, interactingToken);
    if (isItemPileContainer(target, data2)) {
      if (diffData?.closed === true) {
        hooks.callAll(CONSTANTS.HOOKS.PILE.CLOSE, target, interactingToken);
      }
      if (diffData?.locked === true) {
        hooks.callAll(CONSTANTS.HOOKS.PILE.LOCK, target, interactingToken);
      }
      if (diffData?.locked === false) {
        hooks.callAll(CONSTANTS.HOOKS.PILE.UNLOCK, target, interactingToken);
      }
      if (diffData?.closed === false) {
        hooks.callAll(CONSTANTS.HOOKS.PILE.OPEN, target, interactingToken);
      }
    }
  }
  static async _deleteItemPile(targetUuid) {
    const target = getToken(targetUuid);
    if (!target)
      return false;
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_DELETE, target);
    if (hookResult === false)
      return false;
    return target.document.delete();
  }
  /* -------- PRIVATE ITEM PILE METHODS -------- */
  /**
   * Checks whether a given item pile would need to update its images, text, and/or scale
   *
   * @param {foundry.abstract.Document} doc
   * @param {object} changes
   * @param {boolean} force
   * @returns {*}
   * @private
   */
  static async _evaluateItemPileChange(doc, changes = {}, force = false) {
    const duplicatedChanges = foundry.utils.deepClone(changes);
    const target = doc?.token ?? doc;
    if (!isResponsibleGM())
      return;
    if (!force && !shouldEvaluateChange(target, duplicatedChanges))
      return;
    const targetUuid = target.uuid;
    return debounceManager.setDebounce(targetUuid, async (uuid) => {
      if (!getDocument(uuid))
        return;
      const deleted = shouldItemPileBeDeleted(uuid);
      if (deleted)
        return;
      await hooks.runWithout(async () => {
        await updateItemPileData(uuid);
      });
    })(targetUuid);
  }
  /**
   * Pre-loads all images and sounds related to a given token document on the client-side.
   *
   * @param {TokenDocument} tokenDocument
   * @return {Promise<boolean>}
   */
  static async _preloadItemPileFiles(tokenDocument) {
    if (!isItemPileContainer(tokenDocument))
      return false;
    const pileData = getActorFlagData(tokenDocument);
    if (getSetting("preloadFiles")) {
      await Promise.allSettled(Object.entries(pileData).map((entry) => {
        return new Promise(async (resolve) => {
          const [property, filePath] = entry;
          if (Array.isArray(filePath)) {
            return resolve();
          }
          const isImage = property.toLowerCase().includes("image");
          const isSound = property.toLowerCase().includes("sound");
          if (!isImage && !isSound || (!filePath || preloadedFiles.has(filePath)))
            return resolve();
          preloadedFiles.add(filePath);
          if (isImage) {
            await loadTexture(filePath);
            debug(`Preloaded image: ${filePath}`);
          } else if (isSound) {
            debug(`Preloaded sound: ${filePath}`);
            await AudioHelper.preloadSound(filePath);
          }
          resolve();
        });
      }));
    }
    debug(`Initialized item pile with uuid ${tokenDocument.uuid}`);
  }
  /**
   * This executes any macro that is configured on the item pile, providing the macro with extra data relating to the
   * action that prompted the execution (if the advanced-macros module is installed)
   *
   * @param {String} targetUuid
   * @param {Object} macroData
   * @return {Promise/Boolean}
   */
  static async _executeItemPileMacro(targetUuid, macroData) {
    const target = getToken(targetUuid);
    if (!isValidItemPile(target))
      return false;
    const pileData = getActorFlagData(target);
    if (!pileData.macro)
      return false;
    if (macroData.source) {
      macroData.source = fromUuidSync(macroData.source);
    }
    if (Array.isArray(macroData.target)) {
      macroData.target = macroData.target.map((target2) => fromUuidSync(target2));
    } else {
      if (macroData.target) {
        macroData.target = fromUuidSync(macroData.target);
      }
      const sourceActor = macroData.source instanceof TokenDocument ? macroData.source.actor : macroData.source;
      const targetActor = macroData.target instanceof TokenDocument ? macroData.target.actor : macroData.target;
      if (macroData.items) {
        macroData.items = macroData.items.map((item) => targetActor.items.get(item?.item?._id ?? item._id));
      }
      if (macroData.sourceItems) {
        macroData.sourceItems = macroData.sourceItems.map((item) => sourceActor.items.get(item?.item?._id ?? item._id));
      }
      if (macroData.targetItems) {
        macroData.targetItems = macroData.targetItems.map((item) => targetActor.items.get(item?.item?._id ?? item._id));
      }
    }
    return runMacro(pileData.macro, macroData);
  }
  /**
   * This handles any dropped data onto the canvas or a set item pile
   *
   * @param {canvas} canvas
   * @param {Object} data
   * @return {Promise}
   */
  static async _dropData(canvas2, data2) {
    if (data2.type !== "Item")
      return;
    let item = await Item.implementation.fromDropData(data2);
    let itemData = item ? item.toObject() : false;
    if (!itemData) {
      console.error(data2);
      throw custom_error("Something went wrong when dropping this item!");
    }
    const dropData = {
      source: false,
      target: data2?.target ?? false,
      elevation: data2?.elevation,
      itemData: {
        item: itemData,
        quantity: 1
      },
      position: false
    };
    dropData.source = getSourceActorFromDropData(data2);
    if (!dropData.source && !game.user.isGM) {
      return custom_warning(game.i18n.localize("ITEM-PILES.Errors.NoSourceDrop"), true);
    }
    const pre_drop_determined_hook = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_DROP_DETERMINED, dropData.source, dropData.target, dropData.itemData, dropData.position);
    if (pre_drop_determined_hook === false)
      return;
    let droppableDocuments = [];
    let x, y;
    if (dropData.target) {
      droppableDocuments.push(dropData.target);
    } else {
      const position = canvas2.grid.getTopLeft(data2.x, data2.y);
      x = position[0];
      y = position[1];
      droppableDocuments = getTokensAtLocation({ x, y }).map((token) => getDocument(token));
      if (droppableDocuments.length && game.modules.get("midi-qol")?.active && game.settings.get("midi-qol", "DragDropTarget")) {
        custom_warning("You have Drag & Drop Targetting enabled in MidiQOL, which disables drag & drop items");
        return;
      }
      if (!droppableDocuments.length) {
        dropData.position = { x, y };
      }
    }
    const droppableItemPiles = droppableDocuments.filter((token) => isValidItemPile(token));
    const droppableNormalTokens = droppableDocuments.filter((token) => !isValidItemPile(token));
    dropData.target = droppableItemPiles?.[0] ?? droppableNormalTokens[0];
    const sourceIsVault = dropData.source ? isItemPileVault(dropData.source) : false;
    const targetIsVault = isItemPileVault(dropData.target);
    const targetIsItemPile = isValidItemPile(droppableItemPiles[0]);
    const canGiveItems = getSetting(SETTINGS$1.ENABLE_GIVING_ITEMS);
    const canDropItems = getSetting(SETTINGS$1.ENABLE_DROPPING_ITEMS);
    const givingItem = canGiveItems && dropData.target && !targetIsItemPile;
    const droppingItem = canDropItems && (dropData.target || dropData.position);
    if ((sourceIsVault || targetIsVault) && dropData.target) {
      return this._depositWithdrawItem(dropData, sourceIsVault, targetIsVault);
    } else if (givingItem && canGiveItems) {
      return this._giveItem(dropData);
    } else if (droppingItem && canDropItems) {
      return this._dropItem(dropData);
    }
  }
  static async _depositWithdrawItem(dropData, sourceIsVault = false, targetIsVault = true) {
    const sourceActor = getActor(dropData.source);
    const targetActor = getActor(dropData.target);
    if (sourceActor && targetActor && sourceActor === targetActor)
      return;
    const vaultActor = !sourceIsVault && targetIsVault || !sourceActor ? targetActor : sourceActor;
    const localization = !sourceIsVault && targetIsVault || !sourceActor ? "DepositItem" : "WithdrawItem";
    const validItem = await checkItemType(vaultActor, dropData.itemData.item);
    if (!validItem)
      return;
    dropData.itemData.item = validItem;
    const item = await Item.implementation.create(dropData.itemData.item, { temporary: true });
    let itemQuantity = getItemQuantity(dropData.itemData.item);
    if (canItemStack(dropData.itemData.item, vaultActor)) {
      if (itemQuantity > 1) {
        dropData.itemData.quantity = await DropItemDialog.show(item, vaultActor, {
          localizationTitle: localization
        });
      } else if (!itemQuantity || itemQuantity <= 0) {
        custom_warning(game.i18n.localize("ITEM-PILES.Errors.ItemNoQuantity"), true);
        return;
      }
    } else {
      dropData.itemData.quantity = 1;
    }
    setItemQuantity(dropData.itemData.item, dropData.itemData.quantity);
    let flagData = getItemFlagData(dropData.itemData.item);
    if (!sourceIsVault && targetIsVault) {
      foundry.utils.setProperty(flagData, "x", dropData.gridPosition?.x ?? 0);
      foundry.utils.setProperty(flagData, "y", dropData.gridPosition?.y ?? 0);
    }
    foundry.utils.setProperty(dropData.itemData, "flags", flagData);
    if (sourceActor) {
      return game.itempiles.API.transferItems(sourceActor, targetActor, [dropData.itemData], { interactionId: dropData.interactionId });
    }
    if (!game.user.isGM)
      return;
    return game.itempiles.API.addItems(targetActor, [dropData.itemData], { interactionId: dropData.interactionId });
  }
  static async _dropItem(dropData) {
    const sourceActor = getActor(dropData.source);
    const targetActor = getActor(dropData.target);
    if (sourceActor && targetActor && sourceActor === targetActor)
      return;
    if (dropData.target && isItemPileMerchant(dropData.target))
      return;
    const validItem = await checkItemType(dropData.target, dropData.itemData.item);
    if (!validItem)
      return;
    dropData.itemData.item = validItem;
    if (dropData.target && !dropData.position && !game.user.isGM) {
      if (!(dropData.target instanceof Actor && dropData.source instanceof Actor)) {
        const sourceToken = canvas.tokens.placeables.find((token) => token.actor === dropData.source);
        if (sourceToken) {
          const distance = Math.floor(distance_between_rect(sourceToken, dropData.target.object) / canvas.grid.size) + 1;
          const pileData = getActorFlagData(dropData.target);
          const maxDistance = pileData?.distance ? pileData?.distance : Infinity;
          if (distance > maxDistance) {
            custom_warning(game.i18n.localize("ITEM-PILES.Errors.PileTooFar"), true);
            return;
          }
        }
      }
      if (game.itempiles.API.isItemPileLocked(dropData.target)) {
        custom_warning(game.i18n.localize("ITEM-PILES.Errors.PileLocked"), true);
        return;
      }
    }
    dropData.itemData.quantity = 1;
    if (canItemStack(dropData.itemData.item, targetActor)) {
      let itemQuantity = getItemQuantity(dropData.itemData.item);
      if (!itemQuantity || itemQuantity <= 0) {
        custom_warning(game.i18n.localize("ITEM-PILES.Errors.ItemNoQuantity"), true);
        return;
      }
      if (!hotkeyActionState.forceDropOneItem) {
        if (!dropData.skipCheck) {
          const item = await Item.implementation.create(dropData.itemData.item, { temporary: true });
          itemQuantity = await DropItemDialog.show(item, dropData.target, { unlimitedQuantity: !dropData.source && game.user.isGM });
          if (!itemQuantity)
            return;
        }
        dropData.itemData.quantity = Number(itemQuantity);
      }
    }
    setItemQuantity(dropData.itemData.item, dropData.itemData.quantity);
    const hookResult = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_DROP, dropData.source, dropData.target, dropData.position, dropData.itemData);
    if (hookResult === false)
      return;
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.DROP_ITEMS, {
      userId: game.user.id,
      sceneId: canvas?.scene?.id ?? "",
      sourceUuid: getUuid(dropData.source),
      targetUuid: getUuid(dropData.target),
      position: dropData.position,
      elevation: dropData.elevation,
      itemData: dropData.itemData
    });
  }
  static async _giveItem(dropData, options = {}) {
    const sourceActor = getActor(dropData.source);
    const targetActor = getActor(dropData.target);
    if (sourceActor === targetActor)
      return;
    const sourceUuid = getUuid(sourceActor);
    const targetUuid = getUuid(targetActor);
    const validItem = await checkItemType(dropData.target, dropData.itemData.item);
    if (!validItem)
      return;
    dropData.itemData.item = validItem;
    const actorOwners = Object.entries(targetActor.ownership).filter((entry) => {
      return entry[0] !== "default" && entry[1] === CONST.DOCUMENT_PERMISSION_LEVELS.OWNER;
    }).map((entry) => game.users.get(entry[0])).sort((user2) => user2.isGM ? 1 : -1);
    let user = actorOwners?.[0];
    if (user && !user?.active) {
      user = getActiveGMs()?.[0];
    }
    if (user && !user?.active && !game.user.isGM) {
      return TJSDialog.prompt({
        title: game.i18n.localize("ITEM-PILES.Dialogs.GiveItemUserNotActive.Title"),
        content: {
          class: CustomDialog,
          props: {
            content: game.i18n.format("ITEM-PILES.Dialogs.GiveItemUserNotActive.Content", {
              actor_name: targetActor.name,
              user_name: user.name
            })
          }
        }
      });
    }
    const item = await Item.implementation.create(dropData.itemData.item, { temporary: true });
    if (!sourceActor && game.user.isGM) {
      custom_notify(game.i18n.format("ITEM-PILES.Notifications.ItemAdded", {
        target_actor_name: targetActor.name,
        item_name: item.name
      }));
      return this._addItems(targetUuid, [dropData.itemData.item], game.user.id);
    }
    const gms = getActiveGMs().map((user2) => user2.id);
    if (user?.active || gms.length || game.user.isGM) {
      dropData.itemData.quantity = 1;
      if (canItemStack(dropData.itemData.item)) {
        let itemQuantity = getItemQuantity(item);
        if (!itemQuantity || itemQuantity <= 0) {
          custom_warning(game.i18n.localize("ITEM-PILES.Errors.ItemNoQuantity"), true);
          return;
        }
        if (!options?.skipQuantityDialog) {
          dropData.itemData.quantity = await DropItemDialog.show(item, dropData.target.actor, {
            localizationTitle: "GiveItem"
          });
        }
      }
      setItemQuantity(dropData.itemData.item, dropData.itemData.quantity);
      if (Hooks.call(CONSTANTS.HOOKS.ITEM.PRE_GIVE, sourceActor, targetActor, dropData.itemData, user.id) === false) {
        return;
      }
      if ((!user || !user?.active || user === game.user) && game.user.isGM) {
        if (sourceActor) {
          custom_notify(game.i18n.format("ITEM-PILES.Notifications.ItemTransferred", {
            source_actor_name: sourceActor.name,
            target_actor_name: targetActor.name,
            item_name: item.name
          }));
          Hooks.callAll(CONSTANTS.HOOKS.ITEM.GIVE, sourceActor, targetActor, dropData.itemData, game.user.id);
          return this._transferItems(sourceUuid, targetUuid, [dropData.itemData.item], game.user.id);
        }
      }
      return ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.GIVE_ITEMS, [user ? user.id : gms[0]], {
        userId: game.user.id,
        sourceUuid,
        targetUuid,
        itemData: dropData.itemData
      });
    }
  }
  static async _giveItems({ userId, sourceUuid, targetUuid, itemData } = {}) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const item = await Item.implementation.create(itemData.item, { temporary: true });
    const accepted = await TJSDialog.confirm({
      title: "Item Piles - " + game.i18n.localize("ITEM-PILES.Dialogs.ReceiveItem.Title"),
      content: {
        class: Receive_items_shell,
        props: {
          sourceActor,
          targetActor,
          quantity: itemData.quantity,
          item
        }
      }
    });
    if (accepted) {
      await _PrivateAPI._addItems(targetUuid, [itemData], game.user.id);
    }
    return ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.GIVE_ITEMS_RESPONSE, [userId], {
      userId: game.user.id,
      accepted,
      sourceUuid,
      targetUuid,
      itemData
    });
  }
  static async _giveItemsResponse({ userId, accepted, sourceUuid, targetUuid, itemData } = {}) {
    const user = game.users.get(userId);
    if (accepted) {
      await ItemPileSocket.callHook(CONSTANTS.HOOKS.ITEM.GIVE, sourceUuid, targetUuid, itemData, game.user.id, userId);
      await _PrivateAPI._removeItems(sourceUuid, [itemData], game.user.id);
      return custom_notify(game.i18n.format("ITEM-PILES.Notifications.GiveItemAccepted", { user_name: user.name }));
    }
    return custom_warning(game.i18n.format("ITEM-PILES.Warnings.GiveItemDeclined", { user_name: user.name }), true);
  }
  static async _itemPileClicked(pileDocument) {
    if (!isValidItemPile(pileDocument))
      return;
    if (isItemPileLootable(pileDocument) && !isGMConnected()) {
      custom_warning(`Item Piles requires a GM to be connected for players to be able to loot item piles.`, true);
      return;
    }
    const pileToken = pileDocument.object;
    debug(`Clicked: ${pileDocument.uuid}`);
    const pileData = getActorFlagData(pileDocument);
    const maxDistance = pileData.distance ? pileData.distance : Infinity;
    let validTokens = [];
    let playerToken = false;
    if (game.user.character) {
      playerToken = canvas.tokens.placeables.find((token) => token.actor === game.user.character && tokens_close_enough(pileToken, token, maxDistance));
    }
    if (!playerToken && canvas.tokens.controlled.length > 0) {
      validTokens = [...canvas.tokens.controlled];
      validTokens = validTokens.filter((token) => token.document !== pileDocument);
    } else if (game.user.character) {
      if (playerToken) {
        validTokens.push(playerToken);
      }
    }
    if (!validTokens.length && !game.user.isGM) {
      validTokens.push(...canvas.tokens.placeables);
      if (_token) {
        validTokens.unshift(_token);
      }
    }
    validTokens = validTokens.filter((token) => token.owner && token.document !== pileDocument).filter((token) => {
      return tokens_close_enough(pileToken, token, maxDistance) || game.user.isGM;
    });
    let interactingActor;
    if (!validTokens.length && !game.user.isGM) {
      if (maxDistance === Infinity) {
        interactingActor = getUserCharacter();
      }
      if (!interactingActor) {
        custom_warning(game.i18n.localize(maxDistance === Infinity ? "ITEM-PILES.Errors.NoTokenFound" : "ITEM-PILES.Errors.PileTooFar"), true);
        return;
      }
    }
    if (!interactingActor && validTokens.length) {
      if (validTokens.includes(_token)) {
        interactingActor = _token.actor;
      } else if (validTokens.includes(playerToken)) {
        interactingActor = playerToken.actor;
      } else {
        validTokens.sort((potentialTargetA, potentialTargetB) => {
          return grids_between_tokens(pileToken, potentialTargetA) - grids_between_tokens(pileToken, potentialTargetB);
        });
        interactingActor = validTokens[0].actor;
      }
    }
    if (isItemPileContainer(pileDocument) && interactingActor) {
      if (pileData.locked && !game.user.isGM) {
        debug(`Attempted to open locked item pile with UUID ${pileDocument.uuid}`);
        return game.itempiles.API.rattleItemPile(pileDocument, interactingActor);
      }
      if (pileData.closed) {
        debug(`Opened item pile with UUID ${pileDocument.uuid}`);
        await game.itempiles.API.openItemPile(pileDocument, interactingActor);
      }
    }
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_CLICK, pileDocument, interactingActor);
    if (hookResult === false)
      return;
    return this._renderItemPileInterface(pileDocument.uuid, { inspectingTargetUuid: interactingActor?.uuid });
  }
  static async _splitItemPileContents(itemPileUuid, actorUuids, userId, instigator) {
    const itemPileActor = getActor(itemPileUuid);
    const items = getActorItems(itemPileActor);
    const currencies = getActorCurrencies(itemPileActor);
    const pileData = getActorFlagData(itemPileActor);
    const shareData = getItemPileSharingData(itemPileActor);
    const tempPileTransaction = new Transaction(itemPileActor);
    const numPlayers = actorUuids.length;
    if (pileData.shareItemsEnabled) {
      const itemsToRemove = items.map((item) => {
        const itemData = item.toObject();
        const quantity = Math.floor(getItemQuantity(itemData) / numPlayers) * numPlayers;
        return {
          item: itemData,
          quantity
        };
      }).filter((entry) => entry.quantity);
      await tempPileTransaction.appendItemChanges(itemsToRemove, { remove: true });
    }
    const currencyItems = currencies.filter((entry) => entry.type === "item").map((entry) => {
      const itemData = entry.item.toObject();
      const quantity = Math.floor(getItemQuantity(itemData) / numPlayers) * numPlayers;
      return {
        item: itemData,
        quantity
      };
    }).filter((entry) => entry.quantity);
    await tempPileTransaction.appendItemChanges(currencyItems, { remove: true, type: "currency" });
    const attributes = currencies.filter((entry) => entry.type === "attribute").map((attribute) => {
      return {
        ...attribute,
        quantity: Math.floor(attribute.quantity / numPlayers) * numPlayers
      };
    });
    await tempPileTransaction.appendActorChanges(attributes, { remove: true, type: "currency" });
    const preparedData = tempPileTransaction.prepare();
    const transactionMap = actorUuids.map((uuid) => {
      return [uuid, new Transaction(getActor(uuid))];
    });
    for (const [uuid, transaction] of transactionMap) {
      if (pileData.shareItemsEnabled) {
        await transaction.appendItemChanges(foundry.utils.deepClone(preparedData).itemDeltas.filter((delta) => delta.type === "item").map((delta) => {
          delta.quantity = getItemSharesLeftForActor(itemPileActor, delta.item, transaction.actor, {
            players: numPlayers,
            shareData,
            floor: true
          });
          return delta;
        }));
      }
      if (pileData.shareCurrenciesEnabled || pileData.splitAllEnabled) {
        await transaction.appendItemChanges(foundry.utils.deepClone(preparedData).itemDeltas.filter((delta) => delta.type === "currency").map((delta) => {
          delta.quantity = getItemSharesLeftForActor(itemPileActor, delta.item, transaction.actor, {
            players: numPlayers,
            shareData,
            floor: true
          });
          return delta;
        }), { type: "currency" });
        await transaction.appendActorChanges(Object.entries(foundry.utils.deepClone(preparedData).attributeDeltas).map((entry) => {
          let [path] = entry;
          const quantity = getAttributeSharesLeftForActor(itemPileActor, path, transaction.actor, {
            players: numPlayers,
            shareData,
            floor: true
          });
          return { path, quantity };
        }));
      }
    }
    const actorPreparedData = Object.fromEntries(transactionMap.map((entry) => [entry[0], entry[1].prepare()]));
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_SPLIT_INVENTORY, itemPileActor, preparedData, actorPreparedData, userId, instigator);
    if (hookResult === false)
      return false;
    const pileDeltas = await tempPileTransaction.commit();
    const actorDeltas = {};
    for (const [uuid, transaction] of transactionMap) {
      actorDeltas[uuid] = await transaction.commit();
    }
    await clearItemPileSharingData(itemPileActor);
    await ItemPileSocket.callHook(CONSTANTS.HOOKS.PILE.SPLIT_INVENTORY, itemPileUuid, pileDeltas, actorDeltas, userId, instigator);
    await this._executeItemPileMacro(itemPileUuid, {
      action: "splitInventory",
      source: itemPileUuid,
      target: actorUuids,
      transfers: {
        pileDeltas,
        actorDeltas
      },
      userId,
      instigator
    });
    const shouldBeDeleted = shouldItemPileBeDeleted(itemPileUuid);
    if (shouldBeDeleted) {
      await this._deleteItemPile(itemPileUuid);
    }
    return {
      pileDeltas,
      actorDeltas
    };
  }
  static async _updateTokenHud() {
    if (!canvas.tokens.hud.rendered)
      return;
    return canvas.tokens.hud.render(true);
  }
  static async _renderItemPileInterface(targetUuid, {
    inspectingTargetUuid = false,
    useDefaultCharacter = false,
    remote = false
  } = {}) {
    const target = getActor(targetUuid);
    let inspectingTarget;
    if (useDefaultCharacter) {
      inspectingTarget = getUserCharacter();
    } else {
      inspectingTarget = inspectingTargetUuid ? fromUuidSync(inspectingTargetUuid) : false;
    }
    const hookResult = Hooks.call(CONSTANTS.HOOKS.PRE_RENDER_INTERFACE, target, inspectingTarget);
    if (hookResult === false)
      return;
    if (isItemPileVault(target)) {
      return VaultApp.show(target, inspectingTarget);
    }
    if (isItemPileMerchant(target)) {
      return MerchantApp.show(target, inspectingTarget);
    }
    return ItemPileInventoryApp.show(target, inspectingTarget, { remote });
  }
  static async _unrenderItemPileInterface(targetUuid, { remote = false } = {}) {
    const target = getActor(targetUuid);
    return Promise.allSettled(Object.values(ui.windows).filter((app) => {
      return app.id.includes(`-${target.id}-`) || app?.actor === target || app?.merchant === target;
    }).map((app) => app.close()));
  }
  static async _tradeItems(sellerUuid, buyerUuid, items, userId, { interactionId = false } = {}) {
    const sellingActor = getActor(sellerUuid);
    const buyingActor = getActor(buyerUuid);
    const itemPrices = getPaymentData({
      purchaseData: items.map((data2) => {
        return {
          ...data2,
          item: sellingActor.items.get(data2.id)
        };
      }),
      seller: sellingActor,
      buyer: buyingActor
    });
    const preCalcHookResult = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_CALC_TRADE, sellingActor, buyingActor, itemPrices, userId, interactionId);
    if (preCalcHookResult === false)
      return false;
    const sellerTransaction = new Transaction(sellingActor);
    const sellerFlagData = getActorFlagData(sellerTransaction);
    const sellerIsMerchant = isItemPileMerchant(sellingActor, sellerFlagData);
    const sellerInfiniteQuantity = sellerIsMerchant && sellerFlagData.infiniteQuantity;
    const sellerInfiniteCurrencies = sellerIsMerchant && sellerFlagData.infiniteCurrencies;
    const sellerKeepZeroQuantity = sellerIsMerchant && sellerFlagData.keepZeroQuantity;
    for (const payment of itemPrices.sellerReceive) {
      if (!payment.quantity)
        continue;
      if (payment.type === "attribute") {
        await sellerTransaction.appendActorChanges([{
          path: payment.data.path,
          quantity: payment.quantity
        }], { type: payment.isCurrency ? "currency" : payment.type });
      } else {
        await sellerTransaction.appendItemChanges([{
          item: payment.data.item,
          quantity: payment.quantity
        }], { type: payment.isCurrency ? "currency" : payment.type });
      }
    }
    for (const entry of itemPrices.buyerReceive) {
      if (!entry.quantity) {
        continue;
      }
      const onlyDelta = sellerInfiniteCurrencies && entry.isCurrency || sellerInfiniteQuantity && !entry.isCurrency;
      if (entry.type === "attribute") {
        await sellerTransaction.appendActorChanges([{
          path: entry.data.path,
          quantity: entry.quantity
        }], {
          remove: true,
          type: entry.isCurrency ? "currency" : entry.type,
          onlyDelta
        });
      } else {
        const itemFlagData = getItemFlagData(entry.item);
        const itemInfiniteQuantity = {
          "default": sellerFlagData?.infiniteQuantity ?? false,
          "yes": true,
          "no": false
        }[itemFlagData.infiniteQuantity ?? "default"];
        if (sellerIsMerchant && itemInfiniteQuantity)
          continue;
        await sellerTransaction.appendItemChanges([{
          item: entry.item,
          quantity: entry.quantity
        }], {
          remove: true,
          type: entry.isCurrency ? "currency" : entry.type,
          keepIfZero: itemFlagData.isService || sellerKeepZeroQuantity || itemFlagData.keepZeroQuantity,
          onlyDelta
        });
      }
    }
    const buyerTransaction = new Transaction(buyingActor);
    const buyerFlagData = getActorFlagData(buyingActor);
    const buyerIsMerchant = isItemPileMerchant(buyingActor, buyerFlagData);
    const buyerInfiniteCurrencies = buyerIsMerchant && buyerFlagData.infiniteCurrencies;
    const buyerInfiniteQuantity = buyerIsMerchant && buyerFlagData.infiniteQuantity;
    const buyerHidesNewItems = buyerIsMerchant && buyerFlagData.hideNewItems;
    for (const price of itemPrices.finalPrices) {
      if (!price.quantity) {
        continue;
      }
      const onlyDelta = buyerInfiniteCurrencies && price.isCurrency || buyerInfiniteQuantity && !price.isCurrency;
      if (price.type === "attribute") {
        await buyerTransaction.appendActorChanges([{
          path: price.data.path,
          quantity: price.quantity
        }], { remove: true, type: price.isCurrency ? "currency" : price.type, onlyDelta });
      } else {
        await buyerTransaction.appendItemChanges([{
          item: price.data.item,
          quantity: price.quantity
        }], { remove: true, type: price.isCurrency ? "currency" : price.type, onlyDelta });
      }
    }
    for (const entry of itemPrices.buyerReceive) {
      if (!entry.quantity)
        continue;
      if (entry.type === "attribute") {
        await buyerTransaction.appendActorChanges([{
          path: entry.data.path,
          quantity: entry.quantity
        }], { type: entry.type });
      } else {
        const itemFlagData = getItemFlagData(entry.item);
        if (itemFlagData.isService)
          continue;
        const item = entry.item.toObject();
        if (buyerHidesNewItems) {
          foundry.utils.setProperty(item, CONSTANTS.FLAGS.ITEM + ".hidden", true);
        }
        await buyerTransaction.appendItemChanges([{
          item,
          quantity: entry.quantity
        }], { type: entry.type });
      }
    }
    for (const change of itemPrices.buyerChange) {
      if (!change.quantity)
        continue;
      if (change.type === "attribute") {
        await buyerTransaction.appendActorChanges([{
          path: change.data.path,
          quantity: change.quantity
        }], { type: "currency" });
      } else {
        await buyerTransaction.appendItemChanges([{
          item: change.data.item,
          quantity: change.quantity
        }], { type: "currency" });
      }
    }
    const sellerUpdates = sellerTransaction.prepare();
    const buyerUpdates = buyerTransaction.prepare();
    const hookResult = hooks.call(CONSTANTS.HOOKS.ITEM.PRE_TRADE, sellingActor, sellerUpdates, buyingActor, buyerUpdates, userId, interactionId);
    if (hookResult === false)
      return false;
    const sellerTransactionData = await sellerTransaction.commit();
    const buyerTransactionData = await buyerTransaction.commit();
    const itemPileActorUuid = sellerIsMerchant ? sellerUuid : buyerUuid;
    await this._executeItemPileMacro(itemPileActorUuid, {
      action: "tradeItems",
      source: sellerUuid,
      target: buyerUuid,
      sourceIsMerchant: sellerIsMerchant,
      sourceItems: sellerTransactionData.itemDeltas,
      sourceAttributes: sellerTransactionData.attributeDeltas,
      targetItems: buyerTransactionData.itemDeltas,
      targetAttributes: buyerTransactionData.attributeDeltas,
      prices: itemPrices,
      userId,
      interactionId
    });
    const merchantFlagData = sellerIsMerchant ? sellerFlagData : buyerFlagData;
    if (merchantFlagData.logMerchantActivity) {
      const merchantActor = sellerIsMerchant ? sellingActor : buyingActor;
      const regularActor = sellerIsMerchant ? buyingActor : sellingActor;
      await updateMerchantLog(merchantActor, {
        type: "transaction",
        actor: regularActor.name,
        user: userId,
        item: itemPrices["buyerReceive"][0].name,
        qty: itemPrices["buyerReceive"][0].quantity,
        price: itemPrices.basePriceString,
        sold: !sellerIsMerchant
      });
    }
    if (sellerIsMerchant) {
      for (let entry of itemPrices.buyerReceive) {
        const itemFlagData = getItemFlagData(entry.item);
        if (!itemFlagData.macro)
          continue;
        await runMacro(itemFlagData.macro, {
          seller: sellingActor,
          buyer: buyingActor,
          item: entry.item,
          quantity: entry.quantity,
          userId
        });
      }
    }
    await ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.CALL_HOOK, CONSTANTS.HOOKS.ITEM.TRADE, sellerUuid, buyerUuid, itemPrices, userId, interactionId);
    return {
      itemDeltas: buyerTransactionData.itemDeltas,
      attributeDeltas: buyerTransactionData.attributeDeltas,
      itemPrices
    };
  }
  static async _rollItemTable({
    table = "",
    timesToRoll = "1",
    resetTable = true,
    normalizeTable = false,
    displayChat = false,
    rollData = {},
    customCategory = false,
    targetActor = false,
    removeExistingActorItems = false,
    userId = false
  } = {}) {
    let items = await rollTable({
      tableUuid: table,
      formula: timesToRoll,
      normalize: normalizeTable,
      resetTable,
      displayChat,
      rollData,
      customCategory
    });
    if (targetActor) {
      const itemsToAdd = items.map((item) => {
        const actualItem = item.item.toObject();
        return setItemQuantity(actualItem, item.quantity);
      });
      items = await this._addItems(targetActor, itemsToAdd, userId, { removeExistingActorItems });
    }
    return items;
  }
  static async _refreshMerchantInventory(merchantUuid, {
    removeExistingActorItems = false,
    userId = false
  } = {}) {
    const merchant = getActor(merchantUuid);
    const items = await rollMerchantTables({ actor: merchant });
    const itemsToAdd = items.map((item) => {
      const actualItem = item.item.toObject();
      return setItemQuantity(actualItem, item.quantity);
    });
    return this._addItems(merchantUuid, itemsToAdd, userId, { removeExistingActorItems });
  }
};
__name(_PrivateAPI, "PrivateAPI");
let PrivateAPI = _PrivateAPI;
const HOTKEYS = {
  FORCE_DEFAULT_SHEET: "force-open-item-pile-inventory",
  DROP: "force-drop-item",
  DROP_ONE: "force-drop-one-item"
};
const hotkeyActionState = {
  get openPileInventory() {
    const down = game.keybindings.get(CONSTANTS.MODULE_NAME, HOTKEYS.FORCE_DEFAULT_SHEET).some((keybind) => {
      return window.keyboard.downKeys.has(keybind?.key);
    });
    return !down && !game.settings.get(CONSTANTS.MODULE_NAME, "invertSheetOpen") || down && game.settings.get(CONSTANTS.MODULE_NAME, "invertSheetOpen");
  },
  get forceDropItem() {
    return game.keybindings.get(CONSTANTS.MODULE_NAME, HOTKEYS.DROP).some((key) => {
      return window.keyboard.downKeys.has(key);
    });
  },
  get forceDropOneItem() {
    return game.keybindings.get(CONSTANTS.MODULE_NAME, HOTKEYS.DROP).some((key) => {
      return window.keyboard.downKeys.has(key);
    });
  }
};
function registerHotkeysPre() {
  game.keybindings.register(CONSTANTS.MODULE_NAME, HOTKEYS.FORCE_DEFAULT_SHEET, {
    name: "Force open inventory modifier",
    editable: [
      { key: "ControlLeft" }
    ]
  });
  game.keybindings.register(CONSTANTS.MODULE_NAME, HOTKEYS.DROP, {
    name: "Force drop item (GM only) modifier",
    editable: [
      { key: "ShiftLeft" }
    ]
  });
  game.keybindings.register(CONSTANTS.MODULE_NAME, HOTKEYS.DROP_ONE, {
    name: "Force drop one item modifier",
    editable: [
      { key: "AltLeft" }
    ]
  });
}
__name(registerHotkeysPre, "registerHotkeysPre");
function registerHotkeysPost() {
  if (!game.user.isGM) {
    let clicked = false;
    window.addEventListener("mousedown", (event) => {
      if (!canvas.ready)
        return;
      if (!(canvas.activeLayer instanceof TokenLayer))
        return;
      if (game.activeTool !== "select")
        return;
      const hover = document.elementFromPoint(event.clientX, event.clientY);
      if (!hover || hover.id !== "board")
        return;
      if (event.button !== 0)
        return;
      const pos = getCanvasMouse().getLocalPosition(canvas.app.stage);
      const tokens = getTokensAtLocation(pos).filter((token2) => {
        const canView = token2._canView(game.user);
        const canSee = token2.visible || game.user.isGM;
        return !canView && canSee;
      });
      if (!tokens.length)
        return;
      tokens.sort((a, b) => b.zIndex - a.zIndex);
      const token = getDocument(tokens[0]);
      if (clicked === token) {
        clicked = false;
        return PrivateAPI._itemPileClicked(token);
      }
      clicked = token;
      setTimeout(() => {
        clicked = false;
      }, 500);
    });
  }
}
__name(registerHotkeysPost, "registerHotkeysPost");
function getFlagData(inDocument, flag, defaults, existing = false) {
  const defaultFlags = foundry.utils.deepClone(defaults);
  let flags = foundry.utils.deepClone(existing || (getProperty(inDocument, flag) ?? {}));
  if (flag === CONSTANTS.FLAGS.PILE) {
    flags = migrateFlagData(inDocument, flags);
  }
  return foundry.utils.mergeObject(defaultFlags, flags);
}
__name(getFlagData, "getFlagData");
function migrateFlagData(document2, data2 = false) {
  let flags = data2 || getProperty(document2, CONSTANTS.FLAGS.PILE);
  if (flags.type) {
    return flags;
  }
  if (flags.isMerchant) {
    flags.type = CONSTANTS.PILE_TYPES.MERCHANT;
  } else if (flags.isContainer) {
    flags.type = CONSTANTS.PILE_TYPES.CONTAINER;
  } else {
    flags.type = CONSTANTS.PILE_TYPES.PILE;
  }
  return flags;
}
__name(migrateFlagData, "migrateFlagData");
function areItemsColliding(itemA, itemB) {
  const itemAFlags = getItemFlagData(itemA);
  const itemBFlags = getItemFlagData(itemB);
  return itemAFlags.x + (itemAFlags.width - 1) >= itemBFlags.x && itemAFlags.y + (itemAFlags.height - 1) >= itemBFlags.y && itemAFlags.x <= itemBFlags.x + (itemBFlags.width - 1) && itemAFlags.y <= itemBFlags.y + (itemBFlags.height - 1);
}
__name(areItemsColliding, "areItemsColliding");
function canItemStack(item, targetActor) {
  const itemData = item instanceof Item ? item.toObject() : item;
  const itemFlagData = getItemFlagData(itemData);
  const actorFlagData = getActorFlagData(targetActor);
  if (actorFlagData.enabled && actorFlagData.type === CONSTANTS.PILE_TYPES.VAULT && itemFlagData.vaultExpander) {
    return false;
  }
  if (isItemCurrency(itemData))
    return true;
  if (typeof actorFlagData.canStackItems === "boolean") {
    actorFlagData.canStackItems = "yes";
  }
  if (!isItemStackable(itemData))
    return false;
  if (actorFlagData.canStackItems.includes("always")) {
    return actorFlagData.canStackItems === "always";
  }
  return {
    "default": actorFlagData.canStackItems === "yes",
    "yes": true,
    "no": false
  }[itemFlagData?.canStack ?? "default"];
}
__name(canItemStack, "canItemStack");
function getItemFlagData(item, data2 = false) {
  return getFlagData(getDocument(item), CONSTANTS.FLAGS.ITEM, { ...CONSTANTS.ITEM_DEFAULTS }, data2);
}
__name(getItemFlagData, "getItemFlagData");
function getActorFlagData(target, data2 = false) {
  const defaults = foundry.utils.mergeObject({ ...CONSTANTS.PILE_DEFAULTS }, { ...getSetting(SETTINGS$1.PILE_DEFAULTS) ?? {} });
  target = getActor(target);
  if (target?.token) {
    target = target.token;
  }
  return getFlagData(target, CONSTANTS.FLAGS.PILE, defaults, data2);
}
__name(getActorFlagData, "getActorFlagData");
function isValidItemPile(target, data2 = false) {
  const targetActor = getActor(target);
  const pileData = getActorFlagData(targetActor, data2);
  return targetActor && pileData?.enabled;
}
__name(isValidItemPile, "isValidItemPile");
function isItemPileContainer(target, data2 = false) {
  const targetActor = getActor(target);
  const pileData = getActorFlagData(targetActor, data2);
  return pileData?.enabled && pileData?.type === CONSTANTS.PILE_TYPES.CONTAINER;
}
__name(isItemPileContainer, "isItemPileContainer");
function isItemPileLootable(target, data2 = false) {
  const targetActor = getActor(target);
  const pileData = getActorFlagData(targetActor, data2);
  return targetActor && pileData?.enabled && (pileData?.type === CONSTANTS.PILE_TYPES.PILE || pileData?.type === CONSTANTS.PILE_TYPES.CONTAINER);
}
__name(isItemPileLootable, "isItemPileLootable");
function isItemPileVault(target, data2 = false) {
  const targetActor = getActor(target);
  const pileData = getActorFlagData(targetActor, data2);
  return pileData?.enabled && pileData?.type === CONSTANTS.PILE_TYPES.VAULT;
}
__name(isItemPileVault, "isItemPileVault");
function isItemPileMerchant(target, data2 = false) {
  const targetActor = getActor(target);
  const pileData = getActorFlagData(targetActor, data2);
  return pileData?.enabled && pileData?.type === CONSTANTS.PILE_TYPES.MERCHANT;
}
__name(isItemPileMerchant, "isItemPileMerchant");
function isItemPileClosed(target, data2 = false) {
  const targetActor = getActor(target);
  const pileData = getActorFlagData(targetActor, data2);
  if (!pileData?.enabled || pileData?.type !== CONSTANTS.PILE_TYPES.CONTAINER)
    return false;
  return pileData.closed;
}
__name(isItemPileClosed, "isItemPileClosed");
function isItemPileLocked(target, data2 = false) {
  const targetActor = getActor(target);
  const pileData = getActorFlagData(targetActor, data2);
  if (!pileData?.enabled || pileData?.type !== CONSTANTS.PILE_TYPES.CONTAINER)
    return false;
  return pileData.locked;
}
__name(isItemPileLocked, "isItemPileLocked");
function isItemPileEmpty(target) {
  const targetActor = getActor(target);
  if (!targetActor)
    return false;
  const validItemPile = isValidItemPile(targetActor);
  if (!validItemPile)
    return false;
  const hasNoItems = getActorItems(targetActor).length === 0;
  const hasNoAttributes = getActorCurrencies(targetActor).length === 0;
  return validItemPile && hasNoItems && hasNoAttributes;
}
__name(isItemPileEmpty, "isItemPileEmpty");
function shouldItemPileBeDeleted(targetUuid) {
  const target = getToken(targetUuid);
  if (!(target instanceof Token))
    return false;
  const targetDocument = getDocument(target);
  const pileData = getActorFlagData(targetDocument);
  if (!isItemPileLootable(targetDocument, pileData) || !isItemPileEmpty(targetDocument)) {
    return false;
  }
  if (typeof pileData?.deleteWhenEmpty === "boolean") {
    return pileData?.deleteWhenEmpty;
  }
  return {
    "default": getSetting("deleteEmptyPiles"),
    "true": true,
    "false": false
  }[pileData?.deleteWhenEmpty ?? "default"];
}
__name(shouldItemPileBeDeleted, "shouldItemPileBeDeleted");
function getItemPileActors(filter2 = false) {
  return Array.from(game.actors).filter((a) => {
    return getProperty(a, CONSTANTS.FLAGS.PILE)?.enabled && (filter2 ? filter2(a) : true);
  });
}
__name(getItemPileActors, "getItemPileActors");
function getItemPileTokens(filter2 = false) {
  const allTokensOnScenes = Array.from(game.scenes).map((scene) => [scene.id, Array.from(scene.tokens).filter((t) => {
    return getProperty(t, CONSTANTS.FLAGS.PILE)?.enabled && !t.actorLink;
  })]).filter(([_, tokens]) => tokens.length);
  const validTokensOnScenes = allTokensOnScenes.map(([scene, tokens]) => [scene, tokens.filter((token) => {
    return filter2 ? filter2(token) : true;
  })]).filter(([_, tokens]) => tokens.length);
  const mappedValidTokens = Object.fromEntries(validTokensOnScenes);
  const invalidTokensOnScenes = allTokensOnScenes.map(([scene, tokens]) => [scene, tokens.filter((token) => {
    if (mappedValidTokens[scene.id] && mappedValidTokens[scene.id].includes(token))
      return false;
    try {
      if (filter2)
        filter2(token);
    } catch (err) {
      return true;
    }
    return false;
  })]).filter(([_, tokens]) => tokens.length);
  return { invalidTokensOnScenes, validTokensOnScenes };
}
__name(getItemPileTokens, "getItemPileTokens");
function getActorItems(target, { itemFilters = false, getItemCurrencies = false } = {}) {
  const actor = getActor(target);
  const actorItemFilters = itemFilters ? cleanItemFilters(itemFilters) : getActorItemFilters(actor);
  const currencies = (actor ? getActorCurrencies(actor, { getAll: true }) : game.itempiles.API.CURRENCIES.concat(game.itempiles.API.SECONDARY_CURRENCIES)).map((entry) => entry.id);
  return actor.items.filter((item) => (getItemCurrencies || currencies.indexOf(item.id) === -1) && !isItemInvalid(actor, item, actorItemFilters));
}
__name(getActorItems, "getActorItems");
function getActorCurrencies(target, {
  forActor = false,
  currencyList = false,
  getAll = false,
  secondary = true
} = {}) {
  const actor = getActor(target);
  const actorUuid = getUuid(actor.uuid);
  const actorItems = actor ? Array.from(actor.items) : [];
  const cached = cachedActorCurrencies.get(actorUuid);
  currencyList = cached ? false : currencyList || getCurrencyList(forActor || actor);
  let currencies = cached || currencyList.map((currency, index2) => {
    if (currency.type === "attribute" || !currency.type) {
      const path = currency?.data?.path ?? currency?.path;
      return {
        ...currency,
        quantity: 0,
        path,
        id: path,
        index: index2
      };
    }
    const itemData = getItemFromCache(currency.data.uuid) || currency.data.item || false;
    if (!itemData)
      return false;
    const item = findSimilarItem(actorItems, itemData);
    currency.data.item = itemData;
    currency.data.item._id = item?.id ?? itemData._id;
    return {
      ...currency,
      quantity: 0,
      id: item?.id ?? item?._id ?? itemData._id ?? null,
      item,
      index: index2
    };
  }).filter(Boolean);
  cachedActorCurrencies.set(actorUuid, currencies);
  currencies = currencies.map((currency) => {
    currency.quantity = currency.type === "attribute" ? getProperty(actor, currency.path) : getItemQuantity(currency.item);
    return currency;
  });
  if (!getAll) {
    currencies = currencies.filter((currency) => currency.quantity > 0);
  }
  if (!secondary) {
    currencies = currencies.filter((currency) => !currency.secondary);
  }
  return currencies;
}
__name(getActorCurrencies, "getActorCurrencies");
function getActorPrimaryCurrency(target) {
  const actor = getActor(target);
  return getActorCurrencies(actor, { getAll: true }).find((currency) => currency.primary);
}
__name(getActorPrimaryCurrency, "getActorPrimaryCurrency");
function getCurrencyList(target = false, pileData = false) {
  let targetUuid = false;
  if (target) {
    targetUuid = getUuid(target);
    if (cachedCurrencyList.has(targetUuid)) {
      return cachedCurrencyList.get(targetUuid);
    }
    const targetActor = getActor(target);
    pileData = getActorFlagData(targetActor, pileData);
  }
  const primaryCurrencies = pileData?.overrideCurrencies || game.itempiles.API.CURRENCIES;
  const secondaryCurrencies = (pileData?.overrideSecondaryCurrencies || game.itempiles.API.SECONDARY_CURRENCIES).map((currency) => {
    currency.secondary = true;
    return currency;
  });
  const currencies = primaryCurrencies.concat(secondaryCurrencies);
  const currencyList = currencies.map((currency) => {
    currency.name = game.i18n.localize(currency.name);
    return currency;
  });
  if (target) {
    cachedCurrencyList.set(targetUuid, currencyList);
  }
  return currencyList;
}
__name(getCurrencyList, "getCurrencyList");
function getActorItemFilters(target, pileData = false) {
  if (!target)
    return cleanItemFilters(game.itempiles.API.ITEM_FILTERS);
  const targetUuid = getUuid(target);
  if (cachedFilterList.has(targetUuid)) {
    return cachedFilterList.get(targetUuid);
  }
  const targetActor = getActor(target);
  pileData = getActorFlagData(targetActor, pileData);
  const itemFilters = isValidItemPile(targetActor, pileData) && pileData?.overrideItemFilters ? cleanItemFilters(pileData.overrideItemFilters) : cleanItemFilters(game.itempiles.API.ITEM_FILTERS);
  cachedFilterList.set(targetUuid, itemFilters);
  return itemFilters;
}
__name(getActorItemFilters, "getActorItemFilters");
function cleanItemFilters(itemFilters) {
  return itemFilters ? foundry.utils.duplicate(itemFilters).map((filter2) => {
    filter2.path = filter2.path.trim();
    filter2.filters = (Array.isArray(filter2.filters) ? filter2.filters : filter2.filters.split(",")).map((string) => {
      if (typeof string === "boolean")
        return string;
      const str = string.trim();
      if (str.toLowerCase() === "true" || str.toLowerCase() === "false") {
        return str.toLowerCase() === "true";
      }
      return str;
    });
    filter2.filters = new Set(filter2.filters);
    return filter2;
  }) : [];
}
__name(cleanItemFilters, "cleanItemFilters");
function isItemInvalid(targetActor, item, itemFilters = false) {
  const pileItemFilters = itemFilters ? itemFilters : getActorItemFilters(targetActor);
  const itemData = item instanceof Item ? item.toObject() : item;
  for (const filter2 of pileItemFilters) {
    if (!hasProperty(itemData, filter2.path))
      continue;
    const attributeValue = getProperty(itemData, filter2.path);
    if (filter2.filters.has(attributeValue)) {
      return attributeValue;
    }
  }
  return false;
}
__name(isItemInvalid, "isItemInvalid");
async function checkItemType(targetActor, item, {
  errorText = "ITEM-PILES.Errors.DisallowedItemDrop",
  warningTitle = "ITEM-PILES.Dialogs.TypeWarning.Title",
  warningContent = "ITEM-PILES.Dialogs.TypeWarning.DropContent",
  runTransformer = true
} = {}) {
  const disallowedType = isItemInvalid(targetActor, item);
  if (disallowedType) {
    if (!game.user.isGM) {
      return custom_warning(game.i18n.format(errorText, { type: disallowedType }), true);
    }
    if (SYSTEMS.DATA.ITEM_TRANSFORMER && runTransformer) {
      item = await SYSTEMS.DATA.ITEM_TRANSFORMER(item);
    }
    const newDisallowedType = isItemInvalid(targetActor, item);
    if (newDisallowedType && !hotkeyActionState.forceDropItem) {
      const force = await Dialog.confirm({
        title: game.i18n.localize(warningTitle),
        content: `<p class="item-piles-dialog">${game.i18n.format(warningContent, { type: newDisallowedType })}</p>`,
        defaultYes: false
      });
      if (!force) {
        return false;
      }
    }
  } else {
    if (SYSTEMS.DATA.ITEM_TRANSFORMER && runTransformer) {
      item = await SYSTEMS.DATA.ITEM_TRANSFORMER(item);
    }
  }
  return item;
}
__name(checkItemType, "checkItemType");
function isItemCurrency(item, { target = false, actorCurrencies = false } = {}) {
  const currencies = (actorCurrencies || getActorCurrencies(item.parent || false, {
    forActor: target,
    getAll: true
  })).filter((currency) => currency.type === "item").map((item2) => item2.data.item);
  return !!findSimilarItem(currencies, item);
}
__name(isItemCurrency, "isItemCurrency");
function getItemCurrencyData(item, { target = false, actorCurrencies = false }) {
  return (actorCurrencies || getActorCurrencies(item?.parent || false, {
    forActor: target,
    getAll: true,
    combine: true
  })).filter((currency) => currency.type === "item").find((currency) => {
    return item.name === currency.data.item.name && item.type === currency.data.item.type;
  });
}
__name(getItemCurrencyData, "getItemCurrencyData");
function getItemPileTokenImage(token, {
  data: data2 = false,
  items = false,
  currencies = false
} = {}, overrideImage = null) {
  const pileDocument = getDocument(token);
  const itemPileData = getActorFlagData(pileDocument, data2);
  const originalImg = overrideImage ?? (pileDocument instanceof TokenDocument ? pileDocument.texture.src : pileDocument.prototypeToken.texture.src);
  if (!isValidItemPile(pileDocument, itemPileData) || !isItemPileLootable(pileDocument, itemPileData))
    return originalImg;
  items = items || getActorItems(pileDocument);
  currencies = currencies || getActorCurrencies(pileDocument);
  const numItems = items.length + currencies.length;
  let img = originalImg;
  if (itemPileData.type === CONSTANTS.PILE_TYPES.CONTAINER) {
    img = itemPileData.lockedImage || itemPileData.closedImage || itemPileData.openedImage || itemPileData.emptyImage;
    if (itemPileData.locked && itemPileData.lockedImage) {
      img = itemPileData.lockedImage;
    } else if (itemPileData.closed && itemPileData.closedImage) {
      img = itemPileData.closedImage;
    } else if (itemPileData.emptyImage && isItemPileEmpty(pileDocument)) {
      img = itemPileData.emptyImage;
    } else if (itemPileData.openedImage) {
      img = itemPileData.openedImage;
    }
  } else if (itemPileData.displayOne && numItems === 1) {
    img = items.length > 0 ? items[0].img : currencies[0].img;
  } else if (itemPileData.displayOne && numItems > 1) {
    img = originalImg;
  }
  return img || originalImg;
}
__name(getItemPileTokenImage, "getItemPileTokenImage");
function getItemPileTokenScale(target, {
  data: data2 = false,
  items = false,
  currencies = false
} = {}, overrideScale = null) {
  const pileDocument = getDocument(target);
  let itemPileData = getActorFlagData(pileDocument, data2);
  const baseScale = overrideScale ?? (pileDocument instanceof TokenDocument ? pileDocument.texture.scaleX : pileDocument.prototypeToken.texture.scaleX);
  if (!isValidItemPile(pileDocument, itemPileData) || !isItemPileLootable(pileDocument, itemPileData)) {
    return baseScale;
  }
  items = items || getActorItems(pileDocument);
  currencies = currencies || getActorCurrencies(pileDocument);
  const numItems = items.length + currencies.length;
  if (itemPileData?.type === CONSTANTS.PILE_TYPES.CONTAINER || !itemPileData.displayOne || !itemPileData.overrideSingleItemScale || numItems > 1 || numItems === 0) {
    return baseScale;
  }
  return itemPileData.singleItemScale;
}
__name(getItemPileTokenScale, "getItemPileTokenScale");
function getItemPileName(target, { data: data2 = false, items = false, currencies = false } = {}, overrideName = null) {
  const pileDocument = getDocument(target);
  const itemPileData = getActorFlagData(pileDocument, data2);
  let name = overrideName ?? (pileDocument instanceof TokenDocument ? pileDocument.name : pileDocument.prototypeToken.name);
  if (!isValidItemPile(pileDocument, itemPileData) || !isItemPileLootable(pileDocument, itemPileData)) {
    return name;
  }
  items = items || getActorItems(pileDocument);
  currencies = currencies || getActorCurrencies(pileDocument);
  const numItems = items.length + currencies.length;
  if (itemPileData?.type === CONSTANTS.PILE_TYPES.CONTAINER || !itemPileData.displayOne || !itemPileData.showItemName || numItems > 1 || numItems === 0) {
    return name;
  }
  const item = items.length > 0 ? items[0] : currencies[0];
  const quantity = (items.length > 0 ? getItemQuantity(item) : currencies[0]?.quantity) ?? 1;
  return item.name + (quantity > 1 ? " x " + quantity : "");
}
__name(getItemPileName, "getItemPileName");
function shouldEvaluateChange(target, changes) {
  const flags = getActorFlagData(target, getProperty(changes, CONSTANTS.FLAGS.PILE) ?? {});
  if (!isValidItemPile(target, flags))
    return false;
  return flags.type === CONSTANTS.PILE_TYPES.CONTAINER && (flags.closedImage || flags.emptyImage || flags.openedImage || flags.lockedImage) || flags.displayOne || flags.showItemName || flags.overrideSingleItemScale;
}
__name(shouldEvaluateChange, "shouldEvaluateChange");
function getRelevantTokensAndActor(target) {
  const relevantDocument = getDocument(target);
  let documentActor;
  let documentTokens = [];
  if (relevantDocument instanceof Actor) {
    documentActor = relevantDocument;
    if (relevantDocument.token) {
      documentTokens.push(relevantDocument?.token);
    } else {
      documentTokens = canvas.tokens.placeables.filter((token) => token.document.actor === documentActor).map((token) => token.document);
    }
  } else {
    documentActor = relevantDocument.actor;
    if (relevantDocument.isLinked) {
      documentTokens = canvas.tokens.placeables.filter((token) => token.document.actor === documentActor).map((token) => token.document);
    } else {
      documentTokens.push(relevantDocument);
    }
  }
  return [documentActor, documentTokens];
}
__name(getRelevantTokensAndActor, "getRelevantTokensAndActor");
async function updateItemPileData(target, flagData, tokenData) {
  if (!target)
    return;
  if (!flagData)
    flagData = getActorFlagData(target);
  if (!tokenData)
    tokenData = {};
  tokenData = foundry.utils.mergeObject(tokenData, {});
  let [documentActor, documentTokens] = getRelevantTokensAndActor(target);
  const items = getActorItems(documentActor, { itemFilters: flagData.overrideItemFilters });
  const actorCurrencies = (flagData.overrideCurrencies || []).concat(flagData.overrideSecondaryCurrencies || []);
  const currencies = getActorCurrencies(documentActor, { currencyList: actorCurrencies });
  const pileData = { data: flagData, items, currencies };
  flagData = cleanFlagData(flagData);
  const updates = documentTokens.map((tokenDocument) => {
    const overrideImage = getProperty(tokenData, "texture.src") ?? getProperty(tokenData, "img");
    const overrideScale = getProperty(tokenData, "texture.scaleX") ?? getProperty(tokenData, "texture.scaleY") ?? getProperty(tokenData, "scale");
    const scale = getItemPileTokenScale(tokenDocument, pileData, overrideScale);
    const newTokenData = foundry.utils.mergeObject(tokenData, {
      "texture.src": getItemPileTokenImage(tokenDocument, pileData, overrideImage),
      "texture.scaleX": scale,
      "texture.scaleY": scale,
      "name": getItemPileName(tokenDocument, pileData, tokenData?.name)
    });
    const data2 = {
      "_id": tokenDocument.id,
      ...newTokenData
    };
    if (!tokenDocument.actorLink && (tokenDocument.actor === documentActor || !documentActor)) {
      data2[CONSTANTS.FLAGS.PILE] = flagData;
      data2[CONSTANTS.FLAGS.VERSION] = getModuleVersion();
      documentActor = false;
    }
    return data2;
  });
  if (canvas.scene && !foundry.utils.isEmpty(updates)) {
    await canvas.scene.updateEmbeddedDocuments("Token", updates);
  }
  if (documentActor) {
    await documentActor.update({
      [CONSTANTS.FLAGS.PILE]: flagData,
      [CONSTANTS.FLAGS.VERSION]: getModuleVersion()
    });
  }
  return true;
}
__name(updateItemPileData, "updateItemPileData");
function cleanFlagData(flagData) {
  const defaults = foundry.utils.mergeObject({ ...CONSTANTS.PILE_DEFAULTS }, getSetting(SETTINGS$1.PILE_DEFAULTS) ?? {});
  const defaultKeys = Object.keys(defaults);
  const difference = new Set(Object.keys(foundry.utils.diffObject(flagData, defaults)));
  const toRemove = new Set(defaultKeys.filter((key) => !difference.has(key)));
  if (flagData.enabled) {
    toRemove.delete("type");
  }
  if (!CONSTANTS.CUSTOM_PILE_TYPES[flagData.type]) {
    const baseKeys = new Set(defaultKeys);
    for (const key of Object.keys(flagData)) {
      if (!baseKeys.has(key)) {
        delete flagData[key];
        flagData["-=" + key] = null;
      }
    }
  }
  for (const key of toRemove) {
    delete flagData[key];
    flagData["-=" + key] = null;
  }
  return flagData;
}
__name(cleanFlagData, "cleanFlagData");
function cleanItemFlagData(flagData, { addRemoveFlag = false } = {}) {
  const defaults = Object.keys(CONSTANTS.ITEM_DEFAULTS);
  const difference = new Set(Object.keys(foundry.utils.diffObject(flagData, CONSTANTS.ITEM_DEFAULTS)));
  const toRemove = new Set(defaults.filter((key) => !difference.has(key)));
  for (const key of toRemove) {
    delete flagData[key];
    if (!addRemoveFlag) {
      flagData["-=" + key] = null;
    }
  }
  return flagData;
}
__name(cleanItemFlagData, "cleanItemFlagData");
function updateItemData(item, update2, { returnUpdate = false, version = false } = {}) {
  const flagData = cleanItemFlagData(foundry.utils.mergeObject(getItemFlagData(item), update2.flags ?? {}));
  const updates = foundry.utils.mergeObject(update2?.data ?? {}, {});
  setProperty(updates, CONSTANTS.FLAGS.ITEM, flagData);
  setProperty(updates, CONSTANTS.FLAGS.VERSION, version || getModuleVersion());
  if (returnUpdate) {
    updates["_id"] = item?.id ?? item?._id;
    return updates;
  }
  return item.update(updates);
}
__name(updateItemData, "updateItemData");
function getMerchantModifiersForActor(merchant, {
  item = false,
  actor = false,
  pileFlagData = false,
  itemFlagData = false,
  absolute = false
} = {}) {
  let {
    buyPriceModifier,
    sellPriceModifier,
    itemTypePriceModifiers,
    actorPriceModifiers
  } = getActorFlagData(merchant, pileFlagData);
  if (item) {
    if (!itemFlagData) {
      itemFlagData = getItemFlagData(item);
    }
    const itemTypePriceModifier = itemTypePriceModifiers.sort((a, b) => a.type === "custom" && b.type !== "custom" ? -1 : 0).find((priceData) => {
      return priceData.type === "custom" ? priceData.category.toLowerCase() === itemFlagData.customCategory.toLowerCase() : priceData.type === item.type;
    });
    if (itemTypePriceModifier) {
      buyPriceModifier = itemTypePriceModifier.override ? itemTypePriceModifier.buyPriceModifier : buyPriceModifier * itemTypePriceModifier.buyPriceModifier;
      sellPriceModifier = itemTypePriceModifier.override ? itemTypePriceModifier.sellPriceModifier : sellPriceModifier * itemTypePriceModifier.sellPriceModifier;
    }
  }
  if (actor && actorPriceModifiers) {
    const actorSpecificModifiers = actorPriceModifiers?.find((data2) => data2.actorUuid === getUuid(actor) || data2.actor === actor.id);
    if (actorSpecificModifiers) {
      buyPriceModifier = actorSpecificModifiers.override || absolute ? actorSpecificModifiers.buyPriceModifier ?? buyPriceModifier : buyPriceModifier * actorSpecificModifiers.buyPriceModifier;
      sellPriceModifier = actorSpecificModifiers.override || absolute ? actorSpecificModifiers.sellPriceModifier ?? sellPriceModifier : sellPriceModifier * actorSpecificModifiers.sellPriceModifier;
    }
  }
  if (SYSTEMS.DATA.PRICE_MODIFIER_TRANSFORMER && !absolute) {
    const modifiers = SYSTEMS.DATA.PRICE_MODIFIER_TRANSFORMER({
      buyPriceModifier,
      sellPriceModifier,
      merchant,
      item,
      actor,
      actorPriceModifiers
    });
    buyPriceModifier = modifiers.buyPriceModifier;
    sellPriceModifier = modifiers.sellPriceModifier;
  }
  return {
    buyPriceModifier: roundToDecimals(buyPriceModifier, 2),
    sellPriceModifier: roundToDecimals(sellPriceModifier, 2)
  };
}
__name(getMerchantModifiersForActor, "getMerchantModifiersForActor");
function getSmallestExchangeRate(currencies) {
  return currencies.length > 1 ? Math.min(...currencies.filter((currency) => !currency.secondary).map((currency) => currency.exchangeRate)) : getSetting(SETTINGS$1.CURRENCY_DECIMAL_DIGITS) ?? 1e-5;
}
__name(getSmallestExchangeRate, "getSmallestExchangeRate");
function getExchangeRateDecimals(smallestExchangeRate) {
  return smallestExchangeRate.toString().includes(".") ? smallestExchangeRate.toString().split(".")[1].length : 0;
}
__name(getExchangeRateDecimals, "getExchangeRateDecimals");
function getPriceArray(totalCost, currencies) {
  if (!currencies)
    currencies = getCurrencyList();
  const primaryCurrency = currencies.find((currency) => currency.primary);
  if (currencies.length === 1) {
    return [{
      ...primaryCurrency,
      cost: totalCost,
      baseCost: totalCost,
      maxCurrencyCost: totalCost,
      string: primaryCurrency.abbreviation.replace("{#}", totalCost)
    }];
  }
  const smallestExchangeRate = getSmallestExchangeRate(currencies);
  const prices = [];
  if (primaryCurrency.exchangeRate === smallestExchangeRate) {
    let cost2 = totalCost;
    for (const currency of currencies) {
      if (currency.secondary)
        continue;
      const numCurrency = Math.floor(cost2 / currency.exchangeRate);
      cost2 = cost2 - numCurrency * currency.exchangeRate;
      prices.push({
        ...currency,
        cost: Math.round(numCurrency),
        baseCost: Math.round(numCurrency),
        maxCurrencyCost: Math.ceil(totalCost / currency.exchangeRate),
        string: currency.abbreviation.replace("{#}", numCurrency)
      });
    }
    return prices;
  }
  const decimals = getExchangeRateDecimals(smallestExchangeRate);
  let fraction = roundToDecimals(totalCost % 1, decimals);
  let cost = Math.round(totalCost - fraction);
  let skipPrimary = false;
  if (cost) {
    skipPrimary = true;
    prices.push({
      ...primaryCurrency,
      cost,
      baseCost: cost,
      maxCurrencyCost: totalCost,
      string: primaryCurrency.abbreviation.replace("{#}", cost)
    });
  }
  for (const currency of currencies) {
    if (currency === primaryCurrency && skipPrimary || currency.secondary)
      continue;
    const numCurrency = Math.floor(roundToDecimals(fraction / currency.exchangeRate, decimals));
    fraction = roundToDecimals(fraction - numCurrency * currency.exchangeRate, decimals);
    prices.push({
      ...currency,
      cost: Math.round(numCurrency),
      baseCost: Math.round(numCurrency),
      maxCurrencyCost: Math.ceil(totalCost / currency.exchangeRate),
      string: currency.abbreviation.replace("{#}", numCurrency)
    });
  }
  prices.sort((a, b) => b.exchangeRate - a.exchangeRate);
  return prices.map((price) => {
    if (price?.quantity === void 0) {
      price.quantity = price.cost;
    }
    return price;
  });
}
__name(getPriceArray, "getPriceArray");
function getCurrenciesAbbreviations() {
  let primaryAbbreviationsArray = game.itempiles.API.CURRENCIES.filter((currency) => currency.abbreviation).map((currency) => {
    return currency.abbreviation?.replace("{#}", "");
  });
  let secondaryAbbreviationsArray = game.itempiles.API.SECONDARY_CURRENCIES.filter((currency) => currency.abbreviation).map((currency) => {
    return currency.abbreviation?.replace("{#}", "");
  });
  let allAbbreviationsArray = primaryAbbreviationsArray.concat(secondaryAbbreviationsArray);
  return allAbbreviationsArray;
}
__name(getCurrenciesAbbreviations, "getCurrenciesAbbreviations");
function getStringFromCurrencies(currencies) {
  let allAbbreviationsArray = getCurrenciesAbbreviations();
  let priceString = currencies.filter((price) => price.cost).map((price) => {
    let cost = price.cost;
    let abbreviation = price.abbreviation;
    if (!isRealNumber(cost) || !abbreviation) {
      custom_error(`getStringFromCurrencies | The currency element is not valid with cost '${cost}' and abbreviation '${abbreviation}'`, false);
      return "";
    }
    if (!allAbbreviationsArray.includes(abbreviation?.replace("{#}", ""))) {
      custom_error(`getStringFromCurrencies | The currency abbreviation '${abbreviation?.replace("{#}", "")}' is not registered`, false);
      return "";
    }
    if (price.percent && abbreviation.includes("%")) {
      abbreviation = abbreviation.replaceAll("%", "");
    }
    return abbreviation.replace("{#}", price.cost);
  }).join(" ");
  return priceString ? priceString.trim() : "";
}
__name(getStringFromCurrencies, "getStringFromCurrencies");
function getPriceFromString(str, currencyList = false) {
  if (!currencyList) {
    currencyList = getCurrencyList();
  }
  const currencies = foundry.utils.duplicate(currencyList).map((currency) => {
    currency.quantity = 0;
    currency.identifier = currency.abbreviation.toLowerCase().replace("{#}", "").trim();
    return currency;
  });
  const sortedCurrencies = currencies.map((currency) => `(${currency.identifier})`);
  sortedCurrencies.sort((a, b) => b.length - a.length);
  const splitBy = new RegExp("(.*?) *(" + sortedCurrencies.join("|") + ")", "g");
  const parts = [...str.split(",").join("").split(" ").join("").trim().toLowerCase().matchAll(splitBy)];
  let overallCost = 0;
  for (const part of parts) {
    for (const currency of currencies) {
      if (part[2] !== currency.identifier)
        continue;
      try {
        const roll = new Roll(part[1]).evaluate({ async: false });
        currency.quantity = roll.total;
        if (roll.total !== Number(part[1])) {
          currency.roll = roll;
        }
        if (currency.exchangeRate) {
          overallCost += roll.total * currency.exchangeRate;
        }
      } catch (err) {
      }
    }
  }
  if (!currencies.some((currency) => currency.quantity)) {
    try {
      const roll = new Roll(str).evaluate({ async: false });
      if (roll.total) {
        const primaryCurrency = currencies.find((currency) => currency.primary);
        primaryCurrency.quantity = roll.total;
        if (roll.total !== Number(str)) {
          primaryCurrency.roll = roll;
        }
        overallCost = roll.total;
      }
    } catch (err) {
    }
  }
  return { currencies, overallCost };
}
__name(getPriceFromString, "getPriceFromString");
function getCostOfItem(item, defaultCurrencies = false) {
  if (!defaultCurrencies) {
    defaultCurrencies = getCurrencyList().filter((currency) => !currency.secondary);
  }
  let overallCost = 0;
  let itemCost = getItemCost(item);
  if (SYSTEMS.DATA.ITEM_COST_TRANSFORMER) {
    overallCost = SYSTEMS.DATA.ITEM_COST_TRANSFORMER(item, defaultCurrencies);
    if (overallCost === false) {
      debug("failed to find price for item:", item);
    }
  } else if (typeof itemCost === "string" && isNaN(Number(itemCost))) {
    overallCost = getPriceFromString(itemCost, defaultCurrencies).overallCost;
  } else {
    overallCost = Number(itemCost);
  }
  return Math.max(0, overallCost);
}
__name(getCostOfItem, "getCostOfItem");
function getPriceData({
  cost = false,
  item = false,
  seller = false,
  buyer = false,
  sellerFlagData = false,
  buyerFlagData = false,
  itemFlagData = false,
  quantity = 1,
  secondaryPrices = false
} = {}) {
  let priceData = [];
  buyerFlagData = getActorFlagData(buyer, buyerFlagData);
  if (!isItemPileMerchant(buyer, buyerFlagData)) {
    buyerFlagData = false;
  }
  sellerFlagData = getActorFlagData(seller, sellerFlagData);
  if (!isItemPileMerchant(seller, sellerFlagData)) {
    sellerFlagData = false;
  }
  if (cost && !item) {
    item = {};
    setProperty(item, game.itempiles.API.ITEM_PRICE_ATTRIBUTE, cost);
    setProperty(item, CONSTANTS.FLAGS.ITEM, CONSTANTS.ITEM_DEFAULTS);
  }
  itemFlagData = itemFlagData || getItemFlagData(item);
  let merchant = sellerFlagData ? seller : buyer;
  if (merchant === buyer && itemFlagData.cantBeSoldToMerchants) {
    priceData.push({
      free: false,
      basePrices: [],
      basePriceString: "",
      prices: [],
      priceString: "",
      totalCost: 0,
      baseCost: 0,
      primary: true,
      maxQuantity: 0,
      quantity
    });
    return priceData;
  }
  let modifier = 1;
  if (sellerFlagData) {
    modifier = getMerchantModifiersForActor(seller, {
      item,
      actor: buyer,
      pileFlagData: sellerFlagData,
      itemFlagData
    }).buyPriceModifier;
  } else if (buyerFlagData) {
    modifier = getMerchantModifiersForActor(buyer, {
      item,
      actor: seller,
      pileFlagData: buyerFlagData,
      itemFlagData
    }).sellPriceModifier;
  }
  const disableNormalCost = itemFlagData.disableNormalCost && !sellerFlagData.onlyAcceptBasePrice;
  const hasOtherPrices = secondaryPrices?.length > 0 || itemFlagData.prices.filter((priceGroup) => priceGroup.length).length > 0;
  const currencyList = getCurrencyList(merchant);
  const currencies = getActorCurrencies(merchant, { currencyList, getAll: true });
  const defaultCurrencies = currencies.filter((currency) => !currency.secondary);
  const smallestExchangeRate = getSmallestExchangeRate(defaultCurrencies);
  const decimals = getExchangeRateDecimals(smallestExchangeRate);
  let overallCost = getCostOfItem(item, defaultCurrencies);
  if (itemFlagData?.free || !disableNormalCost && (overallCost === 0 || overallCost < smallestExchangeRate) && !hasOtherPrices || modifier <= 0) {
    priceData.push({
      free: true,
      basePrices: [],
      basePriceString: "",
      prices: [],
      priceString: "",
      totalCost: 0,
      baseCost: 0,
      primary: true,
      maxQuantity: Infinity,
      quantity
    });
    return priceData;
  }
  if (overallCost >= smallestExchangeRate && (!itemFlagData.disableNormalCost || merchant === buyer && buyerFlagData.onlyAcceptBasePrice)) {
    const baseCost = roundToDecimals(overallCost * modifier, decimals);
    const basePrices = getPriceArray(baseCost, defaultCurrencies);
    let totalCost = roundToDecimals(overallCost * modifier * quantity, decimals);
    let prices = getPriceArray(totalCost, defaultCurrencies);
    if (baseCost) {
      priceData.push({
        basePrices,
        basePriceString: basePrices.filter((price) => price.cost).map((price) => price.string).join(" "),
        prices,
        priceString: prices.filter((price) => price.cost).map((price) => price.string).join(" "),
        totalCost,
        baseCost,
        primary: true,
        maxQuantity: 0,
        quantity
      });
    }
  }
  if (secondaryPrices?.length) {
    if (!priceData.length) {
      priceData.push({
        basePrices: [],
        basePriceString: "",
        prices: [],
        priceString: "",
        totalCost: 0,
        baseCost: 0,
        primary: true,
        maxQuantity: 0,
        quantity
      });
    }
    for (const secondaryPrice of secondaryPrices) {
      const itemModifier = modifier;
      const cost2 = Math.round(secondaryPrice.quantity * itemModifier * quantity);
      const baseCost = Math.round(secondaryPrice.quantity * itemModifier);
      secondaryPrice.name = game.i18n.localize(secondaryPrice.name);
      if (!secondaryPrice.data?.item) {
        secondaryPrice.data.item = getItemFromCache(secondaryPrice.data.uuid);
      }
      priceData[0].basePrices.push({
        ...secondaryPrice,
        cost: cost2,
        baseCost,
        modifier: itemModifier,
        string: secondaryPrice.abbreviation.replace("{#}", baseCost),
        priceString: cost2 ? secondaryPrice.abbreviation.replace("{#}", cost2) : "",
        basePriceString: baseCost ? secondaryPrice.abbreviation.replace("{#}", baseCost) : ""
      });
      priceData[0].prices.push({
        ...secondaryPrice,
        cost: cost2,
        baseCost,
        modifier: itemModifier,
        string: secondaryPrice.abbreviation.replace("{#}", cost2),
        priceString: cost2 ? secondaryPrice.abbreviation.replace("{#}", cost2) : "",
        basePriceString: baseCost ? secondaryPrice.abbreviation.replace("{#}", baseCost) : ""
      });
      priceData[0].basePriceString = priceData[0].basePrices.filter((price) => price.cost).map((price) => price.string).join(" ");
      priceData[0].priceString = priceData[0].prices.filter((price) => price.cost).map((price) => price.string).join(" ");
    }
  }
  if (itemFlagData.prices.length && !(merchant === buyer && buyerFlagData.onlyAcceptBasePrice)) {
    priceData = priceData.concat(itemFlagData.prices.map((priceGroup) => {
      if (!Array.isArray(priceGroup))
        priceGroup = [priceGroup];
      const prices = priceGroup.map((price) => {
        const itemModifier = price.fixed ? 1 : modifier;
        const cost2 = Math.round(price.quantity * itemModifier * quantity);
        const baseCost = Math.round(price.quantity * itemModifier);
        price.name = game.i18n.localize(price.name);
        if (!price.data?.item) {
          price.data.item = getItemFromCache(price.data.uuid);
        }
        return {
          ...price,
          cost: cost2,
          baseCost,
          modifier: itemModifier,
          priceString: cost2 ? price.abbreviation.replace("{#}", cost2) : "",
          basePriceString: baseCost ? price.abbreviation.replace("{#}", baseCost) : "",
          secondary: true
        };
      });
      return {
        prices,
        priceString: prices.filter((price) => price.priceString).map((price) => price.priceString).join(" "),
        basePriceString: prices.filter((price) => price.basePriceString).map((price) => price.basePriceString).join(" "),
        maxQuantity: 0,
        quantity
      };
    }));
  }
  if (!buyer)
    return priceData;
  const buyerInfiniteCurrencies = buyerFlagData?.infiniteCurrencies;
  const buyerInfiniteQuantity = buyerFlagData?.infiniteQuantity;
  const recipientCurrencies = getActorCurrencies(buyer, { currencyList });
  const totalCurrencies = recipientCurrencies.filter((currency) => currency.exchangeRate !== void 0).map((currency) => currency.quantity * currency.exchangeRate).reduce((acc, num) => acc + num, 0);
  for (const priceGroup of priceData) {
    const primaryPrices = priceGroup.prices.filter((price) => !price.secondary);
    const secondaryPrices2 = priceGroup.prices.filter((price) => price.secondary);
    priceGroup.maxQuantity = Infinity;
    if (primaryPrices.length) {
      priceGroup.prices.forEach((price) => {
        price.maxQuantity = Infinity;
      });
      if (!buyerInfiniteCurrencies) {
        priceGroup.maxQuantity = Math.floor(totalCurrencies / priceGroup.baseCost);
        priceGroup.prices.forEach((price) => {
          price.maxQuantity = priceGroup.maxQuantity;
        });
      }
    }
    for (const price of secondaryPrices2) {
      if (buyerInfiniteQuantity) {
        price.maxQuantity = Infinity;
        continue;
      }
      if (price.type === "attribute") {
        const attributeQuantity = Number(getProperty(buyer, price.data.path));
        price.buyerQuantity = attributeQuantity;
        if (price.percent) {
          const percent = Math.min(1, price.baseCost / 100);
          const percentQuantity = Math.max(0, Math.floor(attributeQuantity * percent));
          price.maxQuantity = Math.floor(attributeQuantity / percentQuantity);
          price.baseCost = !buyer ? price.baseCost : percentQuantity;
          price.cost = !buyer ? price.cost : percentQuantity * quantity;
          price.quantity = !buyer ? price.quantity : percentQuantity;
        } else {
          price.maxQuantity = Math.floor(attributeQuantity / price.baseCost);
        }
        priceGroup.maxQuantity = Math.min(priceGroup.maxQuantity, price.maxQuantity);
      } else {
        const priceItem = getItemFromCache(price.data.uuid);
        const foundItem = priceItem ? findSimilarItem(buyer.items, priceItem) : false;
        const itemQuantity = foundItem ? getItemQuantity(foundItem) : 0;
        price.buyerQuantity = itemQuantity;
        if (!itemQuantity) {
          priceGroup.maxQuantity = 0;
          priceGroup.quantity = 0;
          continue;
        }
        if (price.percent) {
          const percent = Math.min(1, price.baseCost / 100);
          const percentQuantity = Math.max(0, Math.floor(itemQuantity * percent));
          price.maxQuantity = Math.floor(itemQuantity / percentQuantity);
          price.baseCost = !buyer ? price.baseCost : percentQuantity;
          price.cost = !buyer ? price.cost : percentQuantity * quantity;
          price.quantity = !buyer ? price.quantity : percentQuantity;
        } else {
          price.maxQuantity = Math.floor(itemQuantity / price.baseCost);
        }
        priceGroup.maxQuantity = Math.min(priceGroup.maxQuantity, price.maxQuantity);
      }
    }
  }
  return priceData;
}
__name(getPriceData, "getPriceData");
function getPaymentData({
  purchaseData = [],
  seller = false,
  buyer = false,
  sellerFlagData = false,
  buyerFlagData = false
} = {}) {
  buyerFlagData = getActorFlagData(buyer, buyerFlagData);
  if (!isItemPileMerchant(buyer, buyerFlagData)) {
    buyerFlagData = false;
  }
  sellerFlagData = getActorFlagData(seller, sellerFlagData);
  if (!isItemPileMerchant(seller, sellerFlagData)) {
    sellerFlagData = false;
  }
  const merchant = sellerFlagData ? seller : buyer;
  const currencyList = getCurrencyList(merchant);
  const currencies = getActorCurrencies(merchant, { currencyList, getAll: true });
  const smallestExchangeRate = getSmallestExchangeRate(currencies);
  const decimals = getExchangeRateDecimals(smallestExchangeRate);
  const recipientCurrencies = getActorCurrencies(buyer, { currencyList, getAll: true });
  const buyerInfiniteCurrencies = buyerFlagData?.infiniteCurrencies;
  const paymentData = purchaseData.map((data2) => {
    const prices = getPriceData({
      cost: data2.cost,
      item: data2.item,
      secondaryPrices: data2.secondaryPrices,
      seller,
      buyer,
      sellerFlagData,
      buyerFlagData,
      itemFlagData: data2.itemFlagData,
      quantity: data2.quantity || 1
    })[data2.paymentIndex || 0];
    return {
      ...prices,
      item: data2.item
    };
  }).reduce((priceData, priceGroup) => {
    if (!priceGroup.maxQuantity && (buyer || seller)) {
      priceData.canBuy = false;
      priceData.reason = ["ITEM-PILES.Applications.TradeMerchantItem." + (buyer === merchant ? "TheyCantAfford" : "YouCantAfford")];
      return priceData;
    }
    const primaryPrices = priceGroup.prices.filter((price) => !price.secondary && price.cost);
    const secondaryPrices = priceGroup.prices.filter((price) => price.secondary && price.cost);
    if (primaryPrices.length) {
      priceData.totalCurrencyCost = roundToDecimals(priceData.totalCurrencyCost + priceGroup.totalCost, decimals);
      priceData.primary = true;
    }
    if (secondaryPrices.length) {
      for (const price of secondaryPrices) {
        let existingPrice = priceData.otherPrices.find((otherPrice) => {
          return otherPrice.id === price.id || otherPrice.name === price.name && otherPrice.img === price.img && otherPrice.type === price.type;
        });
        if (existingPrice) {
          existingPrice.cost += price.cost;
        } else {
          const index2 = priceData.otherPrices.push(price);
          existingPrice = priceData.otherPrices[index2 - 1];
          existingPrice.quantity = 0;
        }
        existingPrice.quantity += price.cost;
        existingPrice.buyerQuantity -= price.cost;
        if (existingPrice.buyerQuantity < 0) {
          priceData.canBuy = false;
          priceData.reason = ["ITEM-PILES.Applications.TradeMerchantItem." + (buyer === merchant ? "TheyCantAfford" : "YouCantAfford")];
        }
      }
    }
    if (priceGroup.item) {
      const itemQuantity = getItemQuantity(priceGroup.item);
      const quantityPerPrice = game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE ? getProperty(priceGroup.item, game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE) ?? 1 : 1;
      const requiredQuantity = Math.floor(priceGroup.quantity * quantityPerPrice);
      if (requiredQuantity > itemQuantity && requiredQuantity > priceGroup.maxQuantity * quantityPerPrice) {
        priceData.canBuy = false;
        priceData.reason = [`ITEM-PILES.Applications.TradeMerchantItem.${buyer === merchant ? "You" : "They"}LackQuantity`, {
          quantity: itemQuantity,
          requiredQuantity
        }];
      }
      priceData.buyerReceive.push({
        type: "item",
        name: priceGroup.item.name,
        img: priceGroup.item.img,
        quantity: requiredQuantity,
        item: priceGroup.item
      });
    }
    return priceData;
  }, {
    totalCurrencyCost: 0,
    canBuy: true,
    primary: false,
    finalPrices: [],
    otherPrices: [],
    reason: [],
    buyerReceive: [],
    buyerChange: [],
    sellerReceive: []
  });
  if (paymentData.totalCurrencyCost && !seller && !buyer) {
    paymentData.finalPrices = getPriceArray(paymentData.totalCurrencyCost, recipientCurrencies).filter((currency) => !currency.secondary);
  } else if (paymentData.totalCurrencyCost) {
    const prices = getPriceArray(paymentData.totalCurrencyCost, recipientCurrencies).filter((currency) => !currency.secondary);
    let priceLeft = paymentData.totalCurrencyCost;
    const inverse = prices[prices.length - 1].primary && prices[prices.length - 1].exchangeRate === 1;
    for (let i = prices.length - 1, j = 0; i >= 0; i--, j++) {
      const price = prices[inverse ? j : i];
      const buyerPrice = {
        ...price,
        buyerQuantity: buyerInfiniteCurrencies ? Infinity : price.quantity,
        quantity: 0,
        isCurrency: true
      };
      if (price.type === "item") {
        buyerPrice.item = price.data.item ?? getItemFromCache(price.data.uuid);
      }
      if (priceLeft <= 0 || !price.cost || currencies.length === 1) {
        if (currencies.length === 1) {
          buyerPrice.quantity = price.cost;
          priceLeft = 0;
        }
        paymentData.finalPrices.push(buyerPrice);
        continue;
      }
      buyerPrice.quantity = buyerPrice.buyerQuantity < price.cost ? buyerPrice.buyerQuantity : price.cost;
      if (price.primary) {
        const totalCurrencyValue = roundToDecimals(buyerPrice.buyerQuantity * price.exchangeRate, decimals);
        if (totalCurrencyValue > priceLeft) {
          buyerPrice.quantity = Math.ceil(priceLeft);
        }
      }
      paymentData.finalPrices.push(buyerPrice);
      priceLeft = roundToDecimals(priceLeft - buyerPrice.quantity * price.exchangeRate, decimals);
    }
    if (currencies.length > 1) {
      while (priceLeft > 0) {
        for (const buyerPrice of paymentData.finalPrices) {
          let buyerCurrencyQuantity = buyerPrice.buyerQuantity - buyerPrice.quantity;
          if (!buyerCurrencyQuantity)
            continue;
          const newQuantity = Math.ceil(Math.min(buyerCurrencyQuantity, priceLeft / buyerPrice.exchangeRate));
          buyerPrice.quantity += newQuantity;
          priceLeft = roundToDecimals(priceLeft - newQuantity * buyerPrice.exchangeRate, decimals);
          if (priceLeft <= 0)
            break;
        }
        if (priceLeft > 0) {
          paymentData.finalPrices = paymentData.finalPrices.sort((a, b) => b.exchangeRate - a.exchangeRate);
        } else {
          break;
        }
      }
      paymentData.finalPrices = paymentData.finalPrices.sort((a, b) => b.exchangeRate - a.exchangeRate);
      let change = Math.abs(priceLeft);
      for (const currency of currencies) {
        if (!change)
          break;
        let numCurrency = Math.floor(roundToDecimals(change / currency.exchangeRate, decimals));
        change = roundToDecimals(change - numCurrency * currency.exchangeRate, decimals);
        if (numCurrency) {
          const payment = paymentData.finalPrices.find((payment2) => {
            return payment2.id === currency.id || payment2.name === currency.name && payment2.img === currency.img && payment2.type === currency.type;
          });
          if (!payment)
            continue;
          if (payment.quantity - numCurrency >= 0) {
            payment.quantity -= numCurrency;
          } else {
            paymentData.buyerChange.push({
              ...currency,
              isCurrency: true,
              quantity: numCurrency - payment.quantity
            });
            payment.quantity = 0;
          }
        }
      }
    }
    paymentData.sellerReceive = paymentData.finalPrices.map((price) => {
      return { ...price };
    });
    let changeNeeded = paymentData.buyerChange.reduce((acc, change) => {
      const currency = currencies.find((currency2) => {
        return change.id === currency2.id || change.name === currency2.name && change.img === currency2.img && change.type === currency2.type;
      });
      return acc + currency.quantity >= change.quantity ? 0 : (change.quantity - currency.quantity) * change.exchangeRate;
    }, 0);
    if (changeNeeded) {
      const primaryCurrency = paymentData.sellerReceive.find((price) => price.primary && price.quantity * price.exchangeRate > changeNeeded);
      if (primaryCurrency) {
        primaryCurrency.quantity--;
        changeNeeded -= 1 * primaryCurrency.exchangeRate;
      } else {
        const biggestCurrency = paymentData.sellerReceive.find((price) => price.quantity && price.quantity * price.exchangeRate > changeNeeded);
        biggestCurrency.quantity--;
        changeNeeded -= 1 * biggestCurrency.exchangeRate;
      }
      changeNeeded = Math.abs(changeNeeded);
      for (const currency of paymentData.sellerReceive) {
        if (!changeNeeded)
          break;
        let numCurrency = Math.floor(roundToDecimals(changeNeeded / currency.exchangeRate, decimals));
        changeNeeded = roundToDecimals(changeNeeded - numCurrency * currency.exchangeRate, decimals);
        currency.quantity += numCurrency;
      }
    }
  }
  paymentData.finalPrices = paymentData.finalPrices.concat(paymentData.otherPrices);
  paymentData.sellerReceive = paymentData.sellerReceive.concat(paymentData.otherPrices);
  paymentData.basePriceString = paymentData.finalPrices.filter((price) => price.cost).map((price) => {
    let abbreviation = price.abbreviation;
    if (price.percent && abbreviation.includes("%")) {
      abbreviation = abbreviation.replaceAll("%", "");
    }
    return abbreviation.replace("{#}", price.cost);
  }).join(" ");
  delete paymentData.otherPrices;
  return paymentData;
}
__name(getPaymentData, "getPaymentData");
function isMerchantClosed(merchant, { pileData = false } = {}) {
  if (!pileData)
    pileData = getActorFlagData(merchant);
  const timestamp = window.SimpleCalendar.api.timestampToDate(window.SimpleCalendar.api.timestamp());
  const openTimes = pileData.openTimes.open;
  const closeTimes = pileData.openTimes.close;
  const openingTime = Number(openTimes.hour.toString() + "." + openTimes.minute.toString());
  const closingTime = Number(closeTimes.hour.toString() + "." + closeTimes.minute.toString());
  const currentTime = Number(timestamp.hour.toString() + "." + timestamp.minute.toString());
  let isClosed = openingTime > closingTime ? !(currentTime >= openingTime || currentTime <= closingTime) : !(currentTime >= openingTime && currentTime <= closingTime);
  const currentWeekday = window.SimpleCalendar.api.getCurrentWeekday();
  isClosed = isClosed || (pileData.closedDays ?? []).includes(currentWeekday.name);
  const currentDate = window.SimpleCalendar.api.currentDateTime();
  const notes = window.SimpleCalendar.api.getNotesForDay(currentDate.year, currentDate.month, currentDate.day);
  const categories = new Set(notes.map((note) => getProperty(note, "flags.foundryvtt-simple-calendar.noteData.categories") ?? []).deepFlatten());
  return isClosed || categories.intersection(new Set(pileData.closedHolidays ?? [])).size > 0;
}
__name(isMerchantClosed, "isMerchantClosed");
async function updateMerchantLog(itemPile, activityData = {}) {
  const vaultLog = getActorLog(itemPile);
  vaultLog.push({
    ...activityData,
    date: Date.now()
  });
  return itemPile.update({
    [CONSTANTS.FLAGS.LOG]: vaultLog
  });
}
__name(updateMerchantLog, "updateMerchantLog");
function getVaultGridData(vaultActor, { flagData = false, items = false } = {}) {
  const vaultFlags = getActorFlagData(vaultActor, flagData);
  const vaultItems = getActorItems(vaultActor);
  let enabledCols = vaultFlags.cols;
  let enabledRows = vaultFlags.rows;
  const regularItems = (items || vaultItems).map((item) => ({
    item,
    itemFlagData: getItemFlagData(item),
    quantity: getItemQuantity(item)
  })).filter(({ itemFlagData }) => {
    return !itemFlagData.vaultExpander || !vaultFlags.vaultExpansion;
  });
  const vaultExpanders = vaultItems.map((item) => ({
    item,
    itemFlagData: getItemFlagData(item),
    quantity: getItemQuantity(item)
  })).filter(({ itemFlagData }) => {
    return itemFlagData.vaultExpander && vaultFlags.vaultExpansion;
  });
  if (vaultFlags.vaultExpansion) {
    const expansions = vaultExpanders.reduce((acc, item) => {
      acc.cols += (item.itemFlagData.addsCols ?? 0) * item.quantity;
      acc.rows += (item.itemFlagData.addsRows ?? 0) * item.quantity;
      return acc;
    }, {
      cols: vaultFlags.baseExpansionCols ?? 0,
      rows: vaultFlags.baseExpansionRows ?? 0
    });
    enabledCols = expansions.cols;
    enabledRows = expansions.rows;
  }
  enabledCols = Math.min(enabledCols, vaultFlags.cols);
  enabledRows = Math.min(enabledRows, vaultFlags.rows);
  const grid = Array.from(Array(enabledCols).keys()).map(() => {
    return Array.from(Array(enabledRows).keys()).map(() => {
      return null;
    });
  });
  for (const item of regularItems) {
    const { width, height } = getVaultItemDimensions(item.item, item.itemFlagData);
    for (let w = 0; w < width; w++) {
      const x = Math.max(0, Math.min(item.itemFlagData.x + w, enabledCols - 1));
      for (let h = 0; h < height; h++) {
        const y = Math.max(0, Math.min(item.itemFlagData.y + h, enabledRows - 1));
        grid[x][y] = item.item.name;
      }
    }
  }
  let freeCells = [];
  for (let x = 0; x < enabledCols; x++) {
    for (let y = 0; y < enabledRows; y++) {
      if (grid[x][y])
        continue;
      freeCells.push({ x, y });
    }
  }
  return {
    totalSpaces: Math.max(0, vaultFlags.cols * vaultFlags.rows),
    enabledSpaces: Math.max(0, enabledCols * enabledRows),
    freeSpaces: Math.max(0, enabledCols * enabledRows - regularItems.length),
    enabledCols,
    enabledRows,
    cols: vaultFlags.cols,
    rows: vaultFlags.rows,
    items: regularItems,
    grid,
    freeCells
  };
}
__name(getVaultGridData, "getVaultGridData");
function getVaultItemDimensions(item, itemFlagData = false) {
  let { width, height, flipped } = getItemFlagData(item, itemFlagData);
  return {
    width: flipped ? height : width,
    height: flipped ? width : height
  };
}
__name(getVaultItemDimensions, "getVaultItemDimensions");
function fitItemsIntoVault(items, vaultActor, {
  mergeItems = true,
  existingItems = false,
  itemFilters = false
} = {}) {
  if (!isItemPileVault(vaultActor))
    return { updates: items, deletions: [] };
  const vaultItems = existingItems || getActorItems(vaultActor, { itemFilters });
  const gridData = getVaultGridData(vaultActor, { items: existingItems });
  const updates = [];
  const deletions = [];
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    const itemData = foundry.utils.deepClone(item instanceof Item ? item.toObject() : item);
    const flagData = getItemFlagData(itemData);
    const newPosition = canItemFitInVault(itemData, vaultActor, { gridData, items: vaultItems, mergeItems });
    if (typeof newPosition === "string") {
      deletions.push(item._id);
      const update2 = updates.find((update3) => update3._id === newPosition);
      if (update2)
        setItemQuantity(update2, (getItemQuantity(update2) ?? 1) + getItemQuantity(itemData));
      continue;
    } else if (!newPosition) {
      return false;
    }
    setProperty(flagData, "x", newPosition.x);
    setProperty(flagData, "y", newPosition.y);
    setProperty(flagData, "flipped", newPosition.flipped);
    const { width, height } = getVaultItemDimensions(item, flagData);
    for (let w = 0; w < width; w++) {
      const x = Math.max(0, Math.min(newPosition.x + w, gridData.enabledCols - 1));
      for (let h = 0; h < height; h++) {
        const y = Math.max(0, Math.min(newPosition.y + h, gridData.enabledRows - 1));
        gridData.grid[x][y] = item.name;
        const indexToDelete = gridData.freeCells.findIndex((pos) => pos.x === x && pos.y === y);
        if (indexToDelete > -1) {
          gridData.freeCells.splice(indexToDelete, 1);
        }
      }
    }
    setProperty(itemData, CONSTANTS.FLAGS.ITEM, flagData);
    updates.push(itemData);
    vaultItems.push(itemData);
  }
  return {
    updates,
    deletions
  };
}
__name(fitItemsIntoVault, "fitItemsIntoVault");
function canItemFitInVault(item, vaultActor, {
  mergeItems = true,
  gridData = null,
  position = null,
  items = null
} = {}) {
  if (!isItemPileVault(vaultActor))
    return true;
  const vaultItems = items ?? getActorItems(vaultActor);
  if (mergeItems && canItemStack(item, vaultActor)) {
    const similarItem = findSimilarItem(vaultItems, item);
    if (similarItem) {
      const itemFlagData = getItemFlagData(similarItem);
      if (!position || areItemsColliding(position, itemFlagData)) {
        return similarItem.id ?? similarItem._id;
      }
    }
  }
  const vaultGridData = gridData ?? getVaultGridData(vaultActor);
  return getNewItemsVaultPosition(item, vaultGridData, { position, items });
}
__name(canItemFitInVault, "canItemFitInVault");
function getNewItemsVaultPosition(item, gridData, { position = null } = {}) {
  const itemFlagData = getItemFlagData(item);
  let flipped = position?.flipped ?? false;
  const { grid, freeCells, enabledCols, enabledRows } = gridData;
  if (position) {
    let fitsInPosition = true;
    const { width, height } = getVaultItemDimensions(item, { ...itemFlagData, flipped });
    for (let w = 0; w < width; w++) {
      for (let h = 0; h < height; h++) {
        fitsInPosition = position.x + w < enabledCols && position.y + h < enabledRows && !grid[position.x + w][position.y + h];
        if (!fitsInPosition)
          break;
      }
      if (!fitsInPosition)
        break;
    }
    if (fitsInPosition)
      return position;
  } else {
    position = { x: 0, y: 0 };
  }
  const loops = Number(itemFlagData.width > 1 || itemFlagData.height > 1);
  for (let i = 0; i <= loops; i++) {
    const { width, height } = getVaultItemDimensions(item, { ...itemFlagData, flipped });
    const validCells = freeCells.filter((cell) => {
      return cell.x + width <= enabledCols && cell.y + height <= enabledRows;
    });
    const cellsToCheck = validCells.sort((a, b) => {
      const distA = new Ray(a, position).distance;
      const distB = new Ray(b, position).distance;
      return distA - distB;
    });
    if (width === 1 && height === 1 && cellsToCheck.length) {
      return cellsToCheck[0];
    }
    cellLoop:
      for (const { x, y } of cellsToCheck) {
        for (let w = 0; w < width; w++) {
          for (let h = 0; h < height; h++) {
            if (grid[x + w][y + h]) {
              continue cellLoop;
            }
          }
        }
        return { x, y, flipped };
      }
    flipped = !flipped;
  }
  return false;
}
__name(getNewItemsVaultPosition, "getNewItemsVaultPosition");
function getVaultAccess(vaultActor, { flagData = false, hasRecipient = false } = {}) {
  const vaultFlags = getActorFlagData(vaultActor, flagData);
  const vaultAccess = vaultFlags.vaultAccess.filter((access) => {
    return fromUuidSync(access.uuid)?.isOwner;
  });
  return vaultAccess.reduce((acc, access) => {
    acc.canView = acc.canView || (access.view ?? true);
    acc.canOrganize = acc.canOrganize || access.organize;
    acc.canWithdrawItems = (acc.canWithdrawItems || access.items.withdraw) && hasRecipient;
    acc.canDepositItems = (acc.canDepositItems || access.items.deposit) && hasRecipient;
    acc.canWithdrawCurrencies = (acc.canWithdrawCurrencies || access.currencies.withdraw) && hasRecipient;
    acc.canDepositCurrencies = (acc.canDepositCurrencies || access.currencies.deposit) && hasRecipient;
    return acc;
  }, {
    canView: vaultActor.isOwner || !vaultFlags.restrictVaultAccess,
    canOrganize: vaultActor.isOwner,
    canWithdrawItems: vaultActor.isOwner && hasRecipient,
    canDepositItems: vaultActor.isOwner && hasRecipient,
    canWithdrawCurrencies: vaultActor.isOwner && hasRecipient,
    canDepositCurrencies: vaultActor.isOwner && hasRecipient
  });
}
__name(getVaultAccess, "getVaultAccess");
async function updateVaultLog(itemPile, {
  actor = false,
  userId = false,
  items = [],
  attributes = [],
  withdrawal = true,
  vaultLogData = {}
} = {}) {
  const formattedItems = [];
  const formattedCurrencies = [];
  const currencies = getActorCurrencies(itemPile, { getAll: true });
  const date = Date.now();
  for (const itemData of items) {
    if (currencies.some((currency) => currency.name === itemData.item.name)) {
      formattedCurrencies.push({
        actor: actor?.name ?? false,
        user: userId,
        name: itemData.item.name,
        qty: itemData.quantity * (withdrawal ? -1 : 1),
        action: vaultLogData?.action ?? (withdrawal ? "withdrew" : "deposited"),
        date
      });
    } else {
      const item = await Item.implementation.create(itemData.item, { temporary: true });
      formattedItems.push({
        actor: actor?.name ?? false,
        user: userId,
        name: item.name,
        qty: itemData.quantity * (withdrawal ? -1 : 1),
        action: vaultLogData?.action ?? (withdrawal ? "withdrew" : "deposited"),
        date
      });
    }
  }
  for (const [key, quantity] of Object.entries(attributes)) {
    const currency = currencies.find((currency2) => currency2.data.path === key);
    if (currency) {
      formattedCurrencies.push({
        actor: actor?.name ?? false,
        user: userId,
        name: currency.name,
        qty: quantity * (withdrawal ? -1 : 1),
        action: vaultLogData?.action ?? (withdrawal ? "withdrew" : "deposited"),
        date
      });
    }
  }
  const vaultLog = getActorLog(itemPile);
  return itemPile.update({
    [CONSTANTS.FLAGS.LOG]: formattedItems.concat(formattedCurrencies).concat(vaultLog)
  });
}
__name(updateVaultLog, "updateVaultLog");
function getActorLog(actor) {
  return getProperty(getActor(actor), CONSTANTS.FLAGS.LOG) || [];
}
__name(getActorLog, "getActorLog");
function clearActorLog(actor) {
  return actor.update({
    [CONSTANTS.FLAGS.LOG]: []
  });
}
__name(clearActorLog, "clearActorLog");
async function rollTable({
  tableUuid,
  formula = "1",
  resetTable = true,
  normalize = false,
  displayChat = false,
  rollData = {},
  customCategory = false
} = {}) {
  const rolledItems = [];
  const table = await fromUuid(tableUuid);
  if (!tableUuid.startsWith("Compendium")) {
    if (resetTable) {
      await table.reset();
    }
    if (normalize) {
      await table.update({
        results: table.results.map((result) => ({
          _id: result.id,
          weight: result.range[1] - (result.range[0] - 1)
        }))
      });
      await table.normalize();
    }
  }
  const roll = new Roll(formula.toString(), rollData).evaluate({ async: false });
  if (roll.total <= 0) {
    return [];
  }
  let results;
  if (game.modules.get("better-rolltables")?.active) {
    results = (await game.betterTables.roll(table)).itemsData.map((result) => {
      return {
        documentCollection: result.documentCollection,
        documentId: result.documentId,
        text: result.text || result.name,
        img: result.img,
        quantity: 1
      };
    });
  } else {
    results = (await table.drawMany(roll.total, { displayChat, recursive: true })).results;
  }
  for (const rollData2 of results) {
    let rolledQuantity = rollData2?.quantity ?? 1;
    let item;
    if (rollData2.documentCollection === "Item") {
      item = game.items.get(rollData2.documentId);
    } else {
      const compendium = game.packs.get(rollData2.documentCollection);
      if (compendium) {
        item = await compendium.getDocument(rollData2.documentId);
      }
    }
    if (item instanceof RollTable) {
      rolledItems.push(...await rollTable({ tableUuid: item.uuid, resetTable, normalize, displayChat }));
    } else if (item instanceof Item) {
      const quantity = Math.max(getItemQuantity(item) * rolledQuantity, 1);
      rolledItems.push({
        ...rollData2,
        item,
        quantity
      });
    }
  }
  const items = [];
  rolledItems.forEach((newItem) => {
    const existingItem = items.find((item) => item.documentId === newItem.documentId);
    if (existingItem) {
      existingItem.quantity += Math.max(newItem.quantity, 1);
    } else {
      setProperty(newItem, "flags", newItem.item.flags);
      if (game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE && !getProperty(newItem, game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE)) {
        setProperty(newItem, game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE, getItemQuantity(newItem.item));
      }
      if (customCategory) {
        setProperty(newItem, CONSTANTS.FLAGS.CUSTOM_CATEGORY, customCategory);
      }
      items.push({
        ...newItem
      });
    }
  });
  return items;
}
__name(rollTable, "rollTable");
async function rollMerchantTables({ tableData = false, actor = false } = {}) {
  if (tableData && !Array.isArray(tableData)) {
    tableData = [tableData];
  } else if (!tableData && actor) {
    const flagData = getActorFlagData(actor);
    tableData = flagData.tablesForPopulate;
  } else if (!tableData && !actor) {
    return [];
  }
  let items = [];
  for (const table of tableData) {
    const rollableTable = await fromUuid(table.uuid);
    if (!rollableTable)
      continue;
    if (!table.uuid.startsWith("Compendium")) {
      await rollableTable.reset();
    }
    let tableItems = [];
    if (table.addAll) {
      for (const [itemId, formula] of Object.entries(table.items)) {
        const roll = new Roll(formula).evaluate({ async: false });
        if (roll.total <= 0)
          continue;
        const rollResult = rollableTable.results.get(itemId).toObject();
        const potentialPack = game.packs.get(rollResult.documentCollection);
        if (rollResult.documentCollection === "RollTable" || potentialPack?.documentName === "RollTable") {
          const subTable = await getTable(rollResult);
          items.push(...await rollMerchantTables({
            tableData: [{
              uuid: subTable.uuid,
              addAll: false,
              timesToRoll: roll.total,
              customCategory: table.customCategory
            }],
            actor
          }));
          continue;
        }
        const item = await getItem(rollResult);
        if (!item)
          continue;
        const quantity = roll.total * Math.max(getItemQuantity(item), 1);
        tableItems.push({
          ...rollResult,
          customCategory: table.customCategory,
          item,
          quantity
        });
      }
    } else {
      const roll = new Roll((table.timesToRoll ?? "1").toString()).evaluate({ async: false });
      if (roll.total <= 0) {
        continue;
      }
      tableItems = await rollTable({
        tableUuid: table.uuid,
        formula: roll.total
      });
      tableItems.forEach((item) => {
        if (table.customCategory) {
          setProperty(item, CONSTANTS.FLAGS.CUSTOM_CATEGORY, table.customCategory);
        }
      });
    }
    tableItems.forEach((newItem) => {
      const existingItem = items.find((item) => item.documentId === newItem.documentId);
      if (existingItem) {
        existingItem.quantity += Math.max(newItem.quantity, 1);
      } else {
        setProperty(newItem, "flags", newItem.item.flags);
        if (game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE && !getProperty(newItem, game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE)) {
          setProperty(newItem, game.itempiles.API.QUANTITY_FOR_PRICE_ATTRIBUTE, getItemQuantity(newItem.item));
        }
        if (newItem.customCategory) {
          setProperty(newItem, CONSTANTS.FLAGS.CUSTOM_CATEGORY, newItem.customCategory);
        }
        items.push({
          ...newItem,
          quantity: newItem.quantity
        });
      }
    });
  }
  return items;
}
__name(rollMerchantTables, "rollMerchantTables");
async function getTable(tableToGet) {
  let table;
  if (tableToGet.documentCollection === "RollTable") {
    table = game.tables.get(tableToGet.documentId);
  } else {
    const compendium = game.packs.get(tableToGet.documentCollection);
    if (compendium) {
      table = await compendium.getDocument(tableToGet.documentId);
    }
  }
  return table;
}
__name(getTable, "getTable");
async function getItem(itemToGet) {
  let item;
  if (itemToGet.documentCollection === "Item") {
    item = game.items.get(itemToGet.documentId);
  } else {
    const compendium = game.packs.get(itemToGet.documentCollection);
    if (compendium) {
      item = await compendium.getDocument(itemToGet.documentId);
    }
  }
  return item;
}
__name(getItem, "getItem");
const min = Math.min;
const max = Math.max;
const round = Math.round;
const floor = Math.floor;
const createCoords = /* @__PURE__ */ __name((v) => ({
  x: v,
  y: v
}), "createCoords");
const oppositeSideMap = {
  left: "right",
  right: "left",
  bottom: "top",
  top: "bottom"
};
const oppositeAlignmentMap = {
  start: "end",
  end: "start"
};
function clamp$1(start, value, end) {
  return max(start, min(value, end));
}
__name(clamp$1, "clamp$1");
function evaluate(value, param) {
  return typeof value === "function" ? value(param) : value;
}
__name(evaluate, "evaluate");
function getSide(placement) {
  return placement.split("-")[0];
}
__name(getSide, "getSide");
function getAlignment(placement) {
  return placement.split("-")[1];
}
__name(getAlignment, "getAlignment");
function getOppositeAxis(axis) {
  return axis === "x" ? "y" : "x";
}
__name(getOppositeAxis, "getOppositeAxis");
function getAxisLength(axis) {
  return axis === "y" ? "height" : "width";
}
__name(getAxisLength, "getAxisLength");
function getSideAxis(placement) {
  return ["top", "bottom"].includes(getSide(placement)) ? "y" : "x";
}
__name(getSideAxis, "getSideAxis");
function getAlignmentAxis(placement) {
  return getOppositeAxis(getSideAxis(placement));
}
__name(getAlignmentAxis, "getAlignmentAxis");
function getAlignmentSides(placement, rects, rtl) {
  if (rtl === void 0) {
    rtl = false;
  }
  const alignment = getAlignment(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const length = getAxisLength(alignmentAxis);
  let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
  if (rects.reference[length] > rects.floating[length]) {
    mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
  }
  return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
__name(getAlignmentSides, "getAlignmentSides");
function getExpandedPlacements(placement) {
  const oppositePlacement = getOppositePlacement(placement);
  return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
}
__name(getExpandedPlacements, "getExpandedPlacements");
function getOppositeAlignmentPlacement(placement) {
  return placement.replace(/start|end/g, (alignment) => oppositeAlignmentMap[alignment]);
}
__name(getOppositeAlignmentPlacement, "getOppositeAlignmentPlacement");
function getSideList(side, isStart, rtl) {
  const lr = ["left", "right"];
  const rl = ["right", "left"];
  const tb = ["top", "bottom"];
  const bt = ["bottom", "top"];
  switch (side) {
    case "top":
    case "bottom":
      if (rtl)
        return isStart ? rl : lr;
      return isStart ? lr : rl;
    case "left":
    case "right":
      return isStart ? tb : bt;
    default:
      return [];
  }
}
__name(getSideList, "getSideList");
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
  const alignment = getAlignment(placement);
  let list = getSideList(getSide(placement), direction === "start", rtl);
  if (alignment) {
    list = list.map((side) => side + "-" + alignment);
    if (flipAlignment) {
      list = list.concat(list.map(getOppositeAlignmentPlacement));
    }
  }
  return list;
}
__name(getOppositeAxisPlacements, "getOppositeAxisPlacements");
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, (side) => oppositeSideMap[side]);
}
__name(getOppositePlacement, "getOppositePlacement");
function expandPaddingObject(padding) {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    ...padding
  };
}
__name(expandPaddingObject, "expandPaddingObject");
function getPaddingObject(padding) {
  return typeof padding !== "number" ? expandPaddingObject(padding) : {
    top: padding,
    right: padding,
    bottom: padding,
    left: padding
  };
}
__name(getPaddingObject, "getPaddingObject");
function rectToClientRect(rect) {
  return {
    ...rect,
    top: rect.y,
    left: rect.x,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  };
}
__name(rectToClientRect, "rectToClientRect");
function computeCoordsFromPlacement(_ref, placement, rtl) {
  let {
    reference,
    floating
  } = _ref;
  const sideAxis = getSideAxis(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const alignLength = getAxisLength(alignmentAxis);
  const side = getSide(placement);
  const isVertical = sideAxis === "y";
  const commonX = reference.x + reference.width / 2 - floating.width / 2;
  const commonY = reference.y + reference.height / 2 - floating.height / 2;
  const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
  let coords;
  switch (side) {
    case "top":
      coords = {
        x: commonX,
        y: reference.y - floating.height
      };
      break;
    case "bottom":
      coords = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case "right":
      coords = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case "left":
      coords = {
        x: reference.x - floating.width,
        y: commonY
      };
      break;
    default:
      coords = {
        x: reference.x,
        y: reference.y
      };
  }
  switch (getAlignment(placement)) {
    case "start":
      coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
      break;
    case "end":
      coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
      break;
  }
  return coords;
}
__name(computeCoordsFromPlacement, "computeCoordsFromPlacement");
const computePosition$1 = /* @__PURE__ */ __name(async (reference, floating, config) => {
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2
  } = config;
  const validMiddleware = middleware.filter(Boolean);
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating));
  let rects = await platform2.getElementRects({
    reference,
    floating,
    strategy
  });
  let {
    x,
    y
  } = computeCoordsFromPlacement(rects, placement, rtl);
  let statefulPlacement = placement;
  let middlewareData = {};
  let resetCount = 0;
  for (let i = 0; i < validMiddleware.length; i++) {
    const {
      name,
      fn
    } = validMiddleware[i];
    const {
      x: nextX,
      y: nextY,
      data: data2,
      reset
    } = await fn({
      x,
      y,
      initialPlacement: placement,
      placement: statefulPlacement,
      strategy,
      middlewareData,
      rects,
      platform: platform2,
      elements: {
        reference,
        floating
      }
    });
    x = nextX != null ? nextX : x;
    y = nextY != null ? nextY : y;
    middlewareData = {
      ...middlewareData,
      [name]: {
        ...middlewareData[name],
        ...data2
      }
    };
    if (reset && resetCount <= 50) {
      resetCount++;
      if (typeof reset === "object") {
        if (reset.placement) {
          statefulPlacement = reset.placement;
        }
        if (reset.rects) {
          rects = reset.rects === true ? await platform2.getElementRects({
            reference,
            floating,
            strategy
          }) : reset.rects;
        }
        ({
          x,
          y
        } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
      }
      i = -1;
      continue;
    }
  }
  return {
    x,
    y,
    placement: statefulPlacement,
    strategy,
    middlewareData
  };
}, "computePosition$1");
async function detectOverflow(state, options) {
  var _await$platform$isEle;
  if (options === void 0) {
    options = {};
  }
  const {
    x,
    y,
    platform: platform2,
    rects,
    elements,
    strategy
  } = state;
  const {
    boundary = "clippingAncestors",
    rootBoundary = "viewport",
    elementContext = "floating",
    altBoundary = false,
    padding = 0
  } = evaluate(options, state);
  const paddingObject = getPaddingObject(padding);
  const altContext = elementContext === "floating" ? "reference" : "floating";
  const element2 = elements[altBoundary ? altContext : elementContext];
  const clippingClientRect = rectToClientRect(await platform2.getClippingRect({
    element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element2))) != null ? _await$platform$isEle : true) ? element2 : element2.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)),
    boundary,
    rootBoundary,
    strategy
  }));
  const rect = elementContext === "floating" ? {
    ...rects.floating,
    x,
    y
  } : rects.reference;
  const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating));
  const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || {
    x: 1,
    y: 1
  } : {
    x: 1,
    y: 1
  };
  const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({
    rect,
    offsetParent,
    strategy
  }) : rect);
  return {
    top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
    bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
    left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
    right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
  };
}
__name(detectOverflow, "detectOverflow");
const flip = /* @__PURE__ */ __name(function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "flip",
    options,
    async fn(state) {
      var _middlewareData$arrow, _middlewareData$flip;
      const {
        placement,
        middlewareData,
        rects,
        initialPlacement,
        platform: platform2,
        elements
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true,
        fallbackPlacements: specifiedFallbackPlacements,
        fallbackStrategy = "bestFit",
        fallbackAxisSideDirection = "none",
        flipAlignment = true,
        ...detectOverflowOptions
      } = evaluate(options, state);
      if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      const side = getSide(placement);
      const isBasePlacement = getSide(initialPlacement) === initialPlacement;
      const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
      const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
      if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== "none") {
        fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
      }
      const placements = [initialPlacement, ...fallbackPlacements];
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const overflows = [];
      let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
      if (checkMainAxis) {
        overflows.push(overflow[side]);
      }
      if (checkCrossAxis) {
        const sides = getAlignmentSides(placement, rects, rtl);
        overflows.push(overflow[sides[0]], overflow[sides[1]]);
      }
      overflowsData = [...overflowsData, {
        placement,
        overflows
      }];
      if (!overflows.every((side2) => side2 <= 0)) {
        var _middlewareData$flip2, _overflowsData$filter;
        const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
        const nextPlacement = placements[nextIndex];
        if (nextPlacement) {
          return {
            data: {
              index: nextIndex,
              overflows: overflowsData
            },
            reset: {
              placement: nextPlacement
            }
          };
        }
        let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
        if (!resetPlacement) {
          switch (fallbackStrategy) {
            case "bestFit": {
              var _overflowsData$map$so;
              const placement2 = (_overflowsData$map$so = overflowsData.map((d) => [d.placement, d.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0];
              if (placement2) {
                resetPlacement = placement2;
              }
              break;
            }
            case "initialPlacement":
              resetPlacement = initialPlacement;
              break;
          }
        }
        if (placement !== resetPlacement) {
          return {
            reset: {
              placement: resetPlacement
            }
          };
        }
      }
      return {};
    }
  };
}, "flip");
async function convertValueToCoords(state, options) {
  const {
    placement,
    platform: platform2,
    elements
  } = state;
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
  const side = getSide(placement);
  const alignment = getAlignment(placement);
  const isVertical = getSideAxis(placement) === "y";
  const mainAxisMulti = ["left", "top"].includes(side) ? -1 : 1;
  const crossAxisMulti = rtl && isVertical ? -1 : 1;
  const rawValue = evaluate(options, state);
  let {
    mainAxis,
    crossAxis,
    alignmentAxis
  } = typeof rawValue === "number" ? {
    mainAxis: rawValue,
    crossAxis: 0,
    alignmentAxis: null
  } : {
    mainAxis: 0,
    crossAxis: 0,
    alignmentAxis: null,
    ...rawValue
  };
  if (alignment && typeof alignmentAxis === "number") {
    crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
  }
  return isVertical ? {
    x: crossAxis * crossAxisMulti,
    y: mainAxis * mainAxisMulti
  } : {
    x: mainAxis * mainAxisMulti,
    y: crossAxis * crossAxisMulti
  };
}
__name(convertValueToCoords, "convertValueToCoords");
const offset = /* @__PURE__ */ __name(function(options) {
  if (options === void 0) {
    options = 0;
  }
  return {
    name: "offset",
    options,
    async fn(state) {
      const {
        x,
        y
      } = state;
      const diffCoords = await convertValueToCoords(state, options);
      return {
        x: x + diffCoords.x,
        y: y + diffCoords.y,
        data: diffCoords
      };
    }
  };
}, "offset");
const shift = /* @__PURE__ */ __name(function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "shift",
    options,
    async fn(state) {
      const {
        x,
        y,
        placement
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = false,
        limiter = {
          fn: (_ref) => {
            let {
              x: x2,
              y: y2
            } = _ref;
            return {
              x: x2,
              y: y2
            };
          }
        },
        ...detectOverflowOptions
      } = evaluate(options, state);
      const coords = {
        x,
        y
      };
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const crossAxis = getSideAxis(getSide(placement));
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      if (checkMainAxis) {
        const minSide = mainAxis === "y" ? "top" : "left";
        const maxSide = mainAxis === "y" ? "bottom" : "right";
        const min2 = mainAxisCoord + overflow[minSide];
        const max2 = mainAxisCoord - overflow[maxSide];
        mainAxisCoord = clamp$1(min2, mainAxisCoord, max2);
      }
      if (checkCrossAxis) {
        const minSide = crossAxis === "y" ? "top" : "left";
        const maxSide = crossAxis === "y" ? "bottom" : "right";
        const min2 = crossAxisCoord + overflow[minSide];
        const max2 = crossAxisCoord - overflow[maxSide];
        crossAxisCoord = clamp$1(min2, crossAxisCoord, max2);
      }
      const limitedCoords = limiter.fn({
        ...state,
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      });
      return {
        ...limitedCoords,
        data: {
          x: limitedCoords.x - x,
          y: limitedCoords.y - y
        }
      };
    }
  };
}, "shift");
function getNodeName(node) {
  if (isNode(node)) {
    return (node.nodeName || "").toLowerCase();
  }
  return "#document";
}
__name(getNodeName, "getNodeName");
function getWindow(node) {
  var _node$ownerDocument;
  return (node == null ? void 0 : (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
__name(getWindow, "getWindow");
function getDocumentElement(node) {
  var _ref;
  return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
__name(getDocumentElement, "getDocumentElement");
function isNode(value) {
  return value instanceof Node || value instanceof getWindow(value).Node;
}
__name(isNode, "isNode");
function isElement(value) {
  return value instanceof Element || value instanceof getWindow(value).Element;
}
__name(isElement, "isElement");
function isHTMLElement(value) {
  return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
__name(isHTMLElement, "isHTMLElement");
function isShadowRoot(value) {
  if (typeof ShadowRoot === "undefined") {
    return false;
  }
  return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
__name(isShadowRoot, "isShadowRoot");
function isOverflowElement(element2) {
  const {
    overflow,
    overflowX,
    overflowY,
    display
  } = getComputedStyle$1(element2);
  return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !["inline", "contents"].includes(display);
}
__name(isOverflowElement, "isOverflowElement");
function isTableElement(element2) {
  return ["table", "td", "th"].includes(getNodeName(element2));
}
__name(isTableElement, "isTableElement");
function isContainingBlock(element2) {
  const webkit = isWebKit();
  const css = getComputedStyle$1(element2);
  return css.transform !== "none" || css.perspective !== "none" || (css.containerType ? css.containerType !== "normal" : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit && (css.filter ? css.filter !== "none" : false) || ["transform", "perspective", "filter"].some((value) => (css.willChange || "").includes(value)) || ["paint", "layout", "strict", "content"].some((value) => (css.contain || "").includes(value));
}
__name(isContainingBlock, "isContainingBlock");
function getContainingBlock(element2) {
  let currentNode = getParentNode(element2);
  while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
    if (isContainingBlock(currentNode)) {
      return currentNode;
    } else {
      currentNode = getParentNode(currentNode);
    }
  }
  return null;
}
__name(getContainingBlock, "getContainingBlock");
function isWebKit() {
  if (typeof CSS === "undefined" || !CSS.supports)
    return false;
  return CSS.supports("-webkit-backdrop-filter", "none");
}
__name(isWebKit, "isWebKit");
function isLastTraversableNode(node) {
  return ["html", "body", "#document"].includes(getNodeName(node));
}
__name(isLastTraversableNode, "isLastTraversableNode");
function getComputedStyle$1(element2) {
  return getWindow(element2).getComputedStyle(element2);
}
__name(getComputedStyle$1, "getComputedStyle$1");
function getNodeScroll(element2) {
  if (isElement(element2)) {
    return {
      scrollLeft: element2.scrollLeft,
      scrollTop: element2.scrollTop
    };
  }
  return {
    scrollLeft: element2.pageXOffset,
    scrollTop: element2.pageYOffset
  };
}
__name(getNodeScroll, "getNodeScroll");
function getParentNode(node) {
  if (getNodeName(node) === "html") {
    return node;
  }
  const result = (
    // Step into the shadow DOM of the parent of a slotted node.
    node.assignedSlot || // DOM Element detected.
    node.parentNode || // ShadowRoot detected.
    isShadowRoot(node) && node.host || // Fallback.
    getDocumentElement(node)
  );
  return isShadowRoot(result) ? result.host : result;
}
__name(getParentNode, "getParentNode");
function getNearestOverflowAncestor(node) {
  const parentNode = getParentNode(node);
  if (isLastTraversableNode(parentNode)) {
    return node.ownerDocument ? node.ownerDocument.body : node.body;
  }
  if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
    return parentNode;
  }
  return getNearestOverflowAncestor(parentNode);
}
__name(getNearestOverflowAncestor, "getNearestOverflowAncestor");
function getOverflowAncestors(node, list, traverseIframes) {
  var _node$ownerDocument2;
  if (list === void 0) {
    list = [];
  }
  if (traverseIframes === void 0) {
    traverseIframes = true;
  }
  const scrollableAncestor = getNearestOverflowAncestor(node);
  const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
  const win = getWindow(scrollableAncestor);
  if (isBody) {
    return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);
  }
  return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
__name(getOverflowAncestors, "getOverflowAncestors");
function getCssDimensions(element2) {
  const css = getComputedStyle$1(element2);
  let width = parseFloat(css.width) || 0;
  let height = parseFloat(css.height) || 0;
  const hasOffset = isHTMLElement(element2);
  const offsetWidth = hasOffset ? element2.offsetWidth : width;
  const offsetHeight = hasOffset ? element2.offsetHeight : height;
  const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
  if (shouldFallback) {
    width = offsetWidth;
    height = offsetHeight;
  }
  return {
    width,
    height,
    $: shouldFallback
  };
}
__name(getCssDimensions, "getCssDimensions");
function unwrapElement(element2) {
  return !isElement(element2) ? element2.contextElement : element2;
}
__name(unwrapElement, "unwrapElement");
function getScale(element2) {
  const domElement = unwrapElement(element2);
  if (!isHTMLElement(domElement)) {
    return createCoords(1);
  }
  const rect = domElement.getBoundingClientRect();
  const {
    width,
    height,
    $: $2
  } = getCssDimensions(domElement);
  let x = ($2 ? round(rect.width) : rect.width) / width;
  let y = ($2 ? round(rect.height) : rect.height) / height;
  if (!x || !Number.isFinite(x)) {
    x = 1;
  }
  if (!y || !Number.isFinite(y)) {
    y = 1;
  }
  return {
    x,
    y
  };
}
__name(getScale, "getScale");
const noOffsets = /* @__PURE__ */ createCoords(0);
function getVisualOffsets(element2) {
  const win = getWindow(element2);
  if (!isWebKit() || !win.visualViewport) {
    return noOffsets;
  }
  return {
    x: win.visualViewport.offsetLeft,
    y: win.visualViewport.offsetTop
  };
}
__name(getVisualOffsets, "getVisualOffsets");
function shouldAddVisualOffsets(element2, isFixed, floatingOffsetParent) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element2)) {
    return false;
  }
  return isFixed;
}
__name(shouldAddVisualOffsets, "shouldAddVisualOffsets");
function getBoundingClientRect(element2, includeScale, isFixedStrategy, offsetParent) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  const clientRect = element2.getBoundingClientRect();
  const domElement = unwrapElement(element2);
  let scale = createCoords(1);
  if (includeScale) {
    if (offsetParent) {
      if (isElement(offsetParent)) {
        scale = getScale(offsetParent);
      }
    } else {
      scale = getScale(element2);
    }
  }
  const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
  let x = (clientRect.left + visualOffsets.x) / scale.x;
  let y = (clientRect.top + visualOffsets.y) / scale.y;
  let width = clientRect.width / scale.x;
  let height = clientRect.height / scale.y;
  if (domElement) {
    const win = getWindow(domElement);
    const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
    let currentIFrame = win.frameElement;
    while (currentIFrame && offsetParent && offsetWin !== win) {
      const iframeScale = getScale(currentIFrame);
      const iframeRect = currentIFrame.getBoundingClientRect();
      const css = getComputedStyle$1(currentIFrame);
      const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
      const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
      x *= iframeScale.x;
      y *= iframeScale.y;
      width *= iframeScale.x;
      height *= iframeScale.y;
      x += left;
      y += top;
      currentIFrame = getWindow(currentIFrame).frameElement;
    }
  }
  return rectToClientRect({
    width,
    height,
    x,
    y
  });
}
__name(getBoundingClientRect, "getBoundingClientRect");
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
  let {
    rect,
    offsetParent,
    strategy
  } = _ref;
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  const documentElement = getDocumentElement(offsetParent);
  if (offsetParent === documentElement) {
    return rect;
  }
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  let scale = createCoords(1);
  const offsets = createCoords(0);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== "fixed") {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement(offsetParent)) {
      const offsetRect = getBoundingClientRect(offsetParent);
      scale = getScale(offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    }
  }
  return {
    width: rect.width * scale.x,
    height: rect.height * scale.y,
    x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,
    y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y
  };
}
__name(convertOffsetParentRelativeRectToViewportRelativeRect, "convertOffsetParentRelativeRectToViewportRelativeRect");
function getClientRects(element2) {
  return Array.from(element2.getClientRects());
}
__name(getClientRects, "getClientRects");
function getWindowScrollBarX(element2) {
  return getBoundingClientRect(getDocumentElement(element2)).left + getNodeScroll(element2).scrollLeft;
}
__name(getWindowScrollBarX, "getWindowScrollBarX");
function getDocumentRect(element2) {
  const html = getDocumentElement(element2);
  const scroll = getNodeScroll(element2);
  const body = element2.ownerDocument.body;
  const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
  const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
  let x = -scroll.scrollLeft + getWindowScrollBarX(element2);
  const y = -scroll.scrollTop;
  if (getComputedStyle$1(body).direction === "rtl") {
    x += max(html.clientWidth, body.clientWidth) - width;
  }
  return {
    width,
    height,
    x,
    y
  };
}
__name(getDocumentRect, "getDocumentRect");
function getViewportRect(element2, strategy) {
  const win = getWindow(element2);
  const html = getDocumentElement(element2);
  const visualViewport = win.visualViewport;
  let width = html.clientWidth;
  let height = html.clientHeight;
  let x = 0;
  let y = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    const visualViewportBased = isWebKit();
    if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }
  return {
    width,
    height,
    x,
    y
  };
}
__name(getViewportRect, "getViewportRect");
function getInnerBoundingClientRect(element2, strategy) {
  const clientRect = getBoundingClientRect(element2, true, strategy === "fixed");
  const top = clientRect.top + element2.clientTop;
  const left = clientRect.left + element2.clientLeft;
  const scale = isHTMLElement(element2) ? getScale(element2) : createCoords(1);
  const width = element2.clientWidth * scale.x;
  const height = element2.clientHeight * scale.y;
  const x = left * scale.x;
  const y = top * scale.y;
  return {
    width,
    height,
    x,
    y
  };
}
__name(getInnerBoundingClientRect, "getInnerBoundingClientRect");
function getClientRectFromClippingAncestor(element2, clippingAncestor, strategy) {
  let rect;
  if (clippingAncestor === "viewport") {
    rect = getViewportRect(element2, strategy);
  } else if (clippingAncestor === "document") {
    rect = getDocumentRect(getDocumentElement(element2));
  } else if (isElement(clippingAncestor)) {
    rect = getInnerBoundingClientRect(clippingAncestor, strategy);
  } else {
    const visualOffsets = getVisualOffsets(element2);
    rect = {
      ...clippingAncestor,
      x: clippingAncestor.x - visualOffsets.x,
      y: clippingAncestor.y - visualOffsets.y
    };
  }
  return rectToClientRect(rect);
}
__name(getClientRectFromClippingAncestor, "getClientRectFromClippingAncestor");
function hasFixedPositionAncestor(element2, stopNode) {
  const parentNode = getParentNode(element2);
  if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
    return false;
  }
  return getComputedStyle$1(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
}
__name(hasFixedPositionAncestor, "hasFixedPositionAncestor");
function getClippingElementAncestors(element2, cache) {
  const cachedResult = cache.get(element2);
  if (cachedResult) {
    return cachedResult;
  }
  let result = getOverflowAncestors(element2, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body");
  let currentContainingBlockComputedStyle = null;
  const elementIsFixed = getComputedStyle$1(element2).position === "fixed";
  let currentNode = elementIsFixed ? getParentNode(element2) : element2;
  while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
    const computedStyle = getComputedStyle$1(currentNode);
    const currentNodeIsContaining = isContainingBlock(currentNode);
    if (!currentNodeIsContaining && computedStyle.position === "fixed") {
      currentContainingBlockComputedStyle = null;
    }
    const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && ["absolute", "fixed"].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element2, currentNode);
    if (shouldDropCurrentNode) {
      result = result.filter((ancestor) => ancestor !== currentNode);
    } else {
      currentContainingBlockComputedStyle = computedStyle;
    }
    currentNode = getParentNode(currentNode);
  }
  cache.set(element2, result);
  return result;
}
__name(getClippingElementAncestors, "getClippingElementAncestors");
function getClippingRect(_ref) {
  let {
    element: element2,
    boundary,
    rootBoundary,
    strategy
  } = _ref;
  const elementClippingAncestors = boundary === "clippingAncestors" ? getClippingElementAncestors(element2, this._c) : [].concat(boundary);
  const clippingAncestors = [...elementClippingAncestors, rootBoundary];
  const firstClippingAncestor = clippingAncestors[0];
  const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
    const rect = getClientRectFromClippingAncestor(element2, clippingAncestor, strategy);
    accRect.top = max(rect.top, accRect.top);
    accRect.right = min(rect.right, accRect.right);
    accRect.bottom = min(rect.bottom, accRect.bottom);
    accRect.left = max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromClippingAncestor(element2, firstClippingAncestor, strategy));
  return {
    width: clippingRect.right - clippingRect.left,
    height: clippingRect.bottom - clippingRect.top,
    x: clippingRect.left,
    y: clippingRect.top
  };
}
__name(getClippingRect, "getClippingRect");
function getDimensions(element2) {
  return getCssDimensions(element2);
}
__name(getDimensions, "getDimensions");
function getRectRelativeToOffsetParent(element2, offsetParent, strategy) {
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  const documentElement = getDocumentElement(offsetParent);
  const isFixed = strategy === "fixed";
  const rect = getBoundingClientRect(element2, true, isFixed, offsetParent);
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  const offsets = createCoords(0);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isOffsetParentAnElement) {
      const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }
  return {
    x: rect.left + scroll.scrollLeft - offsets.x,
    y: rect.top + scroll.scrollTop - offsets.y,
    width: rect.width,
    height: rect.height
  };
}
__name(getRectRelativeToOffsetParent, "getRectRelativeToOffsetParent");
function getTrueOffsetParent(element2, polyfill) {
  if (!isHTMLElement(element2) || getComputedStyle$1(element2).position === "fixed") {
    return null;
  }
  if (polyfill) {
    return polyfill(element2);
  }
  return element2.offsetParent;
}
__name(getTrueOffsetParent, "getTrueOffsetParent");
function getOffsetParent(element2, polyfill) {
  const window2 = getWindow(element2);
  if (!isHTMLElement(element2)) {
    return window2;
  }
  let offsetParent = getTrueOffsetParent(element2, polyfill);
  while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === "static") {
    offsetParent = getTrueOffsetParent(offsetParent, polyfill);
  }
  if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle$1(offsetParent).position === "static" && !isContainingBlock(offsetParent))) {
    return window2;
  }
  return offsetParent || getContainingBlock(element2) || window2;
}
__name(getOffsetParent, "getOffsetParent");
const getElementRects = /* @__PURE__ */ __name(async function(_ref) {
  let {
    reference,
    floating,
    strategy
  } = _ref;
  const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
  const getDimensionsFn = this.getDimensions;
  return {
    reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy),
    floating: {
      x: 0,
      y: 0,
      ...await getDimensionsFn(floating)
    }
  };
}, "getElementRects");
function isRTL(element2) {
  return getComputedStyle$1(element2).direction === "rtl";
}
__name(isRTL, "isRTL");
const platform = {
  convertOffsetParentRelativeRectToViewportRelativeRect,
  getDocumentElement,
  getClippingRect,
  getOffsetParent,
  getElementRects,
  getClientRects,
  getDimensions,
  getScale,
  isElement,
  isRTL
};
function observeMove(element2, onMove) {
  let io = null;
  let timeoutId;
  const root = getDocumentElement(element2);
  function cleanup() {
    clearTimeout(timeoutId);
    io && io.disconnect();
    io = null;
  }
  __name(cleanup, "cleanup");
  function refresh(skip, threshold) {
    if (skip === void 0) {
      skip = false;
    }
    if (threshold === void 0) {
      threshold = 1;
    }
    cleanup();
    const {
      left,
      top,
      width,
      height
    } = element2.getBoundingClientRect();
    if (!skip) {
      onMove();
    }
    if (!width || !height) {
      return;
    }
    const insetTop = floor(top);
    const insetRight = floor(root.clientWidth - (left + width));
    const insetBottom = floor(root.clientHeight - (top + height));
    const insetLeft = floor(left);
    const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
    const options = {
      rootMargin,
      threshold: max(0, min(1, threshold)) || 1
    };
    let isFirstUpdate = true;
    function handleObserve(entries) {
      const ratio = entries[0].intersectionRatio;
      if (ratio !== threshold) {
        if (!isFirstUpdate) {
          return refresh();
        }
        if (!ratio) {
          timeoutId = setTimeout(() => {
            refresh(false, 1e-7);
          }, 100);
        } else {
          refresh(false, ratio);
        }
      }
      isFirstUpdate = false;
    }
    __name(handleObserve, "handleObserve");
    try {
      io = new IntersectionObserver(handleObserve, {
        ...options,
        // Handle <iframe>s
        root: root.ownerDocument
      });
    } catch (e) {
      io = new IntersectionObserver(handleObserve, options);
    }
    io.observe(element2);
  }
  __name(refresh, "refresh");
  refresh(true);
  return cleanup;
}
__name(observeMove, "observeMove");
function autoUpdate(reference, floating, update2, options) {
  if (options === void 0) {
    options = {};
  }
  const {
    ancestorScroll = true,
    ancestorResize = true,
    elementResize = typeof ResizeObserver === "function",
    layoutShift = typeof IntersectionObserver === "function",
    animationFrame = false
  } = options;
  const referenceEl = unwrapElement(reference);
  const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...getOverflowAncestors(floating)] : [];
  ancestors.forEach((ancestor) => {
    ancestorScroll && ancestor.addEventListener("scroll", update2, {
      passive: true
    });
    ancestorResize && ancestor.addEventListener("resize", update2);
  });
  const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update2) : null;
  let reobserveFrame = -1;
  let resizeObserver2 = null;
  if (elementResize) {
    resizeObserver2 = new ResizeObserver((_ref) => {
      let [firstEntry] = _ref;
      if (firstEntry && firstEntry.target === referenceEl && resizeObserver2) {
        resizeObserver2.unobserve(floating);
        cancelAnimationFrame(reobserveFrame);
        reobserveFrame = requestAnimationFrame(() => {
          resizeObserver2 && resizeObserver2.observe(floating);
        });
      }
      update2();
    });
    if (referenceEl && !animationFrame) {
      resizeObserver2.observe(referenceEl);
    }
    resizeObserver2.observe(floating);
  }
  let frameId;
  let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
  if (animationFrame) {
    frameLoop();
  }
  function frameLoop() {
    const nextRefRect = getBoundingClientRect(reference);
    if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {
      update2();
    }
    prevRefRect = nextRefRect;
    frameId = requestAnimationFrame(frameLoop);
  }
  __name(frameLoop, "frameLoop");
  update2();
  return () => {
    ancestors.forEach((ancestor) => {
      ancestorScroll && ancestor.removeEventListener("scroll", update2);
      ancestorResize && ancestor.removeEventListener("resize", update2);
    });
    cleanupIo && cleanupIo();
    resizeObserver2 && resizeObserver2.disconnect();
    resizeObserver2 = null;
    if (animationFrame) {
      cancelAnimationFrame(frameId);
    }
  };
}
__name(autoUpdate, "autoUpdate");
const computePosition = /* @__PURE__ */ __name((reference, floating, options) => {
  const cache = /* @__PURE__ */ new Map();
  const mergedOptions = {
    platform,
    ...options
  };
  const platformWithCache = {
    ...mergedOptions.platform,
    _c: cache
  };
  return computePosition$1(reference, floating, {
    ...mergedOptions,
    platform: platformWithCache
  });
}, "computePosition");
function createFloatingActions(initOptions) {
  let referenceElement;
  let floatingElement;
  const defaultOptions = {
    autoUpdate: true
  };
  let options = initOptions;
  const getOptions = /* @__PURE__ */ __name((mixin) => {
    return { ...defaultOptions, ...initOptions || {}, ...mixin || {} };
  }, "getOptions");
  const updatePosition = /* @__PURE__ */ __name((updateOptions) => {
    if (referenceElement && floatingElement) {
      options = getOptions(updateOptions);
      computePosition(referenceElement, floatingElement, options).then((v) => {
        Object.assign(floatingElement.style, {
          position: v.strategy,
          left: `${v.x}px`,
          top: `${v.y}px`
        });
        options?.onComputed && options.onComputed(v);
      });
    }
  }, "updatePosition");
  const referenceAction = /* @__PURE__ */ __name((node) => {
    if ("subscribe" in node) {
      setupVirtualElementObserver(node);
      return {};
    } else {
      referenceElement = node;
      updatePosition();
    }
  }, "referenceAction");
  const contentAction = /* @__PURE__ */ __name((node, contentOptions) => {
    let autoUpdateDestroy;
    floatingElement = node;
    options = getOptions(contentOptions);
    setTimeout(() => updatePosition(contentOptions), 0);
    updatePosition(contentOptions);
    const destroyAutoUpdate = /* @__PURE__ */ __name(() => {
      if (autoUpdateDestroy) {
        autoUpdateDestroy();
        autoUpdateDestroy = void 0;
      }
    }, "destroyAutoUpdate");
    const initAutoUpdate = /* @__PURE__ */ __name(({ autoUpdate: autoUpdate$1 } = options || {}) => {
      destroyAutoUpdate();
      if (autoUpdate$1 !== false) {
        return autoUpdate(referenceElement, floatingElement, () => updatePosition(options), autoUpdate$1 === true ? {} : autoUpdate$1);
      }
      return;
    }, "initAutoUpdate");
    autoUpdateDestroy = initAutoUpdate();
    return {
      update(contentOptions2) {
        updatePosition(contentOptions2);
        autoUpdateDestroy = initAutoUpdate(contentOptions2);
      },
      destroy() {
        destroyAutoUpdate();
      }
    };
  }, "contentAction");
  const setupVirtualElementObserver = /* @__PURE__ */ __name((node) => {
    const unsubscribe = node.subscribe(($node) => {
      if (referenceElement === void 0) {
        referenceElement = $node;
        updatePosition();
      } else {
        Object.assign(referenceElement, $node);
        updatePosition();
      }
    });
    onDestroy(unsubscribe);
  }, "setupVirtualElementObserver");
  return [
    referenceAction,
    contentAction,
    updatePosition
  ];
}
__name(createFloatingActions, "createFloatingActions");
function filter({
  loadOptions,
  filterText,
  items,
  multiple,
  value,
  itemId,
  groupBy,
  filterSelectedItems,
  itemFilter,
  convertStringItemsToObjects: convertStringItemsToObjects2,
  filterGroupedItems,
  label
}) {
  if (items && loadOptions)
    return items;
  if (!items)
    return [];
  if (items && items.length > 0 && typeof items[0] !== "object") {
    items = convertStringItemsToObjects2(items);
  }
  let filterResults = items.filter((item) => {
    let matchesFilter = itemFilter(item[label], filterText, item);
    if (matchesFilter && multiple && value?.length) {
      matchesFilter = !value.some((x) => {
        return filterSelectedItems ? x[itemId] === item[itemId] : false;
      });
    }
    return matchesFilter;
  });
  if (groupBy) {
    filterResults = filterGroupedItems(filterResults);
  }
  return filterResults;
}
__name(filter, "filter");
async function getItems({ dispatch: dispatch2, loadOptions, convertStringItemsToObjects: convertStringItemsToObjects2, filterText }) {
  let res = await loadOptions(filterText).catch((err) => {
    console.warn("svelte-select loadOptions error :>> ", err);
    dispatch2("error", { type: "loadOptions", details: err });
  });
  if (res && !res.cancelled) {
    if (res) {
      if (res && res.length > 0 && typeof res[0] !== "object") {
        res = convertStringItemsToObjects2(res);
      }
      dispatch2("loaded", { items: res });
    } else {
      res = [];
    }
    return {
      filteredItems: res,
      loading: false,
      focused: true,
      listOpen: true
    };
  }
}
__name(getItems, "getItems");
const ChevronIcon_svelte_svelte_type_style_lang = "";
function create_fragment$i(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "fill", "currentColor");
      attr(path, "d", "M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747\n          3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0\n          1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502\n          0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0\n          0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 20 20");
      attr(svg, "focusable", "false");
      attr(svg, "aria-hidden", "true");
      attr(svg, "class", "svelte-qbd276");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(svg);
    }
  };
}
__name(create_fragment$i, "create_fragment$i");
const _ChevronIcon = class _ChevronIcon extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$i, safe_not_equal, {});
  }
};
__name(_ChevronIcon, "ChevronIcon");
let ChevronIcon = _ChevronIcon;
const ClearIcon_svelte_svelte_type_style_lang = "";
function create_fragment$h(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "fill", "currentColor");
      attr(path, "d", "M34.923,37.251L24,26.328L13.077,37.251L9.436,33.61l10.923-10.923L9.436,11.765l3.641-3.641L24,19.047L34.923,8.124\n    l3.641,3.641L27.641,22.688L38.564,33.61L34.923,37.251z");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "-2 -2 50 50");
      attr(svg, "focusable", "false");
      attr(svg, "aria-hidden", "true");
      attr(svg, "role", "presentation");
      attr(svg, "class", "svelte-whdbu1");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(svg);
    }
  };
}
__name(create_fragment$h, "create_fragment$h");
const _ClearIcon = class _ClearIcon extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$h, safe_not_equal, {});
  }
};
__name(_ClearIcon, "ClearIcon");
let ClearIcon = _ClearIcon;
const LoadingIcon_svelte_svelte_type_style_lang = "";
function create_fragment$g(ctx) {
  let svg;
  let circle;
  return {
    c() {
      svg = svg_element("svg");
      circle = svg_element("circle");
      attr(circle, "class", "circle_path svelte-1p3nqvd");
      attr(circle, "cx", "50");
      attr(circle, "cy", "50");
      attr(circle, "r", "20");
      attr(circle, "fill", "none");
      attr(circle, "stroke", "currentColor");
      attr(circle, "stroke-width", "5");
      attr(circle, "stroke-miterlimit", "10");
      attr(svg, "class", "loading svelte-1p3nqvd");
      attr(svg, "viewBox", "25 25 50 50");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, circle);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(svg);
    }
  };
}
__name(create_fragment$g, "create_fragment$g");
const _LoadingIcon = class _LoadingIcon extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$g, safe_not_equal, {});
  }
};
__name(_LoadingIcon, "LoadingIcon");
let LoadingIcon = _LoadingIcon;
const Select_svelte_svelte_type_style_lang = "";
const get_required_slot_changes = /* @__PURE__ */ __name((dirty) => ({ value: dirty[0] & /*value*/
8 }), "get_required_slot_changes");
const get_required_slot_context = /* @__PURE__ */ __name((ctx) => ({ value: (
  /*value*/
  ctx[3]
) }), "get_required_slot_context");
const get_input_hidden_slot_changes = /* @__PURE__ */ __name((dirty) => ({ value: dirty[0] & /*value*/
8 }), "get_input_hidden_slot_changes");
const get_input_hidden_slot_context = /* @__PURE__ */ __name((ctx) => ({ value: (
  /*value*/
  ctx[3]
) }), "get_input_hidden_slot_context");
const get_chevron_icon_slot_changes = /* @__PURE__ */ __name((dirty) => ({ listOpen: dirty[0] & /*listOpen*/
64 }), "get_chevron_icon_slot_changes");
const get_chevron_icon_slot_context = /* @__PURE__ */ __name((ctx) => ({ listOpen: (
  /*listOpen*/
  ctx[6]
) }), "get_chevron_icon_slot_context");
const get_clear_icon_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_clear_icon_slot_changes");
const get_clear_icon_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_clear_icon_slot_context");
const get_loading_icon_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_loading_icon_slot_changes");
const get_loading_icon_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_loading_icon_slot_context");
const get_selection_slot_changes_1 = /* @__PURE__ */ __name((dirty) => ({ selection: dirty[0] & /*value*/
8 }), "get_selection_slot_changes_1");
const get_selection_slot_context_1 = /* @__PURE__ */ __name((ctx) => ({ selection: (
  /*value*/
  ctx[3]
) }), "get_selection_slot_context_1");
function get_each_context$7(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[125] = list[i];
  child_ctx[127] = i;
  return child_ctx;
}
__name(get_each_context$7, "get_each_context$7");
const get_multi_clear_icon_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_multi_clear_icon_slot_changes");
const get_multi_clear_icon_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_multi_clear_icon_slot_context");
const get_selection_slot_changes = /* @__PURE__ */ __name((dirty) => ({ selection: dirty[0] & /*value*/
8 }), "get_selection_slot_changes");
const get_selection_slot_context = /* @__PURE__ */ __name((ctx) => ({
  selection: (
    /*item*/
    ctx[125]
  ),
  index: (
    /*i*/
    ctx[127]
  )
}), "get_selection_slot_context");
const get_prepend_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_prepend_slot_changes");
const get_prepend_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_prepend_slot_context");
const get_list_append_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_list_append_slot_changes");
const get_list_append_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_list_append_slot_context");
const get_empty_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_empty_slot_changes");
const get_empty_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_empty_slot_context");
function get_each_context_1$2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[125] = list[i];
  child_ctx[127] = i;
  return child_ctx;
}
__name(get_each_context_1$2, "get_each_context_1$2");
const get_item_slot_changes = /* @__PURE__ */ __name((dirty) => ({
  item: dirty[0] & /*filteredItems*/
  16777216
}), "get_item_slot_changes");
const get_item_slot_context = /* @__PURE__ */ __name((ctx) => ({
  item: (
    /*item*/
    ctx[125]
  ),
  index: (
    /*i*/
    ctx[127]
  )
}), "get_item_slot_context");
const get_list_slot_changes = /* @__PURE__ */ __name((dirty) => ({
  filteredItems: dirty[0] & /*filteredItems*/
  16777216
}), "get_list_slot_changes");
const get_list_slot_context = /* @__PURE__ */ __name((ctx) => ({ filteredItems: (
  /*filteredItems*/
  ctx[24]
) }), "get_list_slot_context");
const get_list_prepend_slot_changes = /* @__PURE__ */ __name((dirty) => ({}), "get_list_prepend_slot_changes");
const get_list_prepend_slot_context = /* @__PURE__ */ __name((ctx) => ({}), "get_list_prepend_slot_context");
function create_if_block_8(ctx) {
  let div;
  let t0;
  let current_block_type_index;
  let if_block1;
  let t1;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*$$slots*/
    ctx[50]["list-prepend"] && create_if_block_13(ctx)
  );
  const if_block_creators = [create_if_block_10, create_if_block_11, create_if_block_12];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*$$slots*/
      ctx2[50].list
    )
      return 0;
    if (
      /*filteredItems*/
      ctx2[24].length > 0
    )
      return 1;
    if (!/*hideEmptyState*/
    ctx2[19])
      return 2;
    return -1;
  }
  __name(select_block_type, "select_block_type");
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  let if_block2 = (
    /*$$slots*/
    ctx[50]["list-append"] && create_if_block_9(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      if (if_block1)
        if_block1.c();
      t1 = space();
      if (if_block2)
        if_block2.c();
      attr(div, "class", "svelte-select-list svelte-82qwg8");
      toggle_class(
        div,
        "prefloat",
        /*prefloat*/
        ctx[28]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t0);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div, null);
      }
      append(div, t1);
      if (if_block2)
        if_block2.m(div, null);
      ctx[90](div);
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(
            /*floatingContent*/
            ctx[49].call(null, div)
          ),
          listen(
            div,
            "scroll",
            /*handleListScroll*/
            ctx[41]
          ),
          listen(div, "pointerup", stop_propagation(prevent_default(
            /*pointerup_handler*/
            ctx[85]
          )))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*$$slots*/
        ctx2[50]["list-prepend"]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[1] & /*$$slots*/
          524288) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_13(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block1) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block1 = if_blocks[current_block_type_index];
          if (!if_block1) {
            if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block1.c();
          } else {
            if_block1.p(ctx2, dirty);
          }
          transition_in(if_block1, 1);
          if_block1.m(div, t1);
        } else {
          if_block1 = null;
        }
      }
      if (
        /*$$slots*/
        ctx2[50]["list-append"]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty[1] & /*$$slots*/
          524288) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_9(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div, null);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (!current || dirty[0] & /*prefloat*/
      268435456) {
        toggle_class(
          div,
          "prefloat",
          /*prefloat*/
          ctx2[28]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
      if (if_block2)
        if_block2.d();
      ctx[90](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_8, "create_if_block_8");
function create_if_block_13(ctx) {
  let current;
  const list_prepend_slot_template = (
    /*#slots*/
    ctx[82]["list-prepend"]
  );
  const list_prepend_slot = create_slot(
    list_prepend_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_list_prepend_slot_context
  );
  return {
    c() {
      if (list_prepend_slot)
        list_prepend_slot.c();
    },
    m(target, anchor) {
      if (list_prepend_slot) {
        list_prepend_slot.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (list_prepend_slot) {
        if (list_prepend_slot.p && (!current || dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            list_prepend_slot,
            list_prepend_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              list_prepend_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_list_prepend_slot_changes
            ),
            get_list_prepend_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(list_prepend_slot, local);
      current = true;
    },
    o(local) {
      transition_out(list_prepend_slot, local);
      current = false;
    },
    d(detaching) {
      if (list_prepend_slot)
        list_prepend_slot.d(detaching);
    }
  };
}
__name(create_if_block_13, "create_if_block_13");
function create_if_block_12(ctx) {
  let current;
  const empty_slot_template = (
    /*#slots*/
    ctx[82].empty
  );
  const empty_slot = create_slot(
    empty_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_empty_slot_context
  );
  const empty_slot_or_fallback = empty_slot || fallback_block_9();
  return {
    c() {
      if (empty_slot_or_fallback)
        empty_slot_or_fallback.c();
    },
    m(target, anchor) {
      if (empty_slot_or_fallback) {
        empty_slot_or_fallback.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (empty_slot) {
        if (empty_slot.p && (!current || dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            empty_slot,
            empty_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              empty_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_empty_slot_changes
            ),
            get_empty_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(empty_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(empty_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (empty_slot_or_fallback)
        empty_slot_or_fallback.d(detaching);
    }
  };
}
__name(create_if_block_12, "create_if_block_12");
function create_if_block_11(ctx) {
  let each_1_anchor;
  let current;
  let each_value_1 = (
    /*filteredItems*/
    ctx[24]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_1$2(get_each_context_1$2(ctx, each_value_1, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  }), "out");
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*filteredItems, value, itemId, listDom, scrollToHoverItem, hoverItemIndex, label*/
      1627402376 | dirty[1] & /*handleHover, handleItemClick, isItemActive*/
      28672 | dirty[2] & /*$$scope*/
      524288) {
        each_value_1 = /*filteredItems*/
        ctx2[24];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1$2(ctx2, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block_1$2(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block_11, "create_if_block_11");
function create_if_block_10(ctx) {
  let current;
  const list_slot_template = (
    /*#slots*/
    ctx[82].list
  );
  const list_slot = create_slot(
    list_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_list_slot_context
  );
  return {
    c() {
      if (list_slot)
        list_slot.c();
    },
    m(target, anchor) {
      if (list_slot) {
        list_slot.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (list_slot) {
        if (list_slot.p && (!current || dirty[0] & /*filteredItems*/
        16777216 | dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            list_slot,
            list_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              list_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_list_slot_changes
            ),
            get_list_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(list_slot, local);
      current = true;
    },
    o(local) {
      transition_out(list_slot, local);
      current = false;
    },
    d(detaching) {
      if (list_slot)
        list_slot.d(detaching);
    }
  };
}
__name(create_if_block_10, "create_if_block_10");
function fallback_block_9(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = "No options";
      attr(div, "class", "empty svelte-82qwg8");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(fallback_block_9, "fallback_block_9");
function fallback_block_8(ctx) {
  let t_value = (
    /*item*/
    ctx[125]?.[
      /*label*/
      ctx[12]
    ] + ""
  );
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*filteredItems, label*/
      16781312 && t_value !== (t_value = /*item*/
      ctx2[125]?.[
        /*label*/
        ctx2[12]
      ] + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(fallback_block_8, "fallback_block_8");
function create_each_block_1$2(ctx) {
  let div1;
  let div0;
  let activeScroll_action;
  let hoverScroll_action;
  let t;
  let current;
  let mounted;
  let dispose;
  const item_slot_template = (
    /*#slots*/
    ctx[82].item
  );
  const item_slot = create_slot(
    item_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_item_slot_context
  );
  const item_slot_or_fallback = item_slot || fallback_block_8(ctx);
  function mouseover_handler() {
    return (
      /*mouseover_handler*/
      ctx[87](
        /*i*/
        ctx[127]
      )
    );
  }
  __name(mouseover_handler, "mouseover_handler");
  function focus_handler() {
    return (
      /*focus_handler*/
      ctx[88](
        /*i*/
        ctx[127]
      )
    );
  }
  __name(focus_handler, "focus_handler");
  function click_handler() {
    return (
      /*click_handler*/
      ctx[89](
        /*item*/
        ctx[125],
        /*i*/
        ctx[127]
      )
    );
  }
  __name(click_handler, "click_handler");
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      if (item_slot_or_fallback)
        item_slot_or_fallback.c();
      t = space();
      attr(div0, "class", "item svelte-82qwg8");
      toggle_class(
        div0,
        "list-group-title",
        /*item*/
        ctx[125].groupHeader
      );
      toggle_class(
        div0,
        "active",
        /*isItemActive*/
        ctx[45](
          /*item*/
          ctx[125],
          /*value*/
          ctx[3],
          /*itemId*/
          ctx[13]
        )
      );
      toggle_class(div0, "first", isItemFirst(
        /*i*/
        ctx[127]
      ));
      toggle_class(
        div0,
        "hover",
        /*hoverItemIndex*/
        ctx[7] === /*i*/
        ctx[127]
      );
      toggle_class(
        div0,
        "group-item",
        /*item*/
        ctx[125].groupItem
      );
      toggle_class(
        div0,
        "not-selectable",
        /*item*/
        ctx[125]?.selectable === false
      );
      attr(div1, "class", "list-item svelte-82qwg8");
      attr(div1, "tabindex", "-1");
      attr(div1, "role", "none");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      if (item_slot_or_fallback) {
        item_slot_or_fallback.m(div0, null);
      }
      append(div1, t);
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(activeScroll_action = /*activeScroll*/
          ctx[46].call(null, div0, {
            scroll: (
              /*isItemActive*/
              ctx[45](
                /*item*/
                ctx[125],
                /*value*/
                ctx[3],
                /*itemId*/
                ctx[13]
              )
            ),
            listDom: (
              /*listDom*/
              ctx[30]
            )
          })),
          action_destroyer(hoverScroll_action = /*hoverScroll*/
          ctx[47].call(null, div0, {
            scroll: (
              /*scrollToHoverItem*/
              ctx[29] === /*i*/
              ctx[127]
            ),
            listDom: (
              /*listDom*/
              ctx[30]
            )
          })),
          listen(div1, "mouseover", mouseover_handler),
          listen(div1, "focus", focus_handler),
          listen(div1, "click", stop_propagation(click_handler)),
          listen(div1, "keydown", stop_propagation(prevent_default(
            /*keydown_handler*/
            ctx[86]
          )))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (item_slot) {
        if (item_slot.p && (!current || dirty[0] & /*filteredItems*/
        16777216 | dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            item_slot,
            item_slot_template,
            ctx,
            /*$$scope*/
            ctx[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[81]
            ) : get_slot_changes(
              item_slot_template,
              /*$$scope*/
              ctx[81],
              dirty,
              get_item_slot_changes
            ),
            get_item_slot_context
          );
        }
      } else {
        if (item_slot_or_fallback && item_slot_or_fallback.p && (!current || dirty[0] & /*filteredItems, label*/
        16781312)) {
          item_slot_or_fallback.p(ctx, !current ? [-1, -1, -1, -1, -1] : dirty);
        }
      }
      if (activeScroll_action && is_function(activeScroll_action.update) && dirty[0] & /*filteredItems, value, itemId, listDom*/
      1090527240)
        activeScroll_action.update.call(null, {
          scroll: (
            /*isItemActive*/
            ctx[45](
              /*item*/
              ctx[125],
              /*value*/
              ctx[3],
              /*itemId*/
              ctx[13]
            )
          ),
          listDom: (
            /*listDom*/
            ctx[30]
          )
        });
      if (hoverScroll_action && is_function(hoverScroll_action.update) && dirty[0] & /*scrollToHoverItem, listDom*/
      1610612736)
        hoverScroll_action.update.call(null, {
          scroll: (
            /*scrollToHoverItem*/
            ctx[29] === /*i*/
            ctx[127]
          ),
          listDom: (
            /*listDom*/
            ctx[30]
          )
        });
      if (!current || dirty[0] & /*filteredItems*/
      16777216) {
        toggle_class(
          div0,
          "list-group-title",
          /*item*/
          ctx[125].groupHeader
        );
      }
      if (!current || dirty[0] & /*filteredItems, value, itemId*/
      16785416 | dirty[1] & /*isItemActive*/
      16384) {
        toggle_class(
          div0,
          "active",
          /*isItemActive*/
          ctx[45](
            /*item*/
            ctx[125],
            /*value*/
            ctx[3],
            /*itemId*/
            ctx[13]
          )
        );
      }
      if (!current || dirty[0] & /*hoverItemIndex*/
      128) {
        toggle_class(
          div0,
          "hover",
          /*hoverItemIndex*/
          ctx[7] === /*i*/
          ctx[127]
        );
      }
      if (!current || dirty[0] & /*filteredItems*/
      16777216) {
        toggle_class(
          div0,
          "group-item",
          /*item*/
          ctx[125].groupItem
        );
      }
      if (!current || dirty[0] & /*filteredItems*/
      16777216) {
        toggle_class(
          div0,
          "not-selectable",
          /*item*/
          ctx[125]?.selectable === false
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(item_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(item_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      if (item_slot_or_fallback)
        item_slot_or_fallback.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block_1$2, "create_each_block_1$2");
function create_if_block_9(ctx) {
  let current;
  const list_append_slot_template = (
    /*#slots*/
    ctx[82]["list-append"]
  );
  const list_append_slot = create_slot(
    list_append_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_list_append_slot_context
  );
  return {
    c() {
      if (list_append_slot)
        list_append_slot.c();
    },
    m(target, anchor) {
      if (list_append_slot) {
        list_append_slot.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (list_append_slot) {
        if (list_append_slot.p && (!current || dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            list_append_slot,
            list_append_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              list_append_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_list_append_slot_changes
            ),
            get_list_append_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(list_append_slot, local);
      current = true;
    },
    o(local) {
      transition_out(list_append_slot, local);
      current = false;
    },
    d(detaching) {
      if (list_append_slot)
        list_append_slot.d(detaching);
    }
  };
}
__name(create_if_block_9, "create_if_block_9");
function create_if_block_7$1(ctx) {
  let span0;
  let t0;
  let t1;
  let span1;
  let t2;
  return {
    c() {
      span0 = element("span");
      t0 = text(
        /*ariaSelection*/
        ctx[32]
      );
      t1 = space();
      span1 = element("span");
      t2 = text(
        /*ariaContext*/
        ctx[31]
      );
      attr(span0, "id", "aria-selection");
      attr(span0, "class", "svelte-82qwg8");
      attr(span1, "id", "aria-context");
      attr(span1, "class", "svelte-82qwg8");
    },
    m(target, anchor) {
      insert(target, span0, anchor);
      append(span0, t0);
      insert(target, t1, anchor);
      insert(target, span1, anchor);
      append(span1, t2);
    },
    p(ctx2, dirty) {
      if (dirty[1] & /*ariaSelection*/
      2)
        set_data(
          t0,
          /*ariaSelection*/
          ctx2[32]
        );
      if (dirty[1] & /*ariaContext*/
      1)
        set_data(
          t2,
          /*ariaContext*/
          ctx2[31]
        );
    },
    d(detaching) {
      if (detaching)
        detach(span0);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(span1);
    }
  };
}
__name(create_if_block_7$1, "create_if_block_7$1");
function create_if_block_4$4(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block_5$1, create_else_block$6];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (
      /*multiple*/
      ctx2[9]
    )
      return 0;
    return 1;
  }
  __name(select_block_type_1, "select_block_type_1");
  current_block_type_index = select_block_type_1(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if_blocks[current_block_type_index].d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_if_block_4$4, "create_if_block_4$4");
function create_else_block$6(ctx) {
  let div;
  let current;
  const selection_slot_template = (
    /*#slots*/
    ctx[82].selection
  );
  const selection_slot = create_slot(
    selection_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_selection_slot_context_1
  );
  const selection_slot_or_fallback = selection_slot || fallback_block_7(ctx);
  return {
    c() {
      div = element("div");
      if (selection_slot_or_fallback)
        selection_slot_or_fallback.c();
      attr(div, "class", "selected-item svelte-82qwg8");
      toggle_class(
        div,
        "hide-selected-item",
        /*hideSelectedItem*/
        ctx[35]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (selection_slot_or_fallback) {
        selection_slot_or_fallback.m(div, null);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (selection_slot) {
        if (selection_slot.p && (!current || dirty[0] & /*value*/
        8 | dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            selection_slot,
            selection_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              selection_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_selection_slot_changes_1
            ),
            get_selection_slot_context_1
          );
        }
      } else {
        if (selection_slot_or_fallback && selection_slot_or_fallback.p && (!current || dirty[0] & /*value, label*/
        4104)) {
          selection_slot_or_fallback.p(ctx2, !current ? [-1, -1, -1, -1, -1] : dirty);
        }
      }
      if (!current || dirty[1] & /*hideSelectedItem*/
      16) {
        toggle_class(
          div,
          "hide-selected-item",
          /*hideSelectedItem*/
          ctx2[35]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(selection_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(selection_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (selection_slot_or_fallback)
        selection_slot_or_fallback.d(detaching);
    }
  };
}
__name(create_else_block$6, "create_else_block$6");
function create_if_block_5$1(ctx) {
  let each_1_anchor;
  let current;
  let each_value = (
    /*value*/
    ctx[3]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$7(get_each_context$7(ctx, each_value, i));
  }
  const out = /* @__PURE__ */ __name((i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  }), "out");
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*activeValue, disabled, multiFullItemClearable, value, label*/
      67116040 | dirty[1] & /*handleMultiItemClear*/
      32 | dirty[2] & /*$$scope*/
      524288) {
        each_value = /*value*/
        ctx2[3];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$7(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block$7(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
__name(create_if_block_5$1, "create_if_block_5$1");
function fallback_block_7(ctx) {
  let t_value = (
    /*value*/
    ctx[3][
      /*label*/
      ctx[12]
    ] + ""
  );
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*value, label*/
      4104 && t_value !== (t_value = /*value*/
      ctx2[3][
        /*label*/
        ctx2[12]
      ] + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(fallback_block_7, "fallback_block_7");
function fallback_block_6(ctx) {
  let t_value = (
    /*item*/
    ctx[125][
      /*label*/
      ctx[12]
    ] + ""
  );
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*value, label*/
      4104 && t_value !== (t_value = /*item*/
      ctx2[125][
        /*label*/
        ctx2[12]
      ] + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
__name(fallback_block_6, "fallback_block_6");
function create_if_block_6$1(ctx) {
  let div;
  let current;
  let mounted;
  let dispose;
  const multi_clear_icon_slot_template = (
    /*#slots*/
    ctx[82]["multi-clear-icon"]
  );
  const multi_clear_icon_slot = create_slot(
    multi_clear_icon_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_multi_clear_icon_slot_context
  );
  const multi_clear_icon_slot_or_fallback = multi_clear_icon_slot || fallback_block_5();
  function pointerup_handler_1() {
    return (
      /*pointerup_handler_1*/
      ctx[91](
        /*i*/
        ctx[127]
      )
    );
  }
  __name(pointerup_handler_1, "pointerup_handler_1");
  return {
    c() {
      div = element("div");
      if (multi_clear_icon_slot_or_fallback)
        multi_clear_icon_slot_or_fallback.c();
      attr(div, "class", "multi-item-clear svelte-82qwg8");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (multi_clear_icon_slot_or_fallback) {
        multi_clear_icon_slot_or_fallback.m(div, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(div, "pointerup", stop_propagation(prevent_default(pointerup_handler_1)));
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (multi_clear_icon_slot) {
        if (multi_clear_icon_slot.p && (!current || dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            multi_clear_icon_slot,
            multi_clear_icon_slot_template,
            ctx,
            /*$$scope*/
            ctx[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[81]
            ) : get_slot_changes(
              multi_clear_icon_slot_template,
              /*$$scope*/
              ctx[81],
              dirty,
              get_multi_clear_icon_slot_changes
            ),
            get_multi_clear_icon_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(multi_clear_icon_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(multi_clear_icon_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (multi_clear_icon_slot_or_fallback)
        multi_clear_icon_slot_or_fallback.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_6$1, "create_if_block_6$1");
function fallback_block_5(ctx) {
  let clearicon;
  let current;
  clearicon = new ClearIcon({});
  return {
    c() {
      create_component(clearicon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(clearicon, target, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      transition_in(clearicon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(clearicon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(clearicon, detaching);
    }
  };
}
__name(fallback_block_5, "fallback_block_5");
function create_each_block$7(ctx) {
  let div;
  let span;
  let t0;
  let t1;
  let current;
  let mounted;
  let dispose;
  const selection_slot_template = (
    /*#slots*/
    ctx[82].selection
  );
  const selection_slot = create_slot(
    selection_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_selection_slot_context
  );
  const selection_slot_or_fallback = selection_slot || fallback_block_6(ctx);
  let if_block = !/*disabled*/
  ctx[11] && !/*multiFullItemClearable*/
  ctx[10] && ClearIcon && create_if_block_6$1(ctx);
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[92](
        /*i*/
        ctx[127]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    c() {
      div = element("div");
      span = element("span");
      if (selection_slot_or_fallback)
        selection_slot_or_fallback.c();
      t0 = space();
      if (if_block)
        if_block.c();
      t1 = space();
      attr(span, "class", "multi-item-text svelte-82qwg8");
      attr(div, "class", "multi-item svelte-82qwg8");
      attr(div, "role", "none");
      toggle_class(
        div,
        "active",
        /*activeValue*/
        ctx[26] === /*i*/
        ctx[127]
      );
      toggle_class(
        div,
        "disabled",
        /*disabled*/
        ctx[11]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      if (selection_slot_or_fallback) {
        selection_slot_or_fallback.m(span, null);
      }
      append(div, t0);
      if (if_block)
        if_block.m(div, null);
      append(div, t1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(div, "click", prevent_default(click_handler_1)),
          listen(div, "keydown", stop_propagation(prevent_default(
            /*keydown_handler_1*/
            ctx[84]
          )))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (selection_slot) {
        if (selection_slot.p && (!current || dirty[0] & /*value*/
        8 | dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            selection_slot,
            selection_slot_template,
            ctx,
            /*$$scope*/
            ctx[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[81]
            ) : get_slot_changes(
              selection_slot_template,
              /*$$scope*/
              ctx[81],
              dirty,
              get_selection_slot_changes
            ),
            get_selection_slot_context
          );
        }
      } else {
        if (selection_slot_or_fallback && selection_slot_or_fallback.p && (!current || dirty[0] & /*value, label*/
        4104)) {
          selection_slot_or_fallback.p(ctx, !current ? [-1, -1, -1, -1, -1] : dirty);
        }
      }
      if (!/*disabled*/
      ctx[11] && !/*multiFullItemClearable*/
      ctx[10] && ClearIcon) {
        if (if_block) {
          if_block.p(ctx, dirty);
          if (dirty[0] & /*disabled, multiFullItemClearable*/
          3072) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_6$1(ctx);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div, t1);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty[0] & /*activeValue*/
      67108864) {
        toggle_class(
          div,
          "active",
          /*activeValue*/
          ctx[26] === /*i*/
          ctx[127]
        );
      }
      if (!current || dirty[0] & /*disabled*/
      2048) {
        toggle_class(
          div,
          "disabled",
          /*disabled*/
          ctx[11]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(selection_slot_or_fallback, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(selection_slot_or_fallback, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (selection_slot_or_fallback)
        selection_slot_or_fallback.d(detaching);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$7, "create_each_block$7");
function create_if_block_3$4(ctx) {
  let div;
  let current;
  const loading_icon_slot_template = (
    /*#slots*/
    ctx[82]["loading-icon"]
  );
  const loading_icon_slot = create_slot(
    loading_icon_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_loading_icon_slot_context
  );
  const loading_icon_slot_or_fallback = loading_icon_slot || fallback_block_4();
  return {
    c() {
      div = element("div");
      if (loading_icon_slot_or_fallback)
        loading_icon_slot_or_fallback.c();
      attr(div, "class", "icon loading svelte-82qwg8");
      attr(div, "aria-hidden", "true");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (loading_icon_slot_or_fallback) {
        loading_icon_slot_or_fallback.m(div, null);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (loading_icon_slot) {
        if (loading_icon_slot.p && (!current || dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            loading_icon_slot,
            loading_icon_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              loading_icon_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_loading_icon_slot_changes
            ),
            get_loading_icon_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(loading_icon_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(loading_icon_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (loading_icon_slot_or_fallback)
        loading_icon_slot_or_fallback.d(detaching);
    }
  };
}
__name(create_if_block_3$4, "create_if_block_3$4");
function fallback_block_4(ctx) {
  let loadingicon;
  let current;
  loadingicon = new LoadingIcon({});
  return {
    c() {
      create_component(loadingicon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(loadingicon, target, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      transition_in(loadingicon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(loadingicon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(loadingicon, detaching);
    }
  };
}
__name(fallback_block_4, "fallback_block_4");
function create_if_block_2$4(ctx) {
  let button;
  let current;
  let mounted;
  let dispose;
  const clear_icon_slot_template = (
    /*#slots*/
    ctx[82]["clear-icon"]
  );
  const clear_icon_slot = create_slot(
    clear_icon_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_clear_icon_slot_context
  );
  const clear_icon_slot_or_fallback = clear_icon_slot || fallback_block_3();
  return {
    c() {
      button = element("button");
      if (clear_icon_slot_or_fallback)
        clear_icon_slot_or_fallback.c();
      attr(button, "type", "button");
      attr(button, "class", "icon clear-select svelte-82qwg8");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (clear_icon_slot_or_fallback) {
        clear_icon_slot_or_fallback.m(button, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*handleClear*/
          ctx[22]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (clear_icon_slot) {
        if (clear_icon_slot.p && (!current || dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            clear_icon_slot,
            clear_icon_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              clear_icon_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_clear_icon_slot_changes
            ),
            get_clear_icon_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(clear_icon_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(clear_icon_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(button);
      if (clear_icon_slot_or_fallback)
        clear_icon_slot_or_fallback.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_2$4, "create_if_block_2$4");
function fallback_block_3(ctx) {
  let clearicon;
  let current;
  clearicon = new ClearIcon({});
  return {
    c() {
      create_component(clearicon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(clearicon, target, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      transition_in(clearicon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(clearicon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(clearicon, detaching);
    }
  };
}
__name(fallback_block_3, "fallback_block_3");
function create_if_block_1$7(ctx) {
  let div;
  let current;
  const chevron_icon_slot_template = (
    /*#slots*/
    ctx[82]["chevron-icon"]
  );
  const chevron_icon_slot = create_slot(
    chevron_icon_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_chevron_icon_slot_context
  );
  const chevron_icon_slot_or_fallback = chevron_icon_slot || fallback_block_2();
  return {
    c() {
      div = element("div");
      if (chevron_icon_slot_or_fallback)
        chevron_icon_slot_or_fallback.c();
      attr(div, "class", "icon chevron svelte-82qwg8");
      attr(div, "aria-hidden", "true");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (chevron_icon_slot_or_fallback) {
        chevron_icon_slot_or_fallback.m(div, null);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (chevron_icon_slot) {
        if (chevron_icon_slot.p && (!current || dirty[0] & /*listOpen*/
        64 | dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            chevron_icon_slot,
            chevron_icon_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              chevron_icon_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_chevron_icon_slot_changes
            ),
            get_chevron_icon_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(chevron_icon_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(chevron_icon_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (chevron_icon_slot_or_fallback)
        chevron_icon_slot_or_fallback.d(detaching);
    }
  };
}
__name(create_if_block_1$7, "create_if_block_1$7");
function fallback_block_2(ctx) {
  let chevronicon;
  let current;
  chevronicon = new ChevronIcon({});
  return {
    c() {
      create_component(chevronicon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chevronicon, target, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      transition_in(chevronicon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chevronicon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chevronicon, detaching);
    }
  };
}
__name(fallback_block_2, "fallback_block_2");
function fallback_block_1(ctx) {
  let input_1;
  let input_1_value_value;
  return {
    c() {
      input_1 = element("input");
      attr(
        input_1,
        "name",
        /*name*/
        ctx[8]
      );
      attr(input_1, "type", "hidden");
      input_1.value = input_1_value_value = /*value*/
      ctx[3] ? JSON.stringify(
        /*value*/
        ctx[3]
      ) : null;
      attr(input_1, "class", "svelte-82qwg8");
    },
    m(target, anchor) {
      insert(target, input_1, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*name*/
      256) {
        attr(
          input_1,
          "name",
          /*name*/
          ctx2[8]
        );
      }
      if (dirty[0] & /*value*/
      8 && input_1_value_value !== (input_1_value_value = /*value*/
      ctx2[3] ? JSON.stringify(
        /*value*/
        ctx2[3]
      ) : null)) {
        input_1.value = input_1_value_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(input_1);
    }
  };
}
__name(fallback_block_1, "fallback_block_1");
function create_if_block$b(ctx) {
  let current;
  const required_slot_template = (
    /*#slots*/
    ctx[82].required
  );
  const required_slot = create_slot(
    required_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_required_slot_context
  );
  const required_slot_or_fallback = required_slot || fallback_block();
  return {
    c() {
      if (required_slot_or_fallback)
        required_slot_or_fallback.c();
    },
    m(target, anchor) {
      if (required_slot_or_fallback) {
        required_slot_or_fallback.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (required_slot) {
        if (required_slot.p && (!current || dirty[0] & /*value*/
        8 | dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            required_slot,
            required_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              required_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_required_slot_changes
            ),
            get_required_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(required_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(required_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (required_slot_or_fallback)
        required_slot_or_fallback.d(detaching);
    }
  };
}
__name(create_if_block$b, "create_if_block$b");
function fallback_block(ctx) {
  let select;
  return {
    c() {
      select = element("select");
      attr(select, "class", "required svelte-82qwg8");
      select.required = true;
      attr(select, "tabindex", "-1");
      attr(select, "aria-hidden", "true");
    },
    m(target, anchor) {
      insert(target, select, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(select);
    }
  };
}
__name(fallback_block, "fallback_block");
function create_fragment$f(ctx) {
  let div3;
  let t0;
  let span;
  let t1;
  let div0;
  let t2;
  let div1;
  let t3;
  let input_1;
  let input_1_readonly_value;
  let t4;
  let div2;
  let t5;
  let t6;
  let t7;
  let t8;
  let div3_class_value;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*listOpen*/
    ctx[6] && create_if_block_8(ctx)
  );
  let if_block1 = (
    /*focused*/
    ctx[2] && create_if_block_7$1(ctx)
  );
  const prepend_slot_template = (
    /*#slots*/
    ctx[82].prepend
  );
  const prepend_slot = create_slot(
    prepend_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_prepend_slot_context
  );
  let if_block2 = (
    /*hasValue*/
    ctx[25] && create_if_block_4$4(ctx)
  );
  let input_1_levels = [
    {
      readOnly: input_1_readonly_value = !/*searchable*/
      ctx[17]
    },
    /*_inputAttributes*/
    ctx[27],
    { placeholder: (
      /*placeholderText*/
      ctx[33]
    ) },
    { style: (
      /*inputStyles*/
      ctx[18]
    ) },
    { disabled: (
      /*disabled*/
      ctx[11]
    ) }
  ];
  let input_data = {};
  for (let i = 0; i < input_1_levels.length; i += 1) {
    input_data = assign(input_data, input_1_levels[i]);
  }
  let if_block3 = (
    /*loading*/
    ctx[5] && create_if_block_3$4(ctx)
  );
  let if_block4 = (
    /*showClear*/
    ctx[34] && create_if_block_2$4(ctx)
  );
  let if_block5 = (
    /*showChevron*/
    ctx[20] && create_if_block_1$7(ctx)
  );
  const input_hidden_slot_template = (
    /*#slots*/
    ctx[82]["input-hidden"]
  );
  const input_hidden_slot = create_slot(
    input_hidden_slot_template,
    ctx,
    /*$$scope*/
    ctx[81],
    get_input_hidden_slot_context
  );
  const input_hidden_slot_or_fallback = input_hidden_slot || fallback_block_1(ctx);
  let if_block6 = (
    /*required*/
    ctx[16] && (!/*value*/
    ctx[3] || /*value*/
    ctx[3].length === 0) && create_if_block$b(ctx)
  );
  return {
    c() {
      div3 = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      span = element("span");
      if (if_block1)
        if_block1.c();
      t1 = space();
      div0 = element("div");
      if (prepend_slot)
        prepend_slot.c();
      t2 = space();
      div1 = element("div");
      if (if_block2)
        if_block2.c();
      t3 = space();
      input_1 = element("input");
      t4 = space();
      div2 = element("div");
      if (if_block3)
        if_block3.c();
      t5 = space();
      if (if_block4)
        if_block4.c();
      t6 = space();
      if (if_block5)
        if_block5.c();
      t7 = space();
      if (input_hidden_slot_or_fallback)
        input_hidden_slot_or_fallback.c();
      t8 = space();
      if (if_block6)
        if_block6.c();
      attr(span, "aria-live", "polite");
      attr(span, "aria-atomic", "false");
      attr(span, "aria-relevant", "additions text");
      attr(span, "class", "a11y-text svelte-82qwg8");
      attr(div0, "class", "prepend svelte-82qwg8");
      set_attributes(input_1, input_data);
      toggle_class(input_1, "svelte-82qwg8", true);
      attr(div1, "class", "value-container svelte-82qwg8");
      attr(div2, "class", "indicators svelte-82qwg8");
      attr(div3, "class", div3_class_value = "svelte-select " + /*containerClasses*/
      ctx[21] + " svelte-82qwg8");
      attr(
        div3,
        "style",
        /*containerStyles*/
        ctx[14]
      );
      attr(div3, "role", "none");
      toggle_class(
        div3,
        "multi",
        /*multiple*/
        ctx[9]
      );
      toggle_class(
        div3,
        "disabled",
        /*disabled*/
        ctx[11]
      );
      toggle_class(
        div3,
        "focused",
        /*focused*/
        ctx[2]
      );
      toggle_class(
        div3,
        "list-open",
        /*listOpen*/
        ctx[6]
      );
      toggle_class(
        div3,
        "show-chevron",
        /*showChevron*/
        ctx[20]
      );
      toggle_class(
        div3,
        "error",
        /*hasError*/
        ctx[15]
      );
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      if (if_block0)
        if_block0.m(div3, null);
      append(div3, t0);
      append(div3, span);
      if (if_block1)
        if_block1.m(span, null);
      append(div3, t1);
      append(div3, div0);
      if (prepend_slot) {
        prepend_slot.m(div0, null);
      }
      append(div3, t2);
      append(div3, div1);
      if (if_block2)
        if_block2.m(div1, null);
      append(div1, t3);
      append(div1, input_1);
      if (input_1.autofocus)
        input_1.focus();
      ctx[93](input_1);
      set_input_value(
        input_1,
        /*filterText*/
        ctx[4]
      );
      append(div3, t4);
      append(div3, div2);
      if (if_block3)
        if_block3.m(div2, null);
      append(div2, t5);
      if (if_block4)
        if_block4.m(div2, null);
      append(div2, t6);
      if (if_block5)
        if_block5.m(div2, null);
      append(div3, t7);
      if (input_hidden_slot_or_fallback) {
        input_hidden_slot_or_fallback.m(div3, null);
      }
      append(div3, t8);
      if (if_block6)
        if_block6.m(div3, null);
      ctx[95](div3);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            window,
            "click",
            /*handleClickOutside*/
            ctx[42]
          ),
          listen(
            window,
            "keydown",
            /*handleKeyDown*/
            ctx[37]
          ),
          listen(
            input_1,
            "keydown",
            /*handleKeyDown*/
            ctx[37]
          ),
          listen(
            input_1,
            "blur",
            /*handleBlur*/
            ctx[39]
          ),
          listen(
            input_1,
            "focus",
            /*handleFocus*/
            ctx[38]
          ),
          listen(
            input_1,
            "input",
            /*input_1_input_handler*/
            ctx[94]
          ),
          listen(div3, "pointerup", prevent_default(
            /*handleClick*/
            ctx[40]
          )),
          listen(div3, "mousedown", prevent_default(
            /*mousedown_handler*/
            ctx[83]
          )),
          action_destroyer(
            /*floatingRef*/
            ctx[48].call(null, div3)
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*listOpen*/
        ctx2[6]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*listOpen*/
          64) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_8(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div3, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*focused*/
        ctx2[2]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_7$1(ctx2);
          if_block1.c();
          if_block1.m(span, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (prepend_slot) {
        if (prepend_slot.p && (!current || dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            prepend_slot,
            prepend_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              prepend_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_prepend_slot_changes
            ),
            get_prepend_slot_context
          );
        }
      }
      if (
        /*hasValue*/
        ctx2[25]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty[0] & /*hasValue*/
          33554432) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_4$4(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div1, t3);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      set_attributes(input_1, input_data = get_spread_update(input_1_levels, [
        (!current || dirty[0] & /*searchable*/
        131072 && input_1_readonly_value !== (input_1_readonly_value = !/*searchable*/
        ctx2[17])) && { readOnly: input_1_readonly_value },
        dirty[0] & /*_inputAttributes*/
        134217728 && /*_inputAttributes*/
        ctx2[27],
        (!current || dirty[1] & /*placeholderText*/
        4) && { placeholder: (
          /*placeholderText*/
          ctx2[33]
        ) },
        (!current || dirty[0] & /*inputStyles*/
        262144) && { style: (
          /*inputStyles*/
          ctx2[18]
        ) },
        (!current || dirty[0] & /*disabled*/
        2048) && { disabled: (
          /*disabled*/
          ctx2[11]
        ) }
      ]));
      if (dirty[0] & /*filterText*/
      16 && input_1.value !== /*filterText*/
      ctx2[4]) {
        set_input_value(
          input_1,
          /*filterText*/
          ctx2[4]
        );
      }
      toggle_class(input_1, "svelte-82qwg8", true);
      if (
        /*loading*/
        ctx2[5]
      ) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
          if (dirty[0] & /*loading*/
          32) {
            transition_in(if_block3, 1);
          }
        } else {
          if_block3 = create_if_block_3$4(ctx2);
          if_block3.c();
          transition_in(if_block3, 1);
          if_block3.m(div2, t5);
        }
      } else if (if_block3) {
        group_outros();
        transition_out(if_block3, 1, 1, () => {
          if_block3 = null;
        });
        check_outros();
      }
      if (
        /*showClear*/
        ctx2[34]
      ) {
        if (if_block4) {
          if_block4.p(ctx2, dirty);
          if (dirty[1] & /*showClear*/
          8) {
            transition_in(if_block4, 1);
          }
        } else {
          if_block4 = create_if_block_2$4(ctx2);
          if_block4.c();
          transition_in(if_block4, 1);
          if_block4.m(div2, t6);
        }
      } else if (if_block4) {
        group_outros();
        transition_out(if_block4, 1, 1, () => {
          if_block4 = null;
        });
        check_outros();
      }
      if (
        /*showChevron*/
        ctx2[20]
      ) {
        if (if_block5) {
          if_block5.p(ctx2, dirty);
          if (dirty[0] & /*showChevron*/
          1048576) {
            transition_in(if_block5, 1);
          }
        } else {
          if_block5 = create_if_block_1$7(ctx2);
          if_block5.c();
          transition_in(if_block5, 1);
          if_block5.m(div2, null);
        }
      } else if (if_block5) {
        group_outros();
        transition_out(if_block5, 1, 1, () => {
          if_block5 = null;
        });
        check_outros();
      }
      if (input_hidden_slot) {
        if (input_hidden_slot.p && (!current || dirty[0] & /*value*/
        8 | dirty[2] & /*$$scope*/
        524288)) {
          update_slot_base(
            input_hidden_slot,
            input_hidden_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[81],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[81]
            ) : get_slot_changes(
              input_hidden_slot_template,
              /*$$scope*/
              ctx2[81],
              dirty,
              get_input_hidden_slot_changes
            ),
            get_input_hidden_slot_context
          );
        }
      } else {
        if (input_hidden_slot_or_fallback && input_hidden_slot_or_fallback.p && (!current || dirty[0] & /*name, value*/
        264)) {
          input_hidden_slot_or_fallback.p(ctx2, !current ? [-1, -1, -1, -1, -1] : dirty);
        }
      }
      if (
        /*required*/
        ctx2[16] && (!/*value*/
        ctx2[3] || /*value*/
        ctx2[3].length === 0)
      ) {
        if (if_block6) {
          if_block6.p(ctx2, dirty);
          if (dirty[0] & /*required, value*/
          65544) {
            transition_in(if_block6, 1);
          }
        } else {
          if_block6 = create_if_block$b(ctx2);
          if_block6.c();
          transition_in(if_block6, 1);
          if_block6.m(div3, null);
        }
      } else if (if_block6) {
        group_outros();
        transition_out(if_block6, 1, 1, () => {
          if_block6 = null;
        });
        check_outros();
      }
      if (!current || dirty[0] & /*containerClasses*/
      2097152 && div3_class_value !== (div3_class_value = "svelte-select " + /*containerClasses*/
      ctx2[21] + " svelte-82qwg8")) {
        attr(div3, "class", div3_class_value);
      }
      if (!current || dirty[0] & /*containerStyles*/
      16384) {
        attr(
          div3,
          "style",
          /*containerStyles*/
          ctx2[14]
        );
      }
      if (!current || dirty[0] & /*containerClasses, multiple*/
      2097664) {
        toggle_class(
          div3,
          "multi",
          /*multiple*/
          ctx2[9]
        );
      }
      if (!current || dirty[0] & /*containerClasses, disabled*/
      2099200) {
        toggle_class(
          div3,
          "disabled",
          /*disabled*/
          ctx2[11]
        );
      }
      if (!current || dirty[0] & /*containerClasses, focused*/
      2097156) {
        toggle_class(
          div3,
          "focused",
          /*focused*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*containerClasses, listOpen*/
      2097216) {
        toggle_class(
          div3,
          "list-open",
          /*listOpen*/
          ctx2[6]
        );
      }
      if (!current || dirty[0] & /*containerClasses, showChevron*/
      3145728) {
        toggle_class(
          div3,
          "show-chevron",
          /*showChevron*/
          ctx2[20]
        );
      }
      if (!current || dirty[0] & /*containerClasses, hasError*/
      2129920) {
        toggle_class(
          div3,
          "error",
          /*hasError*/
          ctx2[15]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(prepend_slot, local);
      transition_in(if_block2);
      transition_in(if_block3);
      transition_in(if_block4);
      transition_in(if_block5);
      transition_in(input_hidden_slot_or_fallback, local);
      transition_in(if_block6);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(prepend_slot, local);
      transition_out(if_block2);
      transition_out(if_block3);
      transition_out(if_block4);
      transition_out(if_block5);
      transition_out(input_hidden_slot_or_fallback, local);
      transition_out(if_block6);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div3);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (prepend_slot)
        prepend_slot.d(detaching);
      if (if_block2)
        if_block2.d();
      ctx[93](null);
      if (if_block3)
        if_block3.d();
      if (if_block4)
        if_block4.d();
      if (if_block5)
        if_block5.d();
      if (input_hidden_slot_or_fallback)
        input_hidden_slot_or_fallback.d(detaching);
      if (if_block6)
        if_block6.d();
      ctx[95](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$f, "create_fragment$f");
function convertStringItemsToObjects(_items) {
  return _items.map((item, index2) => {
    return { index: index2, value: item, label: `${item}` };
  });
}
__name(convertStringItemsToObjects, "convertStringItemsToObjects");
function isItemFirst(itemIndex) {
  return itemIndex === 0;
}
__name(isItemFirst, "isItemFirst");
function isItemSelectable(item) {
  return item.groupHeader && item.selectable || item.selectable || !item.hasOwnProperty("selectable");
}
__name(isItemSelectable, "isItemSelectable");
function instance$f($$self, $$props, $$invalidate) {
  let hasValue;
  let hideSelectedItem;
  let showClear;
  let placeholderText;
  let ariaSelection;
  let ariaContext;
  let filteredItems;
  let listDom;
  let scrollToHoverItem;
  let { $$slots: slots = {}, $$scope } = $$props;
  const $$slots = compute_slots(slots);
  const dispatch2 = createEventDispatcher();
  let { justValue = null } = $$props;
  let { filter: filter$1 = filter } = $$props;
  let { getItems: getItems$1 = getItems } = $$props;
  let { id = null } = $$props;
  let { name = null } = $$props;
  let { container = void 0 } = $$props;
  let { input = void 0 } = $$props;
  let { multiple = false } = $$props;
  let { multiFullItemClearable = false } = $$props;
  let { disabled = false } = $$props;
  let { focused = false } = $$props;
  let { value = null } = $$props;
  let { filterText = "" } = $$props;
  let { placeholder = "Please select" } = $$props;
  let { placeholderAlwaysShow = false } = $$props;
  let { items = null } = $$props;
  let { label = "label" } = $$props;
  let { itemFilter = /* @__PURE__ */ __name((label2, filterText2, option) => `${label2}`.toLowerCase().includes(filterText2.toLowerCase()), "itemFilter") } = $$props;
  let { groupBy = void 0 } = $$props;
  let { groupFilter = /* @__PURE__ */ __name((groups) => groups, "groupFilter") } = $$props;
  let { groupHeaderSelectable = false } = $$props;
  let { itemId = "value" } = $$props;
  let { loadOptions = void 0 } = $$props;
  let { containerStyles = "" } = $$props;
  let { hasError = false } = $$props;
  let { filterSelectedItems = true } = $$props;
  let { required = false } = $$props;
  let { closeListOnChange = true } = $$props;
  let { createGroupHeaderItem = /* @__PURE__ */ __name((groupValue, item) => {
    return { value: groupValue, [label]: groupValue };
  }, "createGroupHeaderItem") } = $$props;
  const getFilteredItems = /* @__PURE__ */ __name(() => {
    return filteredItems;
  }, "getFilteredItems");
  let { searchable = true } = $$props;
  let { inputStyles = "" } = $$props;
  let { clearable = true } = $$props;
  let { loading = false } = $$props;
  let { listOpen = false } = $$props;
  let timeout;
  let { debounce: debounce2 = /* @__PURE__ */ __name((fn, wait2 = 1) => {
    clearTimeout(timeout);
    timeout = setTimeout(fn, wait2);
  }, "debounce") } = $$props;
  let { debounceWait = 300 } = $$props;
  let { hideEmptyState = false } = $$props;
  let { inputAttributes = {} } = $$props;
  let { listAutoWidth = true } = $$props;
  let { showChevron = false } = $$props;
  let { listOffset = 5 } = $$props;
  let { hoverItemIndex = 0 } = $$props;
  let { floatingConfig = {} } = $$props;
  let { class: containerClasses = "" } = $$props;
  let activeValue;
  let prev_value;
  let prev_filterText;
  let prev_multiple;
  function setValue() {
    if (typeof value === "string") {
      let item = (items || []).find((item2) => item2[itemId] === value);
      $$invalidate(3, value = item || { [itemId]: value, label: value });
    } else if (multiple && Array.isArray(value) && value.length > 0) {
      $$invalidate(3, value = value.map((item) => typeof item === "string" ? { value: item, label: item } : item));
    }
  }
  __name(setValue, "setValue");
  let _inputAttributes;
  function assignInputAttributes() {
    $$invalidate(27, _inputAttributes = Object.assign(
      {
        autocapitalize: "none",
        autocomplete: "off",
        autocorrect: "off",
        spellcheck: false,
        tabindex: 0,
        type: "text",
        "aria-autocomplete": "list"
      },
      inputAttributes
    ));
    if (id) {
      $$invalidate(27, _inputAttributes["id"] = id, _inputAttributes);
    }
    if (!searchable) {
      $$invalidate(27, _inputAttributes["readonly"] = true, _inputAttributes);
    }
  }
  __name(assignInputAttributes, "assignInputAttributes");
  function filterGroupedItems(_items) {
    const groupValues = [];
    const groups = {};
    _items.forEach((item) => {
      const groupValue = groupBy(item);
      if (!groupValues.includes(groupValue)) {
        groupValues.push(groupValue);
        groups[groupValue] = [];
        if (groupValue) {
          groups[groupValue].push(Object.assign(createGroupHeaderItem(groupValue, item), {
            id: groupValue,
            groupHeader: true,
            selectable: groupHeaderSelectable
          }));
        }
      }
      groups[groupValue].push(Object.assign({ groupItem: !!groupValue }, item));
    });
    const sortedGroupedItems = [];
    groupFilter(groupValues).forEach((groupValue) => {
      if (groups[groupValue])
        sortedGroupedItems.push(...groups[groupValue]);
    });
    return sortedGroupedItems;
  }
  __name(filterGroupedItems, "filterGroupedItems");
  function dispatchSelectedItem() {
    if (multiple) {
      if (JSON.stringify(value) !== JSON.stringify(prev_value)) {
        if (checkValueForDuplicates()) {
          dispatch2("input", value);
        }
      }
      return;
    }
    if (!prev_value || JSON.stringify(value[itemId]) !== JSON.stringify(prev_value[itemId])) {
      dispatch2("input", value);
    }
  }
  __name(dispatchSelectedItem, "dispatchSelectedItem");
  function setupMulti() {
    if (value) {
      if (Array.isArray(value)) {
        $$invalidate(3, value = [...value]);
      } else {
        $$invalidate(3, value = [value]);
      }
    }
  }
  __name(setupMulti, "setupMulti");
  function setupSingle() {
    if (value)
      $$invalidate(3, value = null);
  }
  __name(setupSingle, "setupSingle");
  function setValueIndexAsHoverIndex() {
    const valueIndex = filteredItems.findIndex((i) => {
      return i[itemId] === value[itemId];
    });
    checkHoverSelectable(valueIndex, true);
  }
  __name(setValueIndexAsHoverIndex, "setValueIndexAsHoverIndex");
  function dispatchHover(i) {
    dispatch2("hoverItem", i);
  }
  __name(dispatchHover, "dispatchHover");
  function checkHoverSelectable(startingIndex = 0, ignoreGroup) {
    $$invalidate(7, hoverItemIndex = startingIndex < 0 ? 0 : startingIndex);
    if (!ignoreGroup && groupBy && filteredItems[hoverItemIndex] && !filteredItems[hoverItemIndex].selectable) {
      setHoverIndex(1);
    }
  }
  __name(checkHoverSelectable, "checkHoverSelectable");
  function setupFilterText() {
    if (!loadOptions && filterText.length === 0)
      return;
    if (loadOptions) {
      debounce2(
        async function() {
          $$invalidate(5, loading = true);
          let res = await getItems$1({
            dispatch: dispatch2,
            loadOptions,
            convertStringItemsToObjects,
            filterText
          });
          if (res) {
            $$invalidate(5, loading = res.loading);
            $$invalidate(6, listOpen = listOpen ? res.listOpen : filterText.length > 0 ? true : false);
            $$invalidate(2, focused = listOpen && res.focused);
            $$invalidate(51, items = groupBy ? filterGroupedItems(res.filteredItems) : res.filteredItems);
          } else {
            $$invalidate(5, loading = false);
            $$invalidate(2, focused = true);
            $$invalidate(6, listOpen = true);
          }
        },
        debounceWait
      );
    } else {
      $$invalidate(6, listOpen = true);
      if (multiple) {
        $$invalidate(26, activeValue = void 0);
      }
    }
  }
  __name(setupFilterText, "setupFilterText");
  function handleFilterEvent(items2) {
    if (listOpen)
      dispatch2("filter", items2);
  }
  __name(handleFilterEvent, "handleFilterEvent");
  beforeUpdate(async () => {
    $$invalidate(77, prev_value = value);
    $$invalidate(78, prev_filterText = filterText);
    $$invalidate(79, prev_multiple = multiple);
  });
  function computeJustValue() {
    if (multiple)
      return value ? value.map((item) => item[itemId]) : null;
    return value ? value[itemId] : value;
  }
  __name(computeJustValue, "computeJustValue");
  function checkValueForDuplicates() {
    let noDuplicates = true;
    if (value) {
      const ids = [];
      const uniqueValues = [];
      value.forEach((val) => {
        if (!ids.includes(val[itemId])) {
          ids.push(val[itemId]);
          uniqueValues.push(val);
        } else {
          noDuplicates = false;
        }
      });
      if (!noDuplicates)
        $$invalidate(3, value = uniqueValues);
    }
    return noDuplicates;
  }
  __name(checkValueForDuplicates, "checkValueForDuplicates");
  function findItem(selection) {
    let matchTo = selection ? selection[itemId] : value[itemId];
    return items.find((item) => item[itemId] === matchTo);
  }
  __name(findItem, "findItem");
  function updateValueDisplay(items2) {
    if (!items2 || items2.length === 0 || items2.some((item) => typeof item !== "object"))
      return;
    if (!value || (multiple ? value.some((selection) => !selection || !selection[itemId]) : !value[itemId]))
      return;
    if (Array.isArray(value)) {
      $$invalidate(3, value = value.map((selection) => findItem(selection) || selection));
    } else {
      $$invalidate(3, value = findItem() || value);
    }
  }
  __name(updateValueDisplay, "updateValueDisplay");
  async function handleMultiItemClear(i) {
    const itemToRemove = value[i];
    if (value.length === 1) {
      $$invalidate(3, value = void 0);
    } else {
      $$invalidate(3, value = value.filter((item) => {
        return item !== itemToRemove;
      }));
    }
    dispatch2("clear", itemToRemove);
  }
  __name(handleMultiItemClear, "handleMultiItemClear");
  function handleKeyDown(e) {
    if (!focused)
      return;
    e.stopPropagation();
    switch (e.key) {
      case "Escape":
        e.preventDefault();
        closeList();
        break;
      case "Enter":
        e.preventDefault();
        if (listOpen) {
          if (filteredItems.length === 0)
            break;
          const hoverItem = filteredItems[hoverItemIndex];
          if (value && !multiple && value[itemId] === hoverItem[itemId]) {
            closeList();
            break;
          } else {
            handleSelect(filteredItems[hoverItemIndex]);
          }
        }
        break;
      case "ArrowDown":
        e.preventDefault();
        if (listOpen) {
          setHoverIndex(1);
        } else {
          $$invalidate(6, listOpen = true);
          $$invalidate(26, activeValue = void 0);
        }
        break;
      case "ArrowUp":
        e.preventDefault();
        if (listOpen) {
          setHoverIndex(-1);
        } else {
          $$invalidate(6, listOpen = true);
          $$invalidate(26, activeValue = void 0);
        }
        break;
      case "Tab":
        if (listOpen && focused) {
          if (filteredItems.length === 0 || value && value[itemId] === filteredItems[hoverItemIndex][itemId])
            return closeList();
          e.preventDefault();
          handleSelect(filteredItems[hoverItemIndex]);
          closeList();
        }
        break;
      case "Backspace":
        if (!multiple || filterText.length > 0)
          return;
        if (multiple && value && value.length > 0) {
          handleMultiItemClear(activeValue !== void 0 ? activeValue : value.length - 1);
          if (activeValue === 0 || activeValue === void 0)
            break;
          $$invalidate(26, activeValue = value.length > activeValue ? activeValue - 1 : void 0);
        }
        break;
      case "ArrowLeft":
        if (!value || !multiple || filterText.length > 0)
          return;
        if (activeValue === void 0) {
          $$invalidate(26, activeValue = value.length - 1);
        } else if (value.length > activeValue && activeValue !== 0) {
          $$invalidate(26, activeValue -= 1);
        }
        break;
      case "ArrowRight":
        if (!value || !multiple || filterText.length > 0 || activeValue === void 0)
          return;
        if (activeValue === value.length - 1) {
          $$invalidate(26, activeValue = void 0);
        } else if (activeValue < value.length - 1) {
          $$invalidate(26, activeValue += 1);
        }
        break;
    }
  }
  __name(handleKeyDown, "handleKeyDown");
  function handleFocus(e) {
    if (focused && input === document?.activeElement)
      return;
    if (e)
      dispatch2("focus", e);
    input.focus();
    $$invalidate(2, focused = true);
  }
  __name(handleFocus, "handleFocus");
  async function handleBlur(e) {
    if (isScrolling)
      return;
    if (listOpen || focused) {
      dispatch2("blur", e);
      closeList();
      $$invalidate(2, focused = false);
      $$invalidate(26, activeValue = void 0);
      input.blur();
    }
  }
  __name(handleBlur, "handleBlur");
  function handleClick() {
    if (disabled)
      return;
    $$invalidate(6, listOpen = !listOpen);
  }
  __name(handleClick, "handleClick");
  function handleClear() {
    dispatch2("clear", value);
    $$invalidate(3, value = void 0);
    closeList();
    handleFocus();
  }
  __name(handleClear, "handleClear");
  onMount(() => {
    if (listOpen)
      $$invalidate(2, focused = true);
    if (focused && input)
      input.focus();
  });
  function itemSelected(selection) {
    if (selection) {
      $$invalidate(4, filterText = "");
      const item = Object.assign({}, selection);
      if (item.groupHeader && !item.selectable)
        return;
      $$invalidate(3, value = multiple ? value ? value.concat([item]) : [item] : $$invalidate(3, value = item));
      setTimeout(() => {
        if (closeListOnChange)
          closeList();
        $$invalidate(26, activeValue = void 0);
        dispatch2("change", value);
        dispatch2("select", selection);
      });
    }
  }
  __name(itemSelected, "itemSelected");
  function closeList() {
    $$invalidate(4, filterText = "");
    $$invalidate(6, listOpen = false);
  }
  __name(closeList, "closeList");
  let { ariaValues = /* @__PURE__ */ __name((values) => {
    return `Option ${values}, selected.`;
  }, "ariaValues") } = $$props;
  let { ariaListOpen = /* @__PURE__ */ __name((label2, count) => {
    return `You are currently focused on option ${label2}. There are ${count} results available.`;
  }, "ariaListOpen") } = $$props;
  let { ariaFocused = /* @__PURE__ */ __name(() => {
    return `Select is focused, type to refine list, press down to open the menu.`;
  }, "ariaFocused") } = $$props;
  function handleAriaSelection(_multiple) {
    let selected = void 0;
    if (_multiple && value.length > 0) {
      selected = value.map((v) => v[label]).join(", ");
    } else {
      selected = value[label];
    }
    return ariaValues(selected);
  }
  __name(handleAriaSelection, "handleAriaSelection");
  function handleAriaContent() {
    if (!filteredItems || filteredItems.length === 0)
      return "";
    let _item = filteredItems[hoverItemIndex];
    if (listOpen && _item) {
      let count = filteredItems ? filteredItems.length : 0;
      return ariaListOpen(_item[label], count);
    } else {
      return ariaFocused();
    }
  }
  __name(handleAriaContent, "handleAriaContent");
  let list = null;
  let isScrollingTimer;
  function handleListScroll() {
    clearTimeout(isScrollingTimer);
    isScrollingTimer = setTimeout(
      () => {
        isScrolling = false;
      },
      100
    );
  }
  __name(handleListScroll, "handleListScroll");
  function handleClickOutside(event) {
    if (!listOpen && !focused && container && !container.contains(event.target) && !list?.contains(event.target)) {
      handleBlur();
    }
  }
  __name(handleClickOutside, "handleClickOutside");
  onDestroy(() => {
    list?.remove();
  });
  let isScrolling = false;
  function handleSelect(item) {
    if (!item || item.selectable === false)
      return;
    itemSelected(item);
  }
  __name(handleSelect, "handleSelect");
  function handleHover(i) {
    if (isScrolling)
      return;
    $$invalidate(7, hoverItemIndex = i);
  }
  __name(handleHover, "handleHover");
  function handleItemClick(args) {
    const { item, i } = args;
    if (item?.selectable === false)
      return;
    if (value && !multiple && value[itemId] === item[itemId])
      return closeList();
    if (isItemSelectable(item)) {
      $$invalidate(7, hoverItemIndex = i);
      handleSelect(item);
    }
  }
  __name(handleItemClick, "handleItemClick");
  function setHoverIndex(increment) {
    let selectableFilteredItems = filteredItems.filter((item) => !Object.hasOwn(item, "selectable") || item.selectable === true);
    if (selectableFilteredItems.length === 0) {
      return $$invalidate(7, hoverItemIndex = 0);
    }
    if (increment > 0 && hoverItemIndex === filteredItems.length - 1) {
      $$invalidate(7, hoverItemIndex = 0);
    } else if (increment < 0 && hoverItemIndex === 0) {
      $$invalidate(7, hoverItemIndex = filteredItems.length - 1);
    } else {
      $$invalidate(7, hoverItemIndex = hoverItemIndex + increment);
    }
    const hover = filteredItems[hoverItemIndex];
    if (hover && hover.selectable === false) {
      if (increment === 1 || increment === -1)
        setHoverIndex(increment);
      return;
    }
  }
  __name(setHoverIndex, "setHoverIndex");
  function isItemActive(item, value2, itemId2) {
    if (multiple)
      return;
    return value2 && value2[itemId2] === item[itemId2];
  }
  __name(isItemActive, "isItemActive");
  const activeScroll = scrollAction;
  const hoverScroll = scrollAction;
  function scrollAction(node) {
    return {
      update(args) {
        if (args.scroll) {
          handleListScroll();
          node.scrollIntoView({ behavior: "auto", block: "nearest" });
        }
      }
    };
  }
  __name(scrollAction, "scrollAction");
  function setListWidth() {
    const { width } = container.getBoundingClientRect();
    $$invalidate(23, list.style.width = listAutoWidth ? width + "px" : "auto", list);
  }
  __name(setListWidth, "setListWidth");
  let _floatingConfig = {
    strategy: "absolute",
    placement: "bottom-start",
    middleware: [offset(listOffset), flip(), shift()],
    autoUpdate: false
  };
  const [floatingRef, floatingContent, floatingUpdate] = createFloatingActions(_floatingConfig);
  let prefloat = true;
  function listMounted(list2, listOpen2) {
    if (!list2 || !listOpen2)
      return $$invalidate(28, prefloat = true);
    setTimeout(
      () => {
        $$invalidate(28, prefloat = false);
      },
      0
    );
  }
  __name(listMounted, "listMounted");
  function mousedown_handler(event) {
    bubble.call(this, $$self, event);
  }
  __name(mousedown_handler, "mousedown_handler");
  function keydown_handler_1(event) {
    bubble.call(this, $$self, event);
  }
  __name(keydown_handler_1, "keydown_handler_1");
  function pointerup_handler2(event) {
    bubble.call(this, $$self, event);
  }
  __name(pointerup_handler2, "pointerup_handler");
  function keydown_handler(event) {
    bubble.call(this, $$self, event);
  }
  __name(keydown_handler, "keydown_handler");
  const mouseover_handler = /* @__PURE__ */ __name((i) => handleHover(i), "mouseover_handler");
  const focus_handler = /* @__PURE__ */ __name((i) => handleHover(i), "focus_handler");
  const click_handler = /* @__PURE__ */ __name((item, i) => handleItemClick({ item, i }), "click_handler");
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      list = $$value;
      $$invalidate(23, list);
    });
  }
  __name(div_binding, "div_binding");
  const pointerup_handler_1 = /* @__PURE__ */ __name((i) => handleMultiItemClear(i), "pointerup_handler_1");
  const click_handler_1 = /* @__PURE__ */ __name((i) => multiFullItemClearable ? handleMultiItemClear(i) : {}, "click_handler_1");
  function input_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      input = $$value;
      $$invalidate(1, input);
    });
  }
  __name(input_1_binding, "input_1_binding");
  function input_1_input_handler() {
    filterText = this.value;
    $$invalidate(4, filterText);
  }
  __name(input_1_input_handler, "input_1_input_handler");
  function div3_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      container = $$value;
      $$invalidate(0, container);
    });
  }
  __name(div3_binding, "div3_binding");
  $$self.$$set = ($$props2) => {
    if ("justValue" in $$props2)
      $$invalidate(52, justValue = $$props2.justValue);
    if ("filter" in $$props2)
      $$invalidate(53, filter$1 = $$props2.filter);
    if ("getItems" in $$props2)
      $$invalidate(54, getItems$1 = $$props2.getItems);
    if ("id" in $$props2)
      $$invalidate(55, id = $$props2.id);
    if ("name" in $$props2)
      $$invalidate(8, name = $$props2.name);
    if ("container" in $$props2)
      $$invalidate(0, container = $$props2.container);
    if ("input" in $$props2)
      $$invalidate(1, input = $$props2.input);
    if ("multiple" in $$props2)
      $$invalidate(9, multiple = $$props2.multiple);
    if ("multiFullItemClearable" in $$props2)
      $$invalidate(10, multiFullItemClearable = $$props2.multiFullItemClearable);
    if ("disabled" in $$props2)
      $$invalidate(11, disabled = $$props2.disabled);
    if ("focused" in $$props2)
      $$invalidate(2, focused = $$props2.focused);
    if ("value" in $$props2)
      $$invalidate(3, value = $$props2.value);
    if ("filterText" in $$props2)
      $$invalidate(4, filterText = $$props2.filterText);
    if ("placeholder" in $$props2)
      $$invalidate(56, placeholder = $$props2.placeholder);
    if ("placeholderAlwaysShow" in $$props2)
      $$invalidate(57, placeholderAlwaysShow = $$props2.placeholderAlwaysShow);
    if ("items" in $$props2)
      $$invalidate(51, items = $$props2.items);
    if ("label" in $$props2)
      $$invalidate(12, label = $$props2.label);
    if ("itemFilter" in $$props2)
      $$invalidate(58, itemFilter = $$props2.itemFilter);
    if ("groupBy" in $$props2)
      $$invalidate(59, groupBy = $$props2.groupBy);
    if ("groupFilter" in $$props2)
      $$invalidate(60, groupFilter = $$props2.groupFilter);
    if ("groupHeaderSelectable" in $$props2)
      $$invalidate(61, groupHeaderSelectable = $$props2.groupHeaderSelectable);
    if ("itemId" in $$props2)
      $$invalidate(13, itemId = $$props2.itemId);
    if ("loadOptions" in $$props2)
      $$invalidate(62, loadOptions = $$props2.loadOptions);
    if ("containerStyles" in $$props2)
      $$invalidate(14, containerStyles = $$props2.containerStyles);
    if ("hasError" in $$props2)
      $$invalidate(15, hasError = $$props2.hasError);
    if ("filterSelectedItems" in $$props2)
      $$invalidate(63, filterSelectedItems = $$props2.filterSelectedItems);
    if ("required" in $$props2)
      $$invalidate(16, required = $$props2.required);
    if ("closeListOnChange" in $$props2)
      $$invalidate(64, closeListOnChange = $$props2.closeListOnChange);
    if ("createGroupHeaderItem" in $$props2)
      $$invalidate(65, createGroupHeaderItem = $$props2.createGroupHeaderItem);
    if ("searchable" in $$props2)
      $$invalidate(17, searchable = $$props2.searchable);
    if ("inputStyles" in $$props2)
      $$invalidate(18, inputStyles = $$props2.inputStyles);
    if ("clearable" in $$props2)
      $$invalidate(67, clearable = $$props2.clearable);
    if ("loading" in $$props2)
      $$invalidate(5, loading = $$props2.loading);
    if ("listOpen" in $$props2)
      $$invalidate(6, listOpen = $$props2.listOpen);
    if ("debounce" in $$props2)
      $$invalidate(68, debounce2 = $$props2.debounce);
    if ("debounceWait" in $$props2)
      $$invalidate(69, debounceWait = $$props2.debounceWait);
    if ("hideEmptyState" in $$props2)
      $$invalidate(19, hideEmptyState = $$props2.hideEmptyState);
    if ("inputAttributes" in $$props2)
      $$invalidate(70, inputAttributes = $$props2.inputAttributes);
    if ("listAutoWidth" in $$props2)
      $$invalidate(71, listAutoWidth = $$props2.listAutoWidth);
    if ("showChevron" in $$props2)
      $$invalidate(20, showChevron = $$props2.showChevron);
    if ("listOffset" in $$props2)
      $$invalidate(72, listOffset = $$props2.listOffset);
    if ("hoverItemIndex" in $$props2)
      $$invalidate(7, hoverItemIndex = $$props2.hoverItemIndex);
    if ("floatingConfig" in $$props2)
      $$invalidate(73, floatingConfig = $$props2.floatingConfig);
    if ("class" in $$props2)
      $$invalidate(21, containerClasses = $$props2.class);
    if ("ariaValues" in $$props2)
      $$invalidate(74, ariaValues = $$props2.ariaValues);
    if ("ariaListOpen" in $$props2)
      $$invalidate(75, ariaListOpen = $$props2.ariaListOpen);
    if ("ariaFocused" in $$props2)
      $$invalidate(76, ariaFocused = $$props2.ariaFocused);
    if ("$$scope" in $$props2)
      $$invalidate(81, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*value*/
    8 | $$self.$$.dirty[1] & /*items*/
    1048576) {
      if (value)
        setValue();
    }
    if ($$self.$$.dirty[0] & /*searchable*/
    131072 | $$self.$$.dirty[2] & /*inputAttributes*/
    256) {
      if (inputAttributes || !searchable)
        assignInputAttributes();
    }
    if ($$self.$$.dirty[0] & /*multiple*/
    512) {
      if (multiple)
        setupMulti();
    }
    if ($$self.$$.dirty[0] & /*multiple*/
    512 | $$self.$$.dirty[2] & /*prev_multiple*/
    131072) {
      if (prev_multiple && !multiple)
        setupSingle();
    }
    if ($$self.$$.dirty[0] & /*multiple, value*/
    520) {
      if (multiple && value && value.length > 1)
        checkValueForDuplicates();
    }
    if ($$self.$$.dirty[0] & /*value*/
    8) {
      if (value)
        dispatchSelectedItem();
    }
    if ($$self.$$.dirty[0] & /*value, multiple*/
    520 | $$self.$$.dirty[2] & /*prev_value*/
    32768) {
      if (!value && multiple && prev_value)
        dispatch2("input", value);
    }
    if ($$self.$$.dirty[0] & /*focused, input*/
    6) {
      if (!focused && input)
        closeList();
    }
    if ($$self.$$.dirty[0] & /*filterText*/
    16 | $$self.$$.dirty[2] & /*prev_filterText*/
    65536) {
      if (filterText !== prev_filterText)
        setupFilterText();
    }
    if ($$self.$$.dirty[0] & /*filterText, multiple, value, itemId, label*/
    12824 | $$self.$$.dirty[1] & /*filter, items, groupBy, itemFilter*/
    407896064 | $$self.$$.dirty[2] & /*loadOptions, filterSelectedItems*/
    3) {
      $$invalidate(24, filteredItems = filter$1({
        loadOptions,
        filterText,
        items,
        multiple,
        value,
        itemId,
        groupBy,
        label,
        filterSelectedItems,
        itemFilter,
        convertStringItemsToObjects,
        filterGroupedItems
      }));
    }
    if ($$self.$$.dirty[0] & /*multiple, listOpen, value, filteredItems*/
    16777800) {
      if (!multiple && listOpen && value && filteredItems)
        setValueIndexAsHoverIndex();
    }
    if ($$self.$$.dirty[0] & /*listOpen, multiple*/
    576) {
      if (listOpen && multiple)
        $$invalidate(7, hoverItemIndex = 0);
    }
    if ($$self.$$.dirty[0] & /*filterText*/
    16) {
      if (filterText)
        $$invalidate(7, hoverItemIndex = 0);
    }
    if ($$self.$$.dirty[0] & /*hoverItemIndex*/
    128) {
      dispatchHover(hoverItemIndex);
    }
    if ($$self.$$.dirty[0] & /*multiple, value*/
    520) {
      $$invalidate(25, hasValue = multiple ? value && value.length > 0 : value);
    }
    if ($$self.$$.dirty[0] & /*hasValue, filterText*/
    33554448) {
      $$invalidate(35, hideSelectedItem = hasValue && filterText.length > 0);
    }
    if ($$self.$$.dirty[0] & /*hasValue, disabled, loading*/
    33556512 | $$self.$$.dirty[2] & /*clearable*/
    32) {
      $$invalidate(34, showClear = hasValue && clearable && !disabled && !loading);
    }
    if ($$self.$$.dirty[0] & /*multiple, value*/
    520 | $$self.$$.dirty[1] & /*placeholderAlwaysShow, placeholder*/
    100663296) {
      $$invalidate(33, placeholderText = placeholderAlwaysShow && multiple ? placeholder : multiple && value?.length === 0 ? placeholder : value ? "" : placeholder);
    }
    if ($$self.$$.dirty[0] & /*value, multiple*/
    520) {
      $$invalidate(32, ariaSelection = value ? handleAriaSelection(multiple) : "");
    }
    if ($$self.$$.dirty[0] & /*filteredItems, hoverItemIndex, focused, listOpen*/
    16777412) {
      $$invalidate(31, ariaContext = handleAriaContent());
    }
    if ($$self.$$.dirty[1] & /*items*/
    1048576) {
      updateValueDisplay(items);
    }
    if ($$self.$$.dirty[0] & /*multiple, value, itemId*/
    8712) {
      $$invalidate(52, justValue = computeJustValue());
    }
    if ($$self.$$.dirty[0] & /*multiple, value*/
    520 | $$self.$$.dirty[2] & /*prev_value*/
    32768) {
      if (!multiple && prev_value && !value)
        dispatch2("input", value);
    }
    if ($$self.$$.dirty[0] & /*listOpen, filteredItems, multiple, value*/
    16777800) {
      if (listOpen && filteredItems && !multiple && !value)
        checkHoverSelectable();
    }
    if ($$self.$$.dirty[0] & /*filteredItems*/
    16777216) {
      handleFilterEvent(filteredItems);
    }
    if ($$self.$$.dirty[0] & /*container*/
    1 | $$self.$$.dirty[2] & /*floatingConfig*/
    2048) {
      if (container && floatingConfig?.autoUpdate === void 0) {
        $$invalidate(80, _floatingConfig.autoUpdate = true, _floatingConfig);
      }
    }
    if ($$self.$$.dirty[0] & /*container*/
    1 | $$self.$$.dirty[2] & /*floatingConfig, _floatingConfig*/
    264192) {
      if (container && floatingConfig)
        floatingUpdate(Object.assign(_floatingConfig, floatingConfig));
    }
    if ($$self.$$.dirty[0] & /*list*/
    8388608) {
      $$invalidate(30, listDom = !!list);
    }
    if ($$self.$$.dirty[0] & /*list, listOpen*/
    8388672) {
      listMounted(list, listOpen);
    }
    if ($$self.$$.dirty[0] & /*listOpen, container, list*/
    8388673) {
      if (listOpen && container && list)
        setListWidth();
    }
    if ($$self.$$.dirty[0] & /*hoverItemIndex*/
    128) {
      $$invalidate(29, scrollToHoverItem = hoverItemIndex);
    }
    if ($$self.$$.dirty[0] & /*input, listOpen, focused*/
    70) {
      if (input && listOpen && !focused)
        handleFocus();
    }
  };
  return [
    container,
    input,
    focused,
    value,
    filterText,
    loading,
    listOpen,
    hoverItemIndex,
    name,
    multiple,
    multiFullItemClearable,
    disabled,
    label,
    itemId,
    containerStyles,
    hasError,
    required,
    searchable,
    inputStyles,
    hideEmptyState,
    showChevron,
    containerClasses,
    handleClear,
    list,
    filteredItems,
    hasValue,
    activeValue,
    _inputAttributes,
    prefloat,
    scrollToHoverItem,
    listDom,
    ariaContext,
    ariaSelection,
    placeholderText,
    showClear,
    hideSelectedItem,
    handleMultiItemClear,
    handleKeyDown,
    handleFocus,
    handleBlur,
    handleClick,
    handleListScroll,
    handleClickOutside,
    handleHover,
    handleItemClick,
    isItemActive,
    activeScroll,
    hoverScroll,
    floatingRef,
    floatingContent,
    $$slots,
    items,
    justValue,
    filter$1,
    getItems$1,
    id,
    placeholder,
    placeholderAlwaysShow,
    itemFilter,
    groupBy,
    groupFilter,
    groupHeaderSelectable,
    loadOptions,
    filterSelectedItems,
    closeListOnChange,
    createGroupHeaderItem,
    getFilteredItems,
    clearable,
    debounce2,
    debounceWait,
    inputAttributes,
    listAutoWidth,
    listOffset,
    floatingConfig,
    ariaValues,
    ariaListOpen,
    ariaFocused,
    prev_value,
    prev_filterText,
    prev_multiple,
    _floatingConfig,
    $$scope,
    slots,
    mousedown_handler,
    keydown_handler_1,
    pointerup_handler2,
    keydown_handler,
    mouseover_handler,
    focus_handler,
    click_handler,
    div_binding,
    pointerup_handler_1,
    click_handler_1,
    input_1_binding,
    input_1_input_handler,
    div3_binding
  ];
}
__name(instance$f, "instance$f");
const _Select = class _Select extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$f,
      create_fragment$f,
      safe_not_equal,
      {
        justValue: 52,
        filter: 53,
        getItems: 54,
        id: 55,
        name: 8,
        container: 0,
        input: 1,
        multiple: 9,
        multiFullItemClearable: 10,
        disabled: 11,
        focused: 2,
        value: 3,
        filterText: 4,
        placeholder: 56,
        placeholderAlwaysShow: 57,
        items: 51,
        label: 12,
        itemFilter: 58,
        groupBy: 59,
        groupFilter: 60,
        groupHeaderSelectable: 61,
        itemId: 13,
        loadOptions: 62,
        containerStyles: 14,
        hasError: 15,
        filterSelectedItems: 63,
        required: 16,
        closeListOnChange: 64,
        createGroupHeaderItem: 65,
        getFilteredItems: 66,
        searchable: 17,
        inputStyles: 18,
        clearable: 67,
        loading: 5,
        listOpen: 6,
        debounce: 68,
        debounceWait: 69,
        hideEmptyState: 19,
        inputAttributes: 70,
        listAutoWidth: 71,
        showChevron: 20,
        listOffset: 72,
        hoverItemIndex: 7,
        floatingConfig: 73,
        class: 21,
        handleClear: 22,
        ariaValues: 74,
        ariaListOpen: 75,
        ariaFocused: 76
      },
      null,
      [-1, -1, -1, -1, -1]
    );
  }
  get getFilteredItems() {
    return this.$$.ctx[66];
  }
  get handleClear() {
    return this.$$.ctx[22];
  }
};
__name(_Select, "Select");
let Select = _Select;
function create_if_block$a(ctx) {
  let div;
  let label;
  let t0_value = localize(`ITEM-PILES.Dialogs.GiveItems.ContentMultipleQuantity`, {
    quantity: (
      /*itemQuantity*/
      ctx[5]
    ),
    itemName: (
      /*item*/
      ctx[0].name
    )
  }) + "";
  let t0;
  let t1;
  let sliderinput;
  let updating_value;
  let current;
  function sliderinput_value_binding(value) {
    ctx[12](value);
  }
  __name(sliderinput_value_binding, "sliderinput_value_binding");
  let sliderinput_props = {
    min: 1,
    max: (
      /*sliderQuantity*/
      ctx[6]
    ),
    maxInput: (
      /*sliderQuantity*/
      ctx[6]
    ),
    divideBy: 1
  };
  if (
    /*quantity*/
    ctx[2] !== void 0
  ) {
    sliderinput_props.value = /*quantity*/
    ctx[2];
  }
  sliderinput = new SliderInput({ props: sliderinput_props });
  binding_callbacks.push(() => bind(sliderinput, "value", sliderinput_value_binding));
  return {
    c() {
      div = element("div");
      label = element("label");
      t0 = text(t0_value);
      t1 = space();
      create_component(sliderinput.$$.fragment);
      attr(div, "class", "form-group item-piles-text-center");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, label);
      append(label, t0);
      insert(target, t1, anchor);
      mount_component(sliderinput, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if ((!current || dirty & /*item*/
      1) && t0_value !== (t0_value = localize(`ITEM-PILES.Dialogs.GiveItems.ContentMultipleQuantity`, {
        quantity: (
          /*itemQuantity*/
          ctx2[5]
        ),
        itemName: (
          /*item*/
          ctx2[0].name
        )
      }) + ""))
        set_data(t0, t0_value);
      const sliderinput_changes = {};
      if (!updating_value && dirty & /*quantity*/
      4) {
        updating_value = true;
        sliderinput_changes.value = /*quantity*/
        ctx2[2];
        add_flush_callback(() => updating_value = false);
      }
      sliderinput.$set(sliderinput_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sliderinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sliderinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t1);
      destroy_component(sliderinput, detaching);
    }
  };
}
__name(create_if_block$a, "create_if_block$a");
function create_fragment$e(ctx) {
  let form_1;
  let h3;
  let t0_value = localize(`ITEM-PILES.Dialogs.GiveItems.Header`, { item_name: (
    /*item*/
    ctx[0].name
  ) }) + "";
  let t0;
  let t1;
  let t2;
  let div;
  let select;
  let div_1;
  let updating_value;
  let t3;
  let footer;
  let button0;
  let i0;
  let t4;
  let t5_value = localize(`ITEM-PILES.Dialogs.GiveItems.Submit`) + "";
  let t5;
  let button0_disabled_value;
  let t6;
  let button1;
  let i1;
  let t7;
  let t8_value = localize("Cancel") + "";
  let t8;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*itemQuantity*/
    ctx[5] > 1 && /*canItemStack*/
    ctx[7] && create_if_block$a(ctx)
  );
  function select_value_binding(value) {
    ctx[13](value);
  }
  __name(select_value_binding, "select_value_binding");
  let select_props = {
    floatingConfig: { strategy: "fixed", placement: "bottom" },
    groupBy: (
      /*groupBy*/
      ctx[9]
    ),
    items: (
      /*items*/
      ctx[8]
    ),
    placeholder: localize("ITEM-PILES.Dialogs.GiveItems.SelectPlaceholder")
  };
  if (
    /*selectedActor*/
    ctx[3] !== void 0
  ) {
    select_props.value = /*selectedActor*/
    ctx[3];
  }
  select = new Select({ props: select_props });
  binding_callbacks.push(() => bind(select, "value", select_value_binding));
  return {
    c() {
      form_1 = element("form");
      h3 = element("h3");
      t0 = text(t0_value);
      t1 = space();
      if (if_block)
        if_block.c();
      t2 = space();
      div = element("div");
      div_1 = element("div");
      create_component(select.$$.fragment);
      t3 = space();
      footer = element("footer");
      button0 = element("button");
      i0 = element("i");
      t4 = space();
      t5 = text(t5_value);
      t6 = space();
      button1 = element("button");
      i1 = element("i");
      t7 = space();
      t8 = text(t8_value);
      set_style(h3, "text-align", "center");
      set_style(div_1, "display", "contents");
      set_style(div_1, "--background", "rgba(0, 0, 0, 0.05)");
      set_style(div_1, "--border-radius", "5px");
      set_style(div_1, "--font-family", "inherit");
      set_style(div_1, "--font-size", "0.833rem");
      set_style(div_1, "--group-item-padding-left", "1rem");
      set_style(div_1, "--group-title-font-size", "0.833rem");
      set_style(div_1, "--group-title-font-weight", "bold");
      set_style(div_1, "--height", "calc(var(--form-field-height) + 1px)");
      set_style(div_1, "--input-color", "black");
      set_style(div_1, "--item-padding", "0.25rem");
      set_style(div_1, "--margin", "0.25rem 0");
      set_style(div_1, "--padding", "0 8px");
      set_style(div_1, "--text-overflow", "ellipsis");
      attr(div, "class", "form-group");
      attr(i0, "class", "fas fa-box");
      button0.disabled = button0_disabled_value = !/*selectedActor*/
      ctx[3];
      attr(button0, "type", "button");
      attr(i1, "class", "fas fa-times");
      attr(button1, "type", "button");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
      set_style(footer, "margin-top", "0.25rem");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-flexcol");
      set_style(form_1, "padding", "0.5rem");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, h3);
      append(h3, t0);
      append(form_1, t1);
      if (if_block)
        if_block.m(form_1, null);
      append(form_1, t2);
      append(form_1, div);
      append(div, div_1);
      mount_component(select, div_1, null);
      append(form_1, t3);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i0);
      append(button0, t4);
      append(button0, t5);
      append(footer, t6);
      append(footer, button1);
      append(button1, i1);
      append(button1, t7);
      append(button1, t8);
      ctx[15](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[10],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[14]
          ),
          listen(form_1, "submit", prevent_default(
            /*submit*/
            ctx[11]
          ), { once: true })
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if ((!current || dirty & /*item*/
      1) && t0_value !== (t0_value = localize(`ITEM-PILES.Dialogs.GiveItems.Header`, { item_name: (
        /*item*/
        ctx2[0].name
      ) }) + ""))
        set_data(t0, t0_value);
      if (
        /*itemQuantity*/
        ctx2[5] > 1 && /*canItemStack*/
        ctx2[7]
      )
        if_block.p(ctx2, dirty);
      const select_changes = {};
      if (!updating_value && dirty & /*selectedActor*/
      8) {
        updating_value = true;
        select_changes.value = /*selectedActor*/
        ctx2[3];
        add_flush_callback(() => updating_value = false);
      }
      select.$set(select_changes);
      if (!current || dirty & /*selectedActor*/
      8 && button0_disabled_value !== (button0_disabled_value = !/*selectedActor*/
      ctx2[3])) {
        button0.disabled = button0_disabled_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      transition_in(select.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      transition_out(select.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      if (if_block)
        if_block.d();
      destroy_component(select);
      ctx[15](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$e, "create_fragment$e");
function instance$e($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { item } = $$props;
  let form;
  const itemQuantity = getItemQuantity(item);
  const sliderQuantity = itemQuantity + (application.options?.quantityAdjustment ?? 0);
  const canItemStack$1 = canItemStack(item);
  let quantity = 1;
  let selectedActor = localStorage.getItem("item-piles-give-item") ?? false;
  let items = Array.from(game.actors).filter((actor) => {
    return (actor.type === "character" || actor.type === "npc") && actor !== item.parent && !isValidItemPile(actor) && (game.user.isGM || (actor.ownership["default"] >= 1 || actor.ownership[game.user.id] >= 1));
  }).map((actor) => ({
    value: actor.uuid,
    label: actor.name,
    actor,
    group: actor.hasPlayerOwner ? "Player Characters" : "Other Characters"
  })).sort((a, b) => {
    return a.name > b.name ? b.actor.hasPlayerOwner - a.actor.hasPlayerOwner - 1 : b.actor.hasPlayerOwner - a.actor.hasPlayerOwner + 1;
  });
  if (selectedActor && !items.some((data2) => data2.value === selectedActor)) {
    selectedActor = false;
  }
  const groupBy = /* @__PURE__ */ __name((item2) => item2.group, "groupBy");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function submit() {
    localStorage.setItem("item-piles-give-item", selectedActor.value);
    application.options.resolve({ quantity, target: selectedActor.value });
    application.close();
  }
  __name(submit, "submit");
  function sliderinput_value_binding(value) {
    quantity = value;
    $$invalidate(2, quantity);
  }
  __name(sliderinput_value_binding, "sliderinput_value_binding");
  function select_value_binding(value) {
    selectedActor = value;
    $$invalidate(3, selectedActor);
  }
  __name(select_value_binding, "select_value_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(1, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
  };
  return [
    item,
    form,
    quantity,
    selectedActor,
    application,
    itemQuantity,
    sliderQuantity,
    canItemStack$1,
    items,
    groupBy,
    requestSubmit,
    submit,
    sliderinput_value_binding,
    select_value_binding,
    click_handler,
    form_1_binding
  ];
}
__name(instance$e, "instance$e");
const _Give_items_shell = class _Give_items_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$e, create_fragment$e, safe_not_equal, { item: 0 });
  }
};
__name(_Give_items_shell, "Give_items_shell");
let Give_items_shell = _Give_items_shell;
const _GiveItems = class _GiveItems extends TJSDialog {
  /**
   *
   * @param item
   * @param options
   */
  constructor(item, options = {}) {
    super({
      title: game.i18n.localize(`ITEM-PILES.Dialogs.GiveItems.Title`),
      id: `item-pile-give-items-${item.id}-${randomID()}`,
      content: {
        class: Give_items_shell,
        props: {
          item
        }
      },
      modal: true,
      draggable: false
    }, {
      ...options,
      focusAuto: false,
      close: () => this.options.resolve?.(null)
    });
    this.item = item;
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      width: 430,
      height: "auto",
      classes: ["item-piles-app visible-overflow"]
    });
  }
  static getActiveApps(id) {
    return getActiveApps(`item-pile-give-items-${id}`);
  }
  static async show(item, options = {}) {
    const apps = this.getActiveApps(item.id);
    if (apps.length) {
      for (let app of apps) {
        app.render(false, { focus: true });
      }
      return;
    }
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(item, options).render(true, { focus: true });
    });
  }
};
__name(_GiveItems, "GiveItems");
let GiveItems = _GiveItems;
const dnd5e = {
  "VERSION": "1.0.7",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price.value",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "spell,feat,class,subclass,background"
    },
    {
      "path": "system.weaponType",
      "filters": "natural"
    }
  ],
  // This function is an optional system handler that specifically transforms an item when it is added to actors
  "ITEM_TRANSFORMER": async (itemData) => {
    ["equipped", "proficient", "prepared"].forEach((key) => {
      if (itemData?.system?.[key] !== void 0) {
        delete itemData.system[key];
      }
    });
    setProperty(itemData, "system.attunement", Math.min(CONFIG.DND5E.attunementTypes.REQUIRED, itemData?.system?.attunement ?? 0));
    if (itemData.type === "spell") {
      try {
        const scroll = await Item.implementation.createScrollFromSpell(itemData);
        itemData = scroll.toObject();
      } catch (err) {
      }
    }
    return itemData;
  },
  // This function is an optional system handler that specifically transforms an item's price into a more unified numeric format
  "ITEM_COST_TRANSFORMER": (item, currencies) => {
    const overallCost = Number(getProperty(item, "system.price.value")) ?? 0;
    const priceDenomination = getProperty(item, "system.price.denomination");
    if (priceDenomination) {
      const currencyDenomination = currencies.filter((currency) => currency.type === "attribute").find((currency) => {
        return currency.data.path.toLowerCase().endsWith(priceDenomination);
      });
      if (currencyDenomination) {
        return overallCost * currencyDenomination.exchangeRate;
      }
    }
    return overallCost ?? 0;
  },
  "PRICE_MODIFIER_TRANSFORMER": ({
    buyPriceModifier,
    sellPriceModifier,
    actor = false,
    actorPriceModifiers = []
  } = {}) => {
    const modifiers = {
      buyPriceModifier,
      sellPriceModifier
    };
    if (!actor)
      return modifiers;
    const groupModifiers = actorPriceModifiers.map((data2) => ({ ...data2, actor: fromUuidSync(data2.actorUuid) })).filter((data2) => {
      return data2.actor && data2.actor.type === "group" && data2.actor.system.members.some((member) => member === actor);
    });
    modifiers.buyPriceModifier = groupModifiers.reduce((acc, data2) => {
      return data2.override ? data2.buyPriceModifier ?? acc : acc * data2.buyPriceModifier;
    }, buyPriceModifier);
    modifiers.sellPriceModifier = groupModifiers.reduce((acc, data2) => {
      return data2.override ? data2.sellPriceModifier ?? acc : acc * data2.sellPriceModifier;
    }, sellPriceModifier);
    return modifiers;
  },
  "SOFT_MIGRATIONS": {
    "1.0.6-1.0.7": {
      "ITEM_FILTERS": [
        {
          "path": "type",
          "filters": "spell,feat,class,subclass,background,race"
        }
      ]
    }
  },
  "PILE_DEFAULTS": {
    merchantColumns: [{
      label: '<i class="fa-solid fa-shield"></i>',
      path: "system.equipped",
      formatting: "{#}",
      buying: false,
      selling: true,
      mapping: {
        "true": "✔",
        "false": ""
      }
    }, {
      label: "Rarity",
      path: "system.rarity",
      formatting: "{#}",
      buying: true,
      selling: true,
      mapping: {
        "common": "DND5E.ItemRarityCommon",
        "uncommon": "DND5E.ItemRarityUncommon",
        "rare": "DND5E.ItemRarityRare",
        "veryRare": "DND5E.ItemRarityVeryRare",
        "legendary": "DND5E.ItemRarityLegendary",
        "artifact": "DND5E.ItemRarityArtifact"
      }
    }]
  },
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "DND5E.CurrencyPP",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}PP",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyGP",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}GP",
      data: {
        path: "system.currency.gp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyEP",
      img: "icons/commodities/currency/coin-inset-copper-axe.webp",
      abbreviation: "{#}EP",
      data: {
        path: "system.currency.ep"
      },
      primary: false,
      exchangeRate: 0.5
    },
    {
      type: "attribute",
      name: "DND5E.CurrencySP",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#}SP",
      data: {
        path: "system.currency.sp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyCP",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}CP",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ],
  "VAULT_STYLES": [
    {
      path: "system.rarity",
      value: "artifact",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,191,0,1)"
      }
    },
    {
      path: "system.rarity",
      value: "legendary",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,119,0,1)"
      }
    },
    {
      path: "system.rarity",
      value: "veryRare",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,0,247,1)"
      }
    },
    {
      path: "system.rarity",
      value: "rare",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(0,136,255,1)"
      }
    },
    {
      path: "system.rarity",
      value: "uncommon",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(0,255,9,1)"
      }
    }
  ],
  "SYSTEM_HOOKS": () => {
    Hooks.on("dnd5e.getItemContextOptions", (item, options) => {
      options.push({
        name: "Give to character",
        icon: "<i class='fa fa-user'></i>",
        callback: async () => {
          const result = await GiveItems.show(item);
          if (!result)
            return;
          PrivateAPI._giveItem({
            itemData: {
              item: item.toObject(),
              quantity: result.quantity
            },
            source: item.parent.uuid,
            target: result.target
          }, { skipQuantityDialog: true });
        },
        condition: !game.itempiles.API.isItemInvalid(item)
      });
    });
  }
};
const dnd5e203 = {
  "VERSION": "1.0.3",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "spell,feat,class,subclass,background"
    },
    {
      "path": "system.weaponType",
      "filters": "natural"
    }
  ],
  // This function is an optional system handler that specifically transforms an item when it is added to actors
  "ITEM_TRANSFORMER": async (itemData) => {
    ["equipped", "proficient", "prepared"].forEach((key) => {
      if (itemData?.system?.[key] !== void 0) {
        delete itemData.system[key];
      }
    });
    setProperty(itemData, "system.attunement", Math.min(CONFIG.DND5E.attunementTypes.REQUIRED, itemData?.system?.attunement ?? 0));
    if (itemData.type === "spell") {
      try {
        const scroll = await Item.implementation.createScrollFromSpell(itemData);
        itemData = scroll.toObject();
      } catch (err) {
      }
    }
    return itemData;
  },
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "DND5E.CurrencyPP",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}PP",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyGP",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}GP",
      data: {
        path: "system.currency.gp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyEP",
      img: "icons/commodities/currency/coin-inset-copper-axe.webp",
      abbreviation: "{#}EP",
      data: {
        path: "system.currency.ep"
      },
      primary: false,
      exchangeRate: 0.5
    },
    {
      type: "attribute",
      name: "DND5E.CurrencySP",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#}SP",
      data: {
        path: "system.currency.sp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyCP",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}CP",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ],
  VAULT_STYLES: [
    {
      path: "system.rarity",
      value: "artifact",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,191,0,1)"
      }
    },
    {
      path: "system.rarity",
      value: "legendary",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,119,0,1)"
      }
    },
    {
      path: "system.rarity",
      value: "veryRare",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,0,247,1)"
      }
    },
    {
      path: "system.rarity",
      value: "rare",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(0,136,255,1)"
      }
    },
    {
      path: "system.rarity",
      value: "uncommon",
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(0,255,9,1)"
      }
    }
  ]
};
const pf1 = {
  "VERSION": "1.0.5",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "npc",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // This function is an optional system handler that specifically transforms an item's price into a more unified numeric format
  "ITEM_COST_TRANSFORMER": (item, currencies) => {
    const origQuantity = item.system.quantity;
    item.system.quantity = 1;
    const value = item.getValue({ sellValue: 1 });
    item.system.quantity = origQuantity;
    return value;
  },
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "attack,buff,class,feat,race,spell"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "PF1.CurrencyPlatinumP",
      img: "systems/pf1/icons/items/inventory/coins-silver.jpg",
      abbreviation: "{#}P",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "PF1.CurrencyGoldP",
      img: "systems/pf1/icons/items/inventory/coin-gold.jpg",
      abbreviation: "{#}G",
      data: {
        path: "system.currency.gp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "PF1.CurrencySilverP",
      img: "systems/pf1/icons/items/inventory/coin-silver.jpg",
      abbreviation: "{#}S",
      data: {
        path: "system.currency.sp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "PF1.CurrencyCopperP",
      img: "systems/pf1/icons/items/inventory/coin-copper.jpg",
      abbreviation: "{#}C",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
function create_fragment$d(ctx) {
  let form;
  let header;
  let img;
  let img_src_value;
  let t0;
  let div;
  let input0;
  let input0_value_value;
  let t1;
  let span1;
  let t4;
  let tags;
  let select;
  let option;
  let t6;
  let span2;
  let t7;
  let t8;
  let input2;
  let t9;
  let span3;
  let raw_value = (
    /*item*/
    ctx[0].system.description.value + ""
  );
  return {
    c() {
      form = element("form");
      header = element("header");
      img = element("img");
      t0 = space();
      div = element("div");
      input0 = element("input");
      t1 = space();
      span1 = element("span");
      span1.innerHTML = `<span>Item</span> 
					<input data-property="system.level.value" disabled="" type="text" value="?"/>`;
      t4 = space();
      tags = element("tags");
      select = element("select");
      option = element("option");
      option.textContent = "Unknown";
      t6 = space();
      span2 = element("span");
      t7 = text("\r\n				​");
      t8 = space();
      input2 = element("input");
      t9 = space();
      span3 = element("span");
      attr(img, "data-edit", "img");
      if (!src_url_equal(img.src, img_src_value = /*item*/
      ctx[0].img))
        attr(img, "src", img_src_value);
      input0.disabled = true;
      attr(input0, "name", "name");
      attr(input0, "placeholder", "Name");
      attr(input0, "spellcheck", "false");
      attr(input0, "type", "text");
      input0.value = input0_value_value = /*item*/
      ctx[0].name;
      attr(span1, "class", "level");
      option.__value = "common";
      option.value = option.__value;
      attr(select, "class", "tag");
      attr(span2, "aria-autocomplete", "both");
      attr(span2, "aria-multiline", "false");
      attr(span2, "aria-placeholder", "Traits");
      attr(span2, "class", "tagify__input");
      attr(span2, "data-placeholder", "Traits");
      attr(span2, "role", "textbox");
      attr(span2, "tabindex", "0");
      attr(tags, "class", "tagify paizo-style tags tagify--noTags tagify--empty");
      attr(tags, "data-name", "system.traits.value");
      attr(tags, "disabled", "");
      attr(tags, "tabindex", "-1");
      attr(input2, "class", "paizo-style tags");
      attr(input2, "data-dtype", "JSON");
      input2.disabled = "";
      attr(input2, "name", "system.traits.value");
      attr(input2, "placeholder", "Traits");
      attr(input2, "tabindex", "-1");
      input2.value = "[]";
      attr(div, "class", "details");
      attr(header, "class", "sheet-header");
      set_style(span3, "padding", "0.5rem");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, header);
      append(header, img);
      append(header, t0);
      append(header, div);
      append(div, input0);
      append(div, t1);
      append(div, span1);
      append(div, t4);
      append(div, tags);
      append(tags, select);
      append(select, option);
      append(tags, t6);
      append(tags, span2);
      append(tags, t7);
      append(div, t8);
      append(div, input2);
      append(form, t9);
      append(form, span3);
      span3.innerHTML = raw_value;
    },
    p(ctx2, [dirty]) {
      if (dirty & /*item*/
      1 && !src_url_equal(img.src, img_src_value = /*item*/
      ctx2[0].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty & /*item*/
      1 && input0_value_value !== (input0_value_value = /*item*/
      ctx2[0].name) && input0.value !== input0_value_value) {
        input0.value = input0_value_value;
      }
      if (dirty & /*item*/
      1 && raw_value !== (raw_value = /*item*/
      ctx2[0].system.description.value + ""))
        span3.innerHTML = raw_value;
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(form);
    }
  };
}
__name(create_fragment$d, "create_fragment$d");
function instance$d($$self, $$props, $$invalidate) {
  let { item } = $$props;
  $$self.$$set = ($$props2) => {
    if ("item" in $$props2)
      $$invalidate(0, item = $$props2.item);
  };
  return [item];
}
__name(instance$d, "instance$d");
const _BasicItemDialog = class _BasicItemDialog extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$d, create_fragment$d, safe_not_equal, { item: 0 });
  }
};
__name(_BasicItemDialog, "BasicItemDialog");
let BasicItemDialog = _BasicItemDialog;
const pf2e = {
  "VERSION": "1.0.4",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "loot",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // The quantity for price attribute is the path to the attribute on each item that determine how many you get for its price
  "QUANTITY_FOR_PRICE_ATTRIBUTE": "system.price.per",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [{
    "path": "type",
    "filters": "action,ancestry,background,class,condition,deity,effect,feat,heritage,lore,melee,spell,spellcastingEntry"
  }],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type", "system.temporary.value"],
  // This function is an optional system handler that specifically transforms an item's price into a more unified numeric format
  "ITEM_COST_TRANSFORMER": (item) => {
    const itemCost = getProperty(item, "system.price");
    const { copperValue } = new game.pf2e.Coins(itemCost?.value ?? {});
    return copperValue / 100;
  },
  "PREVIEW_ITEM_TRANSFORMER": (item) => {
    if (game.user.isGM || item?.identificationStatus !== "unidentified")
      return item;
    new TJSDialog({
      title: item.name,
      content: {
        class: BasicItemDialog,
        props: {
          item
        }
      }
    }, {
      classes: ["pf2e item sheet dorako-ui"],
      resizable: false,
      height: "auto",
      width: "auto"
    }).render(true);
    return false;
  },
  "PILE_DEFAULTS": {
    merchantColumns: [{
      "label": "Rarity",
      "path": "system.traits.rarity",
      "formatting": "{#}",
      "buying": true,
      "selling": true,
      "mapping": {
        "common": "PF2E.TraitCommon",
        "uncommon": "PF2E.TraitUncommon",
        "rare": "PF2E.TraitRare",
        "unique": "PF2E.TraitUnique"
      }
    }, {
      "label": "Bulk",
      "path": "system.bulk.value",
      "formatting": "{#}",
      "buying": true,
      "selling": true,
      "mapping": { "0": "" }
    }]
  },
  "TOKEN_FLAG_DEFAULTS": {
    flags: {
      pf2e: {
        linkToActorSize: false,
        autoscale: false
      }
    }
  },
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()`, put it into `data.item`, and strip out any module data
  "CURRENCIES": [{
    type: "item",
    name: "Platinum Pieces",
    img: "systems/pf2e/icons/equipment/treasure/currency/platinum-pieces.webp",
    abbreviation: "{#}PP",
    data: {
      uuid: "Compendium.pf2e.equipment-srd.JuNPeK5Qm1w6wpb4"
    },
    primary: false,
    exchangeRate: 10
  }, {
    type: "item",
    name: "Gold Pieces",
    img: "systems/pf2e/icons/equipment/treasure/currency/gold-pieces.webp",
    abbreviation: "{#}GP",
    data: {
      uuid: "Compendium.pf2e.equipment-srd.B6B7tBWJSqOBz5zz"
    },
    primary: true,
    exchangeRate: 1
  }, {
    type: "item",
    name: "Silver Pieces",
    img: "systems/pf2e/icons/equipment/treasure/currency/silver-pieces.webp",
    abbreviation: "{#}SP",
    data: {
      uuid: "Compendium.pf2e.equipment-srd.5Ew82vBF9YfaiY9f"
    },
    primary: false,
    exchangeRate: 0.1
  }, {
    type: "item",
    name: "Copper Pieces",
    img: "systems/pf2e/icons/equipment/treasure/currency/copper-pieces.webp",
    abbreviation: "{#}CP",
    data: {
      uuid: "Compendium.pf2e.equipment-srd.lzJ8AVhRcbFul5fh"
    },
    primary: false,
    exchangeRate: 0.01
  }]
};
const ds4 = {
  "VERSION": "1.0.2",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "spell,talent,racialAbility,language,alphabet,specialCreatureAbility"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "DS4.CharacterCurrencyGold",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}G",
      data: {
        path: "system.currency.gold"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DS4.CharacterCurrencySilver",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}S",
      data: {
        path: "system.currency.silver"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "DS4.CharacterCurrencyCopper",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}C",
      data: {
        path: "system.currency.copper"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const d35e = {
  "VERSION": "1.0.2",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "npc",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "spell,feat,class,race,attack,full-attack,buff,aura,alignment,enhancement,damage-type,material"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "DND5E.CurrencyPP",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}PP",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyGP",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}GP",
      data: {
        path: "system.currency.gp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DND5E.CurrencySP",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#}SP",
      data: {
        path: "system.currency.sp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "DND5E.CurrencyCP",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}CP",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const sfrpg = {
  "VERSION": "1.0.2",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "npc2",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "attack,buff,class,feat,race,spell"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  "CURRENCIES": [
    {
      type: "attribute",
      name: "SFRPG.Currencies.Credits",
      img: "systems/sfrpg/icons/equipment/goods/credstick.webp",
      abbreviation: "{#}C",
      data: {
        path: "system.currency.credit"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "SFRPG.Currencies.UPBs",
      img: "systems/sfrpg/icons/equipment/goods/upb.webp",
      abbreviation: "{#} UBP",
      data: {
        path: "system.currency.upb"
      },
      primary: false,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const swade = {
  "VERSION": "1.0.4",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "edge,hindrance,skill,power,ability"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "SWADE.Currency",
      img: "icons/svg/coins.svg",
      abbreviation: "{#}T",
      data: {
        path: "system.details.currency"
      },
      primary: true,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const tormenta20 = {
  "VERSION": "1.0.2",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.qtd",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price.gc",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "magia,poder,classe"
    },
    {
      "path": "system.tipoUso",
      "filters": "nat"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Ouro",
      img: "icons/commodities/currency/coin-embossed-insect-gold.webp",
      abbreviation: "{#}O",
      data: {
        path: "system.dinheiro.to"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "Prata",
      img: "icons/commodities/currency/coin-embossed-unicorn-silver.webp",
      abbreviation: "{#}P",
      data: {
        path: "system.dinheiro.tp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "Cobre",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}C",
      data: {
        path: "system.dinheiro.tc"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const wfrp4e = {
  "VERSION": "1.0.7",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity.value",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "career,container,critical,disease,injury,mutation,prayer,psychology,talent,skill,spell,trait,extendedTest,vehicleMod,cargo"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // This function is an optional system handler that specifically transforms an item's price into a more unified numeric format
  "ITEM_COST_TRANSFORMER": (item) => {
    let overallCost = 0;
    const prices = getProperty(item, "system.price");
    overallCost += (Number(prices?.["gc"]) ?? 0) * 240;
    overallCost += (Number(prices?.["ss"]) ?? 0) * 12;
    overallCost += (Number(prices?.["bp"]) ?? 0) * 1;
    return overallCost;
  },
  "PILE_TYPE_DEFAULTS": {
    [CONSTANTS.PILE_TYPES.MERCHANT]: {
      merchantColumns: [{
        label: "Availability",
        path: "system.availability.value"
      }]
    }
  },
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "item",
      name: "Gold Crown",
      img: "modules/wfrp4e-core/icons/currency/goldcrown.png",
      abbreviation: "{#}GC",
      data: {
        item: {
          "name": "Gold Crown",
          "type": "money",
          "img": "modules/wfrp4e-core/icons/currency/goldcrown.png",
          "system": {
            "quantity": { "type": "Number", "label": "Quantity", "value": 1 },
            "encumbrance": { "type": "Number", "label": "Encumbrance", "value": 5e-3 },
            "coinValue": { "label": "Value (in d)", "type": "Number", "value": 240 },
            "source": { "type": "String", "label": "Source" }
          }
        }
      },
      primary: false,
      exchangeRate: 240
    },
    {
      type: "item",
      name: "Silver Shilling",
      img: "modules/wfrp4e-core/icons/currency/silvershilling.png",
      abbreviation: "{#}SS",
      data: {
        item: {
          "name": "Silver Shilling",
          "type": "money",
          "img": "modules/wfrp4e-core/icons/currency/silvershilling.png",
          "system": {
            "quantity": { "type": "Number", "label": "Quantity", "value": 1 },
            "encumbrance": { "type": "Number", "label": "Encumbrance", "value": 0.01 },
            "coinValue": { "label": "Value (in d)", "type": "Number", "value": 12 },
            "source": { "type": "String", "label": "Source" }
          }
        }
      },
      primary: false,
      exchangeRate: 12
    },
    {
      type: "item",
      name: "Brass Penny",
      img: "modules/wfrp4e-core/icons/currency/brasspenny.png",
      abbreviation: "{#}BP",
      data: {
        item: {
          "name": "Brass Penny",
          "type": "money",
          "img": "modules/wfrp4e-core/icons/currency/brasspenny.png",
          "system": {
            "quantity": { "type": "Number", "label": "Quantity", "value": 1 },
            "encumbrance": { "type": "Number", "label": "Encumbrance", "value": 0.01 },
            "coinValue": { "label": "Value (in d)", "type": "Number", "value": 1 },
            "source": { "type": "String", "label": "Source" }
          }
        }
      },
      primary: true,
      exchangeRate: 1
    }
  ]
};
const splittermond = {
  "VERSION": "1.0.4",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "npc",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "spell,strength,weakness,mastery,species,culture,ancestry,education,resource,npcfeature,moonsign,language,culturelore,statuseffect,spelleffect,npcattack"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type", "system.sufferedDamage", "system.quality"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Solare",
      img: "icons/commodities/currency/coins-assorted-mix-copper.webp",
      abbreviation: "{#}S",
      data: {
        path: "system.currency.S"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "Lunare",
      img: "icons/commodities/currency/coins-assorted-mix-silver.webp",
      abbreviation: "{#}L",
      data: {
        path: "system.currency.L"
      },
      primary: false,
      exchangeRate: 0.01
    },
    {
      type: "attribute",
      name: "Telare",
      img: "icons/commodities/currency/coins-assorted-mix-platinum.webp",
      abbreviation: "{#}T",
      data: {
        path: "system.currency.T"
      },
      primary: false,
      exchangeRate: 1e-4
    }
  ]
};
const forbiddenLands = {
  "VERSION": "1.0.2",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.cost",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "criticalInjury,monsterAttack,monsterTalent"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Gold",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}GP",
      data: {
        path: "system.currency.gold.value"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "Silver",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#}SP",
      data: {
        path: "system.currency.silver.value"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "Copper",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}CP",
      data: {
        path: "system.currency.copper.value"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const icrpg = {
  "VERSION": "1.0.3",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "ability"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Coin",
      img: "icons/svg/coins.svg",
      abbreviation: "{#}C",
      data: {
        path: "system.coin.value"
      },
      primary: true,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const swse = {
  "VERSION": "1.0.3",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "affiliation,background,class,beast quality,destiny,feat,forcePower,forceRegimen,forceSecret,forceTechnique,species,talent,template,trait,vehicleSystem"
    }
  ],
  "ITEM_PRICE_ATTRIBUTE": "system.cost",
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["type", "name", "strippable", "hasPrerequisites", "modifiable", "hasLevels"],
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Credits",
      img: "icons/svg/coins.svg",
      abbreviation: "{#}C",
      data: {
        path: "system.credits"
      },
      primary: true,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const sw5e = {
  VERSION: "1.0.1",
  ACTOR_CLASS_TYPE: "character",
  ITEM_QUANTITY_ATTRIBUTE: "system.quantity",
  ITEM_PRICE_ATTRIBUTE: "system.price.value",
  ITEM_FILTERS: [
    {
      path: "type",
      filters: "power,feat,class,archetype,background"
    },
    {
      path: "system.weaponType",
      filters: "natural"
    }
  ],
  ITEM_TRANSFORMER: async (itemData, actor = false) => {
    ["equipped", "proficient", "prepared"].forEach((key) => {
      if (itemData?.system?.[key] !== void 0) {
        delete itemData.system[key];
      }
    });
    setProperty(
      itemData,
      "system.attunement",
      Math.min(
        CONFIG.SW5E.attunementTypes.REQUIRED,
        itemData?.system?.attunement ?? 0
      )
    );
    return itemData;
  },
  ITEM_SIMILARITIES: ["name", "type"],
  CURRENCIES: [
    {
      type: "attribute",
      name: "SW5E.CurrencyGC",
      img: "systems/sw5e/packs/Icons/Data Recording and Storage/CreditChip.webp",
      abbreviation: "{#}GC",
      data: {
        path: "system.currency.gc"
      },
      primary: true,
      exchangeRate: 1
    }
  ]
};
const sw5e203 = {
  VERSION: "1.0.1",
  ACTOR_CLASS_TYPE: "character",
  ITEM_QUANTITY_ATTRIBUTE: "system.quantity",
  ITEM_PRICE_ATTRIBUTE: "system.price",
  ITEM_FILTERS: [
    {
      path: "type",
      filters: "power,feat,class,archetype,background"
    },
    {
      path: "system.weaponType",
      filters: "natural"
    }
  ],
  ITEM_TRANSFORMER: async (itemData, actor = false) => {
    ["equipped", "proficient", "prepared"].forEach((key) => {
      if (itemData?.system?.[key] !== void 0) {
        delete itemData.system[key];
      }
    });
    setProperty(
      itemData,
      "system.attunement",
      Math.min(
        CONFIG.SW5E.attunementTypes.REQUIRED,
        itemData?.system?.attunement ?? 0
      )
    );
    return itemData;
  },
  ITEM_SIMILARITIES: ["name", "type"],
  CURRENCIES: [
    {
      type: "attribute",
      name: "SW5E.CurrencyGC",
      img: "systems/sw5e/packs/Icons/Data Recording and Storage/CreditChip.webp",
      abbreviation: "{#}GC",
      data: {
        path: "system.currency.gc"
      },
      primary: true,
      exchangeRate: 1
    }
  ]
};
const fallout = {
  "VERSION": "1.0.3",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.cost",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "skill,perk,special_ability"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "FALLOUT.UI.CAPS",
      img: "icons/commodities/currency/coins-engraved-copper.webp",
      abbreviation: "{#}C",
      data: {
        path: "system.currency.caps"
      },
      primary: true,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const cyberpunkRedCore = {
  "VERSION": "1.0.3",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.amount",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price.market",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "role, skill, criticalInjury"
    },
    {
      "path": "system.isInstalled",
      "filters": [true]
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "CPR.characterSheet.rightPane.eurobucks.eurobucks",
      img: "icons/svg/coins.svg",
      abbreviation: "{#}€$",
      data: {
        path: "system.wealth.value"
      },
      primary: true,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const knave = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.coppers",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "spell"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": []
};
const t2k4e = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.qty",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "specialty,injury"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": []
};
const yzecoriolis = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "npc",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.cost",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "injury, shipProblem, shipCriticalDamage, shipLogbook"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "YZECORIOLIS.Birr",
      img: "icons/commodities/currency/coin-inset-insect-gold.webp",
      abbreviation: "{#}B",
      data: {
        path: "system.birr"
      },
      primary: true,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const kamigakari = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "talent,attackOption,race,style,facade,bond"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  "CURRENCIES": [
    {
      type: "attribute",
      name: "KG.Money",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}G",
      data: {
        path: "system.attributes.money"
      },
      primary: true,
      exchangeRate: 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const symbaroum = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "monster",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.number",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.cost",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "ability,boon,burden,mysticalPower,ritual,trait"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Thaler",
      img: "icons/commodities/currency/coins-assorted-mix-copper.webp",
      abbreviation: "{#}T",
      data: {
        path: "system.money.thaler"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "Shilling",
      img: "icons/commodities/currency/coins-assorted-mix-silver.webp",
      abbreviation: "{#}S",
      data: {
        path: "system.money.shilling"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "Orteg",
      img: "icons/commodities/currency/coins-assorted-mix-platinum.webp",
      abbreviation: "{#}O",
      data: {
        path: "system.money.orteg"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const wwn = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "ability, art, asset, focus, skill, spell"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "WWN.items.PP.long",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}PP",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 50
    },
    {
      type: "attribute",
      name: "WWN.items.GP.long",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}GP",
      data: {
        path: "system.currency.gp"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "WWN.items.EP.long",
      img: "icons/commodities/currency/coin-inset-copper-axe.webp",
      abbreviation: "{#}EP",
      data: {
        path: "system.currency.ep"
      },
      primary: false,
      exchangeRate: 5
    },
    {
      type: "attribute",
      name: "WWN.items.SP.long",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#}SP",
      data: {
        path: "system.currency.sp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "WWN.items.CP.long",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}CP",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const cyphersystem = {
  "VERSION": "1.0.1",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "pc",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.basic.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "flags.item-piles.system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "ability, lasting-damage, power-shift, recursion, skill, tag"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Adamantine pieces",
      img: "icons/commodities/currency/coin-embossed-ruby-gold.webp",
      abbreviation: "{#} ap",
      data: {
        path: "system.settings.equipment.currency.quantity6"
      },
      primary: false,
      exchangeRate: 1e3
    },
    {
      type: "attribute",
      name: "Mithral pieces",
      img: "icons/commodities/currency/coin-embossed-unicorn-silver.webp",
      abbreviation: "{#} mp",
      data: {
        path: "system.settings.equipment.currency.quantity5"
      },
      primary: false,
      exchangeRate: 100
    },
    {
      type: "attribute",
      name: "Platinum pieces",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#} pp",
      data: {
        path: "system.settings.equipment.currency.quantity4"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "Gold pieces",
      img: "icons/commodities/currency/coins-plain-gold.webp",
      abbreviation: "{#} gp",
      data: {
        path: "system.settings.equipment.currency.quantity3"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "Silver pieces",
      img: "icons/commodities/currency/coins-engraved-face-silver.webp",
      abbreviation: "{#} sp",
      data: {
        path: "system.settings.equipment.currency.quantity2"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "Copper pieces",
      img: "icons/commodities/currency/coins-engraved-copper.webp",
      abbreviation: "{#} cp",
      data: {
        path: "system.settings.equipment.currency.quantity1"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const ptu = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.cost",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "feat,edge,ability,move,capability,pokeedge,dexentry"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "PTU.Money",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}₱",
      data: {
        path: "system.money"
      },
      primary: true,
      exchangeRate: 1
    }
  ]
};
const dcc = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "Player",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.value",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "spell,skill"
    }
  ],
  // This function is an optional system handler that specifically transforms an item when it is added to actors
  "ITEM_TRANSFORMER": async (itemData) => {
    if (itemData?.system?.equipped) {
      itemData.system.equipped = false;
    }
    ["lost", "mercurialEffect"].forEach((key) => {
      if (itemData?.system?.[key] !== void 0) {
        delete itemData.system[key];
      }
    });
    return itemData;
  },
  // This function is an optional system handler that specifically transforms an item's price into a more unified numeric format
  "ITEM_COST_TRANSFORMER": (item, currencies) => {
    let overallCost = 0;
    currencies.forEach((currency, index2) => {
      let denominationCost = Number(getProperty(item, currency.data.path.replace("system.currency.", "system.value.")));
      if (!isNaN(denominationCost)) {
        overallCost += denominationCost * currency.exchangeRate;
      }
    });
    return overallCost ?? 0;
  },
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "DCC.CurrencyPP",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}Pp",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 100
    },
    {
      type: "attribute",
      name: "DCC.CurrencyEP",
      img: "icons/commodities/currency/coin-inset-copper-axe.webp",
      abbreviation: "{#} Ep",
      data: {
        path: "system.currency.ep"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "DCC.CurrencyGP",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#} Gp",
      data: {
        path: "system.currency.gp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "DCC.CurrencySP",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#} Sp",
      data: {
        path: "system.currency.sp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "DCC.CurrencyCP",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#} Cp",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ]
};
const a5e = {
  "VERSION": "1.0.1",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "feature, maneuver, spell, background, culture, heritage, destiny"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Platinum Pieces",
      img: "icons/commodities/currency/coin-inset-snail-silver.webp",
      abbreviation: "{#}PP",
      data: {
        path: "system.currency.pp"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "Gold Pieces",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#}GP",
      data: {
        path: "system.currency.gp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "Electrum Pieces",
      img: "icons/commodities/currency/coin-inset-copper-axe.webp",
      abbreviation: "{#}EP",
      data: {
        path: "system.currency.ep"
      },
      primary: false,
      exchangeRate: 0.5
    },
    {
      type: "attribute",
      name: "Silver Pieces",
      img: "icons/commodities/currency/coin-engraved-moon-silver.webp",
      abbreviation: "{#}SP",
      data: {
        path: "system.currency.sp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "Copper Pieces",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#}CP",
      data: {
        path: "system.currency.cp"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ],
  "SHEET_OVERRIDES": () => {
    libWrapper.register(CONSTANTS.MODULE_NAME, `game.a5e.applications.ActorSheetA5e.prototype.render`, function(wrapped, forced, options, ...args) {
      const renderItemPileInterface = Hooks.call(CONSTANTS.HOOKS.PRE_RENDER_SHEET, this.actor, forced, options) === false;
      if (this._state > Application.RENDER_STATES.NONE) {
        if (renderItemPileInterface) {
          wrapped(forced, options, ...args);
        } else {
          return wrapped(forced, options, ...args);
        }
      }
      if (renderItemPileInterface)
        return;
      return wrapped(forced, options, ...args);
    }, "MIXED");
  }
};
const darkHeresy2e = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "acolyte",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "specialAbility, aptitude, talent, psychicPower, trait"
    },
    {
      "path": "system.installed",
      "filters": "installed"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": [],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [],
  "CURRENCY_DECIMAL_DIGITS": 1e-5
};
const naheulbeuk = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.prix",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "ape,attaque,competence,coup,etat,metier,origine,region,sort,trait"
    }
  ],
  // This function is an optional system handler that specifically transforms an item when it is added to actors
  "ITEM_TRANSFORMER": async (itemData) => {
    ["equipe"].forEach((key) => {
      if (itemData?.system?.[key] !== void 0) {
        delete itemData.system[key];
      }
    });
    return itemData;
  },
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "item",
      name: "Pièce d'argent",
      img: "systems/naheulbeuk/assets/from-rexard-icons/Tresors/tresor%20(101).webp",
      abbreviation: "{#}PA",
      data: {
        uuid: "Compendium.naheulbeuk.trucs.BTUFKc6sEbJLmlas"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "item",
      name: "Pièce d'or",
      img: "systems/naheulbeuk/assets/from-rexard-icons/Tresors/tresor%20(52).webp",
      abbreviation: "{#}PO",
      data: {
        uuid: "Compendium.naheulbeuk.trucs.AKuErwzQ6wDxtzyp"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "item",
      name: "Lingot de Thrytil",
      img: "systems/naheulbeuk/assets/from-rexard-icons/Objets/Materiaux/objet%20(291).webp",
      abbreviation: "{#}LT",
      data: {
        uuid: "Compendium.naheulbeuk.trucs.tOTNc2WYpkyf2Yyl"
      },
      primary: false,
      exchangeRate: 0.01
    },
    {
      type: "item",
      name: "Lingot de Berylium",
      img: "systems/naheulbeuk/assets/from-rexard-icons/Objets/Materiaux/objet%20(252).webp",
      abbreviation: "{#}LB",
      data: {
        uuid: "Compendium.naheulbeuk.trucs.r4qLXqXaIIdyKzOf"
      },
      primary: false,
      exchangeRate: 2e-3
    }
  ]
};
const icrpgme = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "flags.item-piles.system.price",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "ability,power,augment,spell,part,property"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const bladeRunner = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "loot",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.qty",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.cost",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "upgrade,specialty,injury"
    }
  ],
  "UNSTACKABLE_ITEM_TYPES": ["weapon", "armor"],
  "PILE_DEFAULTS": {
    merchantColumns: [{
      label: "FLBR.ItemAvailability",
      path: "system.availability",
      formatting: "{#}",
      mapping: {
        5: "FLBR.ITEM_AVAILABILITY.Incidental",
        4: "FLBR.ITEM_AVAILABILITY.Standard",
        3: "FLBR.ITEM_AVAILABILITY.Premium",
        2: "FLBR.ITEM_AVAILABILITY.Rare",
        1: "FLBR.ITEM_AVAILABILITY.Luxury"
      }
    }]
  },
  // This function is an optional system handler that specifically transforms an item when it is added to actors
  "ITEM_TRANSFORMER": async (itemData) => {
    if (itemData?.system?.mounted)
      itemData.system.mounted = false;
    return itemData;
  },
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "FLBR.HEADER.ChinyenPoints",
      img: "icons/commodities/currency/coins-plain-stack-silver.webp",
      abbreviation: "{#}C¥",
      data: {
        path: "system.metaCurrencies.chinyen"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "FLBR.HEADER.PromotionPoints",
      img: "icons/commodities/treasure/medal-ribbon-gold-blue.webp",
      abbreviation: "{#}PP",
      data: {
        path: "system.metaCurrencies.promotion"
      },
      primary: false,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "FLBR.HEADER.HumanityPoints",
      img: "icons/sundries/gaming/chess-knight-white.webp",
      abbreviation: "{#}HP",
      data: {
        path: "system.metaCurrencies.humanity"
      },
      primary: false,
      exchangeRate: 1
    }
  ],
  "VAULT_STYLES": [
    {
      path: "system.availability",
      value: 1,
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,119,0,1)"
      }
    },
    {
      path: "system.availability",
      value: 2,
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(255,0,247,1)"
      }
    },
    {
      path: "system.availability",
      value: 3,
      styling: {
        "box-shadow": "inset 0px 0px 7px 0px rgba(0,136,255,1)"
      }
    }
  ]
};
const alienrpg = {
  "VERSION": "1.0.1",
  "CURRENCIES": [
    {
      "type": "attribute",
      "name": "Dollar",
      "img": "",
      "abbreviation": "${#}",
      "data": {
        "path": "system.general.cash.value"
      },
      "primary": true,
      "exchangeRate": 1
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01,
  "ITEM_FILTERS": [{
    "path": "type",
    "filters": "talent,planet-system,skill-stunts,agenda,specialty,critical-injury"
  }],
  "ITEM_COST_TRANSFORMER": (item) => {
    let overallCost = getProperty(item, "system.attributes.cost.value");
    if (overallCost) {
      overallCost = overallCost.replace("$", "").replace(",", "");
    }
    return Number(overallCost) ?? 0;
  },
  "ITEM_SIMILARITIES": ["name", "type"],
  "ACTOR_CLASS_TYPE": "character",
  "ITEM_QUANTITY_ATTRIBUTE": "system.attributes.quantity.value",
  "ITEM_PRICE_ATTRIBUTE": "system.attributes.cost.value"
};
const pirateborg = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "container",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price",
  // Item filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "feature,class,subclass,background"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "PB.Silver",
      img: "systems/pirateborg/icons/misc/thing-of-importance.png",
      abbreviation: "{#}SP",
      data: {
        path: "system.silver"
      },
      primary: true,
      exchangeRate: 1
    }
  ]
};
const starwarsffg = {
  "VERSION": "1.0.0",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "character",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity.value",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.price.value",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "species,career,specialization,ability,criticaldamage,criticalinjury,talent,homesteadupgrade,signatureability,forcepower"
    }
  ],
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      "type": "attribute",
      "name": "Credits",
      "img": "systems/starwarsffg/images/mod-all.png",
      "abbreviation": "{#}cr",
      "data": {
        "path": "system.stats.credits.value"
      },
      "primary": true,
      "exchangeRate": 1,
      "index": 0,
      "id": "system.stats.credits.value"
    }
  ]
};
const demonlord = {
  "VERSION": "1.0.3",
  // The actor class type is the type of actor that will be used for the default item pile actor that is created on first item drop.
  "ACTOR_CLASS_TYPE": "creature",
  // The item quantity attribute is the path to the attribute on items that denote how many of that item that exists
  "ITEM_QUANTITY_ATTRIBUTE": "system.quantity",
  // The item price attribute is the path to the attribute on each item that determine how much it costs
  "ITEM_PRICE_ATTRIBUTE": "system.value",
  // Item types and the filters actively remove items from the item pile inventory UI that users cannot loot, such as spells, feats, and classes
  "ITEM_FILTERS": [
    {
      "path": "type",
      "filters": "feature,ancestry,path,talent,spell"
    }
  ],
  "PILE_DEFAULTS": {
    merchantColumns: [{
      label: "DL.Availability",
      path: "system.availability",
      formatting: "{#}",
      buying: true,
      selling: true,
      mapping: {
        "C": "DL.AvailabilityC",
        "U": "DL.AvailabilityU",
        "R": "DL.AvailabilityR",
        "E": "DL.AvailabilityE"
      }
    }]
  },
  // Item similarities determines how item piles detect similarities and differences in the system
  "ITEM_SIMILARITIES": ["name", "type"],
  // Currencies in item piles is a versatile system that can accept actor attributes (a number field on the actor's sheet) or items (actual items in their inventory)
  // In the case of attributes, the path is relative to the "actor.system"
  // In the case of items, it is recommended you export the item with `.toObject()` and strip out any module data
  "CURRENCIES": [
    {
      type: "attribute",
      name: "Gold Crowns",
      img: "icons/commodities/currency/coin-embossed-crown-gold.webp",
      abbreviation: "{#} gc",
      data: {
        path: "system.wealth.gc"
      },
      primary: false,
      exchangeRate: 10
    },
    {
      type: "attribute",
      name: "Silver Shillings",
      img: "icons/commodities/currency/coin-inset-compass-silver.webp",
      abbreviation: "{#} ss",
      data: {
        path: "system.wealth.ss"
      },
      primary: true,
      exchangeRate: 1
    },
    {
      type: "attribute",
      name: "Copper Pennies",
      img: "icons/commodities/currency/coin-engraved-waves-copper.webp",
      abbreviation: "{#} cp",
      data: {
        path: "system.wealth.cp"
      },
      primary: false,
      exchangeRate: 0.1
    },
    {
      type: "attribute",
      name: "Bits",
      img: "icons/commodities/currency/coins-assorted-mix-platinum.webp",
      abbreviation: "{#} bits",
      data: {
        path: "system.wealth.bits"
      },
      primary: false,
      exchangeRate: 0.01
    }
  ],
  "CURRENCY_DECIMAL_DIGITS": 0.01
};
const SYSTEMS = {
  SUPPORTED_SYSTEMS: {
    // ↓ ADD SYSTEMS HERE ↓
    "alienrpg": {
      "latest": alienrpg
    },
    "dnd4e": {
      "latest": dnd4e
    },
    "dnd5e": {
      "latest": dnd5e,
      "2.0.3": dnd5e203
    },
    "pf1": {
      "latest": pf1
    },
    "pf2e": {
      "latest": pf2e
    },
    "ds4": {
      "latest": ds4
    },
    "d35e": {
      "latest": d35e
    },
    "blade-runner": {
      "latest": bladeRunner
    },
    "sfrpg": {
      "latest": sfrpg
    },
    "swade": {
      "latest": swade
    },
    "tormenta20": {
      "latest": tormenta20
    },
    "wfrp4e": {
      "latest": wfrp4e
    },
    "splittermond": {
      "latest": splittermond
    },
    "forbidden-lands": {
      "latest": forbiddenLands
    },
    "icrpg": {
      "latest": icrpg
    },
    "icrpgme": {
      "latest": icrpgme
    },
    "swse": {
      "latest": swse
    },
    "sw5e": {
      "latest": sw5e,
      "2.0.3.2.3.8": sw5e203
    },
    "fallout": {
      "latest": fallout
    },
    "cyberpunk-red-core": {
      "latest": cyberpunkRedCore
    },
    "knave": {
      "latest": knave
    },
    "t2k4e": {
      "latest": t2k4e
    },
    "yzecoriolis": {
      "latest": yzecoriolis
    },
    "kamigakari": {
      "latest": kamigakari
    },
    "wwn": {
      "latest": wwn
    },
    "symbaroum": {
      "latest": symbaroum
    },
    "cyphersystem": {
      "latest": cyphersystem
    },
    "ptu": {
      "latest": ptu
    },
    "dcc": {
      "latest": dcc
    },
    "a5e": {
      "latest": a5e
    },
    "dark-heresy": {
      "latest": darkHeresy2e
    },
    "naheulbeuk": {
      "latest": naheulbeuk
    },
    "pirateborg": {
      "latest": pirateborg
    },
    "starwarsffg": {
      "latest": starwarsffg
    },
    "demonlord": {
      "latest": demonlord
    }
    // ↑ ADD SYSTEMS HERE ↑
  },
  DEFAULT_SETTINGS: {
    ACTOR_CLASS_TYPE: "",
    ITEM_QUANTITY_ATTRIBUTE: "",
    ITEM_PRICE_ATTRIBUTE: "",
    QUANTITY_FOR_PRICE_ATTRIBUTE: "flags.item-piles.system.quantityForPrice",
    ITEM_FILTERS: [],
    ITEM_SIMILARITIES: [],
    VAULT_STYLES: [],
    CSS_VARIABLES: [],
    UNSTACKABLE_ITEM_TYPES: [],
    CURRENCIES: [],
    SECONDARY_CURRENCIES: [],
    PILE_DEFAULTS: {},
    TOKEN_FLAG_DEFAULTS: {},
    CURRENCY_DECIMAL_DIGITS: 1e-5,
    SOFT_MIGRATIONS: {}
  },
  get HAS_SYSTEM_SUPPORT() {
    return !!this.SUPPORTED_SYSTEMS?.[game.system.id.toLowerCase()];
  },
  _currentSystem: false,
  get DATA() {
    if (this._currentSystem)
      return this._currentSystem;
    const system = this.SUPPORTED_SYSTEMS?.[game.system.id.toLowerCase()];
    if (!system)
      return this.DEFAULT_SETTINGS;
    if (system[game.system.version]) {
      this._currentSystem = foundry.utils.mergeObject(this.DEFAULT_SETTINGS, system[game.system.version]);
      return this._currentSystem;
    }
    const versions = Object.keys(system);
    if (versions.length === 1) {
      this._currentSystem = foundry.utils.mergeObject(this.DEFAULT_SETTINGS, system[versions[0]]);
      return this._currentSystem;
    }
    versions.sort((a, b) => {
      return a === "latest" || b === "latest" ? -Infinity : isNewerVersion(b, a) ? -1 : 1;
    });
    const version = versions.find((version2) => {
      return version2 === "latest" || !isNewerVersion(game.system.version, version2);
    });
    this._currentSystem = foundry.utils.mergeObject(this.DEFAULT_SETTINGS, system[version]);
    return this._currentSystem;
  },
  addSystem(data2) {
    this.SUPPORTED_SYSTEMS[game.system.id.toLowerCase()] = { latest: data2 };
  }
};
const Setting_svelte_svelte_type_style_lang = "";
function get_each_context$6(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[2] = list[i][0];
  child_ctx[8] = list[i][1];
  child_ctx[10] = i;
  return child_ctx;
}
__name(get_each_context$6, "get_each_context$6");
function create_else_block_1$3(ctx) {
  let div;
  let input;
  let t;
  let mounted;
  let dispose;
  let if_block = (
    /*data*/
    ctx[0].localize && create_if_block_4$3(ctx)
  );
  return {
    c() {
      div = element("div");
      input = element("input");
      t = space();
      if (if_block)
        if_block.c();
      attr(input, "type", "text");
      input.disabled = /*disabled*/
      ctx[1];
      attr(input, "class", "svelte-1rcqxnm");
      attr(div, "class", "item-pile-setting-container svelte-1rcqxnm");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*data*/
        ctx[0].value
      );
      append(div, t);
      if (if_block)
        if_block.m(div, null);
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler_1*/
          ctx[7]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*disabled*/
      2) {
        input.disabled = /*disabled*/
        ctx2[1];
      }
      if (dirty & /*data, Object*/
      1 && input.value !== /*data*/
      ctx2[0].value) {
        set_input_value(
          input,
          /*data*/
          ctx2[0].value
        );
      }
      if (
        /*data*/
        ctx2[0].localize
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_4$3(ctx2);
          if_block.c();
          if_block.m(div, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block_1$3, "create_else_block_1$3");
function create_if_block_3$3(ctx) {
  let input;
  let input_step_value;
  let input_min_value;
  let input_max_value;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      attr(input, "type", "number");
      input.disabled = /*disabled*/
      ctx[1];
      attr(input, "step", input_step_value = /*data*/
      ctx[0].step);
      attr(input, "min", input_min_value = /*data*/
      ctx[0].min);
      attr(input, "max", input_max_value = /*data*/
      ctx[0].max);
      attr(input, "class", "svelte-1rcqxnm");
      toggle_class(input, "invalid", !/*data*/
      ctx[0].value && /*data*/
      ctx[0].value !== 0);
    },
    m(target, anchor) {
      insert(target, input, anchor);
      set_input_value(
        input,
        /*data*/
        ctx[0].value
      );
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*input_input_handler*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*disabled*/
      2) {
        input.disabled = /*disabled*/
        ctx2[1];
      }
      if (dirty & /*data, Object*/
      1 && input_step_value !== (input_step_value = /*data*/
      ctx2[0].step)) {
        attr(input, "step", input_step_value);
      }
      if (dirty & /*data, Object*/
      1 && input_min_value !== (input_min_value = /*data*/
      ctx2[0].min)) {
        attr(input, "min", input_min_value);
      }
      if (dirty & /*data, Object*/
      1 && input_max_value !== (input_max_value = /*data*/
      ctx2[0].max)) {
        attr(input, "max", input_max_value);
      }
      if (dirty & /*data, Object*/
      1 && to_number(input.value) !== /*data*/
      ctx2[0].value) {
        set_input_value(
          input,
          /*data*/
          ctx2[0].value
        );
      }
      if (dirty & /*data*/
      1) {
        toggle_class(input, "invalid", !/*data*/
        ctx2[0].value && /*data*/
        ctx2[0].value !== 0);
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$3, "create_if_block_3$3");
function create_if_block_1$6(ctx) {
  let div;
  let select;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let select_name_value;
  let mounted;
  let dispose;
  let each_value = Object.entries(
    /*data*/
    ctx[0].choices
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[10]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$6(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$6(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(select, "name", select_name_value = /*data*/
      ctx[0].key);
      select.disabled = /*disabled*/
      ctx[1];
      attr(select, "class", "svelte-1rcqxnm");
      if (
        /*data*/
        ctx[0].value === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[5].call(select)
        ));
      attr(div, "class", "choice-container svelte-1rcqxnm");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*data*/
        ctx[0].value,
        true
      );
      if (!mounted) {
        dispose = listen(
          select,
          "change",
          /*select_change_handler*/
          ctx[5]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*Object, data, localize, Number*/
      1) {
        each_value = Object.entries(
          /*data*/
          ctx2[0].choices
        );
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, select, destroy_block, create_each_block$6, null, get_each_context$6);
      }
      if (dirty & /*data, Object*/
      1 && select_name_value !== (select_name_value = /*data*/
      ctx2[0].key)) {
        attr(select, "name", select_name_value);
      }
      if (dirty & /*disabled*/
      2) {
        select.disabled = /*disabled*/
        ctx2[1];
      }
      if (dirty & /*data, Object*/
      1) {
        select_option(
          select,
          /*data*/
          ctx2[0].value
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$6, "create_if_block_1$6");
function create_if_block$9(ctx) {
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      attr(input, "type", "checkbox");
      input.disabled = /*disabled*/
      ctx[1];
      attr(input, "class", "svelte-1rcqxnm");
    },
    m(target, anchor) {
      insert(target, input, anchor);
      input.checked = /*data*/
      ctx[0].value;
      if (!mounted) {
        dispose = listen(
          input,
          "change",
          /*input_change_handler*/
          ctx[4]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*disabled*/
      2) {
        input.disabled = /*disabled*/
        ctx2[1];
      }
      if (dirty & /*data, Object*/
      1) {
        input.checked = /*data*/
        ctx2[0].value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$9, "create_if_block$9");
function create_if_block_4$3(ctx) {
  let input;
  let input_value_value;
  return {
    c() {
      input = element("input");
      attr(input, "type", "text");
      input.disabled = true;
      input.value = input_value_value = localize(
        /*data*/
        ctx[0].value
      );
      attr(input, "class", "svelte-1rcqxnm");
    },
    m(target, anchor) {
      insert(target, input, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*data, Object*/
      1 && input_value_value !== (input_value_value = localize(
        /*data*/
        ctx2[0].value
      )) && input.value !== input_value_value) {
        input.value = input_value_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(input);
    }
  };
}
__name(create_if_block_4$3, "create_if_block_4$3");
function create_else_block$5(ctx) {
  let option;
  let t_value = localize(
    /*choice*/
    ctx[8]
  ) + "";
  let t;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*key*/
      ctx[2];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*data*/
      1 && t_value !== (t_value = localize(
        /*choice*/
        ctx2[8]
      ) + ""))
        set_data(t, t_value);
      if (dirty & /*data, Object*/
      1 && option_value_value !== (option_value_value = /*key*/
      ctx2[2])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_else_block$5, "create_else_block$5");
function create_if_block_2$3(ctx) {
  let option;
  let t_value = localize(
    /*choice*/
    ctx[8]
  ) + "";
  let t;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*index*/
      ctx[10];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*data*/
      1 && t_value !== (t_value = localize(
        /*choice*/
        ctx2[8]
      ) + ""))
        set_data(t, t_value);
      if (dirty & /*data, Object*/
      1 && option_value_value !== (option_value_value = /*index*/
      ctx2[10])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_if_block_2$3, "create_if_block_2$3");
function create_each_block$6(key_2, ctx) {
  let first;
  let if_block_anchor;
  function select_block_type_1(ctx2, dirty) {
    if (
      /*data*/
      ctx2[0].type === Number
    )
      return create_if_block_2$3;
    return create_else_block$5;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block = current_block_type(ctx);
  return {
    key: key_2,
    first: null,
    c() {
      first = empty();
      if_block.c();
      if_block_anchor = empty();
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (current_block_type === (current_block_type = select_block_type_1(ctx)) && if_block) {
        if_block.p(ctx, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(first);
      if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
__name(create_each_block$6, "create_each_block$6");
function create_fragment$c(ctx) {
  let div2;
  let div0;
  let label;
  let t0_value = localize(
    /*data*/
    ctx[0].name
  ) + "";
  let t0;
  let t1;
  let a;
  let i;
  let t2;
  let p;
  let t3_value = localize(
    /*data*/
    ctx[0].hint
  ) + "";
  let t3;
  let t4;
  let div1;
  let mounted;
  let dispose;
  function select_block_type(ctx2, dirty) {
    if (
      /*data*/
      ctx2[0].type === Boolean
    )
      return create_if_block$9;
    if (
      /*data*/
      ctx2[0].choices
    )
      return create_if_block_1$6;
    if (
      /*data*/
      ctx2[0].type === Number
    )
      return create_if_block_3$3;
    return create_else_block_1$3;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      div2 = element("div");
      div0 = element("div");
      label = element("label");
      t0 = text(t0_value);
      t1 = space();
      a = element("a");
      i = element("i");
      t2 = space();
      p = element("p");
      t3 = text(t3_value);
      t4 = space();
      div1 = element("div");
      if_block.c();
      attr(i, "class", "fas fa-undo reset-setting svelte-1rcqxnm");
      attr(i, "data-fast-tooltip", "Reset data");
      attr(label, "class", "svelte-1rcqxnm");
      attr(p, "class", "notes");
      attr(div0, "class", "label-side svelte-1rcqxnm");
      attr(div1, "class", "form-fields input-side svelte-1rcqxnm");
      attr(div2, "class", "item-pile-setting form-scope item-piles-flexrow svelte-1rcqxnm");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div0);
      append(div0, label);
      append(label, t0);
      append(label, t1);
      append(label, a);
      append(a, i);
      append(div0, t2);
      append(div0, p);
      append(p, t3);
      append(div2, t4);
      append(div2, div1);
      if_block.m(div1, null);
      if (!mounted) {
        dispose = listen(
          i,
          "click",
          /*click_handler*/
          ctx[3]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*data*/
      1 && t0_value !== (t0_value = localize(
        /*data*/
        ctx2[0].name
      ) + ""))
        set_data(t0, t0_value);
      if (dirty & /*data*/
      1 && t3_value !== (t3_value = localize(
        /*data*/
        ctx2[0].hint
      ) + ""))
        set_data(t3, t3_value);
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(div1, null);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div2);
      if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$c, "create_fragment$c");
function instance$c($$self, $$props, $$invalidate) {
  let { key } = $$props;
  let { data: data2 } = $$props;
  let { disabled = false } = $$props;
  const click_handler = /* @__PURE__ */ __name(() => {
    $$invalidate(0, data2.value = data2.default, data2);
  }, "click_handler");
  function input_change_handler() {
    data2.value = this.checked;
    $$invalidate(0, data2);
  }
  __name(input_change_handler, "input_change_handler");
  function select_change_handler() {
    data2.value = select_value(this);
    $$invalidate(0, data2);
  }
  __name(select_change_handler, "select_change_handler");
  function input_input_handler() {
    data2.value = to_number(this.value);
    $$invalidate(0, data2);
  }
  __name(input_input_handler, "input_input_handler");
  function input_input_handler_1() {
    data2.value = this.value;
    $$invalidate(0, data2);
  }
  __name(input_input_handler_1, "input_input_handler_1");
  $$self.$$set = ($$props2) => {
    if ("key" in $$props2)
      $$invalidate(2, key = $$props2.key);
    if ("data" in $$props2)
      $$invalidate(0, data2 = $$props2.data);
    if ("disabled" in $$props2)
      $$invalidate(1, disabled = $$props2.disabled);
  };
  return [
    data2,
    disabled,
    key,
    click_handler,
    input_change_handler,
    select_change_handler,
    input_input_handler,
    input_input_handler_1
  ];
}
__name(instance$c, "instance$c");
const _Setting = class _Setting extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$c, create_fragment$c, safe_not_equal, { key: 2, data: 0, disabled: 1 });
  }
};
__name(_Setting, "Setting");
let Setting = _Setting;
const pricePresetEditorShell_svelte_svelte_type_style_lang = "";
function create_default_slot$7(ctx) {
  let form_1;
  let p;
  let t1;
  let pricelist;
  let updating_prices;
  let t2;
  let footer;
  let button0;
  let i0;
  let t3;
  let t4_value = localize("ITEM-PILES.Applications.PricePresetEditor.Update") + "";
  let t4;
  let t5;
  let button1;
  let i1;
  let t6;
  let t7_value = localize("Cancel") + "";
  let t7;
  let current;
  let mounted;
  let dispose;
  function pricelist_prices_binding(value) {
    ctx[7](value);
  }
  __name(pricelist_prices_binding, "pricelist_prices_binding");
  let pricelist_props = { presets: false };
  if (
    /*prices*/
    ctx[3] !== void 0
  ) {
    pricelist_props.prices = /*prices*/
    ctx[3];
  }
  pricelist = new PriceList({ props: pricelist_props });
  binding_callbacks.push(() => bind(pricelist, "prices", pricelist_prices_binding));
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.PricePresetEditor.Explanation")}`;
      t1 = space();
      create_component(pricelist.$$.fragment);
      t2 = space();
      footer = element("footer");
      button0 = element("button");
      i0 = element("i");
      t3 = space();
      t4 = text(t4_value);
      t5 = space();
      button1 = element("button");
      i1 = element("i");
      t6 = space();
      t7 = text(t7_value);
      attr(p, "class", "svelte-1vdoydt");
      attr(i0, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i1, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
      attr(form_1, "class", "item-piles-config-container");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(form_1, t1);
      mount_component(pricelist, form_1, null);
      append(form_1, t2);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i0);
      append(button0, t3);
      append(button0, t4);
      append(footer, t5);
      append(footer, button1);
      append(button1, i1);
      append(button1, t6);
      append(button1, t7);
      ctx[9](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[8],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[5]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const pricelist_changes = {};
      if (!updating_prices && dirty & /*prices*/
      8) {
        updating_prices = true;
        pricelist_changes.prices = /*prices*/
        ctx2[3];
        add_flush_callback(() => updating_prices = false);
      }
      pricelist.$set(pricelist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(pricelist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(pricelist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      destroy_component(pricelist);
      ctx[9](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$7, "create_default_slot$7");
function create_fragment$b(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[10](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$7] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, prices*/
      2060) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$b, "create_fragment$b");
function instance$b($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { data: data2 } = $$props;
  let { elementRoot } = $$props;
  let form;
  let prices = foundry.utils.deepClone(data2);
  async function updateSettings() {
    application.options.resolve(prices);
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function pricelist_prices_binding(value) {
    prices = value;
    $$invalidate(3, prices);
  }
  __name(pricelist_prices_binding, "pricelist_prices_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(6, data2 = $$props2.data);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  return [
    elementRoot,
    requestSubmit,
    form,
    prices,
    application,
    updateSettings,
    data2,
    pricelist_prices_binding,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$b, "instance$b");
const _Price_preset_editor_shell = class _Price_preset_editor_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$b, create_fragment$b, safe_not_equal, {
      data: 6,
      elementRoot: 0,
      requestSubmit: 1
    });
  }
  get data() {
    return this.$$.ctx[6];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Price_preset_editor_shell, "Price_preset_editor_shell");
let Price_preset_editor_shell = _Price_preset_editor_shell;
const _PricePresetEditor = class _PricePresetEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      id: `item-pile-price-preset-editor-${randomID()}`,
      title: game.i18n.format("ITEM-PILES.Applications.PricePresetEditor.Title"),
      width: 500,
      svelte: {
        class: Price_preset_editor_shell
      }
    });
  }
};
__name(_PricePresetEditor, "PricePresetEditor");
let PricePresetEditor = _PricePresetEditor;
const unstackableItemTypesEditor_svelte_svelte_type_style_lang = "";
function get_each_context$5(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[17] = list[i];
  child_ctx[18] = list;
  child_ctx[19] = i;
  return child_ctx;
}
__name(get_each_context$5, "get_each_context$5");
function get_each_context_1$1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[20] = list[i];
  return child_ctx;
}
__name(get_each_context_1$1, "get_each_context_1$1");
function create_each_block_1$1(ctx) {
  let option;
  let t0_value = (
    /*systemType*/
    ctx[20] + ""
  );
  let t0;
  let t1;
  let option_disabled_value;
  return {
    c() {
      option = element("option");
      t0 = text(t0_value);
      t1 = space();
      option.__value = /*systemType*/
      ctx[20];
      option.value = option.__value;
      option.disabled = option_disabled_value = /*systemType*/
      ctx[20] !== /*type*/
      ctx[17] && !/*unusedTypes*/
      ctx[4].includes(
        /*systemType*/
        ctx[20]
      );
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p(ctx2, dirty) {
      if (dirty & /*$unstackableItemTypesStore, unusedTypes, systemTypes*/
      148 && option_disabled_value !== (option_disabled_value = /*systemType*/
      ctx2[20] !== /*type*/
      ctx2[17] && !/*unusedTypes*/
      ctx2[4].includes(
        /*systemType*/
        ctx2[20]
      ))) {
        option.disabled = option_disabled_value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block_1$1, "create_each_block_1$1");
function create_each_block$5(key_1, ctx) {
  let tr;
  let td0;
  let select;
  let t0;
  let td1;
  let button;
  let t1;
  let mounted;
  let dispose;
  let each_value_1 = (
    /*systemTypes*/
    ctx[7]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_1$1(get_each_context_1$1(ctx, each_value_1, i));
  }
  function select_change_handler() {
    ctx[12].call(
      select,
      /*each_value*/
      ctx[18],
      /*index*/
      ctx[19]
    );
  }
  __name(select_change_handler, "select_change_handler");
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t0 = space();
      td1 = element("td");
      button = element("button");
      button.innerHTML = `<i class="fas fa-times"></i>`;
      t1 = space();
      attr(select, "class", "svelte-1m1c0js");
      if (
        /*type*/
        ctx[17] === void 0
      )
        add_render_callback(select_change_handler);
      attr(button, "type", "button");
      attr(button, "class", "svelte-1m1c0js");
      attr(td1, "class", "small svelte-1m1c0js");
      attr(tr, "class", "svelte-1m1c0js");
      this.first = tr;
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*type*/
        ctx[17],
        true
      );
      append(tr, t0);
      append(tr, td1);
      append(td1, button);
      append(tr, t1);
      if (!mounted) {
        dispose = [
          listen(select, "change", select_change_handler),
          listen(button, "click", function() {
            if (is_function(
              /*remove*/
              ctx[9](
                /*index*/
                ctx[19]
              )
            ))
              ctx[9](
                /*index*/
                ctx[19]
              ).apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*systemTypes, $unstackableItemTypesStore, unusedTypes*/
      148) {
        each_value_1 = /*systemTypes*/
        ctx[7];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1$1(ctx, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_1$1(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
      if (dirty & /*$unstackableItemTypesStore, systemTypes*/
      132) {
        select_option(
          select,
          /*type*/
          ctx[17]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$5, "create_each_block$5");
function create_default_slot$6(ctx) {
  let form_1;
  let p;
  let t1;
  let table;
  let tr;
  let th0;
  let t3;
  let th1;
  let a;
  let t4;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t5;
  let footer;
  let button0;
  let i1;
  let t6;
  let t7_value = localize("Save") + "";
  let t7;
  let t8;
  let button1;
  let i2;
  let t9;
  let t10_value = localize("Cancel") + "";
  let t10;
  let mounted;
  let dispose;
  let each_value = (
    /*$unstackableItemTypesStore*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[19]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$5(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$5(key, child_ctx));
  }
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.UnstackableItemTypesEditor.Explanation")}`;
      t1 = space();
      table = element("table");
      tr = element("tr");
      th0 = element("th");
      th0.textContent = `${localize("ITEM-PILES.Applications.UnstackableItemTypesEditor.Type")}`;
      t3 = space();
      th1 = element("th");
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus"></i>`;
      t4 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t5 = space();
      footer = element("footer");
      button0 = element("button");
      i1 = element("i");
      t6 = space();
      t7 = text(t7_value);
      t8 = space();
      button1 = element("button");
      i2 = element("i");
      t9 = space();
      t10 = text(t10_value);
      attr(a, "class", "item-piles-clickable svelte-1m1c0js");
      attr(th1, "class", "small svelte-1m1c0js");
      attr(tr, "class", "svelte-1m1c0js");
      attr(table, "class", "svelte-1m1c0js");
      attr(i1, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i2, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(form_1, t1);
      append(form_1, table);
      append(table, tr);
      append(tr, th0);
      append(tr, t3);
      append(tr, th1);
      append(th1, a);
      append(table, t4);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(table, null);
        }
      }
      append(form_1, t5);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i1);
      append(button0, t6);
      append(button0, t7);
      append(footer, t8);
      append(footer, button1);
      append(button1, i2);
      append(button1, t9);
      append(button1, t10);
      ctx[14](form_1);
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*add*/
            ctx[8]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[13],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[10]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*remove, $unstackableItemTypesStore, systemTypes, unusedTypes*/
      660) {
        each_value = /*$unstackableItemTypesStore*/
        ctx2[2];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, table, destroy_block, create_each_block$5, null, get_each_context$5);
      }
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[14](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$6, "create_default_slot$6");
function create_fragment$a(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[15](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$6] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $unstackableItemTypesStore, unusedTypes*/
      8388636) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$a, "create_fragment$a");
function instance$a($$self, $$props, $$invalidate) {
  let $unstackableItemTypesStore;
  const { application } = getContext("#external");
  let form;
  let { elementRoot } = $$props;
  let { data: data2 } = $$props;
  const itemFilters = (getSetting(SETTINGS$1.ITEM_FILTERS).find((filter2) => filter2.path === "type")?.filters ?? "").split(",");
  const unstackableItemTypesStore = writable$1(data2);
  component_subscribe($$self, unstackableItemTypesStore, (value) => $$invalidate(2, $unstackableItemTypesStore = value));
  let systemTypes = game.system.template.Item.types.filter((type) => !itemFilters.includes(type));
  let unusedTypes = [];
  function add() {
    if (!unusedTypes.length)
      return;
    unstackableItemTypesStore.update((arr) => {
      arr.push(unusedTypes[0]);
      return arr;
    });
  }
  __name(add, "add");
  function remove(index2) {
    unstackableItemTypesStore.update((arr) => {
      arr.splice(index2, 1);
      return arr;
    });
  }
  __name(remove, "remove");
  async function updateSettings() {
    application.options.resolve(get_store_value(unstackableItemTypesStore));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function select_change_handler(each_value, index2) {
    each_value[index2] = select_value(this);
    unstackableItemTypesStore.set($unstackableItemTypesStore);
    $$invalidate(7, systemTypes);
  }
  __name(select_change_handler, "select_change_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(3, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("data" in $$props2)
      $$invalidate(11, data2 = $$props2.data);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$unstackableItemTypesStore*/
    4) {
      {
        $$invalidate(4, unusedTypes = systemTypes.filter((systemType) => !$unstackableItemTypesStore.some((type) => type === systemType)));
      }
    }
  };
  return [
    elementRoot,
    requestSubmit,
    $unstackableItemTypesStore,
    form,
    unusedTypes,
    application,
    unstackableItemTypesStore,
    systemTypes,
    add,
    remove,
    updateSettings,
    data2,
    select_change_handler,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$a, "instance$a");
const _Unstackable_item_types_editor = class _Unstackable_item_types_editor extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$a, create_fragment$a, safe_not_equal, {
      elementRoot: 0,
      data: 11,
      requestSubmit: 1
    });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get data() {
    return this.$$.ctx[11];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Unstackable_item_types_editor, "Unstackable_item_types_editor");
let Unstackable_item_types_editor = _Unstackable_item_types_editor;
const _UnstackableItemTypesEditor = class _UnstackableItemTypesEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Applications.UnstackableItemTypesEditor.Title"),
      width: 300,
      svelte: {
        class: Unstackable_item_types_editor
      }
    });
  }
};
__name(_UnstackableItemTypesEditor, "UnstackableItemTypesEditor");
let UnstackableItemTypesEditor = _UnstackableItemTypesEditor;
function get_each_context$4(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[20] = list[i][0];
  child_ctx[21] = list[i][1];
  child_ctx[22] = list;
  child_ctx[23] = i;
  return child_ctx;
}
__name(get_each_context$4, "get_each_context$4");
function create_if_block_1$5(ctx) {
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus"></i>`;
      attr(a, "class", "item-piles-flexrow align-center-row item-piles-clickable-green");
      set_style(a, "text-align", "center");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[11]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1$5, "create_if_block_1$5");
function create_if_block$8(ctx) {
  let a;
  let mounted;
  let dispose;
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx[14](
        /*index*/
        ctx[23]
      )
    );
  }
  __name(click_handler_1, "click_handler_1");
  return {
    c() {
      a = element("a");
      a.innerHTML = `<i class="fas fa-times item-piles-clickable-red"></i> 
					`;
      attr(a, "class", "item-piles-flexrow align-center-row");
      set_style(a, "text-align", "center");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(a, "click", click_handler_1);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$8, "create_if_block$8");
function create_each_block$4(key_1, ctx) {
  let input0;
  let t0;
  let input1;
  let t1;
  let if_block_anchor;
  let mounted;
  let dispose;
  function input0_input_handler() {
    ctx[12].call(
      input0,
      /*each_value*/
      ctx[22],
      /*index*/
      ctx[23]
    );
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler() {
    ctx[13].call(
      input1,
      /*each_value*/
      ctx[22],
      /*index*/
      ctx[23]
    );
  }
  __name(input1_input_handler, "input1_input_handler");
  let if_block = !/*options*/
  ctx[5].readOnly && create_if_block$8(ctx);
  return {
    key: key_1,
    first: null,
    c() {
      input0 = element("input");
      t0 = space();
      input1 = element("input");
      t1 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      input0.disabled = /*options*/
      ctx[5].readOnly;
      attr(input0, "autocomplete", "false");
      attr(input0, "type", "text");
      attr(input1, "autocomplete", "false");
      attr(input1, "type", "text");
      this.first = input0;
    },
    m(target, anchor) {
      insert(target, input0, anchor);
      set_input_value(
        input0,
        /*key*/
        ctx[20]
      );
      insert(target, t0, anchor);
      insert(target, input1, anchor);
      set_input_value(
        input1,
        /*value*/
        ctx[21]
      );
      insert(target, t1, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      if (!mounted) {
        dispose = [
          listen(input0, "input", input0_input_handler),
          listen(input1, "input", input1_input_handler)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*$values*/
      4 && input0.value !== /*key*/
      ctx[20]) {
        set_input_value(
          input0,
          /*key*/
          ctx[20]
        );
      }
      if (dirty & /*$values*/
      4 && input1.value !== /*value*/
      ctx[21]) {
        set_input_value(
          input1,
          /*value*/
          ctx[21]
        );
      }
      if (!/*options*/
      ctx[5].readOnly)
        if_block.p(ctx, dirty);
    },
    d(detaching) {
      if (detaching)
        detach(input0);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(input1);
      if (detaching)
        detach(t1);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_each_block$4, "create_each_block$4");
function create_default_slot$5(ctx) {
  let form_1;
  let div;
  let span0;
  let t1;
  let span1;
  let t3;
  let t4;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t5;
  let footer;
  let button0;
  let i0;
  let t6;
  let t7_value = localize("Save") + "";
  let t7;
  let t8;
  let button1;
  let i1;
  let t9;
  let t10_value = localize("Cancel") + "";
  let t10;
  let mounted;
  let dispose;
  let if_block = !/*options*/
  ctx[5].readOnly && create_if_block_1$5(ctx);
  let each_value = (
    /*$values*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[23]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$4(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$4(key, child_ctx));
  }
  return {
    c() {
      form_1 = element("form");
      div = element("div");
      span0 = element("span");
      span0.textContent = `${localize("ITEM-PILES.Applications.StylesEditor." + /*options*/
      (ctx[5].variables ? "Variable" : "Style"))}`;
      t1 = space();
      span1 = element("span");
      span1.textContent = `${localize("ITEM-PILES.Applications.StylesEditor.Value")}`;
      t3 = space();
      if (if_block)
        if_block.c();
      t4 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t5 = space();
      footer = element("footer");
      button0 = element("button");
      i0 = element("i");
      t6 = space();
      t7 = text(t7_value);
      t8 = space();
      button1 = element("button");
      i1 = element("i");
      t9 = space();
      t10 = text(t10_value);
      attr(div, "class", "item-piles-bottom-divider");
      set_style(div, "display", "grid");
      set_style(div, "grid-template-columns", "1.25fr 2fr " + /*options*/
      (ctx[5].readOnly ? "" : "auto"));
      set_style(div, "gap", "5px");
      attr(i0, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i1, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, div);
      append(div, span0);
      append(div, t1);
      append(div, span1);
      append(div, t3);
      if (if_block)
        if_block.m(div, null);
      append(div, t4);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      append(form_1, t5);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i0);
      append(button0, t6);
      append(button0, t7);
      append(footer, t8);
      append(footer, button1);
      append(button1, i1);
      append(button1, t9);
      append(button1, t10);
      ctx[16](form_1);
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler_2*/
            ctx[15],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[9]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!/*options*/
      ctx2[5].readOnly)
        if_block.p(ctx2, dirty);
      if (dirty & /*remove, $values, options*/
      292) {
        each_value = /*$values*/
        ctx2[2];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, destroy_block, create_each_block$4, null, get_each_context$4);
      }
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      if (if_block)
        if_block.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[16](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$5, "create_default_slot$5");
function create_fragment$9(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[17](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$5] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $values*/
      16777228) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$9, "create_fragment$9");
function instance$9($$self, $$props, $$invalidate) {
  let $values;
  const { application } = getContext("#external");
  let { data: data2 } = $$props;
  let { elementRoot } = $$props;
  let form;
  const options = application.options;
  const styleValues = data2?.subscribe ? data2 : writable$1(data2);
  const styleStore = Object.entries(get_store_value(styleValues));
  let values = writable$1(styleStore.length ? styleStore : [["", ""]]);
  component_subscribe($$self, values, (value) => $$invalidate(2, $values = value));
  function add() {
    values.update((arr) => {
      return [...arr, ["", ""]];
    });
  }
  __name(add, "add");
  function remove(index2) {
    values.update((arr) => {
      arr.splice(index2, 1);
      return arr;
    });
  }
  __name(remove, "remove");
  async function updateSettings() {
    application.options.resolve(Object.fromEntries(get_store_value(values)));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  const click_handler = /* @__PURE__ */ __name(() => add(), "click_handler");
  function input0_input_handler(each_value, index2) {
    each_value[index2][0] = this.value;
    values.set($values);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler(each_value, index2) {
    each_value[index2][1] = this.value;
    values.set($values);
  }
  __name(input1_input_handler, "input1_input_handler");
  const click_handler_1 = /* @__PURE__ */ __name((index2) => remove(index2), "click_handler_1");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    application.options.resolve(null);
    application.close();
  }, "click_handler_2");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(3, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(10, data2 = $$props2.data);
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$values*/
    4) {
      {
        const data3 = Object.fromEntries($values.map((entry) => [entry[0].trim(), entry[1].trim()]).filter((entry) => entry[0].length && entry[1].length));
        styleValues.set(data3);
        if (options.onchange) {
          options.onchange(data3);
        }
      }
    }
  };
  return [
    elementRoot,
    requestSubmit,
    $values,
    form,
    application,
    options,
    values,
    add,
    remove,
    updateSettings,
    data2,
    click_handler,
    input0_input_handler,
    input1_input_handler,
    click_handler_1,
    click_handler_2,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$9, "instance$9");
const _Styles_editor = class _Styles_editor extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$9, create_fragment$9, safe_not_equal, {
      data: 10,
      elementRoot: 0,
      requestSubmit: 1
    });
  }
  get data() {
    return this.$$.ctx[10];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Styles_editor, "Styles_editor");
let Styles_editor = _Styles_editor;
const _StylesEditor = class _StylesEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Applications.StylesEditor.Title"),
      svelte: {
        class: Styles_editor
      }
    });
  }
};
__name(_StylesEditor, "StylesEditor");
let StylesEditor = _StylesEditor;
const StyleEntry_svelte_svelte_type_style_lang = "";
function create_if_block$7(ctx) {
  let img;
  let img_src_value;
  return {
    c() {
      img = element("img");
      attr(img, "class", "item-piles-item-image-example svelte-5lct34");
      if (!src_url_equal(img.src, img_src_value = /*image*/
      ctx[2]))
        attr(img, "src", img_src_value);
    },
    m(target, anchor) {
      insert(target, img, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*image*/
      4 && !src_url_equal(img.src, img_src_value = /*image*/
      ctx2[2])) {
        attr(img, "src", img_src_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(img);
    }
  };
}
__name(create_if_block$7, "create_if_block$7");
function create_fragment$8(ctx) {
  let div0;
  let input0;
  let t0;
  let div1;
  let input1;
  let t1;
  let div3;
  let t2;
  let div2;
  let div2_style_value;
  let t3;
  let div4;
  let a0;
  let t4;
  let div5;
  let a1;
  let mounted;
  let dispose;
  let if_block = (
    /*image*/
    ctx[2] && create_if_block$7(ctx)
  );
  return {
    c() {
      div0 = element("div");
      input0 = element("input");
      t0 = space();
      div1 = element("div");
      input1 = element("input");
      t1 = space();
      div3 = element("div");
      if (if_block)
        if_block.c();
      t2 = space();
      div2 = element("div");
      t3 = space();
      div4 = element("div");
      a0 = element("a");
      a0.innerHTML = `<i class="fas fa-cog svelte-5lct34"></i>`;
      t4 = space();
      div5 = element("div");
      a1 = element("a");
      a1.innerHTML = `<i class="fas fa-times svelte-5lct34"></i>`;
      attr(input0, "placeholder", "system.rarity");
      input0.required = true;
      attr(input0, "type", "text");
      attr(div0, "class", "svelte-5lct34");
      attr(input1, "placeholder", "rare");
      input1.required = true;
      attr(input1, "type", "text");
      attr(div1, "class", "svelte-5lct34");
      attr(div2, "class", "img-div svelte-5lct34");
      attr(div2, "style", div2_style_value = styleFromObject(
        /*$style*/
        ctx[4]
      ));
      attr(div3, "class", "svelte-5lct34");
      attr(a0, "class", "item-piles-clickable-green svelte-5lct34");
      attr(div4, "class", "svelte-5lct34");
      attr(a1, "class", "item-piles-clickable-red svelte-5lct34");
      attr(div5, "class", "svelte-5lct34");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, input0);
      set_input_value(
        input0,
        /*entry*/
        ctx[0].path
      );
      insert(target, t0, anchor);
      insert(target, div1, anchor);
      append(div1, input1);
      set_input_value(
        input1,
        /*entry*/
        ctx[0].value
      );
      insert(target, t1, anchor);
      insert(target, div3, anchor);
      if (if_block)
        if_block.m(div3, null);
      append(div3, t2);
      append(div3, div2);
      insert(target, t3, anchor);
      insert(target, div4, anchor);
      append(div4, a0);
      insert(target, t4, anchor);
      insert(target, div5, anchor);
      append(div5, a1);
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "input",
            /*input0_input_handler*/
            ctx[7]
          ),
          listen(
            input1,
            "input",
            /*input1_input_handler*/
            ctx[8]
          ),
          listen(
            a0,
            "click",
            /*click_handler*/
            ctx[9]
          ),
          listen(a1, "click", function() {
            if (is_function(
              /*remove*/
              ctx[3](
                /*index*/
                ctx[1]
              )
            ))
              ctx[3](
                /*index*/
                ctx[1]
              ).apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx = new_ctx;
      if (dirty & /*entry*/
      1 && input0.value !== /*entry*/
      ctx[0].path) {
        set_input_value(
          input0,
          /*entry*/
          ctx[0].path
        );
      }
      if (dirty & /*entry*/
      1 && input1.value !== /*entry*/
      ctx[0].value) {
        set_input_value(
          input1,
          /*entry*/
          ctx[0].value
        );
      }
      if (
        /*image*/
        ctx[2]
      ) {
        if (if_block) {
          if_block.p(ctx, dirty);
        } else {
          if_block = create_if_block$7(ctx);
          if_block.c();
          if_block.m(div3, t2);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*$style*/
      16 && div2_style_value !== (div2_style_value = styleFromObject(
        /*$style*/
        ctx[4]
      ))) {
        attr(div2, "style", div2_style_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(div1);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(div3);
      if (if_block)
        if_block.d();
      if (detaching)
        detach(t3);
      if (detaching)
        detach(div4);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(div5);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$8, "create_fragment$8");
function instance$8($$self, $$props, $$invalidate) {
  let $style;
  const { application } = getContext("#external");
  let { index: index2 } = $$props;
  let { entry } = $$props;
  let { image } = $$props;
  let { remove } = $$props;
  let style = writable$1(entry.styling);
  component_subscribe($$self, style, (value) => $$invalidate(4, $style = value));
  async function renderStyleEditor(event) {
    const oldStyle = entry.styling;
    const newStyles = await StylesEditor.show(style, {
      width: 400,
      left: application.position.left + 405,
      top: event.clientY - 75,
      readOnly: true
    });
    style.set(newStyles || oldStyle);
    $$invalidate(0, entry.styling = newStyles || oldStyle, entry);
  }
  __name(renderStyleEditor, "renderStyleEditor");
  function input0_input_handler() {
    entry.path = this.value;
    $$invalidate(0, entry);
  }
  __name(input0_input_handler, "input0_input_handler");
  function input1_input_handler() {
    entry.value = this.value;
    $$invalidate(0, entry);
  }
  __name(input1_input_handler, "input1_input_handler");
  const click_handler = /* @__PURE__ */ __name((evt) => renderStyleEditor(evt), "click_handler");
  $$self.$$set = ($$props2) => {
    if ("index" in $$props2)
      $$invalidate(1, index2 = $$props2.index);
    if ("entry" in $$props2)
      $$invalidate(0, entry = $$props2.entry);
    if ("image" in $$props2)
      $$invalidate(2, image = $$props2.image);
    if ("remove" in $$props2)
      $$invalidate(3, remove = $$props2.remove);
  };
  return [
    entry,
    index2,
    image,
    remove,
    $style,
    style,
    renderStyleEditor,
    input0_input_handler,
    input1_input_handler,
    click_handler
  ];
}
__name(instance$8, "instance$8");
const _StyleEntry = class _StyleEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$8, create_fragment$8, safe_not_equal, { index: 1, entry: 0, image: 2, remove: 3 });
  }
};
__name(_StyleEntry, "StyleEntry");
let StyleEntry = _StyleEntry;
const vaultStylesEditor_svelte_svelte_type_style_lang = "";
function get_each_context$3(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[16] = list[i];
  child_ctx[17] = list;
  child_ctx[18] = i;
  return child_ctx;
}
__name(get_each_context$3, "get_each_context$3");
function create_each_block$3(key_1, ctx) {
  let first;
  let styleentry;
  let updating_entry;
  let current;
  function styleentry_entry_binding(value) {
    ctx[11](
      value,
      /*entry*/
      ctx[16],
      /*each_value*/
      ctx[17],
      /*index*/
      ctx[18]
    );
  }
  __name(styleentry_entry_binding, "styleentry_entry_binding");
  let styleentry_props = {
    image: (
      /*images*/
      ctx[3][
        /*index*/
        ctx[18]
      ]
    ),
    index: (
      /*index*/
      ctx[18]
    ),
    remove: (
      /*remove*/
      ctx[8]
    )
  };
  if (
    /*entry*/
    ctx[16] !== void 0
  ) {
    styleentry_props.entry = /*entry*/
    ctx[16];
  }
  styleentry = new StyleEntry({ props: styleentry_props });
  binding_callbacks.push(() => bind(styleentry, "entry", styleentry_entry_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(styleentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(styleentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const styleentry_changes = {};
      if (dirty & /*images, $vaultStyleStore*/
      24)
        styleentry_changes.image = /*images*/
        ctx[3][
          /*index*/
          ctx[18]
        ];
      if (dirty & /*$vaultStyleStore*/
      16)
        styleentry_changes.index = /*index*/
        ctx[18];
      if (!updating_entry && dirty & /*$vaultStyleStore*/
      16) {
        updating_entry = true;
        styleentry_changes.entry = /*entry*/
        ctx[16];
        add_flush_callback(() => updating_entry = false);
      }
      styleentry.$set(styleentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(styleentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(styleentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(styleentry, detaching);
    }
  };
}
__name(create_each_block$3, "create_each_block$3");
function create_default_slot$4(ctx) {
  let form_1;
  let p;
  let t1;
  let div5;
  let div0;
  let t3;
  let div1;
  let t5;
  let div2;
  let t6;
  let div3;
  let t7;
  let div4;
  let a;
  let t8;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t9;
  let footer;
  let button0;
  let i1;
  let t10;
  let t11_value = localize("Save") + "";
  let t11;
  let t12;
  let button1;
  let i2;
  let t13;
  let t14_value = localize("Cancel") + "";
  let t14;
  let current;
  let mounted;
  let dispose;
  let each_value = (
    /*$vaultStyleStore*/
    ctx[4]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*index*/
    ctx2[18]
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$3(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$3(key, child_ctx));
  }
  return {
    c() {
      form_1 = element("form");
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Applications.VaultStylesEditor.Explanation")}`;
      t1 = space();
      div5 = element("div");
      div0 = element("div");
      div0.textContent = `${localize("ITEM-PILES.Applications.VaultStylesEditor.Path")}`;
      t3 = space();
      div1 = element("div");
      div1.textContent = `${localize("ITEM-PILES.Applications.VaultStylesEditor.Value")}`;
      t5 = space();
      div2 = element("div");
      t6 = space();
      div3 = element("div");
      t7 = space();
      div4 = element("div");
      a = element("a");
      a.innerHTML = `<i class="fas fa-plus svelte-1jdz898"></i>`;
      t8 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t9 = space();
      footer = element("footer");
      button0 = element("button");
      i1 = element("i");
      t10 = space();
      t11 = text(t11_value);
      t12 = space();
      button1 = element("button");
      i2 = element("i");
      t13 = space();
      t14 = text(t14_value);
      attr(a, "class", "item-piles-clickable svelte-1jdz898");
      set_style(div4, "text-align", "right");
      attr(div4, "class", "svelte-1jdz898");
      attr(div5, "class", "item-piles-table svelte-1jdz898");
      attr(i1, "class", "far fa-save");
      attr(button0, "type", "button");
      attr(i2, "class", "far fa-times");
      attr(button1, "type", "button");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, p);
      append(form_1, t1);
      append(form_1, div5);
      append(div5, div0);
      append(div5, t3);
      append(div5, div1);
      append(div5, t5);
      append(div5, div2);
      append(div5, t6);
      append(div5, div3);
      append(div5, t7);
      append(div5, div4);
      append(div4, a);
      append(div5, t8);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div5, null);
        }
      }
      append(form_1, t9);
      append(form_1, footer);
      append(footer, button0);
      append(button0, i1);
      append(button0, t10);
      append(button0, t11);
      append(footer, t12);
      append(footer, button1);
      append(button1, i2);
      append(button1, t13);
      append(button1, t14);
      ctx[13](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            a,
            "click",
            /*add*/
            ctx[7]
          ),
          listen(
            button0,
            "click",
            /*requestSubmit*/
            ctx[1],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*click_handler*/
            ctx[12],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[9]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*images, $vaultStyleStore, remove*/
      280) {
        each_value = /*$vaultStyleStore*/
        ctx2[4];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div5, outro_and_destroy_block, create_each_block$3, null, get_each_context$3);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[13](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$4, "create_default_slot$4");
function create_fragment$7(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[14](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$4] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, form, $vaultStyleStore, images*/
      524316) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$7, "create_fragment$7");
function instance$7($$self, $$props, $$invalidate) {
  let $vaultStyleStore;
  const { application } = getContext("#external");
  let form;
  let { elementRoot } = $$props;
  let { data: data2 } = $$props;
  const vaultStyleStore = writable$1(data2);
  component_subscribe($$self, vaultStyleStore, (value) => $$invalidate(4, $vaultStyleStore = value));
  loadImages();
  function add() {
    vaultStyleStore.update((arr) => {
      arr.push({ path: "", value: "", styling: {} });
      return arr;
    });
  }
  __name(add, "add");
  let images = [];
  async function loadImages() {
    const data3 = await FilePicker.browse("public", "icons/weapons/swords/*.webp", { wildcard: true });
    $$invalidate(3, images = data3.files);
  }
  __name(loadImages, "loadImages");
  function remove(index2) {
    vaultStyleStore.update((arr) => {
      arr.splice(index2, 1);
      return arr;
    });
  }
  __name(remove, "remove");
  async function updateSettings() {
    application.options.resolve(get_store_value(vaultStyleStore));
    application.close();
  }
  __name(updateSettings, "updateSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  function styleentry_entry_binding(value, entry, each_value, index2) {
    each_value[index2] = value;
    vaultStyleStore.set($vaultStyleStore);
  }
  __name(styleentry_entry_binding, "styleentry_entry_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    application.close();
  }, "click_handler");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("data" in $$props2)
      $$invalidate(10, data2 = $$props2.data);
  };
  return [
    elementRoot,
    requestSubmit,
    form,
    images,
    $vaultStyleStore,
    application,
    vaultStyleStore,
    add,
    remove,
    updateSettings,
    data2,
    styleentry_entry_binding,
    click_handler,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$7, "instance$7");
const _Vault_styles_editor = class _Vault_styles_editor extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$7, create_fragment$7, safe_not_equal, {
      elementRoot: 0,
      data: 10,
      requestSubmit: 1
    });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get data() {
    return this.$$.ctx[10];
  }
  set data(data2) {
    this.$$set({ data: data2 });
    flush();
  }
  get requestSubmit() {
    return this.$$.ctx[1];
  }
};
__name(_Vault_styles_editor, "Vault_styles_editor");
let Vault_styles_editor = _Vault_styles_editor;
const _VaultStylesEditor = class _VaultStylesEditor extends Editor {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Applications.VaultStylesEditor.Title"),
      svelte: {
        class: Vault_styles_editor
      }
    });
  }
};
__name(_VaultStylesEditor, "VaultStylesEditor");
let VaultStylesEditor = _VaultStylesEditor;
const editors = {
  "currencies": CurrenciesEditor,
  "secondary-currencies": SecondaryCurrenciesEditor,
  "item-filters": ItemFiltersEditor,
  "item-similarities": StringListEditor,
  "item-categories": StringListEditor,
  "styles": StylesEditor,
  "vault-styles": VaultStylesEditor,
  "price-modifiers": PriceModifiersEditor,
  "unstackable-item-types": UnstackableItemTypesEditor,
  "price-presets": PricePresetEditor
};
const SettingButton_svelte_svelte_type_style_lang = "";
function create_if_block$6(ctx) {
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.innerHTML = `<i class="fas fa-undo reset-setting svelte-1e4lcsc"></i>`;
      attr(a, "data-fast-tooltip", "Reset setting");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[4]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$6, "create_if_block$6");
function create_fragment$6(ctx) {
  let div3;
  let div0;
  let label;
  let t0_value = localize(
    /*data*/
    ctx[0].name
  ) + "";
  let t0;
  let t1;
  let t2;
  let p;
  let t3_value = localize(
    /*data*/
    ctx[0].hint
  ) + "";
  let t3;
  let t4;
  let div2;
  let div1;
  let button;
  let i;
  let i_class_value;
  let t5;
  let t6_value = localize(
    /*data*/
    ctx[0].label
  ) + "";
  let t6;
  let mounted;
  let dispose;
  let if_block = !/*data*/
  ctx[0].hideResetButton && create_if_block$6(ctx);
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      label = element("label");
      t0 = text(t0_value);
      t1 = space();
      if (if_block)
        if_block.c();
      t2 = space();
      p = element("p");
      t3 = text(t3_value);
      t4 = space();
      div2 = element("div");
      div1 = element("div");
      button = element("button");
      i = element("i");
      t5 = space();
      t6 = text(t6_value);
      attr(label, "class", "svelte-1e4lcsc");
      attr(p, "class", "notes");
      attr(div0, "class", "label-side svelte-1e4lcsc");
      attr(i, "class", i_class_value = null_to_empty(
        /*data*/
        ctx[0].icon
      ) + " svelte-1e4lcsc");
      attr(button, "type", "button");
      attr(button, "class", "svelte-1e4lcsc");
      attr(div1, "class", "button-container svelte-1e4lcsc");
      attr(div2, "class", "form-fields input-side svelte-1e4lcsc");
      attr(div3, "class", "setting form-scope item-piles-flexrow svelte-1e4lcsc");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div0, label);
      append(label, t0);
      append(label, t1);
      if (if_block)
        if_block.m(label, null);
      append(div0, t2);
      append(div0, p);
      append(p, t3);
      append(div3, t4);
      append(div3, div2);
      append(div2, div1);
      append(div1, button);
      append(button, i);
      append(button, t5);
      append(button, t6);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[5]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*data*/
      1 && t0_value !== (t0_value = localize(
        /*data*/
        ctx2[0].name
      ) + ""))
        set_data(t0, t0_value);
      if (!/*data*/
      ctx2[0].hideResetButton) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$6(ctx2);
          if_block.c();
          if_block.m(label, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*data*/
      1 && t3_value !== (t3_value = localize(
        /*data*/
        ctx2[0].hint
      ) + ""))
        set_data(t3, t3_value);
      if (dirty & /*data*/
      1 && i_class_value !== (i_class_value = null_to_empty(
        /*data*/
        ctx2[0].icon
      ) + " svelte-1e4lcsc")) {
        attr(i, "class", i_class_value);
      }
      if (dirty & /*data*/
      1 && t6_value !== (t6_value = localize(
        /*data*/
        ctx2[0].label
      ) + ""))
        set_data(t6, t6_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div3);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_fragment$6, "create_fragment$6");
function instance$6($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { key } = $$props;
  let { data: data2 } = $$props;
  let { callback = false } = $$props;
  let editor = false;
  if (!callback) {
    editor = editors[data2.application];
    callback = /* @__PURE__ */ __name(() => {
      showEditor();
    }, "callback");
  }
  function showEditor() {
    if (editor) {
      const combinedData = data2?.mergedDefaults ? foundry.utils.mergeObject(data2.mergedDefaults, data2.value) : data2.value;
      openEditor(key, combinedData).then((result) => {
        if (!result)
          return;
        if (data2?.mergedDefaults) {
          result = foundry.utils.diffObject(data2?.mergedDefaults, result);
        }
        $$invalidate(0, data2.value = result, data2);
      });
      application.options.zLevel = 100;
    }
  }
  __name(showEditor, "showEditor");
  function reset() {
    $$invalidate(0, data2.value = foundry.utils.deepClone(data2.default), data2);
  }
  __name(reset, "reset");
  const click_handler = /* @__PURE__ */ __name(() => reset(), "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    callback();
  }, "click_handler_1");
  $$self.$$set = ($$props2) => {
    if ("key" in $$props2)
      $$invalidate(3, key = $$props2.key);
    if ("data" in $$props2)
      $$invalidate(0, data2 = $$props2.data);
    if ("callback" in $$props2)
      $$invalidate(1, callback = $$props2.callback);
  };
  return [data2, callback, reset, key, click_handler, click_handler_1];
}
__name(instance$6, "instance$6");
const _SettingButton = class _SettingButton extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$6, create_fragment$6, safe_not_equal, { key: 3, data: 0, callback: 1 });
  }
};
__name(_SettingButton, "SettingButton");
let SettingButton = _SettingButton;
const settingsShell_svelte_svelte_type_style_lang = "";
function create_if_block_1$4(ctx) {
  let tabs_1;
  let updating_activeTab;
  let current;
  function tabs_1_activeTab_binding(value) {
    ctx[11](value);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  let tabs_1_props = { tabs: (
    /*tabs*/
    ctx[9]
  ) };
  if (
    /*activeTab*/
    ctx[3] !== void 0
  ) {
    tabs_1_props.activeTab = /*activeTab*/
    ctx[3];
  }
  tabs_1 = new Tabs({ props: tabs_1_props });
  binding_callbacks.push(() => bind(tabs_1, "activeTab", tabs_1_activeTab_binding));
  return {
    c() {
      create_component(tabs_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(tabs_1, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const tabs_1_changes = {};
      if (!updating_activeTab && dirty[0] & /*activeTab*/
      8) {
        updating_activeTab = true;
        tabs_1_changes.activeTab = /*activeTab*/
        ctx2[3];
        add_flush_callback(() => updating_activeTab = false);
      }
      tabs_1.$set(tabs_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tabs_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tabs_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(tabs_1, detaching);
    }
  };
}
__name(create_if_block_1$4, "create_if_block_1$4");
function create_if_block$5(ctx) {
  let div0;
  let setting0;
  let updating_data;
  let t0;
  let setting1;
  let updating_data_1;
  let t1;
  let setting2;
  let updating_data_2;
  let t2;
  let setting3;
  let updating_data_3;
  let t3;
  let setting4;
  let updating_data_4;
  let t4;
  let setting5;
  let updating_data_5;
  let t5;
  let setting6;
  let updating_data_6;
  let t6;
  let setting7;
  let updating_data_7;
  let t7;
  let setting8;
  let updating_data_8;
  let t8;
  let settingbutton0;
  let updating_data_9;
  let t9;
  let settingbutton1;
  let updating_data_10;
  let t10;
  let div1;
  let settingbutton2;
  let updating_data_11;
  let t11;
  let settingbutton3;
  let updating_data_12;
  let t12;
  let div2;
  let settingbutton4;
  let t13;
  let setting9;
  let updating_data_13;
  let t14;
  let setting10;
  let updating_data_14;
  let t15;
  let setting11;
  let updating_data_15;
  let t16;
  let settingbutton5;
  let updating_data_16;
  let t17;
  let settingbutton6;
  let updating_data_17;
  let t18;
  let setting12;
  let updating_data_18;
  let t19;
  let settingbutton7;
  let updating_data_19;
  let t20;
  let settingbutton8;
  let updating_data_20;
  let t21;
  let settingbutton9;
  let updating_data_21;
  let current;
  function setting0_data_binding_1(value) {
    ctx[18](value);
  }
  __name(setting0_data_binding_1, "setting0_data_binding_1");
  let setting0_props = { key: SETTINGS$1.ENABLE_DROPPING_ITEMS };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ENABLE_DROPPING_ITEMS] !== void 0
  ) {
    setting0_props.data = /*settings*/
    ctx[1][SETTINGS$1.ENABLE_DROPPING_ITEMS];
  }
  setting0 = new Setting({ props: setting0_props });
  binding_callbacks.push(() => bind(setting0, "data", setting0_data_binding_1));
  function setting1_data_binding_1(value) {
    ctx[19](value);
  }
  __name(setting1_data_binding_1, "setting1_data_binding_1");
  let setting1_props = { key: SETTINGS$1.ENABLE_GIVING_ITEMS };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ENABLE_GIVING_ITEMS] !== void 0
  ) {
    setting1_props.data = /*settings*/
    ctx[1][SETTINGS$1.ENABLE_GIVING_ITEMS];
  }
  setting1 = new Setting({ props: setting1_props });
  binding_callbacks.push(() => bind(setting1, "data", setting1_data_binding_1));
  function setting2_data_binding_1(value) {
    ctx[20](value);
  }
  __name(setting2_data_binding_1, "setting2_data_binding_1");
  let setting2_props = { key: SETTINGS$1.ENABLE_TRADING };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ENABLE_TRADING] !== void 0
  ) {
    setting2_props.data = /*settings*/
    ctx[1][SETTINGS$1.ENABLE_TRADING];
  }
  setting2 = new Setting({ props: setting2_props });
  binding_callbacks.push(() => bind(setting2, "data", setting2_data_binding_1));
  function setting3_data_binding_1(value) {
    ctx[21](value);
  }
  __name(setting3_data_binding_1, "setting3_data_binding_1");
  let setting3_props = { key: SETTINGS$1.SHOW_TRADE_BUTTON };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.SHOW_TRADE_BUTTON] !== void 0
  ) {
    setting3_props.data = /*settings*/
    ctx[1][SETTINGS$1.SHOW_TRADE_BUTTON];
  }
  setting3 = new Setting({ props: setting3_props });
  binding_callbacks.push(() => bind(setting3, "data", setting3_data_binding_1));
  function setting4_data_binding_1(value) {
    ctx[22](value);
  }
  __name(setting4_data_binding_1, "setting4_data_binding_1");
  let setting4_props = { key: SETTINGS$1.INSPECT_ITEMS_IN_TRADE };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.INSPECT_ITEMS_IN_TRADE] !== void 0
  ) {
    setting4_props.data = /*settings*/
    ctx[1][SETTINGS$1.INSPECT_ITEMS_IN_TRADE];
  }
  setting4 = new Setting({ props: setting4_props });
  binding_callbacks.push(() => bind(setting4, "data", setting4_data_binding_1));
  function setting5_data_binding_1(value) {
    ctx[23](value);
  }
  __name(setting5_data_binding_1, "setting5_data_binding_1");
  let setting5_props = { key: SETTINGS$1.OUTPUT_TO_CHAT };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.OUTPUT_TO_CHAT] !== void 0
  ) {
    setting5_props.data = /*settings*/
    ctx[1][SETTINGS$1.OUTPUT_TO_CHAT];
  }
  setting5 = new Setting({ props: setting5_props });
  binding_callbacks.push(() => bind(setting5, "data", setting5_data_binding_1));
  function setting6_data_binding(value) {
    ctx[24](value);
  }
  __name(setting6_data_binding, "setting6_data_binding");
  let setting6_props = { key: SETTINGS$1.DELETE_EMPTY_PILES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.DELETE_EMPTY_PILES] !== void 0
  ) {
    setting6_props.data = /*settings*/
    ctx[1][SETTINGS$1.DELETE_EMPTY_PILES];
  }
  setting6 = new Setting({ props: setting6_props });
  binding_callbacks.push(() => bind(setting6, "data", setting6_data_binding));
  function setting7_data_binding(value) {
    ctx[25](value);
  }
  __name(setting7_data_binding, "setting7_data_binding");
  let setting7_props = { key: SETTINGS$1.POPULATION_TABLES_FOLDER };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.POPULATION_TABLES_FOLDER] !== void 0
  ) {
    setting7_props.data = /*settings*/
    ctx[1][SETTINGS$1.POPULATION_TABLES_FOLDER];
  }
  setting7 = new Setting({ props: setting7_props });
  binding_callbacks.push(() => bind(setting7, "data", setting7_data_binding));
  function setting8_data_binding(value) {
    ctx[26](value);
  }
  __name(setting8_data_binding, "setting8_data_binding");
  let setting8_props = { key: SETTINGS$1.HIDE_TOKEN_BORDER };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.HIDE_TOKEN_BORDER] !== void 0
  ) {
    setting8_props.data = /*settings*/
    ctx[1][SETTINGS$1.HIDE_TOKEN_BORDER];
  }
  setting8 = new Setting({ props: setting8_props });
  binding_callbacks.push(() => bind(setting8, "data", setting8_data_binding));
  function settingbutton0_data_binding(value) {
    ctx[27](value);
  }
  __name(settingbutton0_data_binding, "settingbutton0_data_binding");
  let settingbutton0_props = { key: SETTINGS$1.PRICE_PRESETS };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.PRICE_PRESETS] !== void 0
  ) {
    settingbutton0_props.data = /*settings*/
    ctx[1][SETTINGS$1.PRICE_PRESETS];
  }
  settingbutton0 = new SettingButton({ props: settingbutton0_props });
  binding_callbacks.push(() => bind(settingbutton0, "data", settingbutton0_data_binding));
  function settingbutton1_data_binding(value) {
    ctx[28](value);
  }
  __name(settingbutton1_data_binding, "settingbutton1_data_binding");
  let settingbutton1_props = { key: SETTINGS$1.CUSTOM_ITEM_CATEGORIES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.CUSTOM_ITEM_CATEGORIES] !== void 0
  ) {
    settingbutton1_props.data = /*settings*/
    ctx[1][SETTINGS$1.CUSTOM_ITEM_CATEGORIES];
  }
  settingbutton1 = new SettingButton({ props: settingbutton1_props });
  binding_callbacks.push(() => bind(settingbutton1, "data", settingbutton1_data_binding));
  function settingbutton2_data_binding(value) {
    ctx[29](value);
  }
  __name(settingbutton2_data_binding, "settingbutton2_data_binding");
  let settingbutton2_props = { key: SETTINGS$1.CSS_VARIABLES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.CSS_VARIABLES] !== void 0
  ) {
    settingbutton2_props.data = /*settings*/
    ctx[1][SETTINGS$1.CSS_VARIABLES];
  }
  settingbutton2 = new SettingButton({ props: settingbutton2_props });
  binding_callbacks.push(() => bind(settingbutton2, "data", settingbutton2_data_binding));
  function settingbutton3_data_binding(value) {
    ctx[30](value);
  }
  __name(settingbutton3_data_binding, "settingbutton3_data_binding");
  let settingbutton3_props = { key: SETTINGS$1.VAULT_STYLES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.VAULT_STYLES] !== void 0
  ) {
    settingbutton3_props.data = /*settings*/
    ctx[1][SETTINGS$1.VAULT_STYLES];
  }
  settingbutton3 = new SettingButton({ props: settingbutton3_props });
  binding_callbacks.push(() => bind(settingbutton3, "data", settingbutton3_data_binding));
  settingbutton4 = new SettingButton({
    props: {
      data: {
        name: "ITEM-PILES.Settings.Reset.Title",
        hint: "ITEM-PILES.Settings.Reset.Hint",
        label: "ITEM-PILES.Settings.Reset.Label",
        icon: "fas fa-undo",
        hideResetButton: true
      },
      callback: (
        /*func*/
        ctx[31]
      )
    }
  });
  function setting9_data_binding(value) {
    ctx[32](value);
  }
  __name(setting9_data_binding, "setting9_data_binding");
  let setting9_props = {
    key: SETTINGS$1.ACTOR_CLASS_TYPE,
    options: game.system.template.Actor.types
  };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ACTOR_CLASS_TYPE] !== void 0
  ) {
    setting9_props.data = /*settings*/
    ctx[1][SETTINGS$1.ACTOR_CLASS_TYPE];
  }
  setting9 = new Setting({ props: setting9_props });
  binding_callbacks.push(() => bind(setting9, "data", setting9_data_binding));
  function setting10_data_binding(value) {
    ctx[33](value);
  }
  __name(setting10_data_binding, "setting10_data_binding");
  let setting10_props = { key: SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE] !== void 0
  ) {
    setting10_props.data = /*settings*/
    ctx[1][SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE];
  }
  setting10 = new Setting({ props: setting10_props });
  binding_callbacks.push(() => bind(setting10, "data", setting10_data_binding));
  function setting11_data_binding(value) {
    ctx[34](value);
  }
  __name(setting11_data_binding, "setting11_data_binding");
  let setting11_props = { key: SETTINGS$1.ITEM_PRICE_ATTRIBUTE };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ITEM_PRICE_ATTRIBUTE] !== void 0
  ) {
    setting11_props.data = /*settings*/
    ctx[1][SETTINGS$1.ITEM_PRICE_ATTRIBUTE];
  }
  setting11 = new Setting({ props: setting11_props });
  binding_callbacks.push(() => bind(setting11, "data", setting11_data_binding));
  function settingbutton5_data_binding(value) {
    ctx[35](value);
  }
  __name(settingbutton5_data_binding, "settingbutton5_data_binding");
  let settingbutton5_props = { key: SETTINGS$1.CURRENCIES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.CURRENCIES] !== void 0
  ) {
    settingbutton5_props.data = /*settings*/
    ctx[1][SETTINGS$1.CURRENCIES];
  }
  settingbutton5 = new SettingButton({ props: settingbutton5_props });
  binding_callbacks.push(() => bind(settingbutton5, "data", settingbutton5_data_binding));
  function settingbutton6_data_binding(value) {
    ctx[36](value);
  }
  __name(settingbutton6_data_binding, "settingbutton6_data_binding");
  let settingbutton6_props = { key: SETTINGS$1.SECONDARY_CURRENCIES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.SECONDARY_CURRENCIES] !== void 0
  ) {
    settingbutton6_props.data = /*settings*/
    ctx[1][SETTINGS$1.SECONDARY_CURRENCIES];
  }
  settingbutton6 = new SettingButton({ props: settingbutton6_props });
  binding_callbacks.push(() => bind(settingbutton6, "data", settingbutton6_data_binding));
  function setting12_data_binding(value) {
    ctx[37](value);
  }
  __name(setting12_data_binding, "setting12_data_binding");
  let setting12_props = {
    key: SETTINGS$1.CURRENCY_DECIMAL_DIGITS,
    disabled: (
      /*settings*/
      ctx[1][SETTINGS$1.CURRENCIES].value.length !== 1
    )
  };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.CURRENCY_DECIMAL_DIGITS] !== void 0
  ) {
    setting12_props.data = /*settings*/
    ctx[1][SETTINGS$1.CURRENCY_DECIMAL_DIGITS];
  }
  setting12 = new Setting({ props: setting12_props });
  binding_callbacks.push(() => bind(setting12, "data", setting12_data_binding));
  function settingbutton7_data_binding(value) {
    ctx[38](value);
  }
  __name(settingbutton7_data_binding, "settingbutton7_data_binding");
  let settingbutton7_props = { key: SETTINGS$1.ITEM_FILTERS };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ITEM_FILTERS] !== void 0
  ) {
    settingbutton7_props.data = /*settings*/
    ctx[1][SETTINGS$1.ITEM_FILTERS];
  }
  settingbutton7 = new SettingButton({ props: settingbutton7_props });
  binding_callbacks.push(() => bind(settingbutton7, "data", settingbutton7_data_binding));
  function settingbutton8_data_binding(value) {
    ctx[39](value);
  }
  __name(settingbutton8_data_binding, "settingbutton8_data_binding");
  let settingbutton8_props = { key: SETTINGS$1.ITEM_SIMILARITIES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.ITEM_SIMILARITIES] !== void 0
  ) {
    settingbutton8_props.data = /*settings*/
    ctx[1][SETTINGS$1.ITEM_SIMILARITIES];
  }
  settingbutton8 = new SettingButton({ props: settingbutton8_props });
  binding_callbacks.push(() => bind(settingbutton8, "data", settingbutton8_data_binding));
  function settingbutton9_data_binding(value) {
    ctx[40](value);
  }
  __name(settingbutton9_data_binding, "settingbutton9_data_binding");
  let settingbutton9_props = { key: SETTINGS$1.UNSTACKABLE_ITEM_TYPES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.UNSTACKABLE_ITEM_TYPES] !== void 0
  ) {
    settingbutton9_props.data = /*settings*/
    ctx[1][SETTINGS$1.UNSTACKABLE_ITEM_TYPES];
  }
  settingbutton9 = new SettingButton({ props: settingbutton9_props });
  binding_callbacks.push(() => bind(settingbutton9, "data", settingbutton9_data_binding));
  return {
    c() {
      div0 = element("div");
      create_component(setting0.$$.fragment);
      t0 = space();
      create_component(setting1.$$.fragment);
      t1 = space();
      create_component(setting2.$$.fragment);
      t2 = space();
      create_component(setting3.$$.fragment);
      t3 = space();
      create_component(setting4.$$.fragment);
      t4 = space();
      create_component(setting5.$$.fragment);
      t5 = space();
      create_component(setting6.$$.fragment);
      t6 = space();
      create_component(setting7.$$.fragment);
      t7 = space();
      create_component(setting8.$$.fragment);
      t8 = space();
      create_component(settingbutton0.$$.fragment);
      t9 = space();
      create_component(settingbutton1.$$.fragment);
      t10 = space();
      div1 = element("div");
      create_component(settingbutton2.$$.fragment);
      t11 = space();
      create_component(settingbutton3.$$.fragment);
      t12 = space();
      div2 = element("div");
      create_component(settingbutton4.$$.fragment);
      t13 = space();
      create_component(setting9.$$.fragment);
      t14 = space();
      create_component(setting10.$$.fragment);
      t15 = space();
      create_component(setting11.$$.fragment);
      t16 = space();
      create_component(settingbutton5.$$.fragment);
      t17 = space();
      create_component(settingbutton6.$$.fragment);
      t18 = space();
      create_component(setting12.$$.fragment);
      t19 = space();
      create_component(settingbutton7.$$.fragment);
      t20 = space();
      create_component(settingbutton8.$$.fragment);
      t21 = space();
      create_component(settingbutton9.$$.fragment);
      attr(div0, "class", "tab flex");
      attr(div0, "data-scope", "primary");
      attr(div0, "data-tab", "module");
      toggle_class(
        div0,
        "active",
        /*activeTab*/
        ctx[3] === "module"
      );
      attr(div1, "class", "tab flex");
      attr(div1, "data-scope", "primary");
      attr(div1, "data-tab", "styles");
      toggle_class(
        div1,
        "active",
        /*activeTab*/
        ctx[3] === "styles"
      );
      attr(div2, "class", "tab flex");
      attr(div2, "data-scope", "primary");
      attr(div2, "data-tab", "system");
      toggle_class(
        div2,
        "active",
        /*activeTab*/
        ctx[3] === "system"
      );
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      mount_component(setting0, div0, null);
      append(div0, t0);
      mount_component(setting1, div0, null);
      append(div0, t1);
      mount_component(setting2, div0, null);
      append(div0, t2);
      mount_component(setting3, div0, null);
      append(div0, t3);
      mount_component(setting4, div0, null);
      append(div0, t4);
      mount_component(setting5, div0, null);
      append(div0, t5);
      mount_component(setting6, div0, null);
      append(div0, t6);
      mount_component(setting7, div0, null);
      append(div0, t7);
      mount_component(setting8, div0, null);
      append(div0, t8);
      mount_component(settingbutton0, div0, null);
      append(div0, t9);
      mount_component(settingbutton1, div0, null);
      insert(target, t10, anchor);
      insert(target, div1, anchor);
      mount_component(settingbutton2, div1, null);
      append(div1, t11);
      mount_component(settingbutton3, div1, null);
      insert(target, t12, anchor);
      insert(target, div2, anchor);
      mount_component(settingbutton4, div2, null);
      append(div2, t13);
      mount_component(setting9, div2, null);
      append(div2, t14);
      mount_component(setting10, div2, null);
      append(div2, t15);
      mount_component(setting11, div2, null);
      append(div2, t16);
      mount_component(settingbutton5, div2, null);
      append(div2, t17);
      mount_component(settingbutton6, div2, null);
      append(div2, t18);
      mount_component(setting12, div2, null);
      append(div2, t19);
      mount_component(settingbutton7, div2, null);
      append(div2, t20);
      mount_component(settingbutton8, div2, null);
      append(div2, t21);
      mount_component(settingbutton9, div2, null);
      current = true;
    },
    p(ctx2, dirty) {
      const setting0_changes = {};
      if (!updating_data && dirty[0] & /*settings*/
      2) {
        updating_data = true;
        setting0_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ENABLE_DROPPING_ITEMS];
        add_flush_callback(() => updating_data = false);
      }
      setting0.$set(setting0_changes);
      const setting1_changes = {};
      if (!updating_data_1 && dirty[0] & /*settings*/
      2) {
        updating_data_1 = true;
        setting1_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ENABLE_GIVING_ITEMS];
        add_flush_callback(() => updating_data_1 = false);
      }
      setting1.$set(setting1_changes);
      const setting2_changes = {};
      if (!updating_data_2 && dirty[0] & /*settings*/
      2) {
        updating_data_2 = true;
        setting2_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ENABLE_TRADING];
        add_flush_callback(() => updating_data_2 = false);
      }
      setting2.$set(setting2_changes);
      const setting3_changes = {};
      if (!updating_data_3 && dirty[0] & /*settings*/
      2) {
        updating_data_3 = true;
        setting3_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.SHOW_TRADE_BUTTON];
        add_flush_callback(() => updating_data_3 = false);
      }
      setting3.$set(setting3_changes);
      const setting4_changes = {};
      if (!updating_data_4 && dirty[0] & /*settings*/
      2) {
        updating_data_4 = true;
        setting4_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.INSPECT_ITEMS_IN_TRADE];
        add_flush_callback(() => updating_data_4 = false);
      }
      setting4.$set(setting4_changes);
      const setting5_changes = {};
      if (!updating_data_5 && dirty[0] & /*settings*/
      2) {
        updating_data_5 = true;
        setting5_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.OUTPUT_TO_CHAT];
        add_flush_callback(() => updating_data_5 = false);
      }
      setting5.$set(setting5_changes);
      const setting6_changes = {};
      if (!updating_data_6 && dirty[0] & /*settings*/
      2) {
        updating_data_6 = true;
        setting6_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.DELETE_EMPTY_PILES];
        add_flush_callback(() => updating_data_6 = false);
      }
      setting6.$set(setting6_changes);
      const setting7_changes = {};
      if (!updating_data_7 && dirty[0] & /*settings*/
      2) {
        updating_data_7 = true;
        setting7_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.POPULATION_TABLES_FOLDER];
        add_flush_callback(() => updating_data_7 = false);
      }
      setting7.$set(setting7_changes);
      const setting8_changes = {};
      if (!updating_data_8 && dirty[0] & /*settings*/
      2) {
        updating_data_8 = true;
        setting8_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.HIDE_TOKEN_BORDER];
        add_flush_callback(() => updating_data_8 = false);
      }
      setting8.$set(setting8_changes);
      const settingbutton0_changes = {};
      if (!updating_data_9 && dirty[0] & /*settings*/
      2) {
        updating_data_9 = true;
        settingbutton0_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.PRICE_PRESETS];
        add_flush_callback(() => updating_data_9 = false);
      }
      settingbutton0.$set(settingbutton0_changes);
      const settingbutton1_changes = {};
      if (!updating_data_10 && dirty[0] & /*settings*/
      2) {
        updating_data_10 = true;
        settingbutton1_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.CUSTOM_ITEM_CATEGORIES];
        add_flush_callback(() => updating_data_10 = false);
      }
      settingbutton1.$set(settingbutton1_changes);
      if (!current || dirty[0] & /*activeTab*/
      8) {
        toggle_class(
          div0,
          "active",
          /*activeTab*/
          ctx2[3] === "module"
        );
      }
      const settingbutton2_changes = {};
      if (!updating_data_11 && dirty[0] & /*settings*/
      2) {
        updating_data_11 = true;
        settingbutton2_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.CSS_VARIABLES];
        add_flush_callback(() => updating_data_11 = false);
      }
      settingbutton2.$set(settingbutton2_changes);
      const settingbutton3_changes = {};
      if (!updating_data_12 && dirty[0] & /*settings*/
      2) {
        updating_data_12 = true;
        settingbutton3_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.VAULT_STYLES];
        add_flush_callback(() => updating_data_12 = false);
      }
      settingbutton3.$set(settingbutton3_changes);
      if (!current || dirty[0] & /*activeTab*/
      8) {
        toggle_class(
          div1,
          "active",
          /*activeTab*/
          ctx2[3] === "styles"
        );
      }
      const setting9_changes = {};
      if (!updating_data_13 && dirty[0] & /*settings*/
      2) {
        updating_data_13 = true;
        setting9_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ACTOR_CLASS_TYPE];
        add_flush_callback(() => updating_data_13 = false);
      }
      setting9.$set(setting9_changes);
      const setting10_changes = {};
      if (!updating_data_14 && dirty[0] & /*settings*/
      2) {
        updating_data_14 = true;
        setting10_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE];
        add_flush_callback(() => updating_data_14 = false);
      }
      setting10.$set(setting10_changes);
      const setting11_changes = {};
      if (!updating_data_15 && dirty[0] & /*settings*/
      2) {
        updating_data_15 = true;
        setting11_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ITEM_PRICE_ATTRIBUTE];
        add_flush_callback(() => updating_data_15 = false);
      }
      setting11.$set(setting11_changes);
      const settingbutton5_changes = {};
      if (!updating_data_16 && dirty[0] & /*settings*/
      2) {
        updating_data_16 = true;
        settingbutton5_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.CURRENCIES];
        add_flush_callback(() => updating_data_16 = false);
      }
      settingbutton5.$set(settingbutton5_changes);
      const settingbutton6_changes = {};
      if (!updating_data_17 && dirty[0] & /*settings*/
      2) {
        updating_data_17 = true;
        settingbutton6_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.SECONDARY_CURRENCIES];
        add_flush_callback(() => updating_data_17 = false);
      }
      settingbutton6.$set(settingbutton6_changes);
      const setting12_changes = {};
      if (dirty[0] & /*settings*/
      2)
        setting12_changes.disabled = /*settings*/
        ctx2[1][SETTINGS$1.CURRENCIES].value.length !== 1;
      if (!updating_data_18 && dirty[0] & /*settings*/
      2) {
        updating_data_18 = true;
        setting12_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.CURRENCY_DECIMAL_DIGITS];
        add_flush_callback(() => updating_data_18 = false);
      }
      setting12.$set(setting12_changes);
      const settingbutton7_changes = {};
      if (!updating_data_19 && dirty[0] & /*settings*/
      2) {
        updating_data_19 = true;
        settingbutton7_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ITEM_FILTERS];
        add_flush_callback(() => updating_data_19 = false);
      }
      settingbutton7.$set(settingbutton7_changes);
      const settingbutton8_changes = {};
      if (!updating_data_20 && dirty[0] & /*settings*/
      2) {
        updating_data_20 = true;
        settingbutton8_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.ITEM_SIMILARITIES];
        add_flush_callback(() => updating_data_20 = false);
      }
      settingbutton8.$set(settingbutton8_changes);
      const settingbutton9_changes = {};
      if (!updating_data_21 && dirty[0] & /*settings*/
      2) {
        updating_data_21 = true;
        settingbutton9_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.UNSTACKABLE_ITEM_TYPES];
        add_flush_callback(() => updating_data_21 = false);
      }
      settingbutton9.$set(settingbutton9_changes);
      if (!current || dirty[0] & /*activeTab*/
      8) {
        toggle_class(
          div2,
          "active",
          /*activeTab*/
          ctx2[3] === "system"
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(setting0.$$.fragment, local);
      transition_in(setting1.$$.fragment, local);
      transition_in(setting2.$$.fragment, local);
      transition_in(setting3.$$.fragment, local);
      transition_in(setting4.$$.fragment, local);
      transition_in(setting5.$$.fragment, local);
      transition_in(setting6.$$.fragment, local);
      transition_in(setting7.$$.fragment, local);
      transition_in(setting8.$$.fragment, local);
      transition_in(settingbutton0.$$.fragment, local);
      transition_in(settingbutton1.$$.fragment, local);
      transition_in(settingbutton2.$$.fragment, local);
      transition_in(settingbutton3.$$.fragment, local);
      transition_in(settingbutton4.$$.fragment, local);
      transition_in(setting9.$$.fragment, local);
      transition_in(setting10.$$.fragment, local);
      transition_in(setting11.$$.fragment, local);
      transition_in(settingbutton5.$$.fragment, local);
      transition_in(settingbutton6.$$.fragment, local);
      transition_in(setting12.$$.fragment, local);
      transition_in(settingbutton7.$$.fragment, local);
      transition_in(settingbutton8.$$.fragment, local);
      transition_in(settingbutton9.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(setting0.$$.fragment, local);
      transition_out(setting1.$$.fragment, local);
      transition_out(setting2.$$.fragment, local);
      transition_out(setting3.$$.fragment, local);
      transition_out(setting4.$$.fragment, local);
      transition_out(setting5.$$.fragment, local);
      transition_out(setting6.$$.fragment, local);
      transition_out(setting7.$$.fragment, local);
      transition_out(setting8.$$.fragment, local);
      transition_out(settingbutton0.$$.fragment, local);
      transition_out(settingbutton1.$$.fragment, local);
      transition_out(settingbutton2.$$.fragment, local);
      transition_out(settingbutton3.$$.fragment, local);
      transition_out(settingbutton4.$$.fragment, local);
      transition_out(setting9.$$.fragment, local);
      transition_out(setting10.$$.fragment, local);
      transition_out(setting11.$$.fragment, local);
      transition_out(settingbutton5.$$.fragment, local);
      transition_out(settingbutton6.$$.fragment, local);
      transition_out(setting12.$$.fragment, local);
      transition_out(settingbutton7.$$.fragment, local);
      transition_out(settingbutton8.$$.fragment, local);
      transition_out(settingbutton9.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      destroy_component(setting0);
      destroy_component(setting1);
      destroy_component(setting2);
      destroy_component(setting3);
      destroy_component(setting4);
      destroy_component(setting5);
      destroy_component(setting6);
      destroy_component(setting7);
      destroy_component(setting8);
      destroy_component(settingbutton0);
      destroy_component(settingbutton1);
      if (detaching)
        detach(t10);
      if (detaching)
        detach(div1);
      destroy_component(settingbutton2);
      destroy_component(settingbutton3);
      if (detaching)
        detach(t12);
      if (detaching)
        detach(div2);
      destroy_component(settingbutton4);
      destroy_component(setting9);
      destroy_component(setting10);
      destroy_component(setting11);
      destroy_component(settingbutton5);
      destroy_component(settingbutton6);
      destroy_component(setting12);
      destroy_component(settingbutton7);
      destroy_component(settingbutton8);
      destroy_component(settingbutton9);
    }
  };
}
__name(create_if_block$5, "create_if_block$5");
function create_default_slot$3(ctx) {
  let form_1;
  let h2;
  let t1;
  let t2;
  let section;
  let div1;
  let setting0;
  let updating_data;
  let t3;
  let setting1;
  let updating_data_1;
  let t4;
  let setting2;
  let updating_data_2;
  let t5;
  let setting3;
  let updating_data_3;
  let t6;
  let setting4;
  let updating_data_4;
  let t7;
  let setting5;
  let updating_data_5;
  let t8;
  let div0;
  let p0;
  let p1;
  let p2;
  let a0;
  let t12;
  let p3;
  let t14;
  let p4;
  let t17;
  let t18;
  let footer;
  let button1;
  let i;
  let t19;
  let t20_value = localize("ITEM-PILES.Applications.Settings.Submit") + "";
  let t20;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*userCanChangeSettings*/
    ctx[4] && create_if_block_1$4(ctx)
  );
  function setting0_data_binding(value) {
    ctx[12](value);
  }
  __name(setting0_data_binding, "setting0_data_binding");
  let setting0_props = { key: SETTINGS$1.INVERT_SHEET_OPEN };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.INVERT_SHEET_OPEN] !== void 0
  ) {
    setting0_props.data = /*settings*/
    ctx[1][SETTINGS$1.INVERT_SHEET_OPEN];
  }
  setting0 = new Setting({ props: setting0_props });
  binding_callbacks.push(() => bind(setting0, "data", setting0_data_binding));
  function setting1_data_binding(value) {
    ctx[13](value);
  }
  __name(setting1_data_binding, "setting1_data_binding");
  let setting1_props = { key: SETTINGS$1.HIDE_ACTOR_HEADER_TEXT };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.HIDE_ACTOR_HEADER_TEXT] !== void 0
  ) {
    setting1_props.data = /*settings*/
    ctx[1][SETTINGS$1.HIDE_ACTOR_HEADER_TEXT];
  }
  setting1 = new Setting({ props: setting1_props });
  binding_callbacks.push(() => bind(setting1, "data", setting1_data_binding));
  function setting2_data_binding(value) {
    ctx[14](value);
  }
  __name(setting2_data_binding, "setting2_data_binding");
  let setting2_props = { key: SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON] !== void 0
  ) {
    setting2_props.data = /*settings*/
    ctx[1][SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON];
  }
  setting2 = new Setting({ props: setting2_props });
  binding_callbacks.push(() => bind(setting2, "data", setting2_data_binding));
  function setting3_data_binding(value) {
    ctx[15](value);
  }
  __name(setting3_data_binding, "setting3_data_binding");
  let setting3_props = { key: SETTINGS$1.PRELOAD_FILES };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.PRELOAD_FILES] !== void 0
  ) {
    setting3_props.data = /*settings*/
    ctx[1][SETTINGS$1.PRELOAD_FILES];
  }
  setting3 = new Setting({ props: setting3_props });
  binding_callbacks.push(() => bind(setting3, "data", setting3_data_binding));
  function setting4_data_binding(value) {
    ctx[16](value);
  }
  __name(setting4_data_binding, "setting4_data_binding");
  let setting4_props = { key: SETTINGS$1.DEBUG };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.DEBUG] !== void 0
  ) {
    setting4_props.data = /*settings*/
    ctx[1][SETTINGS$1.DEBUG];
  }
  setting4 = new Setting({ props: setting4_props });
  binding_callbacks.push(() => bind(setting4, "data", setting4_data_binding));
  function setting5_data_binding(value) {
    ctx[17](value);
  }
  __name(setting5_data_binding, "setting5_data_binding");
  let setting5_props = { key: SETTINGS$1.DEBUG_HOOKS };
  if (
    /*settings*/
    ctx[1][SETTINGS$1.DEBUG_HOOKS] !== void 0
  ) {
    setting5_props.data = /*settings*/
    ctx[1][SETTINGS$1.DEBUG_HOOKS];
  }
  setting5 = new Setting({ props: setting5_props });
  binding_callbacks.push(() => bind(setting5, "data", setting5_data_binding));
  let if_block1 = (
    /*userCanChangeSettings*/
    ctx[4] && create_if_block$5(ctx)
  );
  return {
    c() {
      form_1 = element("form");
      h2 = element("h2");
      h2.textContent = `${localize("ITEM-PILES.Applications.Settings.Title")}`;
      t1 = space();
      if (if_block0)
        if_block0.c();
      t2 = space();
      section = element("section");
      div1 = element("div");
      create_component(setting0.$$.fragment);
      t3 = space();
      create_component(setting1.$$.fragment);
      t4 = space();
      create_component(setting2.$$.fragment);
      t5 = space();
      create_component(setting3.$$.fragment);
      t6 = space();
      create_component(setting4.$$.fragment);
      t7 = space();
      create_component(setting5.$$.fragment);
      t8 = space();
      div0 = element("div");
      p0 = element("p");
      p0.textContent = `${localize("ITEM-PILES.Applications.Settings.MoreToCome")} 
					`;
      p1 = element("p");
      p2 = element("p");
      a0 = element("a");
      a0.textContent = `${localize("ITEM-PILES.Applications.Settings.Request")}`;
      t12 = space();
      p3 = element("p");
      p3.textContent = `${localize("ITEM-PILES.Applications.Settings.Donate")}`;
      t14 = space();
      p4 = element("p");
      p4.innerHTML = `<a href="https://ko-fi.com/fantasycomputerworks" style="text-decoration: none !important;" target="_blank"><button class="donate-button svelte-ui4yo1" type="button"><img src="https://storage.ko-fi.com/cdn/cup-border.png" class="svelte-ui4yo1"/> 
								<span class="svelte-ui4yo1">Donate</span></button></a>`;
      t17 = space();
      if (if_block1)
        if_block1.c();
      t18 = space();
      footer = element("footer");
      button1 = element("button");
      i = element("i");
      t19 = space();
      t20 = text(t20_value);
      set_style(h2, "text-align", "center");
      set_style(h2, "margin-bottom", "1rem");
      attr(a0, "class", "link-text svelte-ui4yo1");
      attr(a0, "href", "https://github.com/fantasycalendar/FoundryVTT-ItemPiles/issues/new?assignees=&labels=&template=feature_request.md&title=");
      attr(a0, "target", "_blank");
      set_style(p2, "margin-bottom", "1rem");
      set_style(div0, "text-align", "center");
      set_style(div0, "font-size", "1rem");
      set_style(div0, "margin-top", "3rem");
      attr(div1, "class", "tab flex");
      attr(div1, "data-scope", "primary");
      attr(div1, "data-tab", "local");
      toggle_class(
        div1,
        "active",
        /*activeTab*/
        ctx[3] === "local"
      );
      attr(section, "class", "tab-body svelte-ui4yo1");
      attr(i, "class", "far fa-save");
      attr(button1, "type", "button");
      attr(footer, "class", "svelte-ui4yo1");
      attr(form_1, "autocomplete", "off");
    },
    m(target, anchor) {
      insert(target, form_1, anchor);
      append(form_1, h2);
      append(form_1, t1);
      if (if_block0)
        if_block0.m(form_1, null);
      append(form_1, t2);
      append(form_1, section);
      append(section, div1);
      mount_component(setting0, div1, null);
      append(div1, t3);
      mount_component(setting1, div1, null);
      append(div1, t4);
      mount_component(setting2, div1, null);
      append(div1, t5);
      mount_component(setting3, div1, null);
      append(div1, t6);
      mount_component(setting4, div1, null);
      append(div1, t7);
      mount_component(setting5, div1, null);
      append(div1, t8);
      append(div1, div0);
      append(div0, p0);
      append(div0, p1);
      append(div0, p2);
      append(p2, a0);
      append(div0, t12);
      append(div0, p3);
      append(div0, t14);
      append(div0, p4);
      append(section, t17);
      if (if_block1)
        if_block1.m(section, null);
      append(form_1, t18);
      append(form_1, footer);
      append(footer, button1);
      append(button1, i);
      append(button1, t19);
      append(button1, t20);
      ctx[41](form_1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button1,
            "click",
            /*requestSubmit*/
            ctx[6],
            { once: true }
          ),
          listen(form_1, "submit", prevent_default(
            /*updateSettings*/
            ctx[7]
          ), { once: true })
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*userCanChangeSettings*/
        ctx2[4]
      )
        if_block0.p(ctx2, dirty);
      const setting0_changes = {};
      if (!updating_data && dirty[0] & /*settings*/
      2) {
        updating_data = true;
        setting0_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.INVERT_SHEET_OPEN];
        add_flush_callback(() => updating_data = false);
      }
      setting0.$set(setting0_changes);
      const setting1_changes = {};
      if (!updating_data_1 && dirty[0] & /*settings*/
      2) {
        updating_data_1 = true;
        setting1_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.HIDE_ACTOR_HEADER_TEXT];
        add_flush_callback(() => updating_data_1 = false);
      }
      setting1.$set(setting1_changes);
      const setting2_changes = {};
      if (!updating_data_2 && dirty[0] & /*settings*/
      2) {
        updating_data_2 = true;
        setting2_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON];
        add_flush_callback(() => updating_data_2 = false);
      }
      setting2.$set(setting2_changes);
      const setting3_changes = {};
      if (!updating_data_3 && dirty[0] & /*settings*/
      2) {
        updating_data_3 = true;
        setting3_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.PRELOAD_FILES];
        add_flush_callback(() => updating_data_3 = false);
      }
      setting3.$set(setting3_changes);
      const setting4_changes = {};
      if (!updating_data_4 && dirty[0] & /*settings*/
      2) {
        updating_data_4 = true;
        setting4_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.DEBUG];
        add_flush_callback(() => updating_data_4 = false);
      }
      setting4.$set(setting4_changes);
      const setting5_changes = {};
      if (!updating_data_5 && dirty[0] & /*settings*/
      2) {
        updating_data_5 = true;
        setting5_changes.data = /*settings*/
        ctx2[1][SETTINGS$1.DEBUG_HOOKS];
        add_flush_callback(() => updating_data_5 = false);
      }
      setting5.$set(setting5_changes);
      if (!current || dirty[0] & /*activeTab*/
      8) {
        toggle_class(
          div1,
          "active",
          /*activeTab*/
          ctx2[3] === "local"
        );
      }
      if (
        /*userCanChangeSettings*/
        ctx2[4]
      )
        if_block1.p(ctx2, dirty);
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(setting0.$$.fragment, local);
      transition_in(setting1.$$.fragment, local);
      transition_in(setting2.$$.fragment, local);
      transition_in(setting3.$$.fragment, local);
      transition_in(setting4.$$.fragment, local);
      transition_in(setting5.$$.fragment, local);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(setting0.$$.fragment, local);
      transition_out(setting1.$$.fragment, local);
      transition_out(setting2.$$.fragment, local);
      transition_out(setting3.$$.fragment, local);
      transition_out(setting4.$$.fragment, local);
      transition_out(setting5.$$.fragment, local);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form_1);
      if (if_block0)
        if_block0.d();
      destroy_component(setting0);
      destroy_component(setting1);
      destroy_component(setting2);
      destroy_component(setting3);
      destroy_component(setting4);
      destroy_component(setting5);
      if (if_block1)
        if_block1.d();
      ctx[41](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$3, "create_default_slot$3");
function create_fragment$5(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[42](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$3] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*form, activeTab, settings*/
      14 | dirty[1] & /*$$scope*/
      8192) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$5, "create_fragment$5");
function instance$5($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let form;
  let { settings = {} } = $$props;
  let userCanChangeSettings = game.user.hasPermission("SETTINGS_MODIFY");
  getSettings();
  function getSettings() {
    $$invalidate(1, settings = Object.fromEntries(Object.entries(SETTINGS$1.GET_DEFAULT()).map((entry) => {
      entry[1].value = getSetting(entry[0]);
      return entry;
    })));
    $$invalidate(
      1,
      settings[SETTINGS$1.POPULATION_TABLES_FOLDER].choices = {
        "root": "ITEM-PILES.Settings.PopulationTablesFolder.AllTables",
        ...Object.fromEntries(game.folders.filter((f) => f.type === "RollTable").map((f) => [f.id, f.name]))
      },
      settings
    );
  }
  __name(getSettings, "getSettings");
  function importSettings(incomingSettings) {
    for (const [key, value] of Object.entries(incomingSettings)) {
      if (settings[SETTINGS$1[key]] === void 0)
        continue;
      $$invalidate(1, settings[SETTINGS$1[key]].value = value, settings);
    }
    $$invalidate(1, settings);
  }
  __name(importSettings, "importSettings");
  function requestSubmit() {
    form.requestSubmit();
  }
  __name(requestSubmit, "requestSubmit");
  async function updateSettings() {
    let settingsToUpdate = Object.entries(settings).filter((entry) => userCanChangeSettings || entry[1].scope === "client");
    for (let [key, setting] of settingsToUpdate) {
      await setSetting(key, setting.value);
    }
    application.close();
  }
  __name(updateSettings, "updateSettings");
  async function resetSettings() {
    const doThing = await TJSDialog.confirm({
      title: "Item Piles - " + game.i18n.localize("ITEM-PILES.Dialogs.ResetSettings.Title"),
      content: {
        class: CustomDialog,
        props: {
          content: game.i18n.localize("ITEM-PILES.Dialogs.ResetSettings.Content")
        }
      },
      buttons: {
        yes: {
          icon: '<i class="fas fa-check"></i>',
          label: game.i18n.localize("ITEM-PILES.Dialogs.ResetSettings.Confirm")
        },
        no: {
          icon: '<i class="fas fa-times"></i>',
          label: game.i18n.localize("No")
        }
      },
      modal: true,
      draggable: false,
      rejectClose: false,
      defaultYes: true,
      options: { height: "auto" }
    });
    if (!doThing)
      return;
    return applyDefaultSettings();
  }
  __name(resetSettings, "resetSettings");
  let tabs = [
    {
      value: "local",
      label: localize("ITEM-PILES.Applications.Settings.Local")
    },
    {
      value: "module",
      label: localize("ITEM-PILES.Applications.Settings.Module"),
      hidden: !userCanChangeSettings
    },
    {
      value: "styles",
      label: localize("ITEM-PILES.Applications.Settings.Styles"),
      hidden: !userCanChangeSettings
    },
    {
      value: "system",
      label: localize("ITEM-PILES.Applications.Settings.System"),
      hidden: !userCanChangeSettings
    }
  ];
  let activeTab = tabs[0].value;
  function tabs_1_activeTab_binding(value) {
    activeTab = value;
    $$invalidate(3, activeTab);
  }
  __name(tabs_1_activeTab_binding, "tabs_1_activeTab_binding");
  function setting0_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.INVERT_SHEET_OPEN], value)) {
      settings[SETTINGS$1.INVERT_SHEET_OPEN] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting0_data_binding, "setting0_data_binding");
  function setting1_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.HIDE_ACTOR_HEADER_TEXT], value)) {
      settings[SETTINGS$1.HIDE_ACTOR_HEADER_TEXT] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting1_data_binding, "setting1_data_binding");
  function setting2_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON], value)) {
      settings[SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting2_data_binding, "setting2_data_binding");
  function setting3_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.PRELOAD_FILES], value)) {
      settings[SETTINGS$1.PRELOAD_FILES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting3_data_binding, "setting3_data_binding");
  function setting4_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.DEBUG], value)) {
      settings[SETTINGS$1.DEBUG] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting4_data_binding, "setting4_data_binding");
  function setting5_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.DEBUG_HOOKS], value)) {
      settings[SETTINGS$1.DEBUG_HOOKS] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting5_data_binding, "setting5_data_binding");
  function setting0_data_binding_1(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ENABLE_DROPPING_ITEMS], value)) {
      settings[SETTINGS$1.ENABLE_DROPPING_ITEMS] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting0_data_binding_1, "setting0_data_binding_1");
  function setting1_data_binding_1(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ENABLE_GIVING_ITEMS], value)) {
      settings[SETTINGS$1.ENABLE_GIVING_ITEMS] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting1_data_binding_1, "setting1_data_binding_1");
  function setting2_data_binding_1(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ENABLE_TRADING], value)) {
      settings[SETTINGS$1.ENABLE_TRADING] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting2_data_binding_1, "setting2_data_binding_1");
  function setting3_data_binding_1(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.SHOW_TRADE_BUTTON], value)) {
      settings[SETTINGS$1.SHOW_TRADE_BUTTON] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting3_data_binding_1, "setting3_data_binding_1");
  function setting4_data_binding_1(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.INSPECT_ITEMS_IN_TRADE], value)) {
      settings[SETTINGS$1.INSPECT_ITEMS_IN_TRADE] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting4_data_binding_1, "setting4_data_binding_1");
  function setting5_data_binding_1(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.OUTPUT_TO_CHAT], value)) {
      settings[SETTINGS$1.OUTPUT_TO_CHAT] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting5_data_binding_1, "setting5_data_binding_1");
  function setting6_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.DELETE_EMPTY_PILES], value)) {
      settings[SETTINGS$1.DELETE_EMPTY_PILES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting6_data_binding, "setting6_data_binding");
  function setting7_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.POPULATION_TABLES_FOLDER], value)) {
      settings[SETTINGS$1.POPULATION_TABLES_FOLDER] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting7_data_binding, "setting7_data_binding");
  function setting8_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.HIDE_TOKEN_BORDER], value)) {
      settings[SETTINGS$1.HIDE_TOKEN_BORDER] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting8_data_binding, "setting8_data_binding");
  function settingbutton0_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.PRICE_PRESETS], value)) {
      settings[SETTINGS$1.PRICE_PRESETS] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton0_data_binding, "settingbutton0_data_binding");
  function settingbutton1_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.CUSTOM_ITEM_CATEGORIES], value)) {
      settings[SETTINGS$1.CUSTOM_ITEM_CATEGORIES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton1_data_binding, "settingbutton1_data_binding");
  function settingbutton2_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.CSS_VARIABLES], value)) {
      settings[SETTINGS$1.CSS_VARIABLES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton2_data_binding, "settingbutton2_data_binding");
  function settingbutton3_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.VAULT_STYLES], value)) {
      settings[SETTINGS$1.VAULT_STYLES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton3_data_binding, "settingbutton3_data_binding");
  const func2 = /* @__PURE__ */ __name(async () => {
    await resetSettings();
    getSettings();
  }, "func");
  function setting9_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ACTOR_CLASS_TYPE], value)) {
      settings[SETTINGS$1.ACTOR_CLASS_TYPE] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting9_data_binding, "setting9_data_binding");
  function setting10_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE], value)) {
      settings[SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting10_data_binding, "setting10_data_binding");
  function setting11_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ITEM_PRICE_ATTRIBUTE], value)) {
      settings[SETTINGS$1.ITEM_PRICE_ATTRIBUTE] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting11_data_binding, "setting11_data_binding");
  function settingbutton5_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.CURRENCIES], value)) {
      settings[SETTINGS$1.CURRENCIES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton5_data_binding, "settingbutton5_data_binding");
  function settingbutton6_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.SECONDARY_CURRENCIES], value)) {
      settings[SETTINGS$1.SECONDARY_CURRENCIES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton6_data_binding, "settingbutton6_data_binding");
  function setting12_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.CURRENCY_DECIMAL_DIGITS], value)) {
      settings[SETTINGS$1.CURRENCY_DECIMAL_DIGITS] = value;
      $$invalidate(1, settings);
    }
  }
  __name(setting12_data_binding, "setting12_data_binding");
  function settingbutton7_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ITEM_FILTERS], value)) {
      settings[SETTINGS$1.ITEM_FILTERS] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton7_data_binding, "settingbutton7_data_binding");
  function settingbutton8_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.ITEM_SIMILARITIES], value)) {
      settings[SETTINGS$1.ITEM_SIMILARITIES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton8_data_binding, "settingbutton8_data_binding");
  function settingbutton9_data_binding(value) {
    if ($$self.$$.not_equal(settings[SETTINGS$1.UNSTACKABLE_ITEM_TYPES], value)) {
      settings[SETTINGS$1.UNSTACKABLE_ITEM_TYPES] = value;
      $$invalidate(1, settings);
    }
  }
  __name(settingbutton9_data_binding, "settingbutton9_data_binding");
  function form_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      form = $$value;
      $$invalidate(2, form);
    });
  }
  __name(form_1_binding, "form_1_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("settings" in $$props2)
      $$invalidate(1, settings = $$props2.settings);
  };
  return [
    elementRoot,
    settings,
    form,
    activeTab,
    userCanChangeSettings,
    getSettings,
    requestSubmit,
    updateSettings,
    resetSettings,
    tabs,
    importSettings,
    tabs_1_activeTab_binding,
    setting0_data_binding,
    setting1_data_binding,
    setting2_data_binding,
    setting3_data_binding,
    setting4_data_binding,
    setting5_data_binding,
    setting0_data_binding_1,
    setting1_data_binding_1,
    setting2_data_binding_1,
    setting3_data_binding_1,
    setting4_data_binding_1,
    setting5_data_binding_1,
    setting6_data_binding,
    setting7_data_binding,
    setting8_data_binding,
    settingbutton0_data_binding,
    settingbutton1_data_binding,
    settingbutton2_data_binding,
    settingbutton3_data_binding,
    func2,
    setting9_data_binding,
    setting10_data_binding,
    setting11_data_binding,
    settingbutton5_data_binding,
    settingbutton6_data_binding,
    setting12_data_binding,
    settingbutton7_data_binding,
    settingbutton8_data_binding,
    settingbutton9_data_binding,
    form_1_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$5, "instance$5");
const _Settings_shell = class _Settings_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$5,
      create_fragment$5,
      safe_not_equal,
      {
        elementRoot: 0,
        settings: 1,
        importSettings: 10
      },
      null,
      [-1, -1]
    );
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get settings() {
    return this.$$.ctx[1];
  }
  set settings(settings) {
    this.$$set({ settings });
    flush();
  }
  get importSettings() {
    return this.$$.ctx[10];
  }
};
__name(_Settings_shell, "Settings_shell");
let Settings_shell = _Settings_shell;
const _SettingsApp = class _SettingsApp extends SvelteApplication {
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      id: `item-piles-application-system-settings-${randomID()}`,
      title: "Item Piles Module Configuration",
      width: 600,
      svelte: {
        class: Settings_shell,
        target: document.body
      },
      zIndex: 100,
      classes: ["item-piles-app"]
    });
  }
  static getActiveApp() {
    return getActiveApps("item-piles-application-system-settings", true);
  }
  static async show(options = {}, dialogData = {}) {
    const app = this.getActiveApp();
    if (app)
      return app.render(false, { focus: true });
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(options, dialogData).render(true, { focus: true });
    });
  }
  /** @override */
  _getHeaderButtons() {
    let buttons = super._getHeaderButtons();
    if (game.user.isGM) {
      buttons = [
        {
          label: "ITEM-PILES.Applications.Settings.Export",
          class: "item-piles-export-settings",
          icon: "fas fa-file-export",
          onclick: () => {
            const settingKeys = Object.fromEntries(Object.entries(SETTINGS$1).filter(([_, value]) => typeof value === "string").map(([key, value]) => [value, key]));
            const settings = Object.entries(this.svelte.applicationShell.settings).filter(([_, setting]) => {
              return setting.system && setting.name;
            }).map(([key, setting]) => {
              return [settingKeys[key], setting.value];
            });
            const a = document.createElement("a");
            const file = new Blob([JSON.stringify(Object.fromEntries(settings), null, 4)], { type: "text/json" });
            a.href = URL.createObjectURL(file);
            a.download = `item-piles-${game.system.id}.json`;
            a.click();
            a.remove();
          }
        },
        {
          label: "ITEM-PILES.Applications.Settings.Import",
          class: "item-piles-import-settings",
          icon: "fas fa-file-import",
          onclick: () => {
            const input = document.createElement("input");
            input.type = "file";
            input.onchange = (e) => {
              input.remove();
              const file = e.target.files[0];
              const reader = new FileReader();
              reader.addEventListener("load", async () => {
                try {
                  const incomingSettings = JSON.parse(reader.result);
                  this.svelte.applicationShell.importSettings(incomingSettings);
                } catch (err) {
                  console.error(err);
                }
              });
              reader.readAsText(file);
            };
            input.click();
          }
        }
      ].concat(buttons);
    }
    return buttons;
  }
};
__name(_SettingsApp, "SettingsApp");
let SettingsApp = _SettingsApp;
const _SettingsShim = class _SettingsShim extends FormApplication {
  /**
   * @inheritDoc
   */
  constructor() {
    super({});
    SettingsApp.show();
  }
  async _updateObject(event, formData) {
  }
  render() {
    this.close();
  }
};
__name(_SettingsShim, "SettingsShim");
let SettingsShim = _SettingsShim;
function registerSettings() {
  game.settings.registerMenu(CONSTANTS.MODULE_NAME, "configure-settings", {
    name: "ITEM-PILES.Settings.Configure.Title",
    label: "ITEM-PILES.Settings.Configure.Label",
    hint: "ITEM-PILES.Settings.Configure.Hint",
    icon: "fas fa-cog",
    type: SettingsShim,
    restricted: false
  });
  for (let [name, data2] of Object.entries(SETTINGS$1.GET_DEFAULT())) {
    game.settings.register(CONSTANTS.MODULE_NAME, name, data2);
  }
}
__name(registerSettings, "registerSettings");
async function applyDefaultSettings() {
  const settings = SETTINGS$1.GET_SYSTEM_DEFAULTS();
  for (const [name, data2] of Object.entries(settings)) {
    await setSetting(name, data2.default);
  }
  await setSetting(SETTINGS$1.SYSTEM_VERSION, SYSTEMS.DATA.VERSION);
  await patchCurrencySettings();
}
__name(applyDefaultSettings, "applyDefaultSettings");
async function applySoftMigration(migrationKey) {
  const migrationSettings = SYSTEMS.DATA.SOFT_MIGRATIONS[migrationKey];
  for (const [key, values] of Object.entries(migrationSettings)) {
    const settingsKey = SETTINGS$1[key];
    const currentSettingValue = getSetting(settingsKey);
    await setSetting(settingsKey, foundry.utils.mergeObject(currentSettingValue, values));
  }
  await setSetting(SETTINGS$1.SYSTEM_VERSION, SYSTEMS.DATA.VERSION);
}
__name(applySoftMigration, "applySoftMigration");
async function patchCurrencySettings() {
  const currencies = getSetting(SETTINGS$1.CURRENCIES);
  for (let currency of currencies) {
    if (currency.type !== "item" || !currency.data.uuid || currency.data.item)
      continue;
    const item = await fromUuid(currency.data.uuid);
    if (!item)
      continue;
    currency.data.item = item.toObject();
  }
  return setSetting(SETTINGS$1.CURRENCIES, currencies);
}
__name(patchCurrencySettings, "patchCurrencySettings");
function applySystemSpecificStyles(data2 = false) {
  const defaultCssVariables = foundry.utils.deepClone(SETTINGS$1.DEFAULT_CSS_VARIABLES);
  const cssVariables2 = data2 || getSetting(SETTINGS$1.CSS_VARIABLES);
  const mergedCssVariables = foundry.utils.mergeObject(defaultCssVariables, cssVariables2);
  const root = document.documentElement;
  for (const [style, val] of Object.entries(mergedCssVariables)) {
    if (!val) {
      root.style.removeProperty(`--item-piles-${style}`);
    } else {
      root.style.setProperty(`--item-piles-${style}`, val);
    }
  }
}
__name(applySystemSpecificStyles, "applySystemSpecificStyles");
async function checkSystem() {
  if (!SYSTEMS.HAS_SYSTEM_SUPPORT) {
    if (getSetting(SETTINGS$1.SYSTEM_NOT_FOUND_WARNING_SHOWN))
      return;
    let settingsValid = true;
    for (const [name, data2] of Object.entries(SETTINGS$1.GET_DEFAULT())) {
      settingsValid = settingsValid && getSetting(name).length !== new data2.type().length;
    }
    if (settingsValid)
      return;
    TJSDialog.prompt({
      title: game.i18n.localize("ITEM-PILES.Dialogs.NoSystemFound.Title"),
      content: {
        class: CustomDialog,
        props: {
          content: game.i18n.localize("ITEM-PILES.Dialogs.NoSystemFound.Content")
        }
      }
    });
    return setSetting(SETTINGS$1.SYSTEM_NOT_FOUND_WARNING_SHOWN, true);
  }
  if (getSetting(SETTINGS$1.SYSTEM_FOUND) || SYSTEMS.DATA.INTEGRATION) {
    const currentVersion = getSetting(SETTINGS$1.SYSTEM_VERSION);
    const newVersion = SYSTEMS.DATA.VERSION;
    debug(`Comparing system version - Current: ${currentVersion} - New: ${newVersion}`);
    if (SYSTEMS.DATA.SOFT_MIGRATIONS[currentVersion + "-" + newVersion]) {
      debug(`Applying soft migration for ${game.system.title}`);
      await applySoftMigration(currentVersion + "-" + newVersion);
    } else if (isNewerVersion(newVersion, currentVersion)) {
      debug(`Applying system settings for ${game.system.title}`);
      await applyDefaultSettings();
    }
    return;
  }
  await setSetting(SETTINGS$1.SYSTEM_FOUND, true);
  if (getSetting(SETTINGS$1.SYSTEM_NOT_FOUND_WARNING_SHOWN)) {
    custom_notify(game.i18n.localize("ITEM-PILES.Notifications.SystemSupportFound"));
  }
  return applyDefaultSettings();
}
__name(checkSystem, "checkSystem");
function applyShims() {
  if (game.release.generation !== 11)
    return;
  CONSTANTS.ACTOR_DELTA_PROPERTY = "delta";
  Object.freeze(CONSTANTS);
}
__name(applyShims, "applyShims");
const SETTINGS = {
  // Client settings
  OUTPUT_TO_CHAT: "outputToChat",
  INVERT_SHEET_OPEN: "invertSheetOpen",
  HIDE_ACTOR_HEADER_TEXT: "hideActorHeaderText",
  HIDE_ACTOR_HEADER_BUTTON: "hideActorHeaderButton",
  PRELOAD_FILES: "preloadFiles",
  DEBUG: "debug",
  DEBUG_HOOKS: "debugHooks",
  // Module Settings
  ENABLE_DROPPING_ITEMS: "enableDroppingItems",
  ENABLE_TRADING: "enableTrading",
  ENABLE_GIVING_ITEMS: "enableGivingItems",
  SHOW_TRADE_BUTTON: "showTradeButton",
  DELETE_EMPTY_PILES: "deleteEmptyPiles",
  INSPECT_ITEMS_IN_TRADE: "inspectItemsInTrade",
  POPULATION_TABLES_FOLDER: "populationTablesFolder",
  PRICE_PRESETS: "pricePresets",
  HIDE_TOKEN_BORDER: "hideTokenBorder",
  // Style settings
  CSS_VARIABLES: "cssVariables",
  VAULT_STYLES: "vaultStyles",
  // System Settings
  CURRENCIES: "currencies",
  SECONDARY_CURRENCIES: "secondaryCurrencies",
  CURRENCY_DECIMAL_DIGITS: "currencyDecimalDigits",
  ITEM_FILTERS: "itemFilters",
  ACTOR_CLASS_TYPE: "actorClassType",
  ITEM_QUANTITY_ATTRIBUTE: "itemQuantityAttribute",
  ITEM_PRICE_ATTRIBUTE: "itemPriceAttribute",
  QUANTITY_FOR_PRICE_ATTRIBUTE: "quantityForPriceAttribute",
  ITEM_SIMILARITIES: "itemSimilarities",
  UNSTACKABLE_ITEM_TYPES: "unstackableItemTypes",
  PILE_DEFAULTS: "pileDefaults",
  TOKEN_FLAG_DEFAULTS: "tokenFlagDefaults",
  // Hidden settings
  DEFAULT_ITEM_PILE_JOURNAL_ID: "defaultItemPileJournalID",
  DEFAULT_ITEM_PILE_ACTOR_ID: "defaultItemPileActorID",
  SYSTEM_FOUND: "systemFound",
  SYSTEM_NOT_FOUND_WARNING_SHOWN: "systemNotFoundWarningShown",
  SYSTEM_VERSION: "systemVersion",
  CUSTOM_ITEM_CATEGORIES: "customItemCategories",
  HIDE_TOKEN_BORDER_OPTIONS: {
    EVERYONE: "everyone",
    PLAYERS: "players",
    SHOW: "show"
  },
  DEFAULT_CSS_VARIABLES: {
    "inactive": "rgba(31,143,255,1)",
    "minor-inactive": "rgba(201,200,185,1)",
    "shadow-primary": "rgba(255,0,0,1)",
    "even-color": "rgba(240,240,223,1)",
    "odd-color": "rgba(0,0,0,0)",
    "border-dark-primary": "rgba(25,24,19,1)",
    "border-light-primary": "rgba(181,179,164,1)",
    "text-light-highlight": "rgba(240,240,224,1)",
    "text-important": "rgba(255,100,0,1)"
  },
  GET_DEFAULT() {
    return foundry.utils.deepClone(SETTINGS.DEFAULTS());
  },
  GET_SYSTEM_DEFAULTS() {
    return Object.fromEntries(Object.entries(SETTINGS.GET_DEFAULT()).filter((entry) => {
      return entry[1].system;
    }));
  },
  DEFAULTS: () => ({
    [SETTINGS.CURRENCIES]: {
      name: "ITEM-PILES.Settings.Currencies.Title",
      label: "ITEM-PILES.Settings.Currencies.Label",
      hint: "ITEM-PILES.Settings.Currencies.Hint",
      icon: "fa fa-money-bill-alt",
      application: "currencies",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.CURRENCIES,
      type: Array
    },
    [SETTINGS.SECONDARY_CURRENCIES]: {
      name: "ITEM-PILES.Settings.SecondaryCurrencies.Title",
      label: "ITEM-PILES.Settings.SecondaryCurrencies.Label",
      hint: "ITEM-PILES.Settings.SecondaryCurrencies.Hint",
      icon: "fa fa-money-bill-alt",
      application: "secondary-currencies",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.SECONDARY_CURRENCIES,
      type: Array
    },
    [SETTINGS.CURRENCY_DECIMAL_DIGITS]: {
      name: "ITEM-PILES.Settings.CurrencyDecimalDigits.Title",
      hint: "ITEM-PILES.Settings.CurrencyDecimalDigits.Hint",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.CURRENCY_DECIMAL_DIGITS,
      step: 1e-5,
      min: 0,
      max: 1,
      type: Number
    },
    [SETTINGS.ITEM_FILTERS]: {
      name: "ITEM-PILES.Settings.ItemFilters.Title",
      label: "ITEM-PILES.Settings.ItemFilters.Label",
      hint: "ITEM-PILES.Settings.ItemFilters.Hint",
      icon: "fa fa-filter",
      application: "item-filters",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.ITEM_FILTERS,
      type: Array
    },
    [SETTINGS.ITEM_SIMILARITIES]: {
      name: "ITEM-PILES.Settings.ItemSimilarities.Title",
      label: "ITEM-PILES.Settings.ItemSimilarities.Label",
      hint: "ITEM-PILES.Settings.ItemSimilarities.Hint",
      icon: "fa fa-equals",
      application: "item-similarities",
      applicationOptions: {
        title: "ITEM-PILES.Applications.SimilaritiesEditor.Title",
        content: "ITEM-PILES.Applications.SimilaritiesEditor.Explanation",
        column: "ITEM-PILES.Applications.SimilaritiesEditor.Path"
      },
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.ITEM_SIMILARITIES,
      type: Array
    },
    [SETTINGS.UNSTACKABLE_ITEM_TYPES]: {
      name: "ITEM-PILES.Settings.UnstackableItemTypes.Title",
      label: "ITEM-PILES.Settings.UnstackableItemTypes.Label",
      hint: "ITEM-PILES.Settings.UnstackableItemTypes.Hint",
      icon: "fa fa-equals",
      application: "unstackable-item-types",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.UNSTACKABLE_ITEM_TYPES,
      onChange: () => {
        refreshItemTypesThatCanStack();
      },
      type: Array
    },
    [SETTINGS.CSS_VARIABLES]: {
      name: "ITEM-PILES.Settings.CssVariables.Title",
      label: "ITEM-PILES.Settings.CssVariables.Label",
      hint: "ITEM-PILES.Settings.CssVariables.Hint",
      icon: "fa-solid fa-wand-magic-sparkles",
      application: "styles",
      applicationOptions: {
        readOnly: true,
        variables: true
      },
      scope: "world",
      config: false,
      default: SYSTEMS.DATA.CSS_VARIABLES,
      mergedDefaults: SETTINGS.DEFAULT_CSS_VARIABLES,
      onchange: (data2) => {
        applySystemSpecificStyles(data2);
      },
      type: Object
    },
    [SETTINGS.VAULT_STYLES]: {
      name: "ITEM-PILES.Settings.VaultStyles.Title",
      label: "ITEM-PILES.Settings.VaultStyles.Label",
      hint: "ITEM-PILES.Settings.VaultStyles.Hint",
      icon: "fa-solid fa-wand-magic-sparkles",
      application: "vault-styles",
      scope: "world",
      config: false,
      default: SYSTEMS.DATA.VAULT_STYLES,
      type: Array
    },
    [SETTINGS.ACTOR_CLASS_TYPE]: {
      name: "ITEM-PILES.Settings.ActorClass.Title",
      hint: "ITEM-PILES.Settings.ActorClass.Hint",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.ACTOR_CLASS_TYPE,
      type: String
    },
    [SETTINGS.ITEM_QUANTITY_ATTRIBUTE]: {
      name: "ITEM-PILES.Settings.Quantity.Title",
      hint: "ITEM-PILES.Settings.Quantity.Hint",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.ITEM_QUANTITY_ATTRIBUTE,
      type: String
    },
    [SETTINGS.ITEM_PRICE_ATTRIBUTE]: {
      name: "ITEM-PILES.Settings.Price.Title",
      hint: "ITEM-PILES.Settings.Price.Hint",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.ITEM_PRICE_ATTRIBUTE,
      type: String
    },
    [SETTINGS.QUANTITY_FOR_PRICE_ATTRIBUTE]: {
      name: "ITEM-PILES.Settings.QuantityForPrice.Title",
      hint: "ITEM-PILES.Settings.QuantityForPrice.Hint",
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.QUANTITY_FOR_PRICE_ATTRIBUTE,
      type: String
    },
    [SETTINGS.PILE_DEFAULTS]: {
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.PILE_DEFAULTS,
      type: Object
    },
    [SETTINGS.TOKEN_FLAG_DEFAULTS]: {
      scope: "world",
      config: false,
      system: true,
      default: SYSTEMS.DATA.TOKEN_FLAG_DEFAULTS,
      type: Object
    },
    [SETTINGS.CUSTOM_ITEM_CATEGORIES]: {
      name: "ITEM-PILES.Settings.CustomItemCategories.Title",
      label: "ITEM-PILES.Settings.CustomItemCategories.Label",
      hint: "ITEM-PILES.Settings.CustomItemCategories.Hint",
      application: "item-categories",
      applicationOptions: {
        title: "ITEM-PILES.Applications.CustomItemCategoriesEditor.Title",
        content: "ITEM-PILES.Applications.CustomItemCategoriesEditor.Explanation",
        column: "ITEM-PILES.Applications.CustomItemCategoriesEditor.Category"
      },
      scope: "world",
      config: false,
      default: [],
      type: Array
    },
    [SETTINGS.SYSTEM_VERSION]: {
      scope: "world",
      config: false,
      default: "0.0.0",
      type: String
    },
    [SETTINGS.DEFAULT_ITEM_PILE_ACTOR_ID]: {
      scope: "world",
      config: false,
      default: "",
      type: String
    },
    [SETTINGS.DEFAULT_ITEM_PILE_JOURNAL_ID]: {
      scope: "world",
      config: false,
      default: "",
      type: String
    },
    [SETTINGS.SYSTEM_FOUND]: {
      scope: "world",
      config: false,
      default: false,
      type: Boolean
    },
    [SETTINGS.SYSTEM_NOT_FOUND_WARNING_SHOWN]: {
      scope: "world",
      config: false,
      default: false,
      type: Boolean
    },
    [SETTINGS.OUTPUT_TO_CHAT]: {
      name: "ITEM-PILES.Settings.OutputToChat.Title",
      hint: "ITEM-PILES.Settings.OutputToChat.Hint",
      scope: "world",
      config: false,
      default: 1,
      choices: [
        "ITEM-PILES.Settings.OutputToChat.Off",
        "ITEM-PILES.Settings.OutputToChat.Public",
        "ITEM-PILES.Settings.OutputToChat.SelfGM",
        "ITEM-PILES.Settings.OutputToChat.Blind"
      ],
      type: Number
    },
    [SETTINGS.INSPECT_ITEMS_IN_TRADE]: {
      name: "ITEM-PILES.Settings.InspectItemsTrade.Title",
      hint: "ITEM-PILES.Settings.InspectItemsTrade.Hint",
      scope: "world",
      config: false,
      default: true,
      type: Boolean
    },
    [SETTINGS.POPULATION_TABLES_FOLDER]: {
      name: "ITEM-PILES.Settings.PopulationTablesFolder.Title",
      hint: "ITEM-PILES.Settings.PopulationTablesFolder.Hint",
      scope: "world",
      config: false,
      default: "root",
      type: String
    },
    [SETTINGS.DELETE_EMPTY_PILES]: {
      name: "ITEM-PILES.Settings.DeleteEmptyPiles.Title",
      hint: "ITEM-PILES.Settings.DeleteEmptyPiles.Hint",
      scope: "world",
      config: false,
      default: false,
      type: Boolean
    },
    [SETTINGS.ENABLE_DROPPING_ITEMS]: {
      name: "ITEM-PILES.Settings.EnableDroppingItems.Title",
      hint: "ITEM-PILES.Settings.EnableDroppingItems.Hint",
      scope: "world",
      config: false,
      default: true,
      type: Boolean
    },
    [SETTINGS.ENABLE_TRADING]: {
      name: "ITEM-PILES.Settings.EnableTrading.Title",
      hint: "ITEM-PILES.Settings.EnableTrading.Hint",
      scope: "world",
      config: false,
      default: true,
      type: Boolean
    },
    [SETTINGS.ENABLE_GIVING_ITEMS]: {
      name: "ITEM-PILES.Settings.EnableGivingItems.Title",
      hint: "ITEM-PILES.Settings.EnableGivingItems.Hint",
      scope: "world",
      config: false,
      default: true,
      type: Boolean
    },
    [SETTINGS.SHOW_TRADE_BUTTON]: {
      name: "ITEM-PILES.Settings.ShowTradeButton.Title",
      hint: "ITEM-PILES.Settings.ShowTradeButton.Hint",
      scope: "world",
      config: false,
      default: true,
      type: Boolean
    },
    [SETTINGS.PRICE_PRESETS]: {
      name: "ITEM-PILES.Settings.PricePresets.Title",
      label: "ITEM-PILES.Settings.PricePresets.Label",
      hint: "ITEM-PILES.Settings.PricePresets.Hint",
      scope: "world",
      icon: "fa fa-tags",
      application: "price-presets",
      config: false,
      default: [],
      type: Array
    },
    [SETTINGS.HIDE_TOKEN_BORDER]: {
      name: "ITEM-PILES.Settings.HideTokenBorder.Title",
      label: "ITEM-PILES.Settings.HideTokenBorder.Label",
      hint: "ITEM-PILES.Settings.HideTokenBorder.Hint",
      scope: "world",
      config: false,
      default: SETTINGS.HIDE_TOKEN_BORDER_OPTIONS.EVERYONE,
      choices: {
        [SETTINGS.HIDE_TOKEN_BORDER_OPTIONS.EVERYONE]: "ITEM-PILES.Settings.HideTokenBorder.HideEveryone",
        [SETTINGS.HIDE_TOKEN_BORDER_OPTIONS.PLAYERS]: "ITEM-PILES.Settings.HideTokenBorder.HidePlayers",
        [SETTINGS.HIDE_TOKEN_BORDER_OPTIONS.SHOW]: "ITEM-PILES.Settings.HideTokenBorder.Show"
      },
      type: String
    },
    [SETTINGS.INVERT_SHEET_OPEN]: {
      name: "ITEM-PILES.Settings.InvertSheetOpen.Title",
      hint: "ITEM-PILES.Settings.InvertSheetOpen.Hint",
      scope: "client",
      config: false,
      default: false,
      type: Boolean
    },
    [SETTINGS.HIDE_ACTOR_HEADER_TEXT]: {
      name: "ITEM-PILES.Settings.HideHeaderButtonText.Title",
      hint: "ITEM-PILES.Settings.HideHeaderButtonText.Hint",
      scope: "client",
      config: false,
      default: false,
      type: Boolean
    },
    [SETTINGS.HIDE_ACTOR_HEADER_BUTTON]: {
      name: "ITEM-PILES.Settings.HideHeaderButton.Title",
      hint: "ITEM-PILES.Settings.HideHeaderButton.Hint",
      scope: "client",
      config: false,
      default: false,
      type: Boolean
    },
    [SETTINGS.PRELOAD_FILES]: {
      name: "ITEM-PILES.Settings.PreloadFiles.Title",
      hint: "ITEM-PILES.Settings.PreloadFiles.Hint",
      scope: "client",
      config: false,
      default: true,
      type: Boolean
    },
    [SETTINGS.DEBUG]: {
      name: "ITEM-PILES.Settings.Debug.Title",
      hint: "ITEM-PILES.Settings.Debug.Hint",
      scope: "client",
      config: false,
      default: false,
      type: Boolean
    },
    [SETTINGS.DEBUG_HOOKS]: {
      name: "ITEM-PILES.Settings.DebugHooks.Title",
      hint: "ITEM-PILES.Settings.DebugHooks.Hint",
      scope: "client",
      config: false,
      default: false,
      type: Boolean
    }
  })
};
const SETTINGS$1 = SETTINGS;
function getActor(target) {
  if (target instanceof Actor)
    return target;
  let targetDoc = target;
  if (stringIsUuid(target)) {
    targetDoc = fromUuidSync(target);
    if (!targetDoc && deletedActorCache.has(target)) {
      return deletedActorCache.get(target);
    }
  }
  targetDoc = getDocument(targetDoc);
  return targetDoc?.character ?? targetDoc?.actor ?? targetDoc;
}
__name(getActor, "getActor");
function getToken(documentUuid) {
  let doc = fromUuidSync(documentUuid);
  doc = doc?.token ?? doc;
  return doc instanceof TokenDocument ? doc?.object ?? doc : doc;
}
__name(getToken, "getToken");
function getDocument(target) {
  if (stringIsUuid(target)) {
    target = fromUuidSync(target);
  }
  return target?.document ?? target;
}
__name(getDocument, "getDocument");
function stringIsUuid(inId) {
  return typeof inId === "string" && (inId.match(/\./g) || []).length && !inId.endsWith(".");
}
__name(stringIsUuid, "stringIsUuid");
function getUuid(target) {
  if (stringIsUuid(target))
    return target;
  const document2 = getDocument(target);
  return document2?.uuid ?? false;
}
__name(getUuid, "getUuid");
function findSimilarItem(items, findItem, {
  returnOne = true
} = {}) {
  const itemSimilarities = game.itempiles.API.ITEM_SIMILARITIES;
  let findItemData = findItem instanceof Item ? findItem.toObject() : findItem;
  findItemData = findItemData?.item ?? findItemData;
  const findItemId = findItemData?._id;
  let hasUniqueKey = false;
  for (let prop of CONSTANTS.ITEM_FORCED_UNIQUE_KEYS) {
    if (getProperty(findItemData, prop)) {
      hasUniqueKey = true;
      break;
    }
  }
  const filteredItems = items.filter((item) => {
    for (let prop of CONSTANTS.ITEM_FORCED_UNIQUE_KEYS) {
      if (getProperty(item?.item ?? item, prop)) {
        return false;
      }
    }
    return true;
  }).filter((item) => {
    const itemId = item instanceof Item ? item.id : item?.item?._id ?? item?._id ?? item?.id;
    if (itemId && findItemId && itemId === findItemId) {
      return true;
    }
    if (!itemSimilarities.some((path) => hasProperty(findItem, path))) {
      return false;
    }
    if (hasUniqueKey) {
      return false;
    }
    let itemData = item instanceof Item ? item.toObject() : item;
    itemData = itemData?.item ?? itemData;
    if (areItemsDifferent(itemData, findItemData)) {
      return false;
    }
    return itemSimilarities.length > 0;
  });
  return returnOne ? filteredItems?.[0] ?? false : filteredItems;
}
__name(findSimilarItem, "findSimilarItem");
function areItemsDifferent(itemA, itemB) {
  const itemSimilarities = game.itempiles.API.ITEM_SIMILARITIES;
  for (const path of itemSimilarities) {
    if (getProperty(itemA, path) !== getProperty(itemB, path) || !hasProperty(itemA, path) ^ !hasProperty(itemB, path)) {
      return true;
    }
  }
  return false;
}
__name(areItemsDifferent, "areItemsDifferent");
function setSimilarityProperties(obj, item) {
  const itemData = item instanceof Item ? item.toObject() : item;
  setProperty(obj, "_id", itemData._id);
  game.itempiles.API.ITEM_SIMILARITIES.forEach((prop) => {
    setProperty(obj, prop, getProperty(itemData, prop));
  });
  return obj;
}
__name(setSimilarityProperties, "setSimilarityProperties");
let itemTypesWithQuantities = false;
function refreshItemTypesThatCanStack() {
  itemTypesWithQuantities = false;
  getItemTypesThatCanStack();
}
__name(refreshItemTypesThatCanStack, "refreshItemTypesThatCanStack");
function getItemTypesThatCanStack() {
  if (!itemTypesWithQuantities) {
    itemTypesWithQuantities = /* @__PURE__ */ new Set();
    if (game.system.id === "custom-system-builder") {
      const quantityAttribute = game.itempiles.API.ITEM_QUANTITY_ATTRIBUTE.split(".").pop();
      const itemTemplates = game.items.filter((_i) => _i?.templateSystem?.isTemplate && _i?.templateSystem?.getKeys).filter((_i) => _i.templateSystem.getKeys().has(quantityAttribute));
      for (const item of itemTemplates) {
        itemTypesWithQuantities.add(item.name);
      }
    }
    const unstackableItemTypes = getSetting(SETTINGS$1.UNSTACKABLE_ITEM_TYPES);
    const types = new Set(Object.keys(CONFIG?.Item?.dataModels ?? {}).concat(game.system.template.Item.types));
    itemTypesWithQuantities = new Set([...itemTypesWithQuantities, ...types.filter((type) => {
      let itemTemplate = {};
      if (CONFIG?.Item?.dataModels?.[type]?.defineSchema !== void 0) {
        itemTemplate.system = Object.entries(CONFIG.Item.dataModels[type].defineSchema()).map(([key, schema]) => {
          return [key, schema.fields ?? true];
        });
        itemTemplate.system = Object.fromEntries(itemTemplate.system);
      } else if (game.system?.template?.Item?.[type]) {
        itemTemplate.system = foundry.utils.deepClone(game.system.template.Item[type]);
        if (itemTemplate.system?.templates?.length) {
          const templates = foundry.utils.duplicate(itemTemplate.system.templates);
          for (let template of templates) {
            itemTemplate.system = foundry.utils.mergeObject(itemTemplate.system, foundry.utils.duplicate(game.system.template.Item.templates[template]));
          }
        }
      }
      return hasItemQuantity(itemTemplate);
    })].filter((type) => !unstackableItemTypes.includes(type)));
  }
  return itemTypesWithQuantities;
}
__name(getItemTypesThatCanStack, "getItemTypesThatCanStack");
function isItemStackable(itemData) {
  getItemTypesThatCanStack();
  if (game.system.id === "custom-system-builder" && itemData?.system?.template) {
    const templateItem = game.items.get(itemData?.system?.template);
    if (templateItem) {
      return itemTypesWithQuantities.has(templateItem.name);
    }
  }
  return itemTypesWithQuantities.has(itemData.type);
}
__name(isItemStackable, "isItemStackable");
function getItemQuantity(item) {
  const itemData = item instanceof Item ? item.toObject() : item;
  return Number(getProperty(itemData, game.itempiles.API.ITEM_QUANTITY_ATTRIBUTE) ?? 0);
}
__name(getItemQuantity, "getItemQuantity");
function hasItemQuantity(item) {
  const itemData = item instanceof Item ? item.toObject() : item;
  return hasProperty(itemData, game.itempiles.API.ITEM_QUANTITY_ATTRIBUTE);
}
__name(hasItemQuantity, "hasItemQuantity");
function setItemQuantity(itemData, quantity, requiresExistingQuantity = false) {
  if (!requiresExistingQuantity || getItemTypesThatCanStack().has(itemData.type) || hasItemQuantity(itemData)) {
    setProperty(itemData, game.itempiles.API.ITEM_QUANTITY_ATTRIBUTE, quantity);
  }
  return itemData;
}
__name(setItemQuantity, "setItemQuantity");
function getItemCost(item) {
  const itemData = item instanceof Item ? item.toObject() : item;
  return getProperty(itemData, game.itempiles.API.ITEM_PRICE_ATTRIBUTE) ?? 0;
}
__name(getItemCost, "getItemCost");
function getTokensAtLocation(position) {
  const tokens = [...canvas.tokens.placeables].filter((token) => token?.mesh?.visible);
  return tokens.filter((token) => {
    return position.x >= token.x && position.x < token.x + token.document.width * canvas.grid.size && position.y >= token.y && position.y < token.y + token.document.height * canvas.grid.size;
  });
}
__name(getTokensAtLocation, "getTokensAtLocation");
function distance_between_rect(p1, p2) {
  const x1 = p1.x;
  const y1 = p1.y;
  const x1b = p1.x + p1.w;
  const y1b = p1.y + p1.h;
  const x2 = p2.x;
  const y2 = p2.y;
  const x2b = p2.x + p2.w;
  const y2b = p2.y + p2.h;
  const left = x2b < x1;
  const right = x1b < x2;
  const bottom = y2b < y1;
  const top = y1b < y2;
  if (top && left) {
    return distance_between({ x: x1, y: y1b }, { x: x2b, y: y2 });
  } else if (left && bottom) {
    return distance_between({ x: x1, y: y1 }, { x: x2b, y: y2b });
  } else if (bottom && right) {
    return distance_between({ x: x1b, y: y1 }, { x: x2, y: y2b });
  } else if (right && top) {
    return distance_between({ x: x1b, y: y1b }, { x: x2, y: y2 });
  } else if (left) {
    return x1 - x2b;
  } else if (right) {
    return x2 - x1b;
  } else if (bottom) {
    return y1 - y2b;
  } else if (top) {
    return y2 - y1b;
  }
  return 0;
}
__name(distance_between_rect, "distance_between_rect");
function distance_between(a, b) {
  return new Ray(a, b).distance;
}
__name(distance_between, "distance_between");
function grids_between_tokens(a, b) {
  return Math.floor(distance_between_rect(a, b) / canvas.grid.size) + 1;
}
__name(grids_between_tokens, "grids_between_tokens");
function tokens_close_enough(a, b, maxDistance) {
  const distance = grids_between_tokens(a, b);
  return maxDistance >= distance;
}
__name(tokens_close_enough, "tokens_close_enough");
async function runMacro(macroId, macroData) {
  let macro;
  if (macroId.startsWith("Compendium")) {
    let packArray = macroId.split(".");
    let compendium = game.packs.get(`${packArray[1]}.${packArray[2]}`);
    if (!compendium) {
      throw custom_error(`Compendium ${packArray[1]}.${packArray[2]} was not found`);
    }
    let findMacro = (await compendium.getDocuments()).find((m) => m.name === packArray[3] || m.id === packArray[3]);
    if (!findMacro) {
      throw custom_error(`The "${packArray[3]}" macro was not found in Compendium ${packArray[1]}.${packArray[2]}`);
    }
    macro = new Macro(findMacro?.toObject());
    macro.ownership.default = CONST.DOCUMENT_PERMISSION_LEVELS.OWNER;
  } else {
    macro = game.macros.getName(macroId);
    if (!macro) {
      throw custom_error(`Could not find macro with name "${macroId}"`);
    }
  }
  let result = false;
  try {
    result = await macro.execute(macroData);
  } catch (err) {
    custom_warning(`Error when executing macro ${macroId}!
${err}`, true);
  }
  return result;
}
__name(runMacro, "runMacro");
function getOwnedCharacters(user = false) {
  user = user || game.user;
  return game.actors.filter((actor) => {
    return actor.ownership?.[user.id] === CONST.DOCUMENT_PERMISSION_LEVELS.OWNER && actor.prototypeToken.actorLink;
  }).sort((a, b) => {
    return b._stats.modifiedTime - a._stats.modifiedTime;
  });
}
__name(getOwnedCharacters, "getOwnedCharacters");
function getUserCharacter(user = false) {
  user = user || game.user;
  return user.character || (user.isGM ? false : getOwnedCharacters(user)?.[0] ?? false);
}
__name(getUserCharacter, "getUserCharacter");
async function createFoldersFromNames(folders, type = "Actor") {
  let lastFolder = false;
  for (const folder of folders) {
    let actualFolder = game.folders.getName(folder);
    if (!actualFolder) {
      const folderData = { name: folder, type, sorting: "a" };
      if (lastFolder) {
        folderData.parent = lastFolder.id;
      }
      actualFolder = await Folder.create(folderData);
    }
    lastFolder = actualFolder;
  }
  if (lastFolder) {
    return lastFolder;
  }
}
__name(createFoldersFromNames, "createFoldersFromNames");
function getSourceActorFromDropData(dropData) {
  if (dropData.uuid) {
    const doc = fromUuidSync(dropData.uuid);
    return doc instanceof Actor ? doc : doc.parent;
  } else if (dropData.tokenId) {
    if (dropData.sceneId) {
      const uuid = `Scene.${dropData.sceneId}.Token.${dropData.tokenId}`;
      return fromUuidSync(uuid)?.actor;
    }
    return canvas.tokens.get(dropData.tokenId).actor;
  } else if (dropData.actorId) {
    return game.actors.get(dropData.actorId);
  }
  return false;
}
__name(getSourceActorFromDropData, "getSourceActorFromDropData");
const ActorDropSelect_svelte_svelte_type_style_lang = "";
function get_each_context$2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}
__name(get_each_context$2, "get_each_context$2");
function create_else_block_2(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Trade.Prompt.DropActor")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_else_block_2, "create_else_block_2");
function create_if_block_1$3(ctx) {
  let div;
  let t;
  let if_block0 = (
    /*actor*/
    ctx[0].img && create_if_block_4$2(ctx)
  );
  function select_block_type_1(ctx2, dirty) {
    if (
      /*multipleActors*/
      ctx2[4]
    )
      return create_if_block_2$2;
    return create_else_block_1$2;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block1 = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      if (if_block0)
        if_block0.c();
      t = space();
      if_block1.c();
      attr(div, "class", "align-center-col");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0)
        if_block0.m(div, null);
      append(div, t);
      if_block1.m(div, null);
    },
    p(ctx2, dirty) {
      if (
        /*actor*/
        ctx2[0].img
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_4$2(ctx2);
          if_block0.c();
          if_block0.m(div, t);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if_block1.p(ctx2, dirty);
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block0)
        if_block0.d();
      if_block1.d();
    }
  };
}
__name(create_if_block_1$3, "create_if_block_1$3");
function create_if_block_4$2(ctx) {
  let img;
  let img_src_value;
  return {
    c() {
      img = element("img");
      if (!src_url_equal(img.src, img_src_value = /*actor*/
      ctx[0].img))
        attr(img, "src", img_src_value);
      attr(img, "class", "svelte-1fiqefb");
    },
    m(target, anchor) {
      insert(target, img, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*actor, actors*/
      3 && !src_url_equal(img.src, img_src_value = /*actor*/
      ctx2[0].img)) {
        attr(img, "src", img_src_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(img);
    }
  };
}
__name(create_if_block_4$2, "create_if_block_4$2");
function create_else_block_1$2(ctx) {
  let span;
  let t_value = (
    /*actor*/
    ctx[0].name + ""
  );
  let t;
  return {
    c() {
      span = element("span");
      t = text(t_value);
      attr(span, "class", "svelte-1fiqefb");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*actor*/
      1 && t_value !== (t_value = /*actor*/
      ctx2[0].name + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_else_block_1$2, "create_else_block_1$2");
function create_if_block_2$2(ctx) {
  let span;
  function select_block_type_2(ctx2, dirty) {
    if (
      /*changingActor*/
      ctx2[2]
    )
      return create_if_block_3$2;
    return create_else_block$4;
  }
  __name(select_block_type_2, "select_block_type_2");
  let current_block_type = select_block_type_2(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      span = element("span");
      if_block.c();
      attr(span, "class", "svelte-1fiqefb");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if_block.m(span, null);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_2(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(span, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(span);
      if_block.d();
    }
  };
}
__name(create_if_block_2$2, "create_if_block_2$2");
function create_else_block$4(ctx) {
  let a;
  let t_value = (
    /*actor*/
    ctx[0].name + ""
  );
  let t;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      t = text(t_value);
      attr(a, "class", "item-piles-change-actor item-piles-highlight");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, t);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*actor*/
      1 && t_value !== (t_value = /*actor*/
      ctx2[0].name + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$4, "create_else_block$4");
function create_if_block_3$2(ctx) {
  let select;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let mounted;
  let dispose;
  let each_value = (
    /*actors*/
    ctx[1]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*potentialActor*/
    ctx2[13].id
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$2(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$2(key, child_ctx));
  }
  return {
    c() {
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(select, "class", "item-piles-change-actor-select svelte-1fiqefb");
      if (
        /*actor*/
        ctx[0] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[10].call(select)
        ));
    },
    m(target, anchor) {
      insert(target, select, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*actor*/
        ctx[0],
        true
      );
      if (!mounted) {
        dispose = [
          listen(
            select,
            "change",
            /*select_change_handler*/
            ctx[10]
          ),
          listen(
            select,
            "change",
            /*change_handler*/
            ctx[11]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*actors*/
      2) {
        each_value = /*actors*/
        ctx2[1];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, select, destroy_block, create_each_block$2, null, get_each_context$2);
      }
      if (dirty & /*actor, actors*/
      3) {
        select_option(
          select,
          /*actor*/
          ctx2[0]
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_3$2, "create_if_block_3$2");
function create_each_block$2(key_1, ctx) {
  let option;
  let t_value = (
    /*potentialActor*/
    ctx[13].name + ""
  );
  let t;
  let option_value_value;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*potentialActor*/
      ctx[13];
      option.value = option.__value;
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*actors*/
      2 && t_value !== (t_value = /*potentialActor*/
      ctx[13].name + ""))
        set_data(t, t_value);
      if (dirty & /*actors*/
      2 && option_value_value !== (option_value_value = /*potentialActor*/
      ctx[13])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$2, "create_each_block$2");
function create_if_block$4(ctx) {
  let div;
  let button;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Trade.Prompt.PickToken") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      button = element("button");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-expand");
      attr(button, "type", "button");
      attr(div, "class", "item-piles-flexrow");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button);
      append(button, i);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*setActorFromSelectedToken*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block$4, "create_if_block$4");
function create_fragment$4(ctx) {
  let div1;
  let div0;
  let t;
  let mounted;
  let dispose;
  function select_block_type(ctx2, dirty) {
    if (
      /*actor*/
      ctx2[0]
    )
      return create_if_block_1$3;
    return create_else_block_2;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block0 = current_block_type(ctx);
  let if_block1 = (
    /*hasUnlinkedTokenOwnership*/
    ctx[5] && create_if_block$4(ctx)
  );
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      if_block0.c();
      t = space();
      if (if_block1)
        if_block1.c();
      attr(div0, "class", "form-group item-piles-actor-container align-center-row svelte-1fiqefb");
      toggle_class(
        div0,
        "item-piles-box-highlight",
        /*counter*/
        ctx[3] > 0
      );
      attr(div1, "class", "item-piles-bottom-divider");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      if_block0.m(div0, null);
      append(div1, t);
      if (if_block1)
        if_block1.m(div1, null);
      if (!mounted) {
        dispose = [
          listen(
            div0,
            "dragenter",
            /*dragEnter*/
            ctx[8]
          ),
          listen(
            div0,
            "dragleave",
            /*dragLeave*/
            ctx[9]
          ),
          listen(div0, "dragover", preventDefault),
          listen(div0, "dragstart", preventDefault),
          listen(
            div0,
            "drop",
            /*dropData*/
            ctx[7]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block0) {
        if_block0.p(ctx2, dirty);
      } else {
        if_block0.d(1);
        if_block0 = current_block_type(ctx2);
        if (if_block0) {
          if_block0.c();
          if_block0.m(div0, null);
        }
      }
      if (dirty & /*counter*/
      8) {
        toggle_class(
          div0,
          "item-piles-box-highlight",
          /*counter*/
          ctx2[3] > 0
        );
      }
      if (
        /*hasUnlinkedTokenOwnership*/
        ctx2[5]
      )
        if_block1.p(ctx2, dirty);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div1);
      if_block0.d();
      if (if_block1)
        if_block1.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$4, "create_fragment$4");
function preventDefault(event) {
  event.preventDefault();
}
__name(preventDefault, "preventDefault");
function instance$4($$self, $$props, $$invalidate) {
  let { actor } = $$props;
  let { actors } = $$props;
  let changingActor = false;
  let multipleActors = actors.length > 1 && !game.user.isGM;
  let hasUnlinkedTokenOwnership = actors.filter((a) => !a.prototypeToken.actorLink).length > 0;
  function setActorFromSelectedToken() {
    if (canvas.tokens.controlled.length === 0)
      return;
    $$invalidate(0, actor = canvas.tokens.controlled[0].actor);
  }
  __name(setActorFromSelectedToken, "setActorFromSelectedToken");
  async function dropData(event) {
    $$invalidate(3, counter = 0);
    let data2;
    try {
      data2 = JSON.parse(event.dataTransfer.getData("text/plain"));
    } catch (err) {
      return false;
    }
    if (data2.type !== "Actor")
      return;
    $$invalidate(0, actor = getSourceActorFromDropData(data2));
  }
  __name(dropData, "dropData");
  let counter = 0;
  function dragEnter() {
    $$invalidate(3, counter++, counter);
  }
  __name(dragEnter, "dragEnter");
  function dragLeave() {
    $$invalidate(3, counter--, counter);
  }
  __name(dragLeave, "dragLeave");
  function select_change_handler() {
    actor = select_value(this);
    $$invalidate(0, actor);
    $$invalidate(1, actors);
  }
  __name(select_change_handler, "select_change_handler");
  const change_handler = /* @__PURE__ */ __name(() => {
    $$invalidate(2, changingActor = false);
  }, "change_handler");
  const click_handler = /* @__PURE__ */ __name(() => {
    $$invalidate(2, changingActor = true);
  }, "click_handler");
  $$self.$$set = ($$props2) => {
    if ("actor" in $$props2)
      $$invalidate(0, actor = $$props2.actor);
    if ("actors" in $$props2)
      $$invalidate(1, actors = $$props2.actors);
  };
  return [
    actor,
    actors,
    changingActor,
    counter,
    multipleActors,
    hasUnlinkedTokenOwnership,
    setActorFromSelectedToken,
    dropData,
    dragEnter,
    dragLeave,
    select_change_handler,
    change_handler,
    click_handler
  ];
}
__name(instance$4, "instance$4");
const _ActorDropSelect = class _ActorDropSelect extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$4, create_fragment$4, safe_not_equal, { actor: 0, actors: 1 });
  }
};
__name(_ActorDropSelect, "ActorDropSelect");
let ActorDropSelect = _ActorDropSelect;
const tradeDialogPrompt_svelte_svelte_type_style_lang = "";
function get_each_context$1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}
__name(get_each_context$1, "get_each_context$1");
function create_each_block$1(key_1, ctx) {
  let option;
  let t_value = (
    /*potentialUser*/
    ctx[13].name + ""
  );
  let t;
  let option_value_value;
  return {
    key: key_1,
    first: null,
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = option_value_value = /*potentialUser*/
      ctx[13];
      option.value = option.__value;
      this.first = option;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*users*/
      4 && t_value !== (t_value = /*potentialUser*/
      ctx[13].name + ""))
        set_data(t, t_value);
      if (dirty & /*users*/
      4 && option_value_value !== (option_value_value = /*potentialUser*/
      ctx[13])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
__name(create_each_block$1, "create_each_block$1");
function create_else_block$3(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Trade.Prompt.PickActor")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_else_block$3, "create_else_block$3");
function create_if_block$3(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Trade.Prompt.PickedActor")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block$3, "create_if_block$3");
function create_default_slot$2(ctx) {
  let div4;
  let p0;
  let t0;
  let p1;
  let strong;
  let t2;
  let p2;
  let t4;
  let div1;
  let div0;
  let select;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let t5;
  let div3;
  let div2;
  let label;
  let input;
  let t6;
  let span;
  let t8;
  let small;
  let t10;
  let t11;
  let actordropselect;
  let updating_actor;
  let t12;
  let footer;
  let button;
  let i1;
  let t13;
  let t14_value = localize("ITEM-PILES.Trade.Prompt.Label") + "";
  let t14;
  let button_disabled_value;
  let current;
  let mounted;
  let dispose;
  let each_value = (
    /*users*/
    ctx[2]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*potentialUser*/
    ctx2[13].id
  ), "get_key");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$1(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$1(key, child_ctx));
  }
  function select_block_type(ctx2, dirty) {
    if (
      /*actor*/
      ctx2[5]
    )
      return create_if_block$3;
    return create_else_block$3;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  function actordropselect_actor_binding(value) {
    ctx[9](value);
  }
  __name(actordropselect_actor_binding, "actordropselect_actor_binding");
  let actordropselect_props = { actors: (
    /*actors*/
    ctx[4]
  ) };
  if (
    /*actor*/
    ctx[5] !== void 0
  ) {
    actordropselect_props.actor = /*actor*/
    ctx[5];
  }
  actordropselect = new ActorDropSelect({ props: actordropselect_props });
  binding_callbacks.push(() => bind(actordropselect, "actor", actordropselect_actor_binding));
  return {
    c() {
      div4 = element("div");
      p0 = element("p");
      p0.innerHTML = `<i class="item-piles-header-icon fas fa-handshake svelte-r6pfu5"></i>`;
      t0 = space();
      p1 = element("p");
      strong = element("strong");
      strong.textContent = `${localize("ITEM-PILES.Trade.Prompt.Title")}`;
      t2 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Trade.Prompt.User")}`;
      t4 = space();
      div1 = element("div");
      div0 = element("div");
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t5 = space();
      div3 = element("div");
      div2 = element("div");
      label = element("label");
      input = element("input");
      t6 = space();
      span = element("span");
      span.textContent = `${localize("ITEM-PILES.Trade.Private")}`;
      t8 = space();
      small = element("small");
      small.textContent = `${localize("ITEM-PILES.Trade.PrivateExplanation")}`;
      t10 = space();
      if_block.c();
      t11 = space();
      create_component(actordropselect.$$.fragment);
      t12 = space();
      footer = element("footer");
      button = element("button");
      i1 = element("i");
      t13 = space();
      t14 = text(t14_value);
      set_style(strong, "font-size", "1.2rem");
      set_style(p1, "margin-bottom", "1rem");
      attr(select, "name", "user");
      set_style(select, "width", "66%");
      if (
        /*user*/
        ctx[3] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx[7].call(select)
        ));
      attr(div0, "class", "form-group align-center-row");
      attr(div1, "class", "item-piles-bottom-divider");
      attr(input, "name", "private");
      attr(input, "type", "checkbox");
      attr(label, "class", "align-center-row");
      attr(div2, "class", "form-group align-center-col");
      attr(div3, "class", "item-piles-bottom-divider");
      attr(i1, "class", "fas fa-check");
      button.disabled = button_disabled_value = !/*actor*/
      ctx[5];
      attr(button, "type", "button");
      attr(button, "class", "svelte-r6pfu5");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
      attr(div4, "class", "item-piles-flexcol trade-dialog svelte-r6pfu5");
    },
    m(target, anchor) {
      insert(target, div4, anchor);
      append(div4, p0);
      append(div4, t0);
      append(div4, p1);
      append(p1, strong);
      append(div4, t2);
      append(div4, p2);
      append(div4, t4);
      append(div4, div1);
      append(div1, div0);
      append(div0, select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*user*/
        ctx[3],
        true
      );
      append(div4, t5);
      append(div4, div3);
      append(div3, div2);
      append(div2, label);
      append(label, input);
      input.checked = /*isPrivate*/
      ctx[1];
      append(label, t6);
      append(label, span);
      append(div2, t8);
      append(div2, small);
      append(div4, t10);
      if_block.m(div4, null);
      append(div4, t11);
      mount_component(actordropselect, div4, null);
      append(div4, t12);
      append(div4, footer);
      append(footer, button);
      append(button, i1);
      append(button, t13);
      append(button, t14);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            select,
            "change",
            /*select_change_handler*/
            ctx[7]
          ),
          listen(
            input,
            "change",
            /*input_change_handler*/
            ctx[8]
          ),
          listen(
            button,
            "click",
            /*requestTrade*/
            ctx[6],
            { once: true }
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*users*/
      4) {
        each_value = /*users*/
        ctx2[2];
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, select, destroy_block, create_each_block$1, null, get_each_context$1);
      }
      if (dirty & /*user, users*/
      12) {
        select_option(
          select,
          /*user*/
          ctx2[3]
        );
      }
      if (dirty & /*isPrivate*/
      2) {
        input.checked = /*isPrivate*/
        ctx2[1];
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(div4, t11);
        }
      }
      const actordropselect_changes = {};
      if (dirty & /*actors*/
      16)
        actordropselect_changes.actors = /*actors*/
        ctx2[4];
      if (!updating_actor && dirty & /*actor*/
      32) {
        updating_actor = true;
        actordropselect_changes.actor = /*actor*/
        ctx2[5];
        add_flush_callback(() => updating_actor = false);
      }
      actordropselect.$set(actordropselect_changes);
      if (!current || dirty & /*actor*/
      32 && button_disabled_value !== (button_disabled_value = !/*actor*/
      ctx2[5])) {
        button.disabled = button_disabled_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(actordropselect.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(actordropselect.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div4);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if_block.d();
      destroy_component(actordropselect);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$2, "create_default_slot$2");
function create_fragment$3(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[10](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$2] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, actor, actors, isPrivate, user, users*/
      65598) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$3, "create_fragment$3");
function instance$3($$self, $$props, $$invalidate) {
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let { isPrivate } = $$props;
  let { users } = $$props;
  let { user } = $$props;
  let { actors } = $$props;
  let { actor } = $$props;
  let isGM = game.user.isGM;
  users = game.users.filter((user2) => user2.active && user2 !== game.user);
  user = user || users?.[0] || false;
  actors = actors || game.actors.filter((actor2) => actor2.isOwner);
  actor = actor || game.user.character || (!isGM ? actors?.[0] : false);
  function requestTrade() {
    application.options.resolve({ user, actor, isPrivate });
    application.close();
  }
  __name(requestTrade, "requestTrade");
  function select_change_handler() {
    user = select_value(this);
    $$invalidate(3, user);
    $$invalidate(2, users);
  }
  __name(select_change_handler, "select_change_handler");
  function input_change_handler() {
    isPrivate = this.checked;
    $$invalidate(1, isPrivate);
  }
  __name(input_change_handler, "input_change_handler");
  function actordropselect_actor_binding(value) {
    actor = value;
    $$invalidate(5, actor);
  }
  __name(actordropselect_actor_binding, "actordropselect_actor_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("isPrivate" in $$props2)
      $$invalidate(1, isPrivate = $$props2.isPrivate);
    if ("users" in $$props2)
      $$invalidate(2, users = $$props2.users);
    if ("user" in $$props2)
      $$invalidate(3, user = $$props2.user);
    if ("actors" in $$props2)
      $$invalidate(4, actors = $$props2.actors);
    if ("actor" in $$props2)
      $$invalidate(5, actor = $$props2.actor);
  };
  return [
    elementRoot,
    isPrivate,
    users,
    user,
    actors,
    actor,
    requestTrade,
    select_change_handler,
    input_change_handler,
    actordropselect_actor_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$3, "instance$3");
const _Trade_dialog_prompt = class _Trade_dialog_prompt extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$3, create_fragment$3, safe_not_equal, {
      elementRoot: 0,
      isPrivate: 1,
      users: 2,
      user: 3,
      actors: 4,
      actor: 5
    });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get isPrivate() {
    return this.$$.ctx[1];
  }
  set isPrivate(isPrivate) {
    this.$$set({ isPrivate });
    flush();
  }
  get users() {
    return this.$$.ctx[2];
  }
  set users(users) {
    this.$$set({ users });
    flush();
  }
  get user() {
    return this.$$.ctx[3];
  }
  set user(user) {
    this.$$set({ user });
    flush();
  }
  get actors() {
    return this.$$.ctx[4];
  }
  set actors(actors) {
    this.$$set({ actors });
    flush();
  }
  get actor() {
    return this.$$.ctx[5];
  }
  set actor(actor) {
    this.$$set({ actor });
    flush();
  }
};
__name(_Trade_dialog_prompt, "Trade_dialog_prompt");
let Trade_dialog_prompt = _Trade_dialog_prompt;
function is_date(obj) {
  return Object.prototype.toString.call(obj) === "[object Date]";
}
__name(is_date, "is_date");
function get_interpolator(a, b) {
  if (a === b || a !== a)
    return () => a;
  const type = typeof a;
  if (type !== typeof b || Array.isArray(a) !== Array.isArray(b)) {
    throw new Error("Cannot interpolate values of different type");
  }
  if (Array.isArray(a)) {
    const arr = b.map((bi, i) => {
      return get_interpolator(a[i], bi);
    });
    return (t) => arr.map((fn) => fn(t));
  }
  if (type === "object") {
    if (!a || !b)
      throw new Error("Object cannot be null");
    if (is_date(a) && is_date(b)) {
      a = a.getTime();
      b = b.getTime();
      const delta = b - a;
      return (t) => new Date(a + t * delta);
    }
    const keys = Object.keys(b);
    const interpolators = {};
    keys.forEach((key) => {
      interpolators[key] = get_interpolator(a[key], b[key]);
    });
    return (t) => {
      const result = {};
      keys.forEach((key) => {
        result[key] = interpolators[key](t);
      });
      return result;
    };
  }
  if (type === "number") {
    const delta = b - a;
    return (t) => a + t * delta;
  }
  throw new Error(`Cannot interpolate ${type} values`);
}
__name(get_interpolator, "get_interpolator");
function tweened(value, defaults = {}) {
  const store = writable$1(value);
  let task;
  let target_value = value;
  function set(new_value, opts) {
    if (value == null) {
      store.set(value = new_value);
      return Promise.resolve();
    }
    target_value = new_value;
    let previous_task = task;
    let started = false;
    let { delay = 0, duration = 400, easing = identity, interpolate = get_interpolator } = assign(assign({}, defaults), opts);
    if (duration === 0) {
      if (previous_task) {
        previous_task.abort();
        previous_task = null;
      }
      store.set(value = target_value);
      return Promise.resolve();
    }
    const start = now() + delay;
    let fn;
    task = loop$1((now2) => {
      if (now2 < start)
        return true;
      if (!started) {
        fn = interpolate(value, new_value);
        if (typeof duration === "function")
          duration = duration(value, new_value);
        started = true;
      }
      if (previous_task) {
        previous_task.abort();
        previous_task = null;
      }
      const elapsed = now2 - start;
      if (elapsed > duration) {
        store.set(value = new_value);
        return false;
      }
      store.set(value = fn(easing(elapsed / duration)));
      return true;
    });
    return task.promise;
  }
  __name(set, "set");
  return {
    set,
    update: (fn, opts) => set(fn(target_value, value), opts),
    subscribe: store.subscribe
  };
}
__name(tweened, "tweened");
const tradeDialogRequest_svelte_svelte_type_style_lang = "";
function create_else_block_1$1(ctx) {
  let p;
  let t_value = localize("ITEM-PILES.Trade.Request.Content", {
    trading_user_name: (
      /*tradingUser*/
      ctx[5].name
    ),
    trading_actor_name: (
      /*tradingActor*/
      ctx[4].name
    )
  }) + "";
  let t;
  return {
    c() {
      p = element("p");
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*tradingUser, tradingActor*/
      48 && t_value !== (t_value = localize("ITEM-PILES.Trade.Request.Content", {
        trading_user_name: (
          /*tradingUser*/
          ctx2[5].name
        ),
        trading_actor_name: (
          /*tradingActor*/
          ctx2[4].name
        )
      }) + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_else_block_1$1, "create_else_block_1$1");
function create_if_block_1$2(ctx) {
  let p;
  let raw_value = localize("ITEM-PILES.Trade.Request.PrivateContent", {
    trading_user_name: (
      /*tradingUser*/
      ctx[5].name
    ),
    trading_actor_name: (
      /*tradingActor*/
      ctx[4].name
    )
  }) + "";
  return {
    c() {
      p = element("p");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      p.innerHTML = raw_value;
    },
    p(ctx2, dirty) {
      if (dirty & /*tradingUser, tradingActor*/
      48 && raw_value !== (raw_value = localize("ITEM-PILES.Trade.Request.PrivateContent", {
        trading_user_name: (
          /*tradingUser*/
          ctx2[5].name
        ),
        trading_actor_name: (
          /*tradingActor*/
          ctx2[4].name
        )
      }) + ""))
        p.innerHTML = raw_value;
    },
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block_1$2, "create_if_block_1$2");
function create_else_block$2(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Trade.Prompt.PickActor")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_else_block$2, "create_else_block$2");
function create_if_block$2(ctx) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${localize("ITEM-PILES.Trade.Prompt.PickedActor")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
__name(create_if_block$2, "create_if_block$2");
function create_default_slot$1(ctx) {
  let div2;
  let p0;
  let t0;
  let p1;
  let strong;
  let t2;
  let div0;
  let t3;
  let p2;
  let t5;
  let t6;
  let actordropselect;
  let updating_actor;
  let t7;
  let footer;
  let button0;
  let i1;
  let t8;
  let t9_value = localize("ITEM-PILES.Trade.Accept") + "";
  let t9;
  let button0_disabled_value;
  let t10;
  let button1;
  let i2;
  let t11;
  let t12_value = localize("ITEM-PILES.Trade.Decline") + "";
  let t12;
  let t13;
  let button2;
  let i3;
  let t14;
  let t15_value = localize("ITEM-PILES.Trade.Mute") + "";
  let t15;
  let t16;
  let div1;
  let span;
  let current;
  let mounted;
  let dispose;
  function select_block_type(ctx2, dirty) {
    if (
      /*isPrivate*/
      ctx2[3]
    )
      return create_if_block_1$2;
    return create_else_block_1$1;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block0 = current_block_type(ctx);
  function select_block_type_1(ctx2, dirty) {
    if (
      /*actor*/
      ctx2[2]
    )
      return create_if_block$2;
    return create_else_block$2;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type_1 = select_block_type_1(ctx);
  let if_block1 = current_block_type_1(ctx);
  function actordropselect_actor_binding(value) {
    ctx[14](value);
  }
  __name(actordropselect_actor_binding, "actordropselect_actor_binding");
  let actordropselect_props = { actors: (
    /*actors*/
    ctx[1]
  ) };
  if (
    /*actor*/
    ctx[2] !== void 0
  ) {
    actordropselect_props.actor = /*actor*/
    ctx[2];
  }
  actordropselect = new ActorDropSelect({ props: actordropselect_props });
  binding_callbacks.push(() => bind(actordropselect, "actor", actordropselect_actor_binding));
  return {
    c() {
      div2 = element("div");
      p0 = element("p");
      p0.innerHTML = `<i class="item-piles-header-icon fas fa-handshake svelte-bu4abp"></i>`;
      t0 = space();
      p1 = element("p");
      strong = element("strong");
      strong.textContent = `${localize("ITEM-PILES.Trade.Request.Title")}`;
      t2 = space();
      div0 = element("div");
      if_block0.c();
      t3 = space();
      p2 = element("p");
      p2.textContent = `${localize("ITEM-PILES.Trade.Request.AcceptQuery")}`;
      t5 = space();
      if_block1.c();
      t6 = space();
      create_component(actordropselect.$$.fragment);
      t7 = space();
      footer = element("footer");
      button0 = element("button");
      i1 = element("i");
      t8 = space();
      t9 = text(t9_value);
      t10 = space();
      button1 = element("button");
      i2 = element("i");
      t11 = space();
      t12 = text(t12_value);
      t13 = space();
      button2 = element("button");
      i3 = element("i");
      t14 = space();
      t15 = text(t15_value);
      t16 = space();
      div1 = element("div");
      span = element("span");
      set_style(strong, "font-size", "1.2rem");
      set_style(p1, "margin-bottom", "1rem");
      attr(div0, "class", "item-piles-bottom-divider");
      attr(i1, "class", "fas fa-check");
      button0.disabled = button0_disabled_value = !/*actor*/
      ctx[2];
      attr(button0, "type", "button");
      attr(button0, "class", "svelte-bu4abp");
      attr(i2, "class", "fas fa-times");
      attr(button1, "type", "button");
      attr(button1, "class", "svelte-bu4abp");
      attr(i3, "class", "fas fa-comment-slash");
      attr(button2, "type", "button");
      attr(button2, "class", "svelte-bu4abp");
      attr(footer, "class", "sheet-footer item-piles-flexrow");
      attr(span, "class", "progress-bar svelte-bu4abp");
      set_style(
        span,
        "width",
        /*actualProgress*/
        ctx[6] + "%"
      );
      attr(div1, "class", "item-piles-progress svelte-bu4abp");
      set_style(div1, "flex", "1 0 auto");
      toggle_class(
        div1,
        "active",
        /*actualProgress*/
        ctx[6] > 0
      );
      attr(div2, "class", "item-piles-flexcol trade-dialog svelte-bu4abp");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, p0);
      append(div2, t0);
      append(div2, p1);
      append(p1, strong);
      append(div2, t2);
      append(div2, div0);
      if_block0.m(div0, null);
      append(div0, t3);
      append(div0, p2);
      append(div2, t5);
      if_block1.m(div2, null);
      append(div2, t6);
      mount_component(actordropselect, div2, null);
      append(div2, t7);
      append(div2, footer);
      append(footer, button0);
      append(button0, i1);
      append(button0, t8);
      append(button0, t9);
      append(footer, t10);
      append(footer, button1);
      append(button1, i2);
      append(button1, t11);
      append(button1, t12);
      append(footer, t13);
      append(footer, button2);
      append(button2, i3);
      append(button2, t14);
      append(button2, t15);
      append(div2, t16);
      append(div2, div1);
      append(div1, span);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*accept*/
            ctx[7],
            { once: true }
          ),
          listen(
            button1,
            "click",
            /*decline*/
            ctx[8],
            { once: true }
          ),
          listen(
            button2,
            "click",
            /*mute*/
            ctx[9],
            { once: true }
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block0) {
        if_block0.p(ctx2, dirty);
      } else {
        if_block0.d(1);
        if_block0 = current_block_type(ctx2);
        if (if_block0) {
          if_block0.c();
          if_block0.m(div0, t3);
        }
      }
      if (current_block_type_1 === (current_block_type_1 = select_block_type_1(ctx2)) && if_block1) {
        if_block1.p(ctx2, dirty);
      } else {
        if_block1.d(1);
        if_block1 = current_block_type_1(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div2, t6);
        }
      }
      const actordropselect_changes = {};
      if (dirty & /*actors*/
      2)
        actordropselect_changes.actors = /*actors*/
        ctx2[1];
      if (!updating_actor && dirty & /*actor*/
      4) {
        updating_actor = true;
        actordropselect_changes.actor = /*actor*/
        ctx2[2];
        add_flush_callback(() => updating_actor = false);
      }
      actordropselect.$set(actordropselect_changes);
      if (!current || dirty & /*actor*/
      4 && button0_disabled_value !== (button0_disabled_value = !/*actor*/
      ctx2[2])) {
        button0.disabled = button0_disabled_value;
      }
      if (!current || dirty & /*actualProgress*/
      64) {
        set_style(
          span,
          "width",
          /*actualProgress*/
          ctx2[6] + "%"
        );
      }
      if (!current || dirty & /*actualProgress*/
      64) {
        toggle_class(
          div1,
          "active",
          /*actualProgress*/
          ctx2[6] > 0
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(actordropselect.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(actordropselect.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      if_block0.d();
      if_block1.d();
      destroy_component(actordropselect);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_default_slot$1, "create_default_slot$1");
function create_fragment$2(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[15](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot$1] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const applicationshell_changes = {};
      if (dirty & /*$$scope, actualProgress, actor, actors, tradingUser, tradingActor, isPrivate*/
      8388734) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment$2, "create_fragment$2");
function instance$2($$self, $$props, $$invalidate) {
  let actualProgress;
  let $progress;
  const { application } = getContext("#external");
  let { elementRoot } = $$props;
  let { isPrivate } = $$props;
  let { tradingActor } = $$props;
  let { tradingUser } = $$props;
  let { users } = $$props;
  let { user } = $$props;
  let { actors } = $$props;
  let { actor } = $$props;
  let isGM = game.user.isGM;
  users = game.users.filter((user2) => user2.active && user2 !== game.user);
  user = user || users?.[0] || false;
  actors = actors || game.actors.filter((actor2) => actor2.isOwner);
  actor = actor || game.user.character || (!isGM ? actors?.[0] : false);
  let done = false;
  async function accept() {
    application.options.resolve(actor);
    close();
  }
  __name(accept, "accept");
  async function decline() {
    application.options.resolve(false);
    close();
  }
  __name(decline, "decline");
  async function mute() {
    application.options.resolve("mute");
    close();
  }
  __name(mute, "mute");
  async function disconnected() {
    custom_warning(game.i18n.localize("ITEM-PILES.Trade.Disconnected"), true);
    close();
  }
  __name(disconnected, "disconnected");
  const progress = tweened(0, { duration: 2e4, easing: identity });
  component_subscribe($$self, progress, (value) => $$invalidate(13, $progress = value));
  let timeout = setTimeout(
    () => {
      if (done)
        return;
      progress.set(1);
      timeout = setTimeout(
        () => {
          if (done)
            return;
          custom_warning(localize("ITEM-PILES.Trade.AutoDecline"), true);
          decline();
        },
        21e3
      );
    },
    14e3
  );
  const connection = setInterval(
    () => {
      const user2 = game.users.get(tradingUser.id);
      if (!user2.active) {
        disconnected();
      }
    },
    100
  );
  function close() {
    clearInterval(connection);
    clearTimeout(timeout);
    done = true;
    application.close();
  }
  __name(close, "close");
  function actordropselect_actor_binding(value) {
    actor = value;
    $$invalidate(2, actor);
  }
  __name(actordropselect_actor_binding, "actordropselect_actor_binding");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("isPrivate" in $$props2)
      $$invalidate(3, isPrivate = $$props2.isPrivate);
    if ("tradingActor" in $$props2)
      $$invalidate(4, tradingActor = $$props2.tradingActor);
    if ("tradingUser" in $$props2)
      $$invalidate(5, tradingUser = $$props2.tradingUser);
    if ("users" in $$props2)
      $$invalidate(11, users = $$props2.users);
    if ("user" in $$props2)
      $$invalidate(12, user = $$props2.user);
    if ("actors" in $$props2)
      $$invalidate(1, actors = $$props2.actors);
    if ("actor" in $$props2)
      $$invalidate(2, actor = $$props2.actor);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$progress*/
    8192) {
      $$invalidate(6, actualProgress = $progress * 100);
    }
  };
  return [
    elementRoot,
    actors,
    actor,
    isPrivate,
    tradingActor,
    tradingUser,
    actualProgress,
    accept,
    decline,
    mute,
    progress,
    users,
    user,
    $progress,
    actordropselect_actor_binding,
    applicationshell_elementRoot_binding
  ];
}
__name(instance$2, "instance$2");
const _Trade_dialog_request = class _Trade_dialog_request extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$2, create_fragment$2, safe_not_equal, {
      elementRoot: 0,
      isPrivate: 3,
      tradingActor: 4,
      tradingUser: 5,
      users: 11,
      user: 12,
      actors: 1,
      actor: 2
    });
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get isPrivate() {
    return this.$$.ctx[3];
  }
  set isPrivate(isPrivate) {
    this.$$set({ isPrivate });
    flush();
  }
  get tradingActor() {
    return this.$$.ctx[4];
  }
  set tradingActor(tradingActor) {
    this.$$set({ tradingActor });
    flush();
  }
  get tradingUser() {
    return this.$$.ctx[5];
  }
  set tradingUser(tradingUser) {
    this.$$set({ tradingUser });
    flush();
  }
  get users() {
    return this.$$.ctx[11];
  }
  set users(users) {
    this.$$set({ users });
    flush();
  }
  get user() {
    return this.$$.ctx[12];
  }
  set user(user) {
    this.$$set({ user });
    flush();
  }
  get actors() {
    return this.$$.ctx[1];
  }
  set actors(actors) {
    this.$$set({ actors });
    flush();
  }
  get actor() {
    return this.$$.ctx[2];
  }
  set actor(actor) {
    this.$$set({ actor });
    flush();
  }
};
__name(_Trade_dialog_request, "Trade_dialog_request");
let Trade_dialog_request = _Trade_dialog_request;
const _TradePromptDialog = class _TradePromptDialog extends SvelteApplication {
  constructor(tradeOptions, options = {}) {
    super({
      svelte: {
        class: Trade_dialog_prompt,
        target: document.body,
        props: {
          ...tradeOptions
        }
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Trade.Title"),
      width: 400,
      height: "auto",
      classes: ["dialog", "item-piles-app"]
    });
  }
  static show(tradeOptions, options = {}, dialogData = {}) {
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(tradeOptions, options, dialogData).render(true);
    });
  }
};
__name(_TradePromptDialog, "TradePromptDialog");
let TradePromptDialog = _TradePromptDialog;
const _TradeRequestDialog = class _TradeRequestDialog extends SvelteApplication {
  constructor(tradeOptions, options = {}) {
    super({
      svelte: {
        class: Trade_dialog_request,
        target: document.body,
        props: {
          ...tradeOptions
        }
      },
      close: () => this.options.resolve?.(null),
      ...options
    });
    this.tradeId = tradeOptions.tradeId;
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("ITEM-PILES.Trade.Title"),
      width: 400,
      height: "auto",
      classes: ["dialog"]
    });
  }
  static show(tradeOptions, options = {}) {
    return new Promise((resolve) => {
      options.resolve = resolve;
      new this(tradeOptions, options).render(true);
    });
  }
  static cancel(tradeId) {
    for (const app of Object.values(ui.windows)) {
      if (app instanceof this && app.tradeId === tradeId) {
        app.options.resolve({ type: "cancelled" });
        return app.close();
      }
    }
    return false;
  }
};
__name(_TradeRequestDialog, "TradeRequestDialog");
let TradeRequestDialog = _TradeRequestDialog;
const _TradeStore = class _TradeStore {
  constructor(instigator, leftTrader, rightTrader, publicTradeId, privateTradeId = false, isPrivate = false) {
    this.instigator = instigator;
    this.publicTradeId = publicTradeId;
    this.privateTradeId = privateTradeId;
    this.isPrivate = isPrivate;
    this.leftTraderUser = leftTrader.user;
    this.leftTraderActor = leftTrader.actor;
    this.leftTraderItems = writable$1(leftTrader.items ?? []);
    this.leftTraderCurrencies = writable$1(leftTrader.currencies ?? []);
    this.leftTraderItemCurrencies = writable$1(leftTrader.itemCurrencies ?? []);
    this.leftTraderAccepted = writable$1(leftTrader.accepted ?? false);
    this.rightTraderUser = rightTrader.user;
    this.rightTraderActor = rightTrader.actor;
    this.rightTraderItems = writable$1(rightTrader.items ?? []);
    this.rightTraderCurrencies = writable$1(rightTrader.currencies ?? []);
    this.rightTraderItemCurrencies = writable$1(rightTrader.itemCurrencies ?? []);
    this.rightTraderAccepted = writable$1(rightTrader?.accepted ?? false);
  }
  get isUserParticipant() {
    return game.user === this.leftTraderUser || game.user === this.rightTraderUser;
  }
  get tradeIsAccepted() {
    return get_store_value(this.leftTraderAccepted) && get_store_value(this.rightTraderAccepted);
  }
  static import(tradeData) {
    const leftTrader = {
      user: game.users.get(tradeData.leftTraderData.user),
      actor: fromUuidSync(tradeData.leftTraderData.actor),
      items: tradeData.leftTraderData.items,
      currencies: tradeData.leftTraderData.currencies,
      itemCurrencies: tradeData.leftTraderData.itemCurrencies,
      accepted: tradeData.leftTraderData.accepted
    };
    const rightTrader = {
      user: game.users.get(tradeData.rightTraderData.user),
      actor: fromUuidSync(tradeData.rightTraderData.actor),
      items: tradeData.rightTraderData.items,
      currencies: tradeData.rightTraderData.currencies,
      itemCurrencies: tradeData.rightTraderData.itemCurrencies,
      accepted: tradeData.rightTraderData.accepted
    };
    return new this(tradeData.instigator, leftTrader, rightTrader, tradeData.publicTradeId);
  }
  export() {
    return {
      instigator: this.instigator,
      publicTradeId: this.publicTradeId,
      leftTraderData: {
        user: this.leftTraderUser.id,
        actor: getUuid(this.leftTraderActor),
        items: get_store_value(this.leftTraderItems),
        currencies: get_store_value(this.leftTraderCurrencies),
        itemCurrencies: get_store_value(this.leftTraderItemCurrencies),
        accepted: get_store_value(this.leftTraderAccepted)
      },
      rightTraderData: {
        user: this.rightTraderUser.id,
        actor: getUuid(this.rightTraderActor),
        items: get_store_value(this.rightTraderItems),
        currencies: get_store_value(this.rightTraderCurrencies),
        itemCurrencies: get_store_value(this.rightTraderItemCurrencies),
        accepted: get_store_value(this.rightTraderAccepted)
      }
    };
  }
  getTradeData() {
    return {
      sourceActor: this.leftTraderActor,
      targetActor: this.rightTraderActor,
      remove: {
        items: get_store_value(this.leftTraderItems).concat(get_store_value(this.leftTraderItemCurrencies)),
        attributes: get_store_value(this.leftTraderCurrencies)
      },
      add: {
        items: get_store_value(this.rightTraderItems).concat(get_store_value(this.rightTraderItemCurrencies)),
        attributes: get_store_value(this.rightTraderCurrencies)
      }
    };
  }
  getExistingCurrencies() {
    return [...get_store_value(this.leftTraderCurrencies), ...get_store_value(this.leftTraderItemCurrencies)];
  }
  async toggleAccepted() {
    this.leftTraderAccepted.set(!get_store_value(this.leftTraderAccepted));
  }
  updateItems(userId, inItems) {
    if (userId === game.user.id)
      return;
    this.leftTraderAccepted.set(false);
    this.rightTraderAccepted.set(false);
    if (userId === this.leftTraderUser.id) {
      this.leftTraderItems.set(inItems);
    }
    if (userId === this.rightTraderUser.id) {
      this.rightTraderItems.set(inItems);
    }
  }
  updateItemCurrencies(userId, itemCurrencies) {
    if (userId === game.user.id)
      return;
    this.leftTraderAccepted.set(false);
    this.rightTraderAccepted.set(false);
    if (userId === this.leftTraderUser.id) {
      this.leftTraderItemCurrencies.set(itemCurrencies);
    }
    if (userId === this.rightTraderUser.id) {
      this.rightTraderItemCurrencies.set(itemCurrencies);
    }
  }
  updateCurrencies(userId, inCurrencies) {
    if (userId === game.user.id)
      return;
    this.leftTraderAccepted.set(false);
    this.rightTraderAccepted.set(false);
    if (userId === this.leftTraderUser.id) {
      this.leftTraderCurrencies.set(inCurrencies);
    }
    if (userId === this.rightTraderUser.id) {
      this.rightTraderCurrencies.set(inCurrencies);
    }
  }
  updateAcceptedState(userId, state) {
    if (userId === game.user.id)
      return;
    if (userId === this.leftTraderUser.id) {
      this.leftTraderAccepted.set(state);
    }
    if (userId === this.rightTraderUser.id) {
      this.rightTraderAccepted.set(state);
    }
  }
  addItem(newItem, { uuid = false, quantity = false, currency = false } = {}) {
    const items = !currency ? get_store_value(this.leftTraderItems) : get_store_value(this.leftTraderItemCurrencies);
    const item = findSimilarItem(items, newItem);
    const maxQuantity = game.user.isGM ? Infinity : getItemQuantity(newItem);
    if (item && canItemStack(item)) {
      if (item.quantity >= maxQuantity)
        return;
      if (quantity) {
        item.quantity = Math.min(quantity ? quantity : item.quantity + 1, maxQuantity);
        item.newQuantity = item.quantity;
        item.maxQuantity = maxQuantity;
      } else {
        items.splice(items.indexOf(item));
      }
    } else if (!item && quantity) {
      items.push({
        id: newItem._id ?? newItem.id,
        uuid,
        name: newItem.name,
        img: newItem?.img ?? "",
        type: newItem?.type,
        currency,
        quantity: quantity ? quantity : 1,
        newQuantity: quantity ? quantity : 1,
        maxQuantity,
        data: newItem instanceof Item ? newItem.toObject() : newItem
      });
    }
    if (!currency) {
      this.leftTraderItems.set(items);
    } else {
      this.leftTraderItemCurrencies.set(items);
    }
  }
  addAttribute(newCurrency) {
    const currencies = get_store_value(this.leftTraderCurrencies);
    const existingCurrency = currencies.find((currency) => currency.path === newCurrency.path);
    if (existingCurrency) {
      existingCurrency.quantity = newCurrency.quantity;
      existingCurrency.newQuantity = newCurrency.quantity;
    } else {
      currencies.push(newCurrency);
    }
    currencies.sort((a, b) => a.index - b.index);
    this.leftTraderCurrencies.set(currencies);
  }
  removeEntry(entry) {
    if (entry.id) {
      if (!entry.currency) {
        const items = get_store_value(this.leftTraderItems).filter((item) => item.id !== entry.id);
        this.leftTraderItems.set(items);
      } else {
        const items = get_store_value(this.leftTraderItemCurrencies).filter((item) => item.id !== entry.id);
        this.leftTraderItemCurrencies.set(items);
      }
    } else {
      const items = get_store_value(this.leftTraderCurrencies).filter((currency) => currency.path !== entry.path);
      this.leftTraderCurrencies.set(items);
    }
  }
};
__name(_TradeStore, "TradeStore");
let TradeStore = _TradeStore;
function create_if_block_4$1(ctx) {
  let div;
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      a = element("a");
      a.innerHTML = `<i class="fas fa-times"></i>`;
      attr(a, "class", "item-piles-clickable-red");
      set_style(div, "flex", "0 1 auto");
      set_style(div, "margin", "0 6px");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, a);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler_1*/
          ctx[8]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4$1, "create_if_block_4$1");
function create_if_block_2$1(ctx) {
  let div;
  let if_block = (
    /*data*/
    ctx[0].editing && create_if_block_3$1(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block)
        if_block.c();
      set_style(div, "flex", "0 1 17px");
      set_style(div, "margin", "0 5px");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block)
        if_block.m(div, null);
    },
    p(ctx2, dirty) {
      if (
        /*data*/
        ctx2[0].editing
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_3$1(ctx2);
          if_block.c();
          if_block.m(div, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
    }
  };
}
__name(create_if_block_2$1, "create_if_block_2$1");
function create_if_block_3$1(ctx) {
  let a;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.innerHTML = `<i class="fas fa-check"></i>`;
      attr(a, "class", "item-piles-clickable-green item-piles-confirm-quantity");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*updateQuantity*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_3$1, "create_if_block_3$1");
function create_else_block_1(ctx) {
  let span;
  let t_value = (
    /*data*/
    ctx[0].quantity + ""
  );
  let t;
  return {
    c() {
      span = element("span");
      t = text(t_value);
      attr(span, "class", "item-piles-text");
      set_style(span, "padding-right", "0.5rem");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*data*/
      1 && t_value !== (t_value = /*data*/
      ctx2[0].quantity + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
__name(create_else_block_1, "create_else_block_1");
function create_if_block$1(ctx) {
  let div;
  function select_block_type_1(ctx2, dirty) {
    if (
      /*data*/
      ctx2[0].editing
    )
      return create_if_block_1$1;
    return create_else_block$1;
  }
  __name(select_block_type_1, "select_block_type_1");
  let current_block_type = select_block_type_1(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      if_block.c();
      attr(div, "class", "item-piles-quantity-container");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if_block.m(div, null);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(div, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if_block.d();
    }
  };
}
__name(create_if_block$1, "create_if_block$1");
function create_else_block$1(ctx) {
  let span;
  let t_value = (
    /*data*/
    ctx[0].quantity + ""
  );
  let t;
  let mounted;
  let dispose;
  return {
    c() {
      span = element("span");
      t = text(t_value);
      attr(span, "class", "item-piles-quantity-text");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*click_handler_2*/
          ctx[10]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*data*/
      1 && t_value !== (t_value = /*data*/
      ctx2[0].quantity + ""))
        set_data(t, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(span);
      mounted = false;
      dispose();
    }
  };
}
__name(create_else_block$1, "create_else_block$1");
function create_if_block_1$1(ctx) {
  let div;
  let input;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      input = element("input");
      attr(input, "class", "item-piles-quantity");
      attr(input, "type", "number");
      attr(div, "class", "item-piles-quantity-input-container");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*data*/
        ctx[0].newQuantity
      );
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx[9]
          ),
          listen(
            input,
            "keydown",
            /*onKeyDown*/
            ctx[5]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*data*/
      1 && to_number(input.value) !== /*data*/
      ctx2[0].newQuantity) {
        set_input_value(
          input,
          /*data*/
          ctx2[0].newQuantity
        );
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_if_block_1$1, "create_if_block_1$1");
function create_fragment$1(ctx) {
  let div4;
  let t0;
  let div0;
  let img;
  let img_src_value;
  let t1;
  let div2;
  let div1;
  let p;
  let t2_value = (
    /*data*/
    ctx[0].name + ""
  );
  let t2;
  let t3;
  let t4;
  let div3;
  let mounted;
  let dispose;
  let if_block0 = (
    /*editable*/
    ctx[2] && create_if_block_4$1(ctx)
  );
  let if_block1 = (
    /*editable*/
    ctx[2] && create_if_block_2$1(ctx)
  );
  function select_block_type(ctx2, dirty) {
    if (
      /*editable*/
      ctx2[2]
    )
      return create_if_block$1;
    return create_else_block_1;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block2 = current_block_type(ctx);
  return {
    c() {
      div4 = element("div");
      if (if_block0)
        if_block0.c();
      t0 = space();
      div0 = element("div");
      img = element("img");
      t1 = space();
      div2 = element("div");
      div1 = element("div");
      p = element("p");
      t2 = text(t2_value);
      t3 = space();
      if (if_block1)
        if_block1.c();
      t4 = space();
      div3 = element("div");
      if_block2.c();
      attr(img, "class", "item-piles-img");
      if (!src_url_equal(img.src, img_src_value = /*data*/
      ctx[0].img))
        attr(img, "src", img_src_value);
      attr(div0, "class", "item-piles-img-container");
      toggle_class(
        p,
        "item-piles-clickable-link",
        /*canPreview*/
        ctx[3]
      );
      attr(div1, "class", "item-piles-name-container");
      attr(div2, "class", "item-piles-name item-piles-text");
      attr(div3, "class", "item-piles-text-right");
      toggle_class(
        div3,
        "item-piles-quantity-container",
        /*editable*/
        ctx[2]
      );
      attr(div4, "class", "item-piles-flexrow item-piles-item-row item-piles-even-color");
    },
    m(target, anchor) {
      insert(target, div4, anchor);
      if (if_block0)
        if_block0.m(div4, null);
      append(div4, t0);
      append(div4, div0);
      append(div0, img);
      append(div4, t1);
      append(div4, div2);
      append(div2, div1);
      append(div1, p);
      append(p, t2);
      append(div4, t3);
      if (if_block1)
        if_block1.m(div4, null);
      append(div4, t4);
      append(div4, div3);
      if_block2.m(div3, null);
      if (!mounted) {
        dispose = [
          listen(
            window,
            "click",
            /*click_handler*/
            ctx[7]
          ),
          listen(
            p,
            "click",
            /*previewItem*/
            ctx[4]
          ),
          listen(div3, "click", click_handler_3)
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (
        /*editable*/
        ctx2[2]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_4$1(ctx2);
          if_block0.c();
          if_block0.m(div4, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty & /*data*/
      1 && !src_url_equal(img.src, img_src_value = /*data*/
      ctx2[0].img)) {
        attr(img, "src", img_src_value);
      }
      if (dirty & /*data*/
      1 && t2_value !== (t2_value = /*data*/
      ctx2[0].name + ""))
        set_data(t2, t2_value);
      if (
        /*editable*/
        ctx2[2]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_2$1(ctx2);
          if_block1.c();
          if_block1.m(div4, t4);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block2) {
        if_block2.p(ctx2, dirty);
      } else {
        if_block2.d(1);
        if_block2 = current_block_type(ctx2);
        if (if_block2) {
          if_block2.c();
          if_block2.m(div3, null);
        }
      }
      if (dirty & /*editable*/
      4) {
        toggle_class(
          div3,
          "item-piles-quantity-container",
          /*editable*/
          ctx2[2]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div4);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if_block2.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
__name(create_fragment$1, "create_fragment$1");
const click_handler_3 = /* @__PURE__ */ __name((evt) => evt.stopPropagation(), "click_handler_3");
function instance$1($$self, $$props, $$invalidate) {
  let { store } = $$props;
  let { data: data2 } = $$props;
  let { editable = true } = $$props;
  const canPreview = data2.id && (getSetting(SETTINGS$1.INSPECT_ITEMS_IN_TRADE) || editable);
  function previewItem2() {
    if (!canPreview || !data2.id)
      return;
    const item = store.leftTraderActor.items.get(data2.id) ?? store.rightTraderActor.items.get(data2.id);
    if (!item)
      return;
    if (game.user.isGM || item.ownership[game.user.id] === CONST.DOCUMENT_PERMISSION_LEVELS.OWNER) {
      return item.sheet.render(true);
    }
    const cls = item._getSheetClass();
    const sheet = new cls(item, { editable: false });
    return sheet._render(true);
  }
  __name(previewItem2, "previewItem");
  function onKeyDown(e) {
    if (e.keyCode === 13) {
      updateQuantity();
    }
  }
  __name(onKeyDown, "onKeyDown");
  function updateQuantity() {
    $$invalidate(0, data2.quantity = Math.max(0, Math.min(data2.maxQuantity, data2.newQuantity)), data2);
    if (data2.quantity === 0) {
      return store.removeEntry(data2);
    }
    $$invalidate(0, data2.newQuantity = data2.quantity, data2);
    $$invalidate(0, data2.editing = false, data2);
  }
  __name(updateQuantity, "updateQuantity");
  const click_handler = /* @__PURE__ */ __name(() => {
    if (data2.editing && editable)
      updateQuantity();
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    store.removeEntry(data2);
  }, "click_handler_1");
  function input_input_handler() {
    data2.newQuantity = to_number(this.value);
    $$invalidate(0, data2);
  }
  __name(input_input_handler, "input_input_handler");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    $$invalidate(0, data2.editing = true, data2);
  }, "click_handler_2");
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$invalidate(1, store = $$props2.store);
    if ("data" in $$props2)
      $$invalidate(0, data2 = $$props2.data);
    if ("editable" in $$props2)
      $$invalidate(2, editable = $$props2.editable);
  };
  return [
    data2,
    store,
    editable,
    canPreview,
    previewItem2,
    onKeyDown,
    updateQuantity,
    click_handler,
    click_handler_1,
    input_input_handler,
    click_handler_2
  ];
}
__name(instance$1, "instance$1");
const _TradeEntry = class _TradeEntry extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$1, create_fragment$1, safe_not_equal, { store: 1, data: 0, editable: 2 });
  }
};
__name(_TradeEntry, "TradeEntry");
let TradeEntry = _TradeEntry;
const tradingAppShell_svelte_svelte_type_style_lang = "";
function get_each_context(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[34] = list;
  child_ctx[35] = i;
  return child_ctx;
}
__name(get_each_context, "get_each_context");
function get_each_context_1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[36] = list[i];
  child_ctx[37] = list;
  child_ctx[38] = i;
  return child_ctx;
}
__name(get_each_context_1, "get_each_context_1");
function get_each_context_2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[39] = list;
  child_ctx[40] = i;
  return child_ctx;
}
__name(get_each_context_2, "get_each_context_2");
function get_each_context_3(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[41] = list;
  child_ctx[42] = i;
  return child_ctx;
}
__name(get_each_context_3, "get_each_context_3");
function get_each_context_4(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[36] = list[i];
  child_ctx[43] = list;
  child_ctx[44] = i;
  return child_ctx;
}
__name(get_each_context_4, "get_each_context_4");
function get_each_context_5(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  child_ctx[45] = list;
  child_ctx[46] = i;
  return child_ctx;
}
__name(get_each_context_5, "get_each_context_5");
function create_if_block_7(ctx) {
  let div4;
  let div4_transition;
  let current;
  return {
    c() {
      div4 = element("div");
      div4.innerHTML = `<div class="svelte-3zgsgo"></div> 
			<div class="svelte-3zgsgo"></div> 
			<div class="svelte-3zgsgo"></div> 
			<div class="svelte-3zgsgo"></div>`;
      attr(div4, "class", "lds-ellipsis svelte-3zgsgo");
    },
    m(target, anchor) {
      insert(target, div4, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      add_render_callback(() => {
        if (!current)
          return;
        if (!div4_transition)
          div4_transition = create_bidirectional_transition(div4, fade, {}, true);
        div4_transition.run(1);
      });
      current = true;
    },
    o(local) {
      if (!div4_transition)
        div4_transition = create_bidirectional_transition(div4, fade, {}, false);
      div4_transition.run(0);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div4);
      if (detaching && div4_transition)
        div4_transition.end();
    }
  };
}
__name(create_if_block_7, "create_if_block_7");
function create_if_block_6(ctx) {
  let div;
  let h3;
  return {
    c() {
      div = element("div");
      h3 = element("h3");
      h3.textContent = `${localize("ITEM-PILES.Trade.DragDrop")}`;
      attr(h3, "class", "item-piles-text-center");
      attr(div, "class", "item-piles-flexcol");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, h3);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
__name(create_if_block_6, "create_if_block_6");
function create_each_block_5(key_1, ctx) {
  let first;
  let tradeentry;
  let updating_data;
  let current;
  function tradeentry_data_binding(value) {
    ctx[22](
      value,
      /*item*/
      ctx[33],
      /*each_value_5*/
      ctx[45],
      /*item_index_3*/
      ctx[46]
    );
  }
  __name(tradeentry_data_binding, "tradeentry_data_binding");
  let tradeentry_props = {
    store: (
      /*store*/
      ctx[1]
    ),
    editable: (
      /*store*/
      ctx[1].isUserParticipant
    )
  };
  if (
    /*item*/
    ctx[33] !== void 0
  ) {
    tradeentry_props.data = /*item*/
    ctx[33];
  }
  tradeentry = new TradeEntry({ props: tradeentry_props });
  binding_callbacks.push(() => bind(tradeentry, "data", tradeentry_data_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tradeentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tradeentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tradeentry_changes = {};
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.store = /*store*/
        ctx[1];
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.editable = /*store*/
        ctx[1].isUserParticipant;
      if (!updating_data && dirty[0] & /*$leftItems*/
      16) {
        updating_data = true;
        tradeentry_changes.data = /*item*/
        ctx[33];
        add_flush_callback(() => updating_data = false);
      }
      tradeentry.$set(tradeentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tradeentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tradeentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(tradeentry, detaching);
    }
  };
}
__name(create_each_block_5, "create_each_block_5");
function create_if_block_3(ctx) {
  let div;
  let t0;
  let each_blocks_1 = [];
  let each0_lookup = /* @__PURE__ */ new Map();
  let t1;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let current;
  let if_block = (
    /*store*/
    ctx[1].isUserParticipant && create_if_block_4(ctx)
  );
  let each_value_4 = (
    /*$leftCurrencies*/
    ctx[5]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*currency*/
    ctx2[36].path
  ), "get_key");
  for (let i = 0; i < each_value_4.length; i += 1) {
    let child_ctx = get_each_context_4(ctx, each_value_4, i);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_1[i] = create_each_block_4(key, child_ctx));
  }
  let each_value_3 = (
    /*$leftItemCurrencies*/
    ctx[6]
  );
  const get_key_1 = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[33].id
  ), "get_key_1");
  for (let i = 0; i < each_value_3.length; i += 1) {
    let child_ctx = get_each_context_3(ctx, each_value_3, i);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block_3(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      if (if_block)
        if_block.c();
      t0 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t1 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "row item-piles-items-list item-piles-currency-list svelte-3zgsgo");
      toggle_class(
        div,
        "item-piles-top-divider",
        /*$leftCurrencies*/
        ctx[5].length || /*$leftItemCurrencies*/
        ctx[6].length
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block)
        if_block.m(div, null);
      append(div, t0);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div, null);
        }
      }
      append(div, t1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*store*/
        ctx2[1].isUserParticipant
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_4(ctx2);
          if_block.c();
          if_block.m(div, t0);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty[0] & /*store, $leftCurrencies*/
      34) {
        each_value_4 = /*$leftCurrencies*/
        ctx2[5];
        group_outros();
        each_blocks_1 = update_keyed_each(each_blocks_1, dirty, get_key, 1, ctx2, each_value_4, each0_lookup, div, outro_and_destroy_block, create_each_block_4, t1, get_each_context_4);
        check_outros();
      }
      if (dirty[0] & /*store, $leftItemCurrencies*/
      66) {
        each_value_3 = /*$leftItemCurrencies*/
        ctx2[6];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_1, 1, ctx2, each_value_3, each1_lookup, div, outro_and_destroy_block, create_each_block_3, null, get_each_context_3);
        check_outros();
      }
      if (!current || dirty[0] & /*$leftCurrencies, $leftItemCurrencies*/
      96) {
        toggle_class(
          div,
          "item-piles-top-divider",
          /*$leftCurrencies*/
          ctx2[5].length || /*$leftItemCurrencies*/
          ctx2[6].length
        );
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_4.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value_3.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].d();
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_if_block_3, "create_if_block_3");
function create_if_block_4(ctx) {
  let div;
  let t0;
  let a;
  let i;
  let t1;
  let t2_value = localize("ITEM-PILES.Inspect.AddCurrency") + "";
  let t2;
  let mounted;
  let dispose;
  let if_block = (
    /*isGM*/
    ctx[18] && create_if_block_5(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block)
        if_block.c();
      t0 = space();
      a = element("a");
      i = element("i");
      t1 = space();
      t2 = text(t2_value);
      attr(i, "class", "fas fa-plus");
      attr(a, "class", "item-piles-text-right item-piles-small-text item-piles-middle item-piles-add-currency");
      attr(div, "class", "item-piles-flexrow");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block)
        if_block.m(div, null);
      append(div, t0);
      append(div, a);
      append(a, i);
      append(a, t1);
      append(a, t2);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler_1*/
          ctx[24]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*isGM*/
        ctx2[18]
      )
        if_block.p(ctx2, dirty);
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_4, "create_if_block_4");
function create_if_block_5(ctx) {
  let a;
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Trade.GMAddCurrency") + "";
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-plus");
      attr(a, "class", "item-piles-text-right item-piles-small-text item-piles-middle item-piles-gm-add-currency");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, i);
      append(a, t0);
      append(a, t1);
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*click_handler*/
          ctx[23]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_5, "create_if_block_5");
function create_each_block_4(key_1, ctx) {
  let first;
  let tradeentry;
  let updating_data;
  let current;
  function tradeentry_data_binding_1(value) {
    ctx[25](
      value,
      /*currency*/
      ctx[36],
      /*each_value_4*/
      ctx[43],
      /*currency_index_1*/
      ctx[44]
    );
  }
  __name(tradeentry_data_binding_1, "tradeentry_data_binding_1");
  let tradeentry_props = {
    store: (
      /*store*/
      ctx[1]
    ),
    editable: (
      /*store*/
      ctx[1].isUserParticipant
    )
  };
  if (
    /*currency*/
    ctx[36] !== void 0
  ) {
    tradeentry_props.data = /*currency*/
    ctx[36];
  }
  tradeentry = new TradeEntry({ props: tradeentry_props });
  binding_callbacks.push(() => bind(tradeentry, "data", tradeentry_data_binding_1));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tradeentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tradeentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tradeentry_changes = {};
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.store = /*store*/
        ctx[1];
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.editable = /*store*/
        ctx[1].isUserParticipant;
      if (!updating_data && dirty[0] & /*$leftCurrencies*/
      32) {
        updating_data = true;
        tradeentry_changes.data = /*currency*/
        ctx[36];
        add_flush_callback(() => updating_data = false);
      }
      tradeentry.$set(tradeentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tradeentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tradeentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(tradeentry, detaching);
    }
  };
}
__name(create_each_block_4, "create_each_block_4");
function create_each_block_3(key_1, ctx) {
  let first;
  let tradeentry;
  let updating_data;
  let current;
  function tradeentry_data_binding_2(value) {
    ctx[26](
      value,
      /*item*/
      ctx[33],
      /*each_value_3*/
      ctx[41],
      /*item_index_2*/
      ctx[42]
    );
  }
  __name(tradeentry_data_binding_2, "tradeentry_data_binding_2");
  let tradeentry_props = {
    store: (
      /*store*/
      ctx[1]
    ),
    editable: (
      /*store*/
      ctx[1].isUserParticipant
    )
  };
  if (
    /*item*/
    ctx[33] !== void 0
  ) {
    tradeentry_props.data = /*item*/
    ctx[33];
  }
  tradeentry = new TradeEntry({ props: tradeentry_props });
  binding_callbacks.push(() => bind(tradeentry, "data", tradeentry_data_binding_2));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tradeentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tradeentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tradeentry_changes = {};
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.store = /*store*/
        ctx[1];
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.editable = /*store*/
        ctx[1].isUserParticipant;
      if (!updating_data && dirty[0] & /*$leftItemCurrencies*/
      64) {
        updating_data = true;
        tradeentry_changes.data = /*item*/
        ctx[33];
        add_flush_callback(() => updating_data = false);
      }
      tradeentry.$set(tradeentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tradeentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tradeentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(tradeentry, detaching);
    }
  };
}
__name(create_each_block_3, "create_each_block_3");
function create_if_block_1(ctx) {
  let button;
  let mounted;
  let dispose;
  function select_block_type(ctx2, dirty) {
    if (
      /*$leftTraderAccepted*/
      ctx2[2]
    )
      return create_if_block_2;
    return create_else_block;
  }
  __name(select_block_type, "select_block_type");
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      button = element("button");
      if_block.c();
      attr(button, "type", "button");
      set_style(button, "flex", "0 1 auto");
      set_style(button, "margin-top", "0.25rem");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if_block.m(button, null);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_2*/
          ctx[27]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(button, null);
        }
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      if_block.d();
      mounted = false;
      dispose();
    }
  };
}
__name(create_if_block_1, "create_if_block_1");
function create_else_block(ctx) {
  let i;
  let t0;
  let t1_value = localize("ITEM-PILES.Trade.Accept") + "";
  let t1;
  return {
    c() {
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-check");
    },
    m(target, anchor) {
      insert(target, i, anchor);
      insert(target, t0, anchor);
      insert(target, t1, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(i);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(t1);
    }
  };
}
__name(create_else_block, "create_else_block");
function create_if_block_2(ctx) {
  let i;
  let t0;
  let t1_value = localize("Cancel") + "";
  let t1;
  return {
    c() {
      i = element("i");
      t0 = space();
      t1 = text(t1_value);
      attr(i, "class", "fas fa-times");
    },
    m(target, anchor) {
      insert(target, i, anchor);
      insert(target, t0, anchor);
      insert(target, t1, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(i);
      if (detaching)
        detach(t0);
      if (detaching)
        detach(t1);
    }
  };
}
__name(create_if_block_2, "create_if_block_2");
function create_each_block_2(key_1, ctx) {
  let first;
  let tradeentry;
  let updating_data;
  let current;
  function tradeentry_data_binding_3(value) {
    ctx[28](
      value,
      /*item*/
      ctx[33],
      /*each_value_2*/
      ctx[39],
      /*item_index_1*/
      ctx[40]
    );
  }
  __name(tradeentry_data_binding_3, "tradeentry_data_binding_3");
  let tradeentry_props = { store: (
    /*store*/
    ctx[1]
  ), editable: false };
  if (
    /*item*/
    ctx[33] !== void 0
  ) {
    tradeentry_props.data = /*item*/
    ctx[33];
  }
  tradeentry = new TradeEntry({ props: tradeentry_props });
  binding_callbacks.push(() => bind(tradeentry, "data", tradeentry_data_binding_3));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tradeentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tradeentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tradeentry_changes = {};
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.store = /*store*/
        ctx[1];
      if (!updating_data && dirty[0] & /*$rightItems*/
      128) {
        updating_data = true;
        tradeentry_changes.data = /*item*/
        ctx[33];
        add_flush_callback(() => updating_data = false);
      }
      tradeentry.$set(tradeentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tradeentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tradeentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(tradeentry, detaching);
    }
  };
}
__name(create_each_block_2, "create_each_block_2");
function create_if_block(ctx) {
  let div;
  let each_blocks_1 = [];
  let each0_lookup = /* @__PURE__ */ new Map();
  let t;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let current;
  let each_value_1 = (
    /*$rightCurrencies*/
    ctx[8]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*currency*/
    ctx2[36].path
  ), "get_key");
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_1[i] = create_each_block_1(key, child_ctx));
  }
  let each_value = (
    /*$rightItemCurrencies*/
    ctx[9]
  );
  const get_key_1 = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[33].id
  ), "get_key_1");
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context(ctx, each_value, i);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block(key, child_ctx));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "row item-piles-items-list item-piles-currency-list svelte-3zgsgo");
      toggle_class(
        div,
        "item-piles-top-divider",
        /*$rightCurrencies*/
        ctx[8].length || /*$rightItemCurrencies*/
        ctx[9].length
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div, null);
        }
      }
      append(div, t);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*store, $rightCurrencies*/
      258) {
        each_value_1 = /*$rightCurrencies*/
        ctx2[8];
        group_outros();
        each_blocks_1 = update_keyed_each(each_blocks_1, dirty, get_key, 1, ctx2, each_value_1, each0_lookup, div, outro_and_destroy_block, create_each_block_1, t, get_each_context_1);
        check_outros();
      }
      if (dirty[0] & /*store, $rightItemCurrencies*/
      514) {
        each_value = /*$rightItemCurrencies*/
        ctx2[9];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_1, 1, ctx2, each_value, each1_lookup, div, outro_and_destroy_block, create_each_block, null, get_each_context);
        check_outros();
      }
      if (!current || dirty[0] & /*$rightCurrencies, $rightItemCurrencies*/
      768) {
        toggle_class(
          div,
          "item-piles-top-divider",
          /*$rightCurrencies*/
          ctx2[8].length || /*$rightItemCurrencies*/
          ctx2[9].length
        );
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].d();
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
__name(create_if_block, "create_if_block");
function create_each_block_1(key_1, ctx) {
  let first;
  let tradeentry;
  let updating_data;
  let current;
  function tradeentry_data_binding_4(value) {
    ctx[29](
      value,
      /*currency*/
      ctx[36],
      /*each_value_1*/
      ctx[37],
      /*currency_index*/
      ctx[38]
    );
  }
  __name(tradeentry_data_binding_4, "tradeentry_data_binding_4");
  let tradeentry_props = { store: (
    /*store*/
    ctx[1]
  ), editable: false };
  if (
    /*currency*/
    ctx[36] !== void 0
  ) {
    tradeentry_props.data = /*currency*/
    ctx[36];
  }
  tradeentry = new TradeEntry({ props: tradeentry_props });
  binding_callbacks.push(() => bind(tradeentry, "data", tradeentry_data_binding_4));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tradeentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tradeentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tradeentry_changes = {};
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.store = /*store*/
        ctx[1];
      if (!updating_data && dirty[0] & /*$rightCurrencies*/
      256) {
        updating_data = true;
        tradeentry_changes.data = /*currency*/
        ctx[36];
        add_flush_callback(() => updating_data = false);
      }
      tradeentry.$set(tradeentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tradeentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tradeentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(tradeentry, detaching);
    }
  };
}
__name(create_each_block_1, "create_each_block_1");
function create_each_block(key_1, ctx) {
  let first;
  let tradeentry;
  let updating_data;
  let current;
  function tradeentry_data_binding_5(value) {
    ctx[30](
      value,
      /*item*/
      ctx[33],
      /*each_value*/
      ctx[34],
      /*item_index*/
      ctx[35]
    );
  }
  __name(tradeentry_data_binding_5, "tradeentry_data_binding_5");
  let tradeentry_props = { store: (
    /*store*/
    ctx[1]
  ), editable: false };
  if (
    /*item*/
    ctx[33] !== void 0
  ) {
    tradeentry_props.data = /*item*/
    ctx[33];
  }
  tradeentry = new TradeEntry({ props: tradeentry_props });
  binding_callbacks.push(() => bind(tradeentry, "data", tradeentry_data_binding_5));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tradeentry.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tradeentry, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tradeentry_changes = {};
      if (dirty[0] & /*store*/
      2)
        tradeentry_changes.store = /*store*/
        ctx[1];
      if (!updating_data && dirty[0] & /*$rightItemCurrencies*/
      512) {
        updating_data = true;
        tradeentry_changes.data = /*item*/
        ctx[33];
        add_flush_callback(() => updating_data = false);
      }
      tradeentry.$set(tradeentry_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(tradeentry.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tradeentry.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(first);
      destroy_component(tradeentry, detaching);
    }
  };
}
__name(create_each_block, "create_each_block");
function create_default_slot_1(ctx) {
  let div12;
  let div11;
  let div5;
  let div2;
  let img0;
  let img0_src_value;
  let t0;
  let h20;
  let div0;
  let t1_value = (
    /*store*/
    ctx[1].leftTraderActor.name + ""
  );
  let t1;
  let t2;
  let div1;
  let i0;
  let t3;
  let div4;
  let div3;
  let t4;
  let each_blocks_1 = [];
  let each0_lookup = /* @__PURE__ */ new Map();
  let t5;
  let t6;
  let t7;
  let div10;
  let div7;
  let div6;
  let i1;
  let t8;
  let h21;
  let t9_value = (
    /*store*/
    ctx[1].rightTraderActor.name + ""
  );
  let t9;
  let t10;
  let img1;
  let img1_src_value;
  let t11;
  let div9;
  let div8;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let t12;
  let current;
  let if_block0 = !/*$leftItems*/
  ctx[4].length && /*store*/
  ctx[1].isUserParticipant && create_if_block_6();
  let each_value_5 = (
    /*$leftItems*/
    ctx[4]
  );
  const get_key = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[33].id
  ), "get_key");
  for (let i = 0; i < each_value_5.length; i += 1) {
    let child_ctx = get_each_context_5(ctx, each_value_5, i);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_1[i] = create_each_block_5(key, child_ctx));
  }
  let if_block1 = (
    /*systemHasCurrencies*/
    ctx[19] && create_if_block_3(ctx)
  );
  let if_block2 = (
    /*store*/
    ctx[1].isUserParticipant && create_if_block_1(ctx)
  );
  let each_value_2 = (
    /*$rightItems*/
    ctx[7]
  );
  const get_key_1 = /* @__PURE__ */ __name((ctx2) => (
    /*item*/
    ctx2[33].id
  ), "get_key_1");
  for (let i = 0; i < each_value_2.length; i += 1) {
    let child_ctx = get_each_context_2(ctx, each_value_2, i);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block_2(key, child_ctx));
  }
  let if_block3 = (
    /*systemHasCurrencies*/
    ctx[19] && create_if_block(ctx)
  );
  return {
    c() {
      div12 = element("div");
      div11 = element("div");
      div5 = element("div");
      div2 = element("div");
      img0 = element("img");
      t0 = space();
      h20 = element("h2");
      div0 = element("div");
      t1 = text(t1_value);
      t2 = space();
      div1 = element("div");
      i0 = element("i");
      t3 = space();
      div4 = element("div");
      div3 = element("div");
      if (if_block0)
        if_block0.c();
      t4 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t5 = space();
      if (if_block1)
        if_block1.c();
      t6 = space();
      if (if_block2)
        if_block2.c();
      t7 = space();
      div10 = element("div");
      div7 = element("div");
      div6 = element("div");
      i1 = element("i");
      t8 = space();
      h21 = element("h2");
      t9 = text(t9_value);
      t10 = space();
      img1 = element("img");
      t11 = space();
      div9 = element("div");
      div8 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t12 = space();
      if (if_block3)
        if_block3.c();
      if (!src_url_equal(img0.src, img0_src_value = /*store*/
      ctx[1].leftTraderActor.img))
        attr(img0, "src", img0_src_value);
      attr(h20, "class", "item-piles-character-name");
      attr(i0, "class", "fas accepted-icon");
      toggle_class(
        i0,
        "accepted",
        /*$leftTraderAccepted*/
        ctx[2]
      );
      toggle_class(
        i0,
        "fa-user-check",
        /*$leftTraderAccepted*/
        ctx[2]
      );
      toggle_class(i0, "fa-user-times", !/*$leftTraderAccepted*/
      ctx[2]);
      attr(div2, "class", "item-piles-character-header item-piles-bottom-divider");
      attr(div3, "class", "row item-piles-items-list svelte-3zgsgo");
      attr(div4, "class", "item-piles-flexcol");
      attr(div5, "class", "col item-piles-flexcol svelte-3zgsgo");
      attr(i1, "class", "fas accepted-icon");
      toggle_class(
        i1,
        "accepted",
        /*$rightTraderAccepted*/
        ctx[3]
      );
      toggle_class(
        i1,
        "fa-user-check",
        /*$rightTraderAccepted*/
        ctx[3]
      );
      toggle_class(i1, "fa-user-times", !/*$rightTraderAccepted*/
      ctx[3]);
      attr(h21, "class", "item-piles-character-name");
      if (!src_url_equal(img1.src, img1_src_value = /*store*/
      ctx[1].rightTraderActor.img))
        attr(img1, "src", img1_src_value);
      attr(div7, "class", "item-piles-character-header trader item-piles-bottom-divider");
      attr(div8, "class", "row item-piles-items-list svelte-3zgsgo");
      attr(div9, "class", "item-piles-flexcol");
      attr(div10, "class", "col item-piles-flexcol svelte-3zgsgo");
      attr(div11, "class", "item-piles-flexrow");
      attr(div12, "class", "item-piles-flexcol");
    },
    m(target, anchor) {
      insert(target, div12, anchor);
      append(div12, div11);
      append(div11, div5);
      append(div5, div2);
      append(div2, img0);
      append(div2, t0);
      append(div2, h20);
      append(h20, div0);
      append(div0, t1);
      append(div2, t2);
      append(div2, div1);
      append(div1, i0);
      append(div5, t3);
      append(div5, div4);
      append(div4, div3);
      if (if_block0)
        if_block0.m(div3, null);
      append(div3, t4);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div3, null);
        }
      }
      append(div4, t5);
      if (if_block1)
        if_block1.m(div4, null);
      append(div5, t6);
      if (if_block2)
        if_block2.m(div5, null);
      append(div11, t7);
      append(div11, div10);
      append(div10, div7);
      append(div7, div6);
      append(div6, i1);
      append(div7, t8);
      append(div7, h21);
      append(h21, t9);
      append(div7, t10);
      append(div7, img1);
      append(div10, t11);
      append(div10, div9);
      append(div9, div8);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div8, null);
        }
      }
      append(div9, t12);
      if (if_block3)
        if_block3.m(div9, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (!current || dirty[0] & /*store*/
      2 && !src_url_equal(img0.src, img0_src_value = /*store*/
      ctx2[1].leftTraderActor.img)) {
        attr(img0, "src", img0_src_value);
      }
      if ((!current || dirty[0] & /*store*/
      2) && t1_value !== (t1_value = /*store*/
      ctx2[1].leftTraderActor.name + ""))
        set_data(t1, t1_value);
      if (!current || dirty[0] & /*$leftTraderAccepted*/
      4) {
        toggle_class(
          i0,
          "accepted",
          /*$leftTraderAccepted*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*$leftTraderAccepted*/
      4) {
        toggle_class(
          i0,
          "fa-user-check",
          /*$leftTraderAccepted*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*$leftTraderAccepted*/
      4) {
        toggle_class(i0, "fa-user-times", !/*$leftTraderAccepted*/
        ctx2[2]);
      }
      if (!/*$leftItems*/
      ctx2[4].length && /*store*/
      ctx2[1].isUserParticipant) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_6();
          if_block0.c();
          if_block0.m(div3, t4);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty[0] & /*store, $leftItems*/
      18) {
        each_value_5 = /*$leftItems*/
        ctx2[4];
        group_outros();
        each_blocks_1 = update_keyed_each(each_blocks_1, dirty, get_key, 1, ctx2, each_value_5, each0_lookup, div3, outro_and_destroy_block, create_each_block_5, null, get_each_context_5);
        check_outros();
      }
      if (
        /*systemHasCurrencies*/
        ctx2[19]
      )
        if_block1.p(ctx2, dirty);
      if (
        /*store*/
        ctx2[1].isUserParticipant
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block_1(ctx2);
          if_block2.c();
          if_block2.m(div5, null);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (!current || dirty[0] & /*$rightTraderAccepted*/
      8) {
        toggle_class(
          i1,
          "accepted",
          /*$rightTraderAccepted*/
          ctx2[3]
        );
      }
      if (!current || dirty[0] & /*$rightTraderAccepted*/
      8) {
        toggle_class(
          i1,
          "fa-user-check",
          /*$rightTraderAccepted*/
          ctx2[3]
        );
      }
      if (!current || dirty[0] & /*$rightTraderAccepted*/
      8) {
        toggle_class(i1, "fa-user-times", !/*$rightTraderAccepted*/
        ctx2[3]);
      }
      if ((!current || dirty[0] & /*store*/
      2) && t9_value !== (t9_value = /*store*/
      ctx2[1].rightTraderActor.name + ""))
        set_data(t9, t9_value);
      if (!current || dirty[0] & /*store*/
      2 && !src_url_equal(img1.src, img1_src_value = /*store*/
      ctx2[1].rightTraderActor.img)) {
        attr(img1, "src", img1_src_value);
      }
      if (dirty[0] & /*store, $rightItems*/
      130) {
        each_value_2 = /*$rightItems*/
        ctx2[7];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_1, 1, ctx2, each_value_2, each1_lookup, div8, outro_and_destroy_block, create_each_block_2, null, get_each_context_2);
        check_outros();
      }
      if (
        /*systemHasCurrencies*/
        ctx2[19]
      )
        if_block3.p(ctx2, dirty);
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_5.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      transition_in(if_block1);
      for (let i = 0; i < each_value_2.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(if_block3);
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      transition_out(if_block1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      transition_out(if_block3);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div12);
      if (if_block0)
        if_block0.d();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].d();
      }
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      if (if_block3)
        if_block3.d();
    }
  };
}
__name(create_default_slot_1, "create_default_slot_1");
function create_default_slot(ctx) {
  let t;
  let dropzone;
  let current;
  let if_block = (
    /*$leftTraderAccepted*/
    ctx[2] && /*$rightTraderAccepted*/
    ctx[3] && create_if_block_7()
  );
  dropzone = new DropZone({
    props: {
      callback: (
        /*dropItem*/
        ctx[20]
      ),
      $$slots: { default: [create_default_slot_1] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      if (if_block)
        if_block.c();
      t = space();
      create_component(dropzone.$$.fragment);
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t, anchor);
      mount_component(dropzone, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*$leftTraderAccepted*/
        ctx2[2] && /*$rightTraderAccepted*/
        ctx2[3]
      ) {
        if (if_block) {
          if (dirty[0] & /*$leftTraderAccepted, $rightTraderAccepted*/
          12) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_7();
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(t.parentNode, t);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      const dropzone_changes = {};
      if (dirty[0] & /*$rightCurrencies, $rightItemCurrencies, store, $rightItems, $rightTraderAccepted, $leftTraderAccepted, $leftCurrencies, $leftItemCurrencies, $leftItems*/
      1022 | dirty[1] & /*$$scope*/
      65536) {
        dropzone_changes.$$scope = { dirty, ctx: ctx2 };
      }
      dropzone.$set(dropzone_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      transition_in(dropzone.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      transition_out(dropzone.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(t);
      destroy_component(dropzone, detaching);
    }
  };
}
__name(create_default_slot, "create_default_slot");
function create_fragment(ctx) {
  let applicationshell;
  let updating_elementRoot;
  let current;
  function applicationshell_elementRoot_binding(value) {
    ctx[31](value);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  let applicationshell_props = {
    $$slots: { default: [create_default_slot] },
    $$scope: { ctx }
  };
  if (
    /*elementRoot*/
    ctx[0] !== void 0
  ) {
    applicationshell_props.elementRoot = /*elementRoot*/
    ctx[0];
  }
  applicationshell = new ApplicationShell({ props: applicationshell_props });
  binding_callbacks.push(() => bind(applicationshell, "elementRoot", applicationshell_elementRoot_binding));
  return {
    c() {
      create_component(applicationshell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(applicationshell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const applicationshell_changes = {};
      if (dirty[0] & /*$rightCurrencies, $rightItemCurrencies, store, $rightItems, $rightTraderAccepted, $leftTraderAccepted, $leftCurrencies, $leftItemCurrencies, $leftItems*/
      1022 | dirty[1] & /*$$scope*/
      65536) {
        applicationshell_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_elementRoot && dirty[0] & /*elementRoot*/
      1) {
        updating_elementRoot = true;
        applicationshell_changes.elementRoot = /*elementRoot*/
        ctx2[0];
        add_flush_callback(() => updating_elementRoot = false);
      }
      applicationshell.$set(applicationshell_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(applicationshell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(applicationshell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(applicationshell, detaching);
    }
  };
}
__name(create_fragment, "create_fragment");
function instance($$self, $$props, $$invalidate) {
  let $leftTraderAccepted;
  let $rightTraderAccepted;
  let $leftItems;
  let $leftCurrencies;
  let $leftItemCurrencies;
  let $rightItems;
  let $rightCurrencies;
  let $rightItemCurrencies;
  let { elementRoot } = $$props;
  let { store } = $$props;
  const leftItems = store.leftTraderItems;
  component_subscribe($$self, leftItems, (value) => $$invalidate(4, $leftItems = value));
  const leftCurrencies = store.leftTraderCurrencies;
  component_subscribe($$self, leftCurrencies, (value) => $$invalidate(5, $leftCurrencies = value));
  const leftItemCurrencies = store.leftTraderItemCurrencies;
  component_subscribe($$self, leftItemCurrencies, (value) => $$invalidate(6, $leftItemCurrencies = value));
  const leftTraderAccepted = store.leftTraderAccepted;
  component_subscribe($$self, leftTraderAccepted, (value) => $$invalidate(2, $leftTraderAccepted = value));
  const rightItems = store.rightTraderItems;
  component_subscribe($$self, rightItems, (value) => $$invalidate(7, $rightItems = value));
  const rightCurrencies = store.rightTraderCurrencies;
  component_subscribe($$self, rightCurrencies, (value) => $$invalidate(8, $rightCurrencies = value));
  const rightItemCurrencies = store.rightTraderItemCurrencies;
  component_subscribe($$self, rightItemCurrencies, (value) => $$invalidate(9, $rightItemCurrencies = value));
  const rightTraderAccepted = store.rightTraderAccepted;
  component_subscribe($$self, rightTraderAccepted, (value) => $$invalidate(3, $rightTraderAccepted = value));
  let isGM = game.user.isGM;
  let systemHasCurrencies = game.itempiles.API.CURRENCIES.length > 0;
  async function dropItem(data2) {
    if (data2.type !== "Item")
      return;
    let item = (await Item.implementation.fromDropData(data2)).toObject();
    data2.actorId = getSourceActorFromDropData(data2)?.id;
    if (!data2.actorId && !game.user.isGM) {
      return custom_warning(game.i18n.localize("ITEM-PILES.Errors.NoSourceDrop"), true);
    }
    if (!game.user.isGM && data2.actorId && data2.actorId !== store.leftTraderActor.id) {
      throw custom_error(`You cannot drop items into the trade UI from a different actor than ${store.leftTraderActor.name}!`);
    }
    const validItem = await checkItemType(store.rightTraderActor, item, {
      errorText: "ITEM-PILES.Errors.DisallowedItemTrade",
      warningTitle: "ITEM-PILES.Dialogs.TypeWarning.Title",
      warningContent: "ITEM-PILES.Dialogs.TypeWarning.TradeContent"
    });
    if (!validItem)
      return;
    const actorItemCurrencyList = getCurrencyList(store.leftTraderActor).filter((entry) => entry.type !== "attribute");
    const isCurrency = !!findSimilarItem(actorItemCurrencyList.map((item2) => item2.data), validItem);
    if (!validItem._id) {
      validItem._id = item._id;
    }
    const itemToSend = await Item.implementation.create(validItem, { temporary: true });
    return store.addItem(itemToSend, {
      uuid: data2.uuid,
      quantity: 1,
      currency: isCurrency
    });
  }
  __name(dropItem, "dropItem");
  if (store.isUserParticipant) {
    const itemsUpdatedDebounce = debounce(
      async (items) => {
        await ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.PRIVATE_TRADE_UPDATE_ITEMS, [store.leftTraderUser.id, store.rightTraderUser.id], store.privateTradeId, game.user.id, items);
        return executeSocketAction(ItemPileSocket.HANDLERS.PUBLIC_TRADE_UPDATE_ITEMS, store.publicTradeId, game.user.id, items);
      },
      20
    );
    leftItems.subscribe(itemsUpdatedDebounce);
    const itemCurrenciesUpdatedDebounce = debounce(
      async (items) => {
        await ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.PRIVATE_TRADE_UPDATE_ITEM_CURRENCIES, [store.leftTraderUser.id, store.rightTraderUser.id], store.privateTradeId, game.user.id, items);
        return executeSocketAction(ItemPileSocket.HANDLERS.PUBLIC_TRADE_UPDATE_ITEM_CURRENCIES, store.publicTradeId, game.user.id, items);
      },
      20
    );
    leftItemCurrencies.subscribe(itemCurrenciesUpdatedDebounce);
    const attributesUpdatedDebounce = debounce(
      async (attributes) => {
        await ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.PRIVATE_TRADE_UPDATE_CURRENCIES, [store.leftTraderUser.id, store.rightTraderUser.id], store.privateTradeId, game.user.id, attributes);
        return executeSocketAction(ItemPileSocket.HANDLERS.PUBLIC_TRADE_UPDATE_CURRENCIES, store.publicTradeId, game.user.id, attributes);
      },
      40
    );
    leftCurrencies.subscribe(attributesUpdatedDebounce);
    const acceptedDebounce = debounce(
      async (acceptedState) => {
        await ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.PRIVATE_TRADE_STATE, [store.leftTraderUser.id, store.rightTraderUser.id], store.privateTradeId, game.user.id, acceptedState);
        return executeSocketAction(ItemPileSocket.HANDLERS.PUBLIC_TRADE_STATE, store.publicTradeId, game.user.id, acceptedState);
      },
      10
    );
    leftTraderAccepted.subscribe(acceptedDebounce);
  }
  async function executeSocketAction(socketHandler, ...args) {
    if (store.isPrivate) {
      return ItemPileSocket.executeForUsers(socketHandler, [store.leftTraderUser.id, store.rightTraderUser.id], ...args);
    }
    return ItemPileSocket.executeForEveryone(socketHandler, ...args);
  }
  __name(executeSocketAction, "executeSocketAction");
  async function addCurrency(asGM = false) {
    const currenciesToAdd = await DropCurrencyDialog.show(store.leftTraderActor, store.rightTraderActor, {
      existingCurrencies: store.getExistingCurrencies(),
      title: game.i18n.localize("ITEM-PILES.Trade.AddCurrency.Title"),
      content: game.i18n.format("ITEM-PILES.Trade.AddCurrency.Content", {
        trader_actor_name: store.rightTraderActor.name
      }),
      button: game.i18n.localize("ITEM-PILES.Trade.AddCurrency.Label"),
      unlimitedCurrencies: asGM
    });
    if (!currenciesToAdd || foundry.utils.isEmpty(currenciesToAdd.attributes) && !currenciesToAdd.items.length)
      return;
    currenciesToAdd.items.forEach((item) => {
      const itemData = store.leftTraderActor.items.get(item.item._id).toObject();
      store.addItem(itemData, { quantity: item.quantity, currency: true });
    });
    const currencies = getActorCurrencies(store.leftTraderActor, { getAll: asGM }).filter((currency) => currency.type === "attribute");
    Object.entries(currenciesToAdd.attributes).forEach(([path, quantity]) => {
      const currency = currencies.find((currency2) => currency2.path === path);
      store.addAttribute({
        path,
        quantity,
        newQuantity: quantity,
        name: currency.name,
        img: currency.img,
        maxQuantity: !game.user.isGM ? currency.quantity : Infinity,
        index: currency.index
      });
    });
  }
  __name(addCurrency, "addCurrency");
  function tradeentry_data_binding(value, item, each_value_5, item_index_3) {
    each_value_5[item_index_3] = value;
    leftItems.set($leftItems);
  }
  __name(tradeentry_data_binding, "tradeentry_data_binding");
  const click_handler = /* @__PURE__ */ __name(() => {
    addCurrency(true);
  }, "click_handler");
  const click_handler_1 = /* @__PURE__ */ __name(() => {
    addCurrency();
  }, "click_handler_1");
  function tradeentry_data_binding_1(value, currency, each_value_4, currency_index_1) {
    each_value_4[currency_index_1] = value;
    leftCurrencies.set($leftCurrencies);
  }
  __name(tradeentry_data_binding_1, "tradeentry_data_binding_1");
  function tradeentry_data_binding_2(value, item, each_value_3, item_index_2) {
    each_value_3[item_index_2] = value;
    leftItemCurrencies.set($leftItemCurrencies);
  }
  __name(tradeentry_data_binding_2, "tradeentry_data_binding_2");
  const click_handler_2 = /* @__PURE__ */ __name(() => {
    store.toggleAccepted(store.leftTraderUser.id);
  }, "click_handler_2");
  function tradeentry_data_binding_3(value, item, each_value_2, item_index_1) {
    each_value_2[item_index_1] = value;
    rightItems.set($rightItems);
  }
  __name(tradeentry_data_binding_3, "tradeentry_data_binding_3");
  function tradeentry_data_binding_4(value, currency, each_value_1, currency_index) {
    each_value_1[currency_index] = value;
    rightCurrencies.set($rightCurrencies);
  }
  __name(tradeentry_data_binding_4, "tradeentry_data_binding_4");
  function tradeentry_data_binding_5(value, item, each_value, item_index) {
    each_value[item_index] = value;
    rightItemCurrencies.set($rightItemCurrencies);
  }
  __name(tradeentry_data_binding_5, "tradeentry_data_binding_5");
  function applicationshell_elementRoot_binding(value) {
    elementRoot = value;
    $$invalidate(0, elementRoot);
  }
  __name(applicationshell_elementRoot_binding, "applicationshell_elementRoot_binding");
  $$self.$$set = ($$props2) => {
    if ("elementRoot" in $$props2)
      $$invalidate(0, elementRoot = $$props2.elementRoot);
    if ("store" in $$props2)
      $$invalidate(1, store = $$props2.store);
  };
  return [
    elementRoot,
    store,
    $leftTraderAccepted,
    $rightTraderAccepted,
    $leftItems,
    $leftCurrencies,
    $leftItemCurrencies,
    $rightItems,
    $rightCurrencies,
    $rightItemCurrencies,
    leftItems,
    leftCurrencies,
    leftItemCurrencies,
    leftTraderAccepted,
    rightItems,
    rightCurrencies,
    rightItemCurrencies,
    rightTraderAccepted,
    isGM,
    systemHasCurrencies,
    dropItem,
    addCurrency,
    tradeentry_data_binding,
    click_handler,
    click_handler_1,
    tradeentry_data_binding_1,
    tradeentry_data_binding_2,
    click_handler_2,
    tradeentry_data_binding_3,
    tradeentry_data_binding_4,
    tradeentry_data_binding_5,
    applicationshell_elementRoot_binding
  ];
}
__name(instance, "instance");
const _Trading_app_shell = class _Trading_app_shell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance, create_fragment, safe_not_equal, { elementRoot: 0, store: 1 }, null, [-1, -1]);
  }
  get elementRoot() {
    return this.$$.ctx[0];
  }
  set elementRoot(elementRoot) {
    this.$$set({ elementRoot });
    flush();
  }
  get store() {
    return this.$$.ctx[1];
  }
  set store(store) {
    this.$$set({ store });
    flush();
  }
};
__name(_Trading_app_shell, "Trading_app_shell");
let Trading_app_shell = _Trading_app_shell;
const _TradingApp = class _TradingApp extends SvelteApplication {
  constructor(store, options = {}, dialogData = {}) {
    super({
      title: game.i18n.format("ITEM-PILES.Trade.Between", {
        actor_1: store.leftTraderActor.name,
        actor_2: store.rightTraderActor.name
      }),
      svelte: {
        class: Trading_app_shell,
        target: document.body,
        props: {
          store
        }
      },
      ...options
    }, dialogData);
    this.store = store;
    this.publicTradeId = store.publicTradeId;
  }
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      zIndex: 100,
      classes: ["dialog", "item-piles-trading-sheet", "item-piles", "item-piles-app"],
      width: 800,
      height: "auto",
      closeOnSubmit: false
    });
  }
  static getActiveApp(publicTradeId) {
    for (const app of Object.values(ui.windows)) {
      if (app instanceof this && app?.publicTradeId === publicTradeId) {
        return app;
      }
    }
    return false;
  }
  async close(options = {}) {
    if (!options?.callback && this.store.isUserParticipant) {
      await ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.TRADE_CLOSED, this.publicTradeId, game.user.id);
    }
    return super.close(options);
  }
};
__name(_TradingApp, "TradingApp");
let TradingApp = _TradingApp;
const mutedUsers = /* @__PURE__ */ new Set();
const ongoingTrades = /* @__PURE__ */ new Map();
const _TradeAPI = class _TradeAPI {
  static initialize() {
    Hooks.on("renderPlayerList", this._userDisconnected.bind(this));
  }
  static async _requestTrade(user = false) {
    const users = game.users.filter((user2) => user2.active && user2 !== game.user);
    if (!users.length) {
      return TJSDialog.prompt({
        title: game.i18n.localize("ITEM-PILES.Trade.Title"),
        content: {
          class: CustomDialog,
          props: {
            header: game.i18n.localize("ITEM-PILES.Trade.NoActiveUsers.Title"),
            content: game.i18n.localize("ITEM-PILES.Trade.NoActiveUsers.Content"),
            icon: "fas fa-heart-broken"
          }
        },
        modal: true,
        draggable: false,
        options: {
          height: "auto"
        }
      });
    }
    let userId;
    let actor;
    let isPrivate;
    const actors = game.actors.filter((actor2) => actor2.isOwner);
    if (actors.length === 1 && user) {
      userId = user.id;
      actor = actors[0];
      isPrivate = false;
    } else {
      const result = await TradePromptDialog.show({ actors, users, user });
      if (!result)
        return;
      userId = result.user.id;
      actor = result.actor;
      isPrivate = result.private;
    }
    if (!actor)
      return false;
    actor = getActor(actor);
    const actorOwner = game.users.find((user2) => user2.character === actor && user2 !== game.user);
    if (actorOwner) {
      const doContinue = await TJSDialog.confirm({
        title: game.i18n.localize("ITEM-PILES.Trade.Title"),
        content: {
          class: CustomDialog,
          props: {
            header: game.i18n.localize("ITEM-PILES.Trade.Title"),
            content: actorOwner.active ? game.i18n.format("ITEM-PILES.Trade.UserActiveCharacterWarning", {
              actor_name: actor.name,
              player_name: actorOwner.name
            }) : game.i18n.format("ITEM-PILES.Trade.UserCharacterWarning", {
              actor_name: actor.name,
              player_name: actorOwner.name
            }),
            icon: "fas fa-exclamation-triangle"
          }
        },
        modal: true,
        draggable: false,
        rejectClose: false,
        defaultYes: true,
        options: {
          height: "auto"
        }
      });
      if (!doContinue) {
        return;
      }
    }
    const privateTradeId = randomID();
    const publicTradeId = randomID();
    const cancelDialog = new Dialog({
      title: game.i18n.localize("ITEM-PILES.Trade.Title"),
      content: `<p style="text-align: center">${game.i18n.format("ITEM-PILES.Trade.OngoingRequest.Content", { user_name: game.users.get(userId).name })}</p>`,
      buttons: {
        confirm: {
          icon: '<i class="fas fa-times"></i>',
          label: game.i18n.localize("ITEM-PILES.Trade.OngoingRequest.Label"),
          callback: () => {
            ItemPileSocket.executeAsUser(ItemPileSocket.HANDLERS.TRADE_REQUEST_CANCELLED, userId, game.user.id, privateTradeId);
          }
        }
      }
    }, {
      top: 50,
      width: 300
    }).render(true);
    return ItemPileSocket.executeAsUser(ItemPileSocket.HANDLERS.TRADE_REQUEST_PROMPT, userId, game.user.id, actor.uuid, privateTradeId, publicTradeId, isPrivate).then(async (data2) => {
      if (data2 === "cancelled")
        return;
      cancelDialog.close();
      if (data2 === "same-actor") {
        return custom_warning(game.i18n.localize("ITEM-PILES.Trade.SameActor"), true);
      }
      if (!data2 || !data2.fullPrivateTradeId.includes(privateTradeId)) {
        return custom_warning(game.i18n.localize("ITEM-PILES.Trade.Declined"), true);
      }
      const traderActor = getActor(data2.actorUuid);
      if (traderActor === actor) {
        return custom_warning(game.i18n.localize("ITEM-PILES.Trade.SameActor"), true);
      }
      const store = new TradeStore(game.user.id, {
        user: game.user,
        actor
      }, {
        user: game.users.get(userId),
        actor: traderActor
      }, data2.fullPublicTradeId, data2.fullPrivateTradeId, isPrivate);
      const [actorSheet, tradeApp] = getApplicationPositions(actor.sheet);
      const app = new TradingApp(store, tradeApp).render(true);
      ongoingTrades.set(data2.fullPublicTradeId, { app, store });
      actorSheet.byassItemPiles = true;
      actor.sheet.render(true, actorSheet);
      if (isPrivate) {
        return ItemPileSocket.callHookForUsers(CONSTANTS.HOOKS.TRADE.STARTED, [game.user.id, userId], {
          user: game.user.id,
          actor: actor.uuid
        }, { user: userId, actor: data2.actorUuid }, data2.fullPublicTradeId, isPrivate);
      }
      return ItemPileSocket.callHook(CONSTANTS.HOOKS.TRADE.STARTED, {
        user: game.user.id,
        actor: actor.uuid
      }, { user: userId, actor: data2.actorUuid }, data2.fullPublicTradeId, isPrivate);
    }).catch((err) => {
      console.error(err);
      custom_warning(game.i18n.localize("ITEM-PILES.Trade.Disconnected"), true);
      cancelDialog.close();
    });
  }
  static async _respondPrompt(tradingUserId, tradingActorUuid, privateTradeId, publicTradeId, isPrivate) {
    if (mutedUsers.has(tradingUserId)) {
      await wait(Math.random() * 15e3);
      return false;
    }
    const fullPrivateTradeId = privateTradeId + randomID();
    const fullPublicTradeId = publicTradeId + randomID();
    const tradingUser = game.users.get(tradingUserId);
    const tradingActor = getActor(tradingActorUuid);
    const result = await TradeRequestDialog.show({ tradeId: privateTradeId, tradingUser, tradingActor, isPrivate });
    if (!result)
      return false;
    if (result === "cancelled") {
      return "cancelled";
    }
    if (result === "mute") {
      mutedUsers.push(tradingUserId);
      return false;
    }
    const actor = result.actor ?? result;
    if (actor === tradingActor) {
      custom_warning(game.i18n.localize("ITEM-PILES.Trade.SameActor"), true);
      return "same-actor";
    }
    const store = new TradeStore(tradingUserId, {
      user: game.user,
      actor
    }, {
      user: tradingUser,
      actor: tradingActor
    }, fullPublicTradeId, fullPrivateTradeId, isPrivate);
    const [actorSheet, tradeApp] = getApplicationPositions(actor.sheet);
    const app = new TradingApp(store, tradeApp).render(true);
    ongoingTrades.set(fullPublicTradeId, { app, store });
    actorSheet.byassItemPiles = true;
    actor.sheet.render(true, actorSheet);
    return {
      fullPrivateTradeId,
      fullPublicTradeId,
      actorUuid: result.uuid
    };
  }
  static getAppOptions(actor) {
    const midPoint = window.innerWidth / 2 - 200;
    return {
      actorSheet: { left: midPoint - actor.sheet.position.width - 25 },
      tradeApp: { left: midPoint + 25 }
    };
  }
  static async _tradeCancelled(userId, privateTradeId) {
    TJSDialog.prompt({
      title: game.i18n.localize("ITEM-PILES.Trade.Title"),
      content: {
        class: CustomDialog,
        props: {
          header: game.i18n.localize("ITEM-PILES.Trade.Title"),
          content: game.i18n.format("ITEM-PILES.Trade.CancelledRequest.Content", { user_name: game.users.get(userId).name }),
          icon: "fas fa-exclamation-triangle"
        }
      },
      modal: true,
      draggable: false,
      options: {
        height: "auto"
      }
    });
    return TradeRequestDialog.cancel(privateTradeId);
  }
  static async _requestTradeData({ tradeId, tradeUser } = {}) {
    const ongoingTrade = this._getOngoingTrade(tradeId);
    if (ongoingTrade) {
      return ongoingTrade.store.export();
    }
    const user = game.users.get(tradeUser);
    if (!user?.active) {
      return false;
    }
    const ongoingTradeData = await ItemPileSocket.executeAsUser(ItemPileSocket.HANDLERS.REQUEST_TRADE_DATA, tradeUser, tradeId, game.user.id);
    if (!ongoingTradeData) {
      return false;
    }
    return ongoingTradeData;
  }
  static async _spectateTrade({ tradeId, tradeUser } = {}) {
    const existingApp = TradingApp.getActiveApp(tradeId);
    if (existingApp) {
      return existingApp.render(false, { focus: true });
    }
    const ongoingTradeData = await this._requestTradeData({ tradeId, tradeUser });
    if (!ongoingTradeData) {
      if (isGMConnected()) {
        ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.DISABLE_CHAT_TRADE_BUTTON, tradeId);
      }
      return custom_warning(game.i18n.localize("ITEM-PILES.Trade.Over"), true);
    }
    const store = TradeStore.import(ongoingTradeData);
    const app = new TradingApp(store).render(true);
    ongoingTrades.set(store.publicTradeId, { app, store });
  }
  static async _respondActiveTradeData(tradeId, requesterId) {
    const trade = this._getOngoingTrade(tradeId, requesterId);
    if (!trade)
      return;
    return trade.store.export();
  }
  static _getOngoingTrade(tradeId, requesterId = game.user.id) {
    if (!ongoingTrades.has(tradeId))
      return false;
    const trade = ongoingTrades.get(tradeId);
    if (!trade.store.isPrivate) {
      return trade;
    }
    if (trade.store.leftTraderUser.id !== requesterId && trade.store.rightTraderUser.id !== requesterId)
      return false;
    return trade;
  }
  static async _updateItems(tradeId, userId, items) {
    const trade = this._getOngoingTrade(tradeId);
    if (!trade)
      return;
    trade.store.updateItems(userId, items);
  }
  static async _updateItemCurrencies(tradeId, userId, items) {
    const trade = this._getOngoingTrade(tradeId);
    if (!trade)
      return;
    trade.store.updateItemCurrencies(userId, items);
  }
  static async _updateCurrencies(tradeId, userId, currencies) {
    const trade = this._getOngoingTrade(tradeId);
    if (!trade)
      return;
    trade.store.updateCurrencies(userId, currencies);
  }
  static async _updateAcceptedState(tradeId, userId, status) {
    const trade = this._getOngoingTrade(tradeId);
    if (!trade)
      return;
    trade.store.updateAcceptedState(userId, status);
    if (userId === game.user.id && (trade.store.leftTraderUser.id === game.user.id || trade.store.rightTraderUser.id === game.user.id)) {
      if (trade.store.tradeIsAccepted) {
        setTimeout(async () => {
          if (trade.store.tradeIsAccepted) {
            ItemPileSocket.executeForUsers(
              ItemPileSocket.HANDLERS.EXECUTE_TRADE,
              [trade.store.leftTraderUser.id, trade.store.rightTraderUser.id],
              trade.store.publicTradeId,
              trade.store.privateTradeId,
              userId
            );
          }
        }, 2e3);
      }
    }
  }
  static async _userDisconnected() {
    const tradesToDelete = [];
    const activeUsers = game.users.filter((user) => user.active);
    for (let [tradeId, trade] of ongoingTrades) {
      const foundLeft = activeUsers.find((u) => u === trade.store.leftTraderUser);
      const foundRight = activeUsers.find((u) => u === trade.store.rightTraderUser);
      if (foundLeft && foundRight)
        continue;
      tradesToDelete.push(tradeId);
      custom_warning(game.i18n.localize("ITEM-PILES.Trade.Disconnected"), true);
      await trade.app.close({ callback: true });
      if (foundLeft === game.user || foundRight === game.user) {
        if (isGMConnected()) {
          await ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.DISABLE_CHAT_TRADE_BUTTON, tradeId);
        }
      }
    }
    tradesToDelete.forEach((tradeId) => ongoingTrades.delete(tradeId));
  }
  static async _tradeClosed(tradeId, closeUserId) {
    const trade = this._getOngoingTrade(tradeId);
    if (!trade)
      return;
    if (trade.store.leftTraderUser.id === game.user.id || trade.store.rightTraderUser.id === game.user.id) {
      if (closeUserId === trade.store.rightTraderUser.id) {
        TJSDialog.prompt({
          title: game.i18n.localize("ITEM-PILES.Trade.Closed.Title"),
          content: {
            class: CustomDialog,
            props: {
              header: game.i18n.localize("ITEM-PILES.Trade.Closed.Title"),
              content: game.i18n.format("ITEM-PILES.Trade.Closed.Them", {
                user_name: trade.store.rightTraderUser.name
              }),
              icon: "fas fa-exclamation-triangle"
            }
          },
          modal: false,
          draggable: true,
          options: {
            height: "auto"
          }
        });
      } else {
        if (trade.store.isPrivate) {
          const otherUserId = trade.store.leftTraderUser.id === game.user.id ? trade.store.rightTraderUser.id : trade.store.leftTraderUser.id;
          ItemPileSocket.executeAsUser(ItemPileSocket.HANDLERS.TRADE_CLOSED, otherUserId, tradeId, game.user.id);
        } else {
          ItemPileSocket.executeForOthers(ItemPileSocket.HANDLERS.TRADE_CLOSED, tradeId, game.user.id);
        }
        TJSDialog.prompt({
          title: game.i18n.localize("ITEM-PILES.Trade.Closed.Title"),
          content: {
            class: CustomDialog,
            props: {
              header: game.i18n.localize("ITEM-PILES.Trade.Closed.Title"),
              content: game.i18n.format("ITEM-PILES.Trade.Closed.You"),
              icon: "fas fa-exclamation-triangle"
            }
          },
          modal: false,
          draggable: true,
          options: {
            height: "auto"
          }
        });
        if (isGMConnected()) {
          await ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.DISABLE_CHAT_TRADE_BUTTON, tradeId);
        }
      }
    } else {
      custom_warning(game.i18n.localize("ITEM-PILES.Trade.Closed.Someone"), true);
    }
    trade.app.close({ callback: true });
    ongoingTrades.delete(tradeId);
  }
  static async _executeTrade(tradeId, privateId, userId) {
    const trade = this._getOngoingTrade(tradeId);
    if (!trade)
      return;
    if (trade.store.privateTradeId !== privateId)
      return;
    const updates = trade.store.getTradeData();
    const itemsToAdd = [];
    for (const entry of updates.add.items) {
      let item = updates.targetActor.items.get(entry.id);
      if (!item) {
        item = await fromUuid(entry.uuid);
        if (!item)
          continue;
      }
      const itemData = item.toObject();
      itemsToAdd.push(setItemQuantity(itemData, entry.quantity, true));
    }
    const itemsToRemove = [];
    for (const entry of updates.remove.items) {
      const item = updates.sourceActor.items.get(entry.id);
      if (!item)
        continue;
      const itemData = item.toObject();
      itemsToRemove.push(setItemQuantity(itemData, entry.quantity, true));
    }
    const transaction = new Transaction(updates.sourceActor);
    await transaction.appendItemChanges(itemsToAdd);
    await transaction.appendItemChanges(itemsToRemove, { remove: true });
    await transaction.appendActorChanges(updates.add.attributes);
    await transaction.appendActorChanges(updates.remove.attributes, { remove: true });
    await transaction.commit();
    if (trade.store.isPrivate) {
      Hooks.callAll(CONSTANTS.HOOKS.TRADE.COMPLETE, trade.store.instigator, data[0], data[1], tradeId);
      trade.app.close({ callback: true });
      ongoingTrades.delete(tradeId);
    } else if (userId === game.user.id) {
      if (isGMConnected()) {
        await ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.DISABLE_CHAT_TRADE_BUTTON, tradeId);
      }
      return ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.TRADE_COMPLETED, tradeId, updates);
    }
  }
  static async _tradeCompleted(tradeId) {
    const trade = this._getOngoingTrade(tradeId);
    if (!trade)
      return;
    const data2 = trade.store.export();
    if (data2.instigator === game.user.id) {
      if (trade.store.isPrivate) {
        Hooks.callAll(CONSTANTS.HOOKS.TRADE.COMPLETE, data2.instigator, data2.leftTraderData, data2.rightTraderData, tradeId);
      } else {
        ItemPileSocket.executeForEveryone(
          ItemPileSocket.HANDLERS.CALL_HOOK,
          CONSTANTS.HOOKS.TRADE.COMPLETE,
          trade.store.instigator,
          data2.leftTraderData,
          data2.rightTraderData,
          tradeId,
          trade.store.isPrivate
        );
      }
    }
    trade.app.close({ callback: true });
    ongoingTrades.delete(tradeId);
  }
};
__name(_TradeAPI, "TradeAPI");
let TradeAPI = _TradeAPI;
const _ChatAPI = class _ChatAPI {
  static initialize() {
    hooks.on("preCreateChatMessage", this._preCreateChatMessage.bind(this));
    hooks.on("renderChatMessage", this._renderChatMessage.bind(this));
    hooks.on(CONSTANTS.HOOKS.ITEM.TRANSFER, this._outputTransferItem.bind(this));
    hooks.on(CONSTANTS.HOOKS.ATTRIBUTE.TRANSFER, this._outputTransferCurrency.bind(this));
    hooks.on(CONSTANTS.HOOKS.TRANSFER_EVERYTHING, this._outputTransferEverything.bind(this));
    hooks.on(CONSTANTS.HOOKS.PILE.SPLIT_INVENTORY, this._outputSplitItemPileInventory.bind(this));
    hooks.on(CONSTANTS.HOOKS.TRADE.STARTED, this._outputTradeStarted.bind(this));
    hooks.on(CONSTANTS.HOOKS.TRADE.COMPLETE, this._outputTradeComplete.bind(this));
    hooks.on(CONSTANTS.HOOKS.ITEM.TRADE, this._outputMerchantTradeComplete.bind(this));
    hooks.on(CONSTANTS.HOOKS.ITEM.GIVE, this._outputGiveItem.bind(this));
    $(document).on("click", ".item-piles-chat-card .item-piles-collapsible", async function() {
      if ($(this).attr("open"))
        return;
      await wait(25);
      $(this).parent()[0].scrollIntoView({ behavior: "smooth", block: "nearest", inline: "start" });
    });
  }
  static _preCreateChatMessage(chatMessage) {
    if (!getSetting(SETTINGS$1.ENABLE_TRADING))
      return;
    const content = chatMessage.content.toLowerCase();
    if (!(content.startsWith("!itempiles") || content.startsWith("!ip")))
      return;
    const args = content.split(" ").slice(1);
    if (args[0] === "trade") {
      setTimeout(() => {
        game.itempiles.API.requestTrade();
      });
    }
    return false;
  }
  static _renderChatMessage(app, html) {
    html.find(".item-piles-specate-trade").click(function() {
      game.itempiles.API.spectateTrade($(this).data());
    });
  }
  static _disableTradingButton(publicTradeId) {
    const message = Array.from(game.messages).find((message2) => {
      return foundry.utils.getProperty(message2, CONSTANTS.FLAGS.PUBLIC_TRADE_ID) === publicTradeId;
    });
    if (!message)
      return;
    const update2 = this._replaceChatContent(message);
    return message.update(update2);
  }
  static async disablePastTradingButtons() {
    if (!game.user.isGM)
      return;
    const messages = Array.from(game.messages).filter((message) => {
      return foundry.utils.getProperty(message, CONSTANTS.FLAGS.PUBLIC_TRADE_ID);
    });
    if (!messages.length)
      return;
    const updates = [];
    for (let message of messages) {
      const update2 = this._replaceChatContent(message);
      const tradeId = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PUBLIC_TRADE_ID);
      const tradeUsers = foundry.utils.getProperty(message, CONSTANTS.FLAGS.TRADE_USERS);
      const bothUsersActive = tradeUsers.filter((userId) => game.users.get(userId).active).length === tradeUsers.length;
      if (!bothUsersActive) {
        updates.push(update2);
      } else {
        const otherUsers = tradeUsers.filter((userId) => userId !== game.user.id);
        const tradeData = await TradeAPI._requestTradeData({ tradeId, tradeUser: otherUsers[0] });
        if (!tradeData) {
          updates.push(update2);
        }
      }
    }
    if (!updates.length)
      return;
    return ChatMessage.updateDocuments(updates);
  }
  static _replaceChatContent(message) {
    const tradeId = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PUBLIC_TRADE_ID);
    const stringToFind = `data-trade-id="${tradeId}"`;
    let content = message.content;
    content = content.replace(stringToFind, "");
    content = content.replace(stringToFind, "disabled");
    content = content.replace(game.i18n.localize("ITEM-PILES.Chat.TradeSpectate"), game.i18n.localize("ITEM-PILES.Chat.SpectateDisabled"));
    return {
      _id: message.id,
      content,
      [`flags.-=${CONSTANTS.MODULE_NAME}`]: null
    };
  }
  /**
   * Outputs to chat based on transferring an item from or to an item pile
   *
   * @param source
   * @param target
   * @param items
   * @param userId
   * @param interactionId
   * @returns {Promise}
   */
  static async _outputTransferItem(source, target, items, userId, interactionId) {
    if (!isItemPileLootable(source))
      return;
    if (!interactionId || game.user.id !== userId || !getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    const [itemData, itemCurrencies] = await this._formatItemData(source, items);
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.PICKUP_CHAT_MESSAGE, source.uuid, target.uuid, itemData, itemCurrencies, userId, interactionId);
  }
  /**
   * Outputs to chat based on transferring a currency from or to an item pile
   *
   * @param source
   * @param target
   * @param currencies
   * @param userId
   * @param interactionId
   * @returns {Promise}
   */
  static async _outputTransferCurrency(source, target, currencies, userId, interactionId) {
    if (!isItemPileLootable(source))
      return;
    if (!interactionId || game.user.id !== userId || !getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    const currencyData = this._formatCurrencyData(source, currencies);
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.PICKUP_CHAT_MESSAGE, source.uuid, target.uuid, [], currencyData, userId, interactionId);
  }
  /**
   * Outputs to chat based on giving an item from one actor to another
   *
   * @param source
   * @param target
   * @param item
   * @param userId
   * @returns {Promise}
   */
  static async _outputGiveItem(source, target, item, userId) {
    if (game.user.id !== userId || !getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    const [itemData, itemCurrencies] = await this._formatItemData(source, [item]);
    return this._giveChatMessage(source, target, itemData.concat(itemCurrencies), userId);
  }
  /**
   * Outputs to chat based on transferring everything from or to an item pile
   *
   * @param source
   * @param target
   * @param items
   * @param currencies
   * @param userId
   * @param interactionId
   * @returns {Promise}
   */
  static async _outputTransferEverything(source, target, items, currencies, userId, interactionId) {
    if (!isItemPileLootable(source))
      return;
    if (!interactionId || game.user.id !== userId || !getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    const [itemData, itemCurrencies] = await this._formatItemData(source, items);
    const currencyData = this._formatCurrencyData(source, currencies).concat(itemCurrencies);
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.PICKUP_CHAT_MESSAGE, source.uuid, target.uuid, itemData, currencyData, userId, interactionId);
  }
  static _outputSplitItemPileInventory(source, pileDeltas, actorDeltas, userId) {
    if (!isItemPileLootable(source))
      return;
    if (game.user.id !== userId || !getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.SPLIT_CHAT_MESSAGE, source.uuid, pileDeltas, actorDeltas, userId);
  }
  static async _outputTradeStarted(party_1, party_2, publicTradeId, isPrivate) {
    if (party_1.user !== game.user.id || !getSetting(SETTINGS$1.OUTPUT_TO_CHAT) || isPrivate)
      return;
    return this._outputTradeStartedToChat(party_1, party_2, publicTradeId);
  }
  static async _outputTradeComplete(instigator, party_1, party_2, publicTradeId, isPrivate) {
    if (!getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    return this._outputTradeCompleteToChat(instigator, party_1, party_2, publicTradeId, isPrivate);
  }
  static async _outputMerchantTradeComplete(source, target, priceInformation, userId, interactionId) {
    if (!getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    if (!isItemPileMerchant(source))
      return;
    if (!interactionId || game.user.id !== userId || !getSetting(SETTINGS$1.OUTPUT_TO_CHAT))
      return;
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.MERCHANT_TRADE_CHAT_MESSAGE, source.uuid, target.uuid, priceInformation, userId, interactionId);
  }
  /**
   * Formats item data to a chat friendly structure
   *
   * @param itemPile
   * @param items
   * @param divideBy
   * @returns {Promise<Array>}
   */
  static async _formatItemData(itemPile, items, divideBy = 1) {
    const formattedItems = [];
    const formattedCurrencies = [];
    const currencyList = getActorCurrencies(itemPile, { getAll: true });
    for (const itemData of items) {
      const tempItem = await Item.implementation.create(itemData.item, { temporary: true });
      const data2 = {
        name: game.i18n.localize(tempItem.name),
        img: tempItem.img ?? itemData?.item?.img ?? "",
        quantity: Math.abs(itemData.quantity) / divideBy
      };
      if (isItemCurrency(tempItem, { actorCurrencies: currencyList })) {
        formattedCurrencies.push(data2);
      } else {
        formattedItems.push(data2);
      }
    }
    return [formattedItems, formattedCurrencies];
  }
  /**
   * Formats currency data to a chat friendly structure
   *
   * @param itemPile
   * @param currencies
   * @param divideBy
   * @returns {Array}
   */
  static _formatCurrencyData(itemPile, currencies, divideBy = 1) {
    const currencyList = getActorCurrencies(itemPile, { getAll: true });
    return Object.entries(currencies).map((entry) => {
      const currency = currencyList.find((currency2) => currency2.id === entry[0]);
      return {
        name: game.i18n.localize(currency.name),
        img: currency.img ?? "",
        quantity: Math.abs(entry[1]) / divideBy,
        index: currencyList.indexOf(currency)
      };
    });
  }
  /**
   * Outputs the transferred data in chat
   *
   * @param sourceUuid
   * @param targetUuid
   * @param items
   * @param currencies
   * @param userId
   * @param interactionId
   * @returns {Promise}
   */
  static async _outputPickupToChat(sourceUuid, targetUuid, items, currencies, userId, interactionId) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const now2 = +/* @__PURE__ */ new Date();
    const messages = Array.from(game.messages).filter((message) => now2 - message.timestamp <= 108e5).slice(-10);
    messages.reverse();
    for (const message of messages) {
      const flags = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PILE);
      if (flags && flags.version && !foundry.utils.isNewerVersion(getModuleVersion(), flags.version) && flags.source === sourceUuid && flags.target === targetUuid && flags.interactionId === interactionId) {
        return this._updateExistingPickupMessage(message, sourceActor, targetActor, items, currencies, interactionId);
      }
    }
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/looted.html", {
      message: game.i18n.format("ITEM-PILES.Chat.Pickup", { name: targetActor.name }),
      itemPile: sourceActor,
      actor: targetActor,
      items,
      currencies
    });
    return this._createNewChatMessage(userId, {
      user: game.user.id,
      type: CONST.CHAT_MESSAGE_TYPES.OTHER,
      content: chatCardHtml,
      flavor: "Item Piles",
      speaker: ChatMessage.getSpeaker({ alias: game.user.name }),
      [CONSTANTS.FLAGS.PILE]: {
        version: getModuleVersion(),
        source: sourceUuid,
        target: targetUuid,
        items,
        currencies,
        interactionId
      }
    });
  }
  static _matchEntries(existingEntries, incomingEntries) {
    const combinedEntries = existingEntries.map((existingEntry) => {
      const foundEntry = incomingEntries.find((item) => item.name === existingEntry.name && existingEntry.img === item.img);
      if (foundEntry) {
        existingEntry.quantity += foundEntry.quantity;
        incomingEntries.splice(incomingEntries.indexOf(foundEntry), 1);
      }
      return existingEntry;
    });
    incomingEntries.forEach((item) => combinedEntries.push(item));
    return combinedEntries;
  }
  static async _updateExistingPickupMessage(message, sourceActor, targetActor, items, currencies, interactionId) {
    const flags = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PILE);
    const newItems = this._matchEntries(flags.items, items);
    const newCurrencies = this._matchEntries(flags.currencies, currencies);
    newCurrencies.sort((a, b) => {
      return a.index - b.index;
    });
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/looted.html", {
      message: game.i18n.format("ITEM-PILES.Chat.Pickup", { name: targetActor.name }),
      itemPile: sourceActor,
      actor: targetActor,
      items: newItems,
      currencies: newCurrencies
    });
    return message.update({
      content: chatCardHtml,
      [`${CONSTANTS.FLAGS.PILE}.interactionId`]: interactionId,
      [`${CONSTANTS.FLAGS.PILE}.items`]: newItems,
      [`${CONSTANTS.FLAGS.PILE}.currencies`]: newCurrencies
    });
  }
  static async _outputSplitToChat(sourceUuid, pileDeltas, actorDeltas, userId) {
    const sourceActor = getActor(sourceUuid);
    const divideBy = Object.values(actorDeltas).length;
    const [items, itemCurrencies] = await this._formatItemData(sourceActor, pileDeltas.itemDeltas, divideBy);
    const currencies = this._formatCurrencyData(sourceActor, pileDeltas.attributeDeltas, divideBy).concat(itemCurrencies);
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/looted.html", {
      message: game.i18n.format("ITEM-PILES.Chat.Split", { num_players: divideBy }),
      itemPile: sourceActor,
      items,
      currencies
    });
    return this._createNewChatMessage(userId, {
      user: game.user.id,
      type: CONST.CHAT_MESSAGE_TYPES.OTHER,
      content: chatCardHtml,
      flavor: "Item Piles",
      speaker: ChatMessage.getSpeaker({ alias: game.user.name })
    });
  }
  static async _outputTradeStartedToChat(party_1, party_2, publicTradeId) {
    const party_1_actor = getActor(party_1.actor);
    const party_2_actor = getActor(party_2.actor);
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/trade-started.html", {
      party_1_actor,
      party_2_actor,
      publicTradeId,
      userId: game.user.id
    });
    return this._createNewChatMessage(game.user.id, {
      user: game.user.id,
      type: CONST.CHAT_MESSAGE_TYPES.OTHER,
      content: chatCardHtml,
      flavor: "Item Piles",
      speaker: ChatMessage.getSpeaker({ alias: game.user.name }),
      [CONSTANTS.FLAGS.PUBLIC_TRADE_ID]: publicTradeId,
      [CONSTANTS.FLAGS.TRADE_USERS]: [party_1.user, party_2.user]
    });
  }
  static async _outputTradeCompleteToChat(instigator, party_1, party_2, publicTradeId, isPrivate) {
    if (instigator !== game.user.id)
      return;
    const party_1_actor = getActor(party_1.actor);
    const party_1_data = {
      actor: party_1_actor,
      items: party_2.items,
      currencies: party_2.currencies.concat(party_2.itemCurrencies)
    };
    party_1_data.got_nothing = !party_1_data.items.length && !party_1_data.currencies.length;
    const party_2_actor = getActor(party_2.actor);
    const party_2_data = {
      actor: party_2_actor,
      items: party_1.items,
      currencies: party_1.currencies.concat(party_1.itemCurrencies)
    };
    party_2_data.got_nothing = !party_2_data.items.length && !party_2_data.currencies.length;
    if (party_1.got_nothing && party_2.got_nothing)
      return;
    const enableCollapse = party_1_data.items.length + party_1_data.currencies.length + party_2_data.items.length + party_2_data.currencies.length > 6;
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/trade-complete.html", {
      party_1: party_1_data,
      party_2: party_2_data,
      publicTradeId,
      isPrivate,
      enableCollapse
    });
    return this._createNewChatMessage(game.user.id, {
      user: game.user.id,
      type: isPrivate ? CONST.CHAT_MESSAGE_TYPES.WHISPER : CONST.CHAT_MESSAGE_TYPES.OTHER,
      content: chatCardHtml,
      flavor: "Item Piles" + (isPrivate ? ": " + game.i18n.localize("ITEM-PILES.Chat.PrivateTrade") : ""),
      speaker: ChatMessage.getSpeaker({ alias: game.user.name }),
      whisper: isPrivate ? [party_2.user] : []
    });
  }
  static async _outputMerchantTradeToChat(sourceUuid, targetUuid, priceInformation, userId, interactionId) {
    const sourceActor = getActor(sourceUuid);
    const targetActor = getActor(targetUuid);
    const now2 = +/* @__PURE__ */ new Date();
    priceInformation.id = randomID();
    const messages = Array.from(game.messages).filter((message) => now2 - message.timestamp <= 108e5).slice(-10);
    messages.reverse();
    for (const message of messages) {
      const flags = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PILE);
      if (flags && flags.version && !foundry.utils.isNewerVersion(getModuleVersion(), flags.version) && flags.source === sourceUuid && flags.target === targetUuid && flags.interactionId === interactionId) {
        return this._updateExistingMerchantMessage(message, sourceActor, targetActor, priceInformation, interactionId);
      }
    }
    const pileData = getActorFlagData(sourceActor);
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/merchant-traded.html", {
      message: game.i18n.format("ITEM-PILES.Chat.MerchantTraded", {
        name: targetActor.name,
        merchant: sourceActor.name
      }),
      merchant: {
        name: sourceActor.name,
        img: pileData.merchantImage || sourceActor.img
      },
      actor: targetActor,
      priceInformation: [priceInformation]
    });
    return this._createNewChatMessage(userId, {
      user: game.user.id,
      type: CONST.CHAT_MESSAGE_TYPES.OTHER,
      content: chatCardHtml,
      flavor: "Item Piles",
      speaker: ChatMessage.getSpeaker({ alias: game.user.name }),
      [CONSTANTS.FLAGS.PILE]: {
        version: getModuleVersion(),
        source: sourceUuid,
        target: targetUuid,
        priceInformation: [priceInformation],
        interactionId
      }
    });
  }
  static async _giveChatMessage(source, target, items) {
    const now2 = +/* @__PURE__ */ new Date();
    const sourceActor = getActor(source);
    const targetActor = getActor(target);
    const messages = Array.from(game.messages).filter((message) => now2 - message.timestamp <= 6e4).slice(-5).reverse();
    for (const message of messages) {
      const flags = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PILE);
      if (flags && flags.version && !foundry.utils.isNewerVersion(getModuleVersion(), flags.version) && flags.source === sourceActor.uuid && flags.target === targetActor.uuid && message.isAuthor) {
        return this._updateExistingGiveMessage(message, sourceActor, targetActor, items);
      }
    }
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/gave-items.html", {
      message: game.i18n.format("ITEM-PILES.Chat.GaveItems", { source: sourceActor.name, target: targetActor.name }),
      source: sourceActor,
      target: targetActor,
      items
    });
    return this._createNewChatMessage(game.user.id, {
      user: game.user.id,
      type: CONST.CHAT_MESSAGE_TYPES.OTHER,
      content: chatCardHtml,
      flavor: "Item Piles",
      speaker: ChatMessage.getSpeaker({ alias: game.user.name }),
      [CONSTANTS.FLAGS.PILE]: {
        version: getModuleVersion(),
        source: sourceActor.uuid,
        target: targetActor.uuid,
        items
      }
    });
  }
  static async _updateExistingGiveMessage(message, sourceActor, targetActor, items) {
    const flags = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PILE);
    const newItems = this._matchEntries(flags.items, items);
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/gave-items.html", {
      message: game.i18n.format("ITEM-PILES.Chat.GaveItems", { source: sourceActor.name, target: targetActor.name }),
      source: sourceActor,
      target: targetActor,
      items: newItems
    });
    return message.update({
      content: chatCardHtml,
      [`${CONSTANTS.FLAGS.PILE}.items`]: newItems
    });
  }
  static async _updateExistingMerchantMessage(message, sourceActor, targetActor, incomingPriceInformation, interactionId) {
    const flags = foundry.utils.getProperty(message, CONSTANTS.FLAGS.PILE);
    const newPriceInformation = flags.priceInformation.map((priceInformation) => {
      const boughtItem = incomingPriceInformation.buyerReceive[0];
      const foundEntry = findSimilarItem(priceInformation.buyerReceive, boughtItem);
      if (foundEntry) {
        if (incomingPriceInformation.primary && priceInformation.primary) {
          foundEntry.quantity += boughtItem.quantity;
          incomingPriceInformation.buyerReceive.splice(0, 1);
          priceInformation.totalCurrencyCost += incomingPriceInformation.totalCurrencyCost;
          priceInformation.basePriceString = getPriceArray(priceInformation.totalCurrencyCost, priceInformation.finalPrices).filter((price) => price.cost).map((price) => price.string).join(" ");
        } else {
          const sameTypePrice = incomingPriceInformation.finalPrices.map((price) => {
            const foundItem = findSimilarItem(priceInformation.buyerReceive, price);
            if (foundItem) {
              return { foundItem, price };
            }
            return false;
          }).filter(Boolean);
          if (sameTypePrice.length) {
            incomingPriceInformation.buyerReceive.splice(0, 1);
            sameTypePrice.forEach((match) => {
              match.price.quantity += match.foundItem.quantity;
            });
          }
        }
      }
      return priceInformation;
    }).concat([incomingPriceInformation].filter((priceInformation) => priceInformation.buyerReceive.length));
    const pileData = getActorFlagData(sourceActor);
    const chatCardHtml = await renderTemplate(CONSTANTS.PATH + "templates/chat/merchant-traded.html", {
      message: game.i18n.format("ITEM-PILES.Chat.MerchantTraded", {
        name: targetActor.name,
        merchant: sourceActor.name
      }),
      merchant: {
        name: sourceActor.name,
        img: pileData.merchantImage || sourceActor.img
      },
      actor: targetActor,
      priceInformation: newPriceInformation
    });
    return message.update({
      content: chatCardHtml,
      [`${CONSTANTS.FLAGS.PILE}.interactionId`]: interactionId,
      [`${CONSTANTS.FLAGS.PILE}.priceInformation`]: newPriceInformation
    });
  }
  static _createNewChatMessage(userId, chatData) {
    if (!chatData.whisper) {
      const mode = getSetting(SETTINGS$1.OUTPUT_TO_CHAT);
      if (mode > 1) {
        chatData.whisper = Array.from(game.users).filter((user) => user.isGM).map((user) => user.id);
        if (mode === 2) {
          chatData.whisper.push(userId);
        }
        chatData.type = CONST.CHAT_MESSAGE_TYPES.WHISPER;
      }
    }
    return ChatMessage.create(chatData);
  }
};
__name(_ChatAPI, "ChatAPI");
let ChatAPI = _ChatAPI;
const _ItemPileSocket = class _ItemPileSocket {
  static initialize() {
    InterfaceTracker.initialize();
    this._socket = socketlib.registerModule(CONSTANTS.MODULE_NAME);
    for (let [key, callback] of Object.entries(this.BINDINGS)) {
      this._socket.register(key, callback);
      debug(`Registered itemPileSocket: ${key}`);
    }
    debug("Registered all Item Piles sockets");
    this.ready = true;
  }
  static executeAsGM(handler, ...args) {
    if (!isGMConnected()) {
      custom_warning(game.i18n.format("ITEM-PILES.Warnings.NoGMsConnectedAction", { action: handler }), true);
      return false;
    }
    return this._socket.executeAsGM(handler, ...args);
  }
  static executeAsUser(handler, userId, ...args) {
    return this._socket.executeAsUser(handler, userId, ...args);
  }
  static executeForAllGMs(handler, ...args) {
    return this._socket.executeForAllGMs(handler, ...args);
  }
  static executeForOtherGMs(handler, ...args) {
    return this._socket.executeForOtherGMs(handler, ...args);
  }
  static executeForEveryone(handler, ...args) {
    return this._socket.executeForEveryone(handler, ...args);
  }
  static executeForOthers(handler, ...args) {
    return this._socket.executeForOthers(handler, ...args);
  }
  static executeForUsers(handler, userIds, ...args) {
    return this._socket.executeForUsers(handler, userIds, ...args);
  }
  static callHook(hook, ...args) {
    if (!hooks.run)
      return;
    return this._socket.executeForEveryone(this.HANDLERS.CALL_HOOK, hook, ...args);
  }
  static callHookForUsers(hook, users, ...args) {
    if (!hooks.run)
      return;
    return this._socket.executeForUsers(this.HANDLERS.CALL_HOOK, users, hook, ...args);
  }
};
__name(_ItemPileSocket, "ItemPileSocket");
__publicField(_ItemPileSocket, "ready", false);
__publicField(_ItemPileSocket, "HANDLERS", {
  /**
   * Generic sockets
   */
  CALL_HOOK: "callHook",
  TOGGLE_HOOKS: "toggleHooks",
  /**
   * Chat messages
   */
  PICKUP_CHAT_MESSAGE: "pickupChatMessage",
  SPLIT_CHAT_MESSAGE: "splitChatMessage",
  MERCHANT_TRADE_CHAT_MESSAGE: "merchantTradeChatMessage",
  DISABLE_CHAT_TRADE_BUTTON: "disableChatTradeButton",
  /**
   * Item pile sockets
   */
  CREATE_PILE: "createItemPile",
  UPDATE_PILE: "updateItemPile",
  UPDATED_PILE: "updatedPile",
  DELETE_PILE: "deleteItemPile",
  TURN_INTO_PILE: "turnIntoPiles",
  REVERT_FROM_PILE: "revertFromPiles",
  REFRESH_PILE: "refreshItemPile",
  SPLIT_PILE: "splitItemPileContent",
  /**
   * UI sockets
   */
  RENDER_INTERFACE: "renderItemPileApplication",
  UNRENDER_INTERFACE: "unrenderItemPileApplication",
  RERENDER_TOKEN_HUD: "rerenderTokenHud",
  USER_OPENED_INTERFACE: "userOpenedInterface",
  USER_CLOSED_INTERFACE: "userClosedInterface",
  /**
   * Item & attribute sockets
   */
  GIVE_ITEMS: "giveItems",
  GIVE_ITEMS_RESPONSE: "giveItemsResponse",
  DROP_ITEMS: "dropItems",
  ADD_ITEMS: "addItems",
  REMOVE_ITEMS: "removeItems",
  TRANSFER_ITEMS: "transferItems",
  TRANSFER_ALL_ITEMS: "transferAllItems",
  ADD_CURRENCIES: "addCurrencies",
  REMOVE_CURRENCIES: "removeCurrencies",
  TRANSFER_CURRENCIES: "transferCurrencies",
  TRANSFER_ALL_CURRENCIES: "transferAllCurrencies",
  SET_ATTRIBUTES: "setAttributes",
  ADD_ATTRIBUTES: "addAttributes",
  REMOVE_ATTRIBUTES: "removeAttributes",
  TRANSFER_ATTRIBUTES: "transferAttributes",
  TRANSFER_ALL_ATTRIBUTES: "transferAllAttributes",
  TRANSFER_EVERYTHING: "transferEverything",
  COMMIT_ACTOR_CHANGES: "commitActorChanges",
  ROLL_ITEM_TABLE: "rollItemTable",
  REFRESH_MERCHANT_INVENTORY: "refreshMerchantInventory",
  /**
   * Trading sockets
   */
  TRADE_REQUEST_PROMPT: "tradePrompt",
  TRADE_REQUEST_CANCELLED: "tradeCancelled",
  REQUEST_TRADE_DATA: "requestTradeData",
  TRADE_CLOSED: "publicTradeClosed",
  PUBLIC_TRADE_UPDATE_ITEMS: "publicTradeUpdateItems",
  PUBLIC_TRADE_UPDATE_ITEM_CURRENCIES: "publicTradeUpdateItemCurrencies",
  PUBLIC_TRADE_UPDATE_CURRENCIES: "publicTradeUpdateCurrencies",
  PUBLIC_TRADE_STATE: "publicTradeAcceptedState",
  PRIVATE_TRADE_UPDATE_ITEMS: "privateTradeUpdateItems",
  PRIVATE_TRADE_UPDATE_ITEM_CURRENCIES: "privateTradeUpdateItemCurrencies",
  PRIVATE_TRADE_UPDATE_CURRENCIES: "privateTradeUpdateCurrencies",
  PRIVATE_TRADE_STATE: "privateTradeAcceptedState",
  EXECUTE_TRADE: "executeTrade",
  TRADE_COMPLETED: "tradeCompleted",
  /**
   * Merchant sockets
   */
  TRADE_ITEMS: "tradeItems"
});
__publicField(_ItemPileSocket, "BINDINGS", {
  [_ItemPileSocket.HANDLERS.CALL_HOOK]: (hook, response, ...args) => callHook(hook, response, ...args),
  [_ItemPileSocket.HANDLERS.TOGGLE_HOOKS]: (toggle) => {
    hooks.run = toggle;
  },
  [_ItemPileSocket.HANDLERS.DROP_ITEMS]: (args) => PrivateAPI._dropItems(args),
  [_ItemPileSocket.HANDLERS.GIVE_ITEMS]: (...args) => PrivateAPI._giveItems(...args),
  [_ItemPileSocket.HANDLERS.GIVE_ITEMS_RESPONSE]: (...args) => PrivateAPI._giveItemsResponse(...args),
  [_ItemPileSocket.HANDLERS.ADD_ITEMS]: (...args) => PrivateAPI._addItems(...args),
  [_ItemPileSocket.HANDLERS.REMOVE_ITEMS]: (...args) => PrivateAPI._removeItems(...args),
  [_ItemPileSocket.HANDLERS.TRANSFER_ITEMS]: (...args) => PrivateAPI._transferItems(...args),
  [_ItemPileSocket.HANDLERS.TRANSFER_ALL_ITEMS]: (...args) => PrivateAPI._transferAllItems(...args),
  [_ItemPileSocket.HANDLERS.ADD_CURRENCIES]: (...args) => PrivateAPI._addCurrencies(...args),
  [_ItemPileSocket.HANDLERS.REMOVE_CURRENCIES]: (...args) => PrivateAPI._removeCurrencies(...args),
  [_ItemPileSocket.HANDLERS.TRANSFER_CURRENCIES]: (...args) => PrivateAPI._transferCurrencies(...args),
  [_ItemPileSocket.HANDLERS.TRANSFER_ALL_CURRENCIES]: (...args) => PrivateAPI._transferAllCurrencies(...args),
  [_ItemPileSocket.HANDLERS.SET_ATTRIBUTES]: (...args) => PrivateAPI._setAttributes(...args),
  [_ItemPileSocket.HANDLERS.ADD_ATTRIBUTES]: (...args) => PrivateAPI._addAttributes(...args),
  [_ItemPileSocket.HANDLERS.REMOVE_ATTRIBUTES]: (...args) => PrivateAPI._removeAttributes(...args),
  [_ItemPileSocket.HANDLERS.TRANSFER_ATTRIBUTES]: (...args) => PrivateAPI._transferAttributes(...args),
  [_ItemPileSocket.HANDLERS.TRANSFER_ALL_ATTRIBUTES]: (...args) => PrivateAPI._transferAllAttributes(...args),
  [_ItemPileSocket.HANDLERS.TRANSFER_EVERYTHING]: (...args) => PrivateAPI._transferEverything(...args),
  [_ItemPileSocket.HANDLERS.COMMIT_ACTOR_CHANGES]: (...args) => PrivateAPI._commitActorChanges(...args),
  [_ItemPileSocket.HANDLERS.ROLL_ITEM_TABLE]: (...args) => PrivateAPI._rollItemTable(...args),
  [_ItemPileSocket.HANDLERS.REFRESH_MERCHANT_INVENTORY]: (...args) => PrivateAPI._refreshMerchantInventory(...args),
  [_ItemPileSocket.HANDLERS.CREATE_PILE]: (...args) => PrivateAPI._createItemPile(...args),
  [_ItemPileSocket.HANDLERS.UPDATE_PILE]: (...args) => PrivateAPI._updateItemPile(...args),
  [_ItemPileSocket.HANDLERS.UPDATED_PILE]: (...args) => PrivateAPI._updatedItemPile(...args),
  [_ItemPileSocket.HANDLERS.DELETE_PILE]: (...args) => PrivateAPI._deleteItemPile(...args),
  [_ItemPileSocket.HANDLERS.TURN_INTO_PILE]: (...args) => PrivateAPI._turnTokensIntoItemPiles(...args),
  [_ItemPileSocket.HANDLERS.REVERT_FROM_PILE]: (...args) => PrivateAPI._revertTokensFromItemPiles(...args),
  [_ItemPileSocket.HANDLERS.SPLIT_PILE]: (...args) => PrivateAPI._splitItemPileContents(...args),
  [_ItemPileSocket.HANDLERS.TRADE_REQUEST_PROMPT]: (...args) => TradeAPI._respondPrompt(...args),
  [_ItemPileSocket.HANDLERS.TRADE_REQUEST_CANCELLED]: (...args) => TradeAPI._tradeCancelled(...args),
  [_ItemPileSocket.HANDLERS.EXECUTE_TRADE]: (...args) => TradeAPI._executeTrade(...args),
  [_ItemPileSocket.HANDLERS.TRADE_COMPLETED]: (...args) => TradeAPI._tradeCompleted(...args),
  [_ItemPileSocket.HANDLERS.REQUEST_TRADE_DATA]: (...args) => TradeAPI._respondActiveTradeData(...args),
  [_ItemPileSocket.HANDLERS.TRADE_CLOSED]: (...args) => TradeAPI._tradeClosed(...args),
  [_ItemPileSocket.HANDLERS.PUBLIC_TRADE_UPDATE_ITEMS]: (...args) => TradeAPI._updateItems(...args),
  [_ItemPileSocket.HANDLERS.PUBLIC_TRADE_UPDATE_ITEM_CURRENCIES]: (...args) => TradeAPI._updateItemCurrencies(...args),
  [_ItemPileSocket.HANDLERS.PUBLIC_TRADE_UPDATE_CURRENCIES]: (...args) => TradeAPI._updateCurrencies(...args),
  [_ItemPileSocket.HANDLERS.PUBLIC_TRADE_STATE]: (...args) => TradeAPI._updateAcceptedState(...args),
  [_ItemPileSocket.HANDLERS.PRIVATE_TRADE_UPDATE_ITEMS]: (...args) => TradeAPI._updateItems(...args),
  [_ItemPileSocket.HANDLERS.PRIVATE_TRADE_UPDATE_ITEM_CURRENCIES]: (...args) => TradeAPI._updateItemCurrencies(...args),
  [_ItemPileSocket.HANDLERS.PRIVATE_TRADE_UPDATE_CURRENCIES]: (...args) => TradeAPI._updateCurrencies(...args),
  [_ItemPileSocket.HANDLERS.PRIVATE_TRADE_STATE]: (...args) => TradeAPI._updateAcceptedState(...args),
  [_ItemPileSocket.HANDLERS.PICKUP_CHAT_MESSAGE]: (...args) => ChatAPI._outputPickupToChat(...args),
  [_ItemPileSocket.HANDLERS.SPLIT_CHAT_MESSAGE]: (...args) => ChatAPI._outputSplitToChat(...args),
  [_ItemPileSocket.HANDLERS.MERCHANT_TRADE_CHAT_MESSAGE]: (...args) => ChatAPI._outputMerchantTradeToChat(...args),
  [_ItemPileSocket.HANDLERS.DISABLE_CHAT_TRADE_BUTTON]: (...args) => ChatAPI._disableTradingButton(...args),
  [_ItemPileSocket.HANDLERS.RENDER_INTERFACE]: (...args) => PrivateAPI._renderItemPileInterface(...args),
  [_ItemPileSocket.HANDLERS.UNRENDER_INTERFACE]: (...args) => PrivateAPI._unrenderItemPileInterface(...args),
  [_ItemPileSocket.HANDLERS.RERENDER_TOKEN_HUD]: (...args) => PrivateAPI._updateTokenHud(...args),
  [_ItemPileSocket.HANDLERS.USER_OPENED_INTERFACE]: (...args) => InterfaceTracker.userOpened(...args),
  [_ItemPileSocket.HANDLERS.USER_CLOSED_INTERFACE]: (...args) => InterfaceTracker.userClosed(...args),
  [_ItemPileSocket.HANDLERS.TRADE_ITEMS]: (...args) => PrivateAPI._tradeItems(...args)
});
__publicField(_ItemPileSocket, "_socket");
let ItemPileSocket = _ItemPileSocket;
async function callHook(hook, ...args) {
  const newArgs = [];
  for (let arg of args) {
    if (stringIsUuid(arg)) {
      const testArg = fromUuidSync(arg);
      if (testArg) {
        arg = testArg;
      }
    }
    newArgs.push(arg);
  }
  return Hooks.callAll(hook, ...newArgs);
}
__name(callHook, "callHook");
const InterfaceTracker = {
  users: {},
  initialize() {
    this.users = {};
    Array.from(game.users).forEach((user) => {
      this.users[user.id] = /* @__PURE__ */ new Set();
    });
    Hooks.on(CONSTANTS.HOOKS.OPEN_INTERFACE, (app) => {
      ItemPileSocket.executeForOthers(ItemPileSocket.HANDLERS.USER_OPENED_INTERFACE, game.user.id, app.id);
    });
    Hooks.on(CONSTANTS.HOOKS.CLOSE_INTERFACE, (app) => {
      ItemPileSocket.executeForOthers(ItemPileSocket.HANDLERS.USER_CLOSED_INTERFACE, game.user.id, app.id);
    });
  },
  userOpened(userId, id) {
    if (!this.users[userId])
      return;
    this.users[userId].add(id);
  },
  userClosed(userId, id) {
    if (!this.users[userId])
      return;
    this.users[userId].delete(id);
  },
  isOpened(id) {
    return Object.values(this.users).some((interfaceList) => interfaceList.has(id));
  }
};
const debounceManager = {
  debounces: {},
  setDebounce(id, method) {
    if (this.debounces[id]) {
      return this.debounces[id];
    }
    this.debounces[id] = debounce(function(...args) {
      delete debounceManager.debounces[id];
      return method(...args);
    }, 250);
    return this.debounces[id];
  }
};
const hooks = {
  run: true,
  _hooks: {},
  async runWithout(callback) {
    await ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.TOGGLE_HOOKS, false);
    await callback();
    await ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.TOGGLE_HOOKS, true);
  },
  call(hook, ...args) {
    if (!this.run)
      return;
    return Hooks.call(hook, ...args);
  },
  callAll(hook, ...args) {
    if (!this.run)
      return;
    return Hooks.callAll(hook, ...args);
  },
  on(hook, callback) {
    Hooks.on(hook, (...args) => {
      if (!this.run)
        return;
      callback(...args);
    });
  }
};
function getModuleVersion() {
  return game.modules.get(CONSTANTS.MODULE_NAME).version;
}
__name(getModuleVersion, "getModuleVersion");
function isFunction(inFunc) {
  return inFunc && ({}.toString.call(inFunc) === "[object Function]" || {}.toString.call(inFunc) === "[object AsyncFunction]");
}
__name(isFunction, "isFunction");
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
__name(wait, "wait");
function getSetting(key) {
  return game.settings.get(CONSTANTS.MODULE_NAME, key);
}
__name(getSetting, "getSetting");
function setSetting(key, value) {
  if (value === void 0) {
    throw new Error("setSetting | value must not be undefined!");
  }
  return game.settings.set(CONSTANTS.MODULE_NAME, key, value);
}
__name(setSetting, "setSetting");
function debug(msg, args = "") {
  if (game.settings.get(CONSTANTS.MODULE_NAME, "debug")) {
    console.log(`DEBUG | Item Piles | ${msg}`, args);
  }
}
__name(debug, "debug");
function custom_notify(message) {
  message = `Item Piles | ${message}`;
  ui.notifications.notify(message, { console: false });
  console.log(message.replace("<br>", "\n"));
}
__name(custom_notify, "custom_notify");
function custom_warning(warning, notify = false) {
  warning = `Item Piles | ${warning}`;
  if (notify) {
    ui.notifications.warn(warning, { console: false });
  }
  console.warn(warning.replace("<br>", "\n"));
}
__name(custom_warning, "custom_warning");
function custom_error(error, notify = true) {
  error = `Item Piles | ${error}`;
  if (notify) {
    ui.notifications.error(error, { console: false });
  }
  return new Error(error.replace("<br>", "\n"));
}
__name(custom_error, "custom_error");
function isRealNumber(inNumber) {
  return !isNaN(inNumber) && typeof inNumber === "number" && isFinite(inNumber);
}
__name(isRealNumber, "isRealNumber");
function isActiveGM(user) {
  return user.active && user.isGM;
}
__name(isActiveGM, "isActiveGM");
function getActiveGMs() {
  return game.users.filter(isActiveGM);
}
__name(getActiveGMs, "getActiveGMs");
function isResponsibleGM() {
  if (!game.user.isGM) {
    return false;
  }
  return !getActiveGMs().some((other) => other.id < game.user.id);
}
__name(isResponsibleGM, "isResponsibleGM");
function isGMConnected() {
  return !!Array.from(game.users).find((user) => user.isGM && user.active);
}
__name(isGMConnected, "isGMConnected");
function roundToDecimals(num, decimals) {
  if (!decimals)
    return Math.floor(num);
  return Number(Math.round(num + "e" + decimals) + "e-" + decimals);
}
__name(roundToDecimals, "roundToDecimals");
function clamp(num, min2, max2) {
  return Math.max(Math.min(num, max2), min2);
}
__name(clamp, "clamp");
function getActiveApps(id, single = false) {
  const apps = Object.values(ui.windows).filter((app) => app.id.startsWith(id) && app._state > Application.RENDER_STATES.CLOSED);
  if (single) {
    return apps?.[0] ?? false;
  }
  return apps;
}
__name(getActiveApps, "getActiveApps");
async function getFiles(inFile, { applyWildCard = false, softFail = false } = {}) {
  let source = "data";
  const browseOptions = { wildcard: applyWildCard };
  if (/\.s3\./.test(inFile)) {
    source = "s3";
    const { bucket, keyPrefix } = FilePicker.parseS3URL(inFile);
    if (bucket) {
      browseOptions.bucket = bucket;
      inFile = keyPrefix;
    }
  }
  try {
    return (await FilePicker.browse(source, inFile, browseOptions)).files;
  } catch (err) {
    if (softFail)
      return false;
    throw custom_error(`Could not get files! | ${err}`);
  }
}
__name(getFiles, "getFiles");
function random_float_between(min2, max2) {
  const random = Math.random();
  const _max = Math.max(max2, min2);
  const _min = Math.min(max2, min2);
  return random * (_max - _min) + _min;
}
__name(random_float_between, "random_float_between");
function random_int_between(min2, max2) {
  return Math.floor(random_float_between(min2, max2));
}
__name(random_int_between, "random_int_between");
function random_array_element(inArray, { recurse = false } = {}) {
  let choice = inArray[random_int_between(0, inArray.length)];
  if (recurse && Array.isArray(choice)) {
    return random_array_element(choice, { recurse: true });
  }
  return choice;
}
__name(random_array_element, "random_array_element");
function styleFromObject(obj, vars = false) {
  return Object.entries(obj).map((entry) => (vars ? "--" : "") + entry[0] + ": " + entry[1] + ";").join("");
}
__name(styleFromObject, "styleFromObject");
function abbreviateNumbers(number, decPlaces = 2) {
  decPlaces = Math.pow(10, decPlaces);
  let abbrev = ["k", "m", "b", "t"];
  for (let i = abbrev.length - 1; i >= 0; i--) {
    let size = Math.pow(10, (i + 1) * 3);
    if (size <= number) {
      number = Math.round(number * decPlaces / size) / decPlaces;
      if (number === 1e3 && i < abbrev.length - 1) {
        number = 1;
        i++;
      }
      number += abbrev[i];
      break;
    }
  }
  return number;
}
__name(abbreviateNumbers, "abbreviateNumbers");
function timeSince(date) {
  const seconds = Math.floor((/* @__PURE__ */ new Date() - date) / 1e3);
  const intervals = {
    "d": 86400,
    "h": 3600,
    "m": 60
  };
  for (const [key, value] of Object.entries(intervals)) {
    const interval = seconds / value;
    if (interval > 1) {
      return Math.floor(interval) + key;
    }
  }
  return Math.ceil(seconds) + "s";
}
__name(timeSince, "timeSince");
function getApplicationPositions(application_1, application_2 = false) {
  let midPoint = window.innerWidth / 2;
  if (!application_2) {
    if (midPoint - 200 - application_1.position.width - 25 > 0) {
      midPoint -= 200;
    }
    return [
      { left: midPoint - application_1.position.width - 25 },
      { left: midPoint + 25 }
    ];
  }
  const application_1_position = {
    left: application_1.position.left,
    top: application_1.position.top,
    width: application_1.position.width
  };
  const application_2_position = {
    left: application_2.position.left,
    top: application_1.position.top,
    width: application_2.position.width
  };
  application_2_position.left = application_1_position.left - application_2_position.width - 25;
  if (application_2_position.left < 0) {
    application_2_position.left = application_1_position.left + application_1_position.width + 25;
  }
  if (application_2_position.left + application_2_position.width > window.innerWidth) {
    application_2_position.left = midPoint - application_2_position.width - 25;
    application_1_position.left = midPoint + 25;
  }
  return [
    application_1_position,
    application_2_position
  ];
}
__name(getApplicationPositions, "getApplicationPositions");
async function openEditor(key, data2 = false) {
  const setting = SETTINGS$1.DEFAULTS()[key];
  const editor = editors[setting.application];
  if (!data2) {
    data2 = getSetting(key);
  }
  const result = await editor.show(data2, { ...setting.applicationOptions, onchange: setting.onchange });
  if (setting.onchange && result)
    setting.onchange(result);
  return result;
}
__name(openEditor, "openEditor");
function isCoordinateWithinPosition(x, y, position) {
  return x >= position.left && x < position.left + position.width && y >= position.top && y < position.top + position.height;
}
__name(isCoordinateWithinPosition, "isCoordinateWithinPosition");
function getCanvasMouse() {
  return game.release.generation === 11 ? canvas.app.renderer.plugins.interaction.pointer : canvas.app.renderer.plugins.interaction.mouse;
}
__name(getCanvasMouse, "getCanvasMouse");
let fastToolTip = null;
function registerUIOverrides() {
  Hooks.on("renderPlayerList", addTradeButton);
  Hooks.on("getActorDirectoryEntryContext", insertActorContextMenuItems);
  Hooks.on("getActorSheetHeaderButtons", insertActorHeaderButtons);
  Hooks.on("getItemSheetHeaderButtons", insertItemHeaderButtons);
  Hooks.on("renderSidebarTab", hideTemporaryItems);
  Hooks.on("renderTokenHUD", renderPileHUD);
  Hooks.on("hoverToken", handleTokenBorders);
  Hooks.on("controlToken", handleTokenBorders);
  fastToolTip = new FastTooltipManager();
  fastToolTip.activateEventListeners();
}
__name(registerUIOverrides, "registerUIOverrides");
function handleTokenBorders(token) {
  if (!isValidItemPile(token))
    return;
  const setting = getSetting(SETTINGS$1.HIDE_TOKEN_BORDER);
  token.border.renderable = token.controlled || setting !== SETTINGS$1.HIDE_TOKEN_BORDER_OPTIONS.EVERYONE && (setting === SETTINGS$1.HIDE_TOKEN_BORDER_OPTIONS.SHOW || setting === SETTINGS$1.HIDE_TOKEN_BORDER_OPTIONS.PLAYERS && game.user.isGM);
}
__name(handleTokenBorders, "handleTokenBorders");
function hideTemporaryItems(sidebar) {
  if (sidebar.tabName !== "items")
    return;
  Array.from(game.items).filter((item) => {
    return getProperty(item.toObject(), CONSTANTS.FLAGS.TEMPORARY_ITEM);
  }).forEach((item) => {
    const element2 = sidebar.element.find(`.directory-item[data-document-id="${item.id}"]`);
    if (!element2.length)
      return;
    if (element2.parent().children().length === 1) {
      return element2.parent().empty();
    }
    element2.find(`.directory-item[data-document-id="${item.id}"]`).remove();
  });
}
__name(hideTemporaryItems, "hideTemporaryItems");
function addTradeButton(app, html) {
  if (!getSetting(SETTINGS$1.ENABLE_TRADING) || !getSetting(SETTINGS$1.SHOW_TRADE_BUTTON))
    return;
  const minimalUI = game.modules.get("minimal-ui")?.active;
  const classes = "item-piles-player-list-trade-button" + (minimalUI ? " item-piles-minimal-ui" : "");
  const text2 = !minimalUI ? game.i18n.localize("ITEM-PILES.ContextMenu.RequestTrade") : "";
  const button = $(`<button type="button" class="${classes}"><i class="fas fa-handshake"></i>${text2}</button>`);
  button.click(() => {
    game.itempiles.API.requestTrade();
  });
  html.append(button);
}
__name(addTradeButton, "addTradeButton");
function insertActorContextMenuItems(html, menuItems) {
  menuItems.push({
    name: "Item Piles: " + game.i18n.localize("ITEM-PILES.ContextMenu.ShowToPlayers"),
    icon: `<i class="fas fa-eye"></i>`,
    callback: async (html2) => {
      const actorId = html2[0].dataset.documentId;
      const actor = game.actors.get(actorId);
      const activeUsers = Array.from(game.users).filter((u) => u.active && u !== game.user).map((u) => u.id);
      if (!activeUsers.length) {
        return custom_warning(game.i18n.localize("ITEM-PILES.Warnings.NoPlayersActive"), true);
      }
      const users = await UserSelectDialog.show();
      if (!users || !users.length)
        return;
      custom_notify(game.i18n.format("ITEM-PILES.Notifications.ShownToPlayers", { actor_name: actor.name }));
      return game.itempiles.API.renderItemPileInterface(actor, { userIds: users, useDefaultCharacter: true });
    },
    condition: (html2) => {
      const actorId = html2[0].dataset.documentId;
      const actor = game.actors.get(actorId);
      return game.user.isGM && isValidItemPile(actor);
    }
  }, {
    name: "Item Piles: " + game.i18n.localize("ITEM-PILES.ContextMenu.RequestTrade"),
    icon: `<i class="fas fa-handshake"></i>`,
    callback: (html2) => {
      const actorId = html2[0].dataset.documentId;
      const actor = game.actors.get(actorId);
      const user = Array.from(game.users).find((u) => u.character === actor && u.active);
      return game.itempiles.API.requestTrade(user);
    },
    condition: (html2) => {
      const actorId = html2[0].dataset.documentId;
      const actor = game.actors.get(actorId);
      return getSetting(SETTINGS$1.ENABLE_TRADING) && (game.user?.character !== actor || Array.from(game.users).find((u) => u.character === actor && u.active));
    }
  });
}
__name(insertActorContextMenuItems, "insertActorContextMenuItems");
function insertActorHeaderButtons(actorSheet, buttons) {
  if (!game.user.isGM || getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON))
    return;
  let obj = actorSheet?.object ?? actorSheet?.actor;
  buttons.unshift({
    label: getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "" : "Configure",
    icon: "fas fa-box-open",
    class: "item-piles-config-button",
    onclick: () => {
      ItemPileConfig.show(obj);
    }
  });
}
__name(insertActorHeaderButtons, "insertActorHeaderButtons");
function insertItemHeaderButtons(itemSheet, buttons) {
  if (!game.user.isGM || getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_BUTTON))
    return;
  let obj = itemSheet?.object ?? itemSheet?.item;
  buttons.unshift({
    label: getSetting(SETTINGS$1.HIDE_ACTOR_HEADER_TEXT) ? "" : "Configure",
    icon: "fas fa-box-open",
    class: "item-piles-config-button",
    onclick: async (event) => {
      if (game.modules.get("item-linking")?.active && !event.ctrlKey) {
        const linkedItemUuid = getProperty(obj, "flags.item-linking.baseItem") ?? false;
        if (linkedItemUuid) {
          obj = await fromUuid(linkedItemUuid);
          return ItemEditor.show(obj, {
            extraTitle: " - Compendium"
          });
        }
      }
      return ItemEditor.show(obj);
    }
  });
}
__name(insertItemHeaderButtons, "insertItemHeaderButtons");
function renderPileHUD(app, html) {
  const document2 = app?.object?.document;
  if (!document2)
    return;
  if (!isValidItemPile(document2))
    return;
  if (isItemPileContainer(document2)) {
    const pileData = getActorFlagData(document2);
    const container = $(`<div class="col right" style="right:-130px;"></div>`);
    const lock_button = $(`<div class="control-icon item-piles" data-fast-tooltip="${game.i18n.localize("ITEM-PILES.HUD.ToggleLocked")}"><i class="fas fa-lock${pileData.locked ? "" : "-open"}"></i></div>`);
    lock_button.click(async function() {
      $(this).find(".fas").toggleClass("fa-lock").toggleClass("fa-lock-open");
      await game.itempiles.API.toggleItemPileLocked(document2);
    });
    container.append(lock_button);
    const open_button = $(`<div class="control-icon item-piles" data-fast-tooltip="${game.i18n.localize("ITEM-PILES.HUD.ToggleClosed")}"><i class="fas fa-box${pileData.closed ? "" : "-open"}"></i></div>`);
    open_button.click(async function() {
      $(this).find(".fas").toggleClass("fa-box").toggleClass("fa-box-open");
      await game.itempiles.API.toggleItemPileClosed(document2);
    });
    container.append(open_button);
    const configure_button = $(`<div class="control-icon item-piles" data-fast-tooltip="${game.i18n.localize("ITEM-PILES.HUD.Configure")}"><i class="fas fa-toolbox"></i></div>`);
    configure_button.click(async function() {
      ItemPileConfig.show(document2);
    });
    container.append(configure_button);
    html.append(container);
  }
}
__name(renderPileHUD, "renderPileHUD");
const _FastTooltipManager = class _FastTooltipManager extends TooltipManager {
  constructor() {
    super();
    /* -------------------------------------------- */
    /**
     * Handle hover events which activate a tooltipped element.
     * @param {PointerEvent} event    The initiating pointerenter event
     */
    __privateAdd(this, _onActivate);
    /* -------------------------------------------- */
    /**
     * Handle hover events which deactivate a tooltipped element.
     * @param {PointerEvent} event    The initiating pointerleave event
     */
    __privateAdd(this, _onDeactivate);
    /* -------------------------------------------- */
    /**
     * Start the deactivation process.
     */
    __privateAdd(this, _startDeactivation);
    /* -------------------------------------------- */
    /**
     * Clear any existing deactivation workflow.
     */
    __privateAdd(this, _clearDeactivation);
    /**
     * A reference to the HTML element which is currently tool-tipped, if any.
     * @type {HTMLElement|null}
     */
    __publicField(this, "element", null);
    /**
     * Is the tooltip currently active?
     * @type {boolean}
     */
    __privateAdd(this, _active, false);
    /**
     * A reference to a window timeout function when an element is activated.
     * @private
     */
    __privateAdd(this, _activationTimeout, void 0);
    /**
     * A reference to a window timeout function when an element is deactivated.
     * @private
     */
    __privateAdd(this, _deactivationTimeout, void 0);
    /**
     * An element which is pending tooltip activation if hover is sustained
     * @type {HTMLElement|null}
     */
    __privateAdd(this, _pending, void 0);
    const tooltipElem = $(`<aside id="fast-tooltip" role="tooltip"></aside>`);
    $("body").append(tooltipElem);
    this.tooltip = document.getElementById("fast-tooltip");
  }
  /* -------------------------------------------- */
  /**
   * Activate interactivity by listening for hover events on HTML elements which have a data-fast-tooltip defined.
   */
  activateEventListeners() {
    document.body.addEventListener("pointerenter", __privateMethod(this, _onActivate, onActivate_fn).bind(this), true);
    document.body.addEventListener("pointerleave", __privateMethod(this, _onDeactivate, onDeactivate_fn).bind(this), true);
  }
  activate(element2, { text: text2, direction, cssClass } = {}) {
    if (!document.body.contains(element2))
      return;
    __privateMethod(this, _clearDeactivation, clearDeactivation_fn).call(this);
    __privateSet(this, _active, true);
    this.element = element2;
    element2.setAttribute("aria-describedby", "fast-tooltip");
    this.tooltip.innerHTML = text2 || game.i18n.localize(element2.dataset.fastTooltip);
    this.tooltip.removeAttribute("class");
    this.tooltip.classList.add("active");
    if (cssClass)
      this.tooltip.classList.add(cssClass);
    direction = direction || element2.closest("[data-tooltip-direction]")?.dataset.tooltipDirection;
    if (!direction)
      direction = this._determineDirection();
    this._setAnchor(direction);
  }
};
_active = new WeakMap();
_activationTimeout = new WeakMap();
_deactivationTimeout = new WeakMap();
_pending = new WeakMap();
_onActivate = new WeakSet();
onActivate_fn = /* @__PURE__ */ __name(function(event) {
  if (Tour.tourInProgress)
    return;
  const element2 = event.target;
  if (!element2.dataset.fastTooltip) {
    if (__privateGet(this, _active) && this.element && !this.element.contains(element2))
      __privateMethod(this, _startDeactivation, startDeactivation_fn).call(this);
    return;
  }
  if (element2.matches("#context-menu") || element2.querySelector("#context-menu"))
    return;
  if (__privateGet(this, _active))
    this.activate(element2);
  else
    __privateMethod(this, _clearDeactivation, clearDeactivation_fn).call(this);
  __privateSet(this, _pending, element2);
  __privateSet(this, _activationTimeout, window.setTimeout(() => {
    this.activate(element2);
  }, Number(element2?.dataset?.tooltipActivationSpeed) ?? this.constructor.TOOLTIP_ACTIVATION_MS));
}, "#onActivate");
_onDeactivate = new WeakSet();
onDeactivate_fn = /* @__PURE__ */ __name(function(event) {
  if (event.target !== (this.element ?? __privateGet(this, _pending)))
    return;
  __privateMethod(this, _startDeactivation, startDeactivation_fn).call(this);
}, "#onDeactivate");
_startDeactivation = new WeakSet();
startDeactivation_fn = /* @__PURE__ */ __name(function() {
  window.clearTimeout(__privateGet(this, _activationTimeout));
  __privateSet(this, _pending, __privateSet(this, _activationTimeout, null));
  window.clearTimeout(__privateGet(this, _deactivationTimeout));
  __privateSet(this, _deactivationTimeout, window.setTimeout(() => {
    if (!__privateGet(this, _pending))
      this.deactivate();
  }, Number(this.element?.dataset?.tooltipDeactivationSpeed) ?? this.constructor.TOOLTIP_DEACTIVATION_MS));
}, "#startDeactivation");
_clearDeactivation = new WeakSet();
clearDeactivation_fn = /* @__PURE__ */ __name(function() {
  window.clearTimeout(__privateGet(this, _deactivationTimeout));
  __privateSet(this, _pending, __privateSet(this, _deactivationTimeout, null));
}, "#clearDeactivation");
__name(_FastTooltipManager, "FastTooltipManager");
/**
 * An amount of margin which is used to offset tooltips from their anchored element.
 * @type {number}
 */
__publicField(_FastTooltipManager, "TOOLTIP_MARGIN_PX", 5);
/**
 * The number of milliseconds delay which activates a tooltip on a "long hover".
 * @type {number}
 */
__publicField(_FastTooltipManager, "TOOLTIP_ACTIVATION_MS", 500);
/**
 * The number of milliseconds delay which activates a tooltip on a "long hover".
 * @type {number}
 */
__publicField(_FastTooltipManager, "TOOLTIP_DEACTIVATION_MS", 500);
/**
 * The directions in which a tooltip can extend, relative to its tool-tipped element.
 * @enum {string}
 */
__publicField(_FastTooltipManager, "TOOLTIP_DIRECTIONS", {
  UP: "UP",
  DOWN: "DOWN",
  LEFT: "LEFT",
  RIGHT: "RIGHT",
  CENTER: "CENTER"
});
let FastTooltipManager = _FastTooltipManager;
function registerLibwrappers() {
  libWrapper.register(CONSTANTS.MODULE_NAME, "Token.prototype._onClickLeft2", function(wrapped, ...args) {
    if (isValidItemPile(this.document) && hotkeyActionState.openPileInventory) {
      return PrivateAPI._itemPileClicked(this.document);
    }
    return wrapped(...args);
  }, "MIXED");
  const versionIsEleven = foundry.utils.isNewerVersion(game.version, "10.999");
  const overrideMethod = versionIsEleven ? `DocumentDirectory.prototype._onClickEntryName` : `SidebarDirectory.prototype._onClickDocumentName`;
  libWrapper.register(CONSTANTS.MODULE_NAME, overrideMethod, function(wrapped, event) {
    event.preventDefault();
    const element2 = event.currentTarget;
    if (!(this instanceof Compendium)) {
      const documentId = element2.parentElement.dataset.documentId;
      const document2 = this.constructor.collection.get(documentId);
      if (isValidItemPile(document2)) {
        const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_DIRECTORY_CLICK, document2);
        if (hookResult === false)
          return false;
      }
    }
    return wrapped(event);
  }, "MIXED");
  Hooks.on(CONSTANTS.HOOKS.PRE_RENDER_SHEET, (doc, forced, options) => {
    const renderItemPileInterface = forced && !options?.bypassItemPiles && isValidItemPile(doc) && hotkeyActionState.openPileInventory;
    if (!renderItemPileInterface)
      return;
    game.itempiles.API.renderItemPileInterface(doc, { useDefaultCharacter: true });
    return false;
  });
  libWrapper.register(CONSTANTS.MODULE_NAME, `ActorSheet.prototype.render`, function(wrapped, forced, options, ...args) {
    const renderItemPileInterface = Hooks.call(CONSTANTS.HOOKS.PRE_RENDER_SHEET, this.document, forced, options) === false;
    if (this._state > Application.RENDER_STATES.NONE) {
      if (renderItemPileInterface) {
        wrapped(forced, options, ...args);
      } else {
        return wrapped(forced, options, ...args);
      }
    }
    if (renderItemPileInterface)
      return;
    return wrapped(forced, options, ...args);
  }, "MIXED");
  libWrapper.register(CONSTANTS.MODULE_NAME, "DragDrop.prototype.callback", function(wrapped, event, type) {
    const result = wrapped(event, type);
    const hookType = {
      "dragstart": CONSTANTS.HOOKS.DRAG_DOCUMENT,
      "drop": CONSTANTS.HOOKS.DROP_DOCUMENT
    }[type] ?? false;
    if (hookType) {
      try {
        const value = JSON.parse(event.dataTransfer.getData("text/plain"));
        Hooks.callAll(hookType, value);
      } catch (err) {
      }
    }
    return result;
  }, "WRAPPER");
  if (SYSTEMS.DATA.SHEET_OVERRIDES) {
    SYSTEMS.DATA.SHEET_OVERRIDES();
  }
}
__name(registerLibwrappers, "registerLibwrappers");
const _API = class _API {
  /**
   * @class API
   */
  /**
   * The actor class type used for the original item pile actor in this system
   *
   * @returns {string}
   */
  static get ACTOR_CLASS_TYPE() {
    return getSetting(SETTINGS$1.ACTOR_CLASS_TYPE);
  }
  /**
   * The currencies used in this system
   *
   * @returns {Array<{primary: boolean, name: string, data: Object, img: string, abbreviation: string, exchange: number}>}
   */
  static get CURRENCIES() {
    return foundry.utils.deepClone(getSetting(SETTINGS$1.CURRENCIES).map((currency) => {
      if (currency.type === "item" && currency.data.uuid) {
        const compendiumItem = getItemFromCache(currency.data.uuid);
        if (compendiumItem) {
          currency.data.item = compendiumItem;
        }
      }
      delete currency["quantity"];
      currency.secondary = false;
      return currency;
    }));
  }
  /**
   * The secondary currencies used in this system
   *
   * @returns {Array<{name: string, data: Object, img: string, abbreviation: string}>}
   */
  static get SECONDARY_CURRENCIES() {
    return foundry.utils.deepClone(getSetting(SETTINGS$1.SECONDARY_CURRENCIES).map((currency) => {
      if (currency.type === "item" && currency.data.uuid) {
        const compendiumItem = getItemFromCache(currency.data.uuid);
        if (compendiumItem) {
          currency.data.item = compendiumItem;
        }
      }
      delete currency["quantity"];
      currency.secondary = true;
      return currency;
    }));
  }
  /**
   * The smallest decimal digits shown for any fractional currency amounts. Only used when there is only one currency.
   *
   * @returns {Number}
   */
  static get CURRENCY_DECIMAL_DIGITS() {
    return getSetting(SETTINGS$1.CURRENCY_DECIMAL_DIGITS);
  }
  /**
   * The attribute used to track the price of items in this system
   *
   * @returns {string}
   */
  static get ITEM_PRICE_ATTRIBUTE() {
    return getSetting(SETTINGS$1.ITEM_PRICE_ATTRIBUTE);
  }
  /**
   * The attribute used to track the quantity of items you would get for the price of an item
   *
   * @returns {string}
   */
  static get QUANTITY_FOR_PRICE_ATTRIBUTE() {
    return getSetting(SETTINGS$1.QUANTITY_FOR_PRICE_ATTRIBUTE);
  }
  /**
   * The attribute used to track the quantity of items in this system
   *
   * @returns {string}
   */
  static get ITEM_QUANTITY_ATTRIBUTE() {
    return getSetting(SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE);
  }
  /**
   * The filters for item types eligible for interaction within this system
   *
   * @returns {Array<{name: string, filters: string}>}
   */
  static get ITEM_FILTERS() {
    return getSetting(SETTINGS$1.ITEM_FILTERS);
  }
  /**
   * The attributes for detecting item similarities
   *
   * @returns {Array<string>}
   */
  static get ITEM_SIMILARITIES() {
    return getSetting(SETTINGS$1.ITEM_SIMILARITIES);
  }
  /**
   * The types of items that will always be considered unique when transferring between actors
   *
   * @returns {Array<string>}
   */
  static get UNSTACKABLE_ITEM_TYPES() {
    return getSetting(SETTINGS$1.UNSTACKABLE_ITEM_TYPES);
  }
  /**
   * The system specific default values for item pile actors created in this system
   *
   * @returns {Object}
   */
  static get PILE_DEFAULTS() {
    return getSetting(SETTINGS$1.PILE_DEFAULTS);
  }
  /**
   * The system specific default values for item pile tokens created in this system
   *
   * @returns {Object}
   */
  static get TOKEN_FLAG_DEFAULTS() {
    return getSetting(SETTINGS$1.TOKEN_FLAG_DEFAULTS);
  }
  /**
   * Sets the actor class type used for the original item pile actor in this system
   *
   * @param {string} inClassType
   * @returns {Promise}
   */
  static async setActorClassType(inClassType) {
    if (typeof inClassType !== "string") {
      throw custom_error("setActorTypeClass | inClassType must be of type string");
    }
    return setSetting(SETTINGS$1.ACTOR_CLASS_TYPE, inClassType);
  }
  /**
   * Sets the currencies used in this system
   *
   * @param {Array<Object>} inCurrencies
   * @returns {Promise}
   */
  static async setCurrencies(inCurrencies) {
    if (!Array.isArray(inCurrencies)) {
      throw custom_error("setCurrencies | inCurrencies must be an array");
    }
    inCurrencies.forEach((currency) => {
      if (typeof currency !== "object") {
        throw custom_error("setCurrencies | each entry in inCurrencies must be of type object");
      }
      if (typeof currency.primary !== "boolean") {
        throw custom_error("setCurrencies | currency.primary must be of type boolean");
      }
      if (typeof currency.name !== "string") {
        throw custom_error("setCurrencies | currency.name must be of type string");
      }
      if (typeof currency.abbreviation !== "string") {
        throw custom_error("setCurrencies | currency.abbreviation must be of type string");
      }
      if (typeof currency.exchangeRate !== "number") {
        throw custom_error("setCurrencies | currency.exchangeRate must be of type number");
      }
      if (typeof currency.data !== "object") {
        throw custom_error("setCurrencies | currency.data must be of type object");
      }
      if (typeof currency.data.path !== "string" && typeof currency.data.uuid !== "string" && typeof currency.data.item !== "object") {
        throw custom_error('setCurrencies | currency.data must contain either "path" (string), "uuid" (string), or "item" (object)');
      }
      if (currency.img && typeof currency.img !== "string") {
        throw custom_error("setCurrencies | currency.img must be of type string");
      }
    });
    return setSetting(SETTINGS$1.CURRENCIES, inCurrencies);
  }
  /**
   * Sets the secondary currencies used in this system
   *
   * @param {Array<Object>} inSecondaryCurrencies
   * @returns {Promise}
   */
  static async setSecondaryCurrencies(inSecondaryCurrencies) {
    if (!Array.isArray(inSecondaryCurrencies)) {
      throw custom_error("setSecondaryCurrencies | inSecondaryCurrencies must be an array");
    }
    inSecondaryCurrencies.forEach((currency) => {
      if (typeof currency !== "object") {
        throw custom_error("setSecondaryCurrencies | each entry in inSecondaryCurrencies must be of type object");
      }
      if (typeof currency.name !== "string") {
        throw custom_error("setSecondaryCurrencies | currency.name must be of type string");
      }
      if (typeof currency.abbreviation !== "string") {
        throw custom_error("setSecondaryCurrencies | currency.abbreviation must be of type string");
      }
      if (typeof currency.data !== "object") {
        throw custom_error("setSecondaryCurrencies | currency.data must be of type object");
      }
      if (typeof currency.data.path !== "string" && typeof currency.data.uuid !== "string" && typeof currency.data.item !== "object") {
        throw custom_error('setSecondaryCurrencies | currency.data must contain either "path" (string), "uuid" (string), or "item" (object)');
      }
      if (currency.img && typeof currency.img !== "string") {
        throw custom_error("setSecondaryCurrencies | currency.img must be of type string");
      }
    });
    return setSetting(SETTINGS$1.SECONDARY_CURRENCIES, inSecondaryCurrencies);
  }
  /**
   * Set the smallest decimal digits shown for any fractional currency amounts. Only used when there is only one currency.
   *
   * @param {Number} inDecimalDigits
   * @returns {Promise}
   */
  static setCurrencyDecimalDigits(inDecimalDigits) {
    if (typeof inDecimalDigits !== "number") {
      throw custom_error("setCurrencyDecimalDigits | inDecimalDigits must be of type string");
    }
    return setSetting(SETTINGS$1.CURRENCY_DECIMAL_DIGITS, inDecimalDigits);
  }
  /**
   * Sets the attribute used to track the quantity of items in this system
   *
   * @param {string} inAttribute
   * @returns {Promise}
   */
  static async setItemQuantityAttribute(inAttribute) {
    if (typeof inAttribute !== "string") {
      throw custom_error("setItemQuantityAttribute | inAttribute must be of type string");
    }
    return setSetting(SETTINGS$1.ITEM_QUANTITY_ATTRIBUTE, inAttribute);
  }
  /**
   * Sets the attribute used to track the price of items in this system
   *
   * @param {string} inAttribute
   * @returns {Promise}
   */
  static async setItemPriceAttribute(inAttribute) {
    if (typeof inAttribute !== "string") {
      throw custom_error("setItemPriceAttribute | inAttribute must be of type string");
    }
    return setSetting(SETTINGS$1.ITEM_PRICE_ATTRIBUTE, inAttribute);
  }
  /**
   * Sets the attribute used to track the price of items in this system
   *
   * @param {string} inAttribute
   * @returns {Promise}
   */
  static async setQuantityForPriceAttribute(inAttribute) {
    if (typeof inAttribute !== "string") {
      throw custom_error("setQuantityForPriceAttribute | inAttribute must be of type string");
    }
    return setSetting(SETTINGS$1.QUANTITY_FOR_PRICE_ATTRIBUTE, inAttribute);
  }
  /**
   * Sets the items filters for interaction within this system
   *
   * @param {Array<{path: string, filters: string}>} inFilters
   * @returns {Promise}
   */
  static async setItemFilters(inFilters) {
    if (!Array.isArray(inFilters)) {
      throw custom_error("setItemFilters | inFilters must be of type array");
    }
    inFilters.forEach((filter2) => {
      if (typeof filter2?.path !== "string") {
        throw custom_error('setItemFilters | each entry in inFilters must have a "path" property with a value that is of type string');
      }
      if (typeof filter2?.filters !== "string") {
        throw custom_error('setItemFilters | each entry in inFilters must have a "filters" property with a value that is of type string');
      }
    });
    return setSetting(SETTINGS$1.ITEM_FILTERS, inFilters);
  }
  /**
   * Sets the attributes for detecting item similarities
   *
   * @param {Array<string>} inPaths
   * @returns {Promise}
   */
  static async setItemSimilarities(inPaths) {
    if (!Array.isArray(inPaths)) {
      throw custom_error("setItemSimilarities | inPaths must be of type array");
    }
    inPaths.forEach((path) => {
      if (typeof path !== "string") {
        throw custom_error("setItemSimilarities | each entry in inPaths must be of type string");
      }
    });
    return setSetting(SETTINGS$1.ITEM_SIMILARITIES, inPaths);
  }
  /**
   * Sets the types of items that will always be considered unique when transferring between actors
   *
   * @param {Array<string>} inTypes
   * @returns {Promise}
   */
  static async setUnstackableItemTypes(inTypes) {
    if (!Array.isArray(inTypes)) {
      throw custom_error("setUnstackableItemTypes | inTypes must be of type array");
    }
    inTypes.forEach((path) => {
      if (typeof path !== "string") {
        throw custom_error("setUnstackableItemTypes | each entry in inTypes must be of type string");
      }
    });
    return setSetting(SETTINGS$1.UNSTACKABLE_ITEM_TYPES, inTypes);
  }
  /**
   * Sets the types of items that will always be considered unique when transferring between actors
   *
   * @param {Object} inDefaults
   * @returns {Promise}
   */
  static async setPileDefaults(inDefaults) {
    if (typeof inDefaults !== "object") {
      throw custom_error("setPileDefaults | inDefaults must be of type object");
    }
    const validKeys = new Set(Object.keys(CONSTANTS.PILE_DEFAULTS));
    for (const key of Object.keys(inDefaults)) {
      if (!validKeys.has(key)) {
        throw custom_error(`setPileDefaults | ${key} is not a valid pile setting`);
      }
    }
    return setSetting(SETTINGS$1.PILE_DEFAULTS, inDefaults);
  }
  /**
   * Set the flags that will be applied to any tokens created through item piles
   *
   * @param {Object} inDefaults
   * @returns {Promise}
   */
  static async setTokenFlagDefaults(inDefaults) {
    if (typeof inDefaults !== "object") {
      throw custom_error("setTokenFlagDefaults | inDefaults must be of type object");
    }
    return setSetting(SETTINGS$1.TOKEN_FLAG_DEFAULTS, inDefaults);
  }
  /**
   * A combination of all the methods above, but this integrates a system's specific
   * settings more readily into item piles, allowing users to also change the settings
   * afterward.
   *
   * @param {Object<{
   *   VERSION: string,
   *   ACTOR_CLASS_TYPE: string,
   *   ITEM_QUANTITY_ATTRIBUTE: string,
   *   ITEM_PRICE_ATTRIBUTE: string,
   *   QUANTITY_FOR_PRICE_ATTRIBUTE: string,
   *   ITEM_FILTERS: Array<{path: string, filters: string}>,
   *   ITEM_SIMILARITIES: Array<string>,
   *   UNSTACKABLE_ITEM_TYPES: Array<string>,
   *   PILE_DEFAULTS: Object,
   *   TOKEN_FLAG_DEFAULTS: Object,
   *   ITEM_TRANSFORMER: undefined/Function,
   *   PRICE_MODIFIER_TRANSFORMER: undefined/Function,
   *   SYSTEM_HOOKS: undefined/Function,
   *   SHEET_OVERRIDES: undefined/Function,
   *   CURRENCIES: Array<{
   *     primary: boolean,
   *     type: string ["attribute"/"item"],
   *     img: string,
   *     abbreviation: string,
   *     data: Object<{ path: string }|{ uuid: string }|{ item: object }>,
   *     exchangeRate: number
   *   }>,
   *   SECONDARY_CURRENCIES: Array<{
   *     type: string ["attribute"/"item"],
   *     img: string,
   *     abbreviation: string,
   *     data: Object<{ path: string }|{ uuid: string }|{ item: object }>
   *   }>,
   *   CURRENCY_DECIMAL_DIGITS: undefined/number
   * }>} inData
   */
  static addSystemIntegration(inData) {
    const data2 = foundry.utils.mergeObject({
      VERSION: "",
      ACTOR_CLASS_TYPE: "",
      ITEM_QUANTITY_ATTRIBUTE: "",
      ITEM_PRICE_ATTRIBUTE: "",
      QUANTITY_FOR_PRICE_ATTRIBUTE: "flags.item-piles.system.quantityForPrice",
      ITEM_FILTERS: [],
      ITEM_SIMILARITIES: [],
      UNSTACKABLE_ITEM_TYPES: [],
      PILE_DEFAULTS: {},
      TOKEN_FLAG_DEFAULTS: {},
      ITEM_TRANSFORMER: null,
      PRICE_MODIFIER_TRANSFORMER: null,
      SYSTEM_HOOKS: null,
      SHEET_OVERRIDES: null,
      CURRENCIES: [],
      SECONDARY_CURRENCIES: [],
      CURRENCY_DECIMAL_DIGITS: 1e-5
    }, inData);
    if (typeof data2["VERSION"] !== "string") {
      throw custom_error("addSystemIntegration | data.VERSION must be of type string");
    }
    if (typeof data2["ACTOR_CLASS_TYPE"] !== "string") {
      throw custom_error("addSystemIntegration | data.ACTOR_CLASS_TYPE must be of type string");
    }
    if (typeof data2["ITEM_QUANTITY_ATTRIBUTE"] !== "string") {
      throw custom_error("addSystemIntegration | data.ITEM_QUANTITY_ATTRIBUTE must be of type string");
    }
    if (typeof data2["ITEM_PRICE_ATTRIBUTE"] !== "string") {
      throw custom_error("addSystemIntegration | data.ITEM_PRICE_ATTRIBUTE must be of type string");
    }
    if (data2["QUANTITY_FOR_PRICE_ATTRIBUTE"] && typeof data2["QUANTITY_FOR_PRICE_ATTRIBUTE"] !== "string") {
      throw custom_error("addSystemIntegration | data.QUANTITY_FOR_PRICE_ATTRIBUTE must be of type string");
    }
    if (!Array.isArray(data2["ITEM_FILTERS"])) {
      throw custom_error("addSystemIntegration | data.ITEM_FILTERS must be of type array");
    }
    data2["ITEM_FILTERS"].forEach((filter2) => {
      if (typeof filter2?.path !== "string") {
        throw custom_error('addSystemIntegration | each entry in data.ITEM_FILTERS must have a "path" property with a value that is of type string');
      }
      if (typeof filter2?.filters !== "string") {
        throw custom_error('addSystemIntegration | each entry in data.ITEM_FILTERS must have a "filters" property with a value that is of type string');
      }
    });
    if (data2["ITEM_TRANSFORMER"]) {
      if (!isFunction(data2["ITEM_TRANSFORMER"])) {
        throw custom_error("addSystemIntegration | data.ITEM_TRANSFORMER must be of type function");
      }
      if (typeof data2["ITEM_TRANSFORMER"]({}) !== "object") {
        throw custom_error("addSystemIntegration | data.ITEM_TRANSFORMER's return value must be of type object");
      }
    }
    if (data2["PRICE_MODIFIER_TRANSFORMER"]) {
      if (!isFunction(data2["PRICE_MODIFIER_TRANSFORMER"])) {
        throw custom_error("addSystemIntegration | data.PRICE_MODIFIER_TRANSFORMER must be of type function");
      }
      if (typeof data2["PRICE_MODIFIER_TRANSFORMER"]({}) !== "object") {
        throw custom_error("addSystemIntegration | data.PRICE_MODIFIER_TRANSFORMER's return value must be of type object");
      }
    }
    if (data2["SYSTEM_HOOKS"]) {
      if (!isFunction(data2["SYSTEM_HOOKS"])) {
        throw custom_error("addSystemIntegration | data.SYSTEM_HOOKS must be of type function");
      }
    }
    if (data2["SHEET_OVERRIDES"]) {
      if (!isFunction(data2["SHEET_OVERRIDES"])) {
        throw custom_error("addSystemIntegration | data.SHEET_OVERRIDES must be of type function");
      }
    }
    if (typeof data2["PILE_DEFAULTS"] !== "object") {
      throw custom_error("addSystemIntegration | data.PILE_DEFAULTS must be of type object");
    }
    const validKeys = new Set(Object.keys(CONSTANTS.PILE_DEFAULTS));
    for (const key of Object.keys(data2["PILE_DEFAULTS"])) {
      if (!validKeys.has(key)) {
        throw custom_error(`addSystemIntegration | data.PILE_DEFAULTS contains illegal key "${key}" that is not a valid pile default`);
      }
    }
    if (typeof data2["TOKEN_FLAG_DEFAULTS"] !== "object") {
      throw custom_error("addSystemIntegration | data.TOKEN_FLAG_DEFAULTS must be of type object");
    }
    if (!Array.isArray(data2["ITEM_SIMILARITIES"])) {
      throw custom_error("addSystemIntegration | data.ITEM_SIMILARITIES must be of type array");
    }
    data2["ITEM_SIMILARITIES"].forEach((path) => {
      if (typeof path !== "string") {
        throw custom_error("addSystemIntegration | each entry in data.ITEM_SIMILARITIES must be of type string");
      }
    });
    if (data2["UNSTACKABLE_ITEM_TYPES"]) {
      if (!Array.isArray(data2["UNSTACKABLE_ITEM_TYPES"])) {
        throw custom_error("addSystemIntegration | data.UNSTACKABLE_ITEM_TYPES must be of type array");
      }
      data2["UNSTACKABLE_ITEM_TYPES"].forEach((path) => {
        if (typeof path !== "string") {
          throw custom_error("addSystemIntegration | each entry in data.UNSTACKABLE_ITEM_TYPES must be of type string");
        }
      });
    }
    if (!Array.isArray(data2["CURRENCIES"])) {
      throw custom_error("addSystemIntegration | data.CURRENCIES must be an array");
    }
    data2["CURRENCIES"].forEach((currency) => {
      if (typeof currency !== "object") {
        throw custom_error("addSystemIntegration | CURRENCIES | each entry in data.CURRENCIES must be of type object");
      }
      if (typeof currency.primary !== "boolean") {
        throw custom_error("addSystemIntegration | CURRENCIES | currency.primary must be of type boolean");
      }
      if (typeof currency.name !== "string") {
        throw custom_error("addSystemIntegration | CURRENCIES | currency.name must be of type string");
      }
      if (typeof currency.abbreviation !== "string") {
        throw custom_error("addSystemIntegration | CURRENCIES | currency.abbreviation must be of type string");
      }
      if (typeof currency.exchangeRate !== "number") {
        throw custom_error("addSystemIntegration | CURRENCIES | currency.exchangeRate must be of type number");
      }
      if (typeof currency.data !== "object") {
        throw custom_error("addSystemIntegration | CURRENCIES | currency.data must be of type object");
      }
      if (typeof currency.data.path !== "string" && typeof currency.data.uuid !== "string" && typeof currency.data.item !== "object") {
        throw custom_error('addSystemIntegration | CURRENCIES | currency.data must contain either "path" (string), "uuid" (string), or "item" (object)');
      }
      if (currency.img && typeof currency.img !== "string") {
        throw custom_error("addSystemIntegration | CURRENCIES | currency.img must be of type string");
      }
    });
    if (!Array.isArray(data2["SECONDARY_CURRENCIES"])) {
      throw custom_error("addSystemIntegration | data.SECONDARY_CURRENCIES must be an array");
    }
    data2["SECONDARY_CURRENCIES"].forEach((currency) => {
      if (typeof currency !== "object") {
        throw custom_error("addSystemIntegration | SECONDARY_CURRENCIES | each entry in data.SECONDARY_CURRENCIES must be of type object");
      }
      if (typeof currency.name !== "string") {
        throw custom_error("addSystemIntegration | SECONDARY_CURRENCIES | currency.name must be of type string");
      }
      if (typeof currency.abbreviation !== "string") {
        throw custom_error("addSystemIntegration | SECONDARY_CURRENCIES | currency.abbreviation must be of type string");
      }
      if (typeof currency.data !== "object") {
        throw custom_error("addSystemIntegration | SECONDARY_CURRENCIES | currency.data must be of type object");
      }
      if (typeof currency.data.path !== "string" && typeof currency.data.uuid !== "string" && typeof currency.data.item !== "object") {
        throw custom_error('addSystemIntegration | SECONDARY_CURRENCIES | currency.data must contain either "path" (string), "uuid" (string), or "item" (object)');
      }
      if (currency.img && typeof currency.img !== "string") {
        throw custom_error("addSystemIntegration | SECONDARY_CURRENCIES | currency.img must be of type string");
      }
    });
    if (data2["CURRENCY_DECIMAL_DIGITS"] && typeof data2["CURRENCY_DECIMAL_DIGITS"] !== "number") {
      throw custom_error("addSystemIntegration | data.CURRENCY_DECIMAL_DIGITS must be of type number");
    }
    data2["INTEGRATION"] = true;
    SYSTEMS.addSystem(data2);
    debug(`Registered system settings for ${game.system.id}`, data2);
  }
  /**
   * Gets all the system item types, including custom item piles item categories
   *
   * @returns {Array<{primary: boolean, name: string, data: Object, img: string, abbreviation: string, exchange: number}>}
   */
  static getPrimaryCurrency(actor = false) {
    if (actor && actor instanceof Actor) {
      return getActorPrimaryCurrency(actor);
    }
    return this.CURRENCIES.find((currency) => currency.primary);
  }
  /**
   * Retrieves all the system item types, including custom item piles item categories
   *
   * @returns {Object}
   */
  static getItemCategories() {
    let systemTypes = Object.entries(CONFIG.Item.typeLabels).map(([key, value]) => {
      return [key, game.i18n.localize(value)];
    });
    systemTypes.shift();
    let customItemPilesCategories = Array.from(new Set(getSetting(SETTINGS$1.CUSTOM_ITEM_CATEGORIES))).map((cat) => {
      return [cat, cat];
    });
    return Object.fromEntries(systemTypes.concat(customItemPilesCategories).sort((a, b) => a[1] > b[1] ? 1 : -1));
  }
  /* ================= ITEM PILE METHODS ================= */
  /**
   * Creates an item pile token at a location, or an item pile actor, or both at the same time.
   *
   * @param {object} options                                          Options to pass to the function
   * @param {object/boolean} [options.position=false]                 Where to create the item pile, with x and y coordinates
   * @param {string/boolean} [options.sceneId=game.user.viewedScene]  Which scene to create the item pile on
   * @param {object} [options.tokenOverrides={}]                      Token data to apply to the newly created token
   * @param {object} [options.actorOverrides={}]                      Actor data to apply to the newly created actor (if unlinked)
   * @param {object} [options.itemPileFlags={}]                       Item pile specific flags to apply to the token and actor
   * @param {Array/boolean} [options.items=false]                     Any items to create on the item pile
   * @param {boolean} [options.createActor=false]                     Whether to create a new item pile actor
   * @param {string/boolean} [options.actor=false]                    The UUID, ID, or name of the actor to use when creating this item pile
   * @param {Array<string>/>string/boolean} [options.folders=false]   The folder to create the actor in, this can be an array of folder names, which will be traversed and created
   *
   * @returns {Promise<string>}
   */
  static async createItemPile({
    position = false,
    sceneId = game.user.viewedScene,
    tokenOverrides = {},
    actorOverrides = {},
    itemPileFlags = {},
    items = false,
    createActor = false,
    actor = false,
    folders = false
  } = {}) {
    if (position) {
      if (typeof position !== "object") {
        throw custom_error(`createItemPile | position must be of type object`);
      } else if (!isRealNumber(position.x) || !isRealNumber(position.y)) {
        throw custom_error(`createItemPile | position.x and position.y must be of type numbers`);
      }
    }
    if (folders) {
      if (!Array.isArray(folders)) {
        folders = [folders];
      }
      folders.forEach((f) => {
        if (typeof f !== "string") {
          throw custom_error(`createItemPile | folder must be of type string or array of strings`);
        }
      });
    }
    if (actor && !createActor) {
      if (typeof actor !== "string") {
        throw custom_error(`createItemPile | actor must be of type string`);
      }
      let pileActor = await fromUuid(actor);
      if (!pileActor) {
        pileActor = game.actors.getName(actor);
      }
      if (!pileActor) {
        pileActor = game.actors.get(actor);
      }
      if (!pileActor) {
        throw custom_error(`createItemPile | Could not find actor with the identifier of "${actor}"`);
      }
      actor = pileActor.uuid;
    }
    if (typeof sceneId !== "string") {
      throw custom_error(`createItemPile | sceneId must be of type string`);
    }
    if (typeof tokenOverrides !== "object") {
      throw custom_error(`createItemPile | tokenOverrides must be of type object`);
    }
    if (typeof actorOverrides !== "object") {
      throw custom_error(`createItemPile | tokenOverrides must be of type object`);
    }
    if (typeof itemPileFlags !== "object") {
      throw custom_error(`createItemPile | tokenOverrides must be of type object`);
    }
    if (items) {
      if (!Array.isArray(items))
        items = [items];
      items = items.map((item) => {
        return item instanceof Item ? item.toObject() : item;
      });
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.CREATE_PILE, {
      sceneId,
      position,
      actor,
      createActor,
      items,
      tokenOverrides,
      actorOverrides,
      itemPileFlags,
      folders
    });
  }
  /**
   * Turns tokens and its actors into item piles
   *
   * @param {Token/TokenDocument/Array<Token/TokenDocument>} targets  The targets to be turned into item piles
   * @param {object} options                                          Options to pass to the function
   * @param {object} options.pileSettings                             Overriding settings to be put on the item piles' settings
   * @param {object/Function} options.tokenSettings                   Overriding settings that will update the tokens' settings
   *
   * @return {Promise<Array>}                                         The uuids of the targets after they were turned into item piles
   */
  static turnTokensIntoItemPiles(targets, { pileSettings = {}, tokenSettings = {} } = {}) {
    if (!Array.isArray(targets))
      targets = [targets];
    const targetUuids = targets.map((target) => {
      if (!(target instanceof Token || target instanceof TokenDocument)) {
        throw custom_error(`turnTokensIntoItemPiles | Target must be of type Token or TokenDocument`);
      }
      const targetUuid = getUuid(target);
      if (!targetUuid)
        throw custom_error(`turnTokensIntoItemPiles | Could not determine the UUID, please provide a valid target`);
      return targetUuid;
    });
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TURN_INTO_PILE, targetUuids, pileSettings, tokenSettings);
  }
  /**
   * Reverts tokens from an item pile into a normal token and actor
   *
   * @param {Token/TokenDocument/Array<Token/TokenDocument>} targets  The targets to be reverted from item piles
   * @param {object} options                                          Options to pass to the function
   * @param {object/Function} options.tokenSettings                   Overriding settings that will update the tokens
   *
   * @return {Promise<Array>}                                         The uuids of the targets after they were reverted from being item piles
   */
  static revertTokensFromItemPiles(targets, { tokenSettings = {} } = {}) {
    if (!Array.isArray(targets))
      targets = [targets];
    const targetUuids = targets.map((target) => {
      if (!(target instanceof Token || target instanceof TokenDocument)) {
        throw custom_error(`revertTokensFromItemPiles | Target must be of type Token or TokenDocument`);
      }
      const targetUuid = getUuid(target);
      if (!targetUuid)
        throw custom_error(`revertTokensFromItemPiles | Could not determine the UUID, please provide a valid target`);
      return targetUuid;
    });
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.REVERT_FROM_PILE, targetUuids, tokenSettings);
  }
  /**
   * Opens a pile if it is enabled and a container
   *
   * @param {Token/TokenDocument} target
   * @param {Token/TokenDocument/boolean} [interactingToken=false]
   *
   * @return {Promise/boolean}
   */
  static openItemPile(target, interactingToken = false) {
    const targetActor = getActor(target);
    if (!isItemPileContainer(target))
      return false;
    const interactingTokenDocument = interactingToken ? getActor(interactingToken) : false;
    const pileData = getActorFlagData(targetActor);
    const wasLocked = pileData.locked;
    const wasClosed = pileData.closed;
    pileData.closed = false;
    pileData.locked = false;
    if (wasLocked) {
      const hookResult2 = hooks.call(CONSTANTS.HOOKS.PILE.PRE_UNLOCK, targetActor, pileData, interactingTokenDocument);
      if (hookResult2 === false)
        return false;
    }
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_OPEN, targetActor, pileData, interactingTokenDocument);
    if (hookResult === false)
      return false;
    if (wasClosed && pileData.openSound) {
      let sound = pileData.openSound;
      if (pileData.openSound.includes("*")) {
        sound = random_array_element(pileData.openSounds);
      }
      AudioHelper.play({ src: sound }, true);
    }
    return this.updateItemPile(targetActor, pileData, { interactingToken: interactingTokenDocument });
  }
  /**
   * Closes a pile if it is enabled and a container
   *
   * @param {Token/TokenDocument} target          Target pile to close
   * @param {Token/TokenDocument/boolean} [interactingToken=false]
   *
   * @return {Promise/boolean}
   */
  static closeItemPile(target, interactingToken = false) {
    const targetActor = getActor(target);
    if (!isItemPileContainer(target))
      return false;
    const interactingTokenDocument = interactingToken ? getActor(interactingToken) : false;
    const pileData = getActorFlagData(targetActor);
    const wasOpen = !pileData.closed;
    pileData.closed = true;
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_CLOSE, targetActor, pileData, interactingTokenDocument);
    if (hookResult === false)
      return false;
    if (wasOpen && pileData.closeSound) {
      let sound = pileData.closeSound;
      if (pileData.closeSound.includes("*")) {
        sound = random_array_element(pileData.closeSounds);
      }
      AudioHelper.play({ src: sound }, true);
    }
    return this.updateItemPile(targetActor, pileData, { interactingToken: interactingTokenDocument });
  }
  /**
   * Toggles a pile's closed state if it is enabled and a container
   *
   * @param {Token/TokenDocument} target          Target pile to open or close
   * @param {Token/TokenDocument/boolean} [interactingToken=false]
   *
   * @return {Promise/boolean}
   */
  static async toggleItemPileClosed(target, interactingToken = false) {
    const targetActor = getActor(target);
    if (!isItemPileContainer(target))
      return false;
    const interactingTokenDocument = interactingToken ? getActor(interactingToken) : false;
    const pileData = getActorFlagData(targetActor);
    if (pileData.closed) {
      await this.openItemPile(targetActor, interactingTokenDocument);
    } else {
      await this.closeItemPile(targetActor, interactingTokenDocument);
    }
    return !pileData.closed;
  }
  /**
   * Locks a pile if it is enabled and a container
   *
   * @param {Token/TokenDocument} target          Target pile to lock
   * @param {Token/TokenDocument/boolean} [interactingToken=false]
   *
   * @return {Promise/boolean}
   */
  static lockItemPile(target, interactingToken = false) {
    const targetActor = getActor(target);
    if (!isItemPileContainer(target))
      return false;
    const interactingTokenDocument = interactingToken ? getActor(interactingToken) : false;
    const pileData = getActorFlagData(targetActor);
    const wasClosed = pileData.closed;
    pileData.closed = true;
    pileData.locked = true;
    if (!wasClosed) {
      const hookResult2 = hooks.call(CONSTANTS.HOOKS.PILE.PRE_CLOSE, targetActor, pileData, interactingTokenDocument);
      if (hookResult2 === false)
        return false;
    }
    const hookResult = hooks.call(CONSTANTS.HOOKS.PILE.PRE_LOCK, targetActor, pileData, interactingTokenDocument);
    if (hookResult === false)
      return false;
    if (!wasClosed && pileData.closeSound) {
      let sound = pileData.closeSound;
      if (pileData.closeSound.includes("*")) {
        sound = random_array_element(pileData.closeSounds);
      }
      AudioHelper.play({ src: sound }, true);
    }
    return this.updateItemPile(targetActor, pileData, { interactingToken: interactingTokenDocument });
  }
  /**
   * Unlocks a pile if it is enabled and a container
   *
   * @param {Token/TokenDocument} target          Target pile to unlock
   * @param {Token/TokenDocument/boolean} [interactingToken=false]
   *
   * @return {Promise/boolean}
   */
  static unlockItemPile(target, interactingToken = false) {
    const targetActor = getActor(target);
    if (!isItemPileContainer(target))
      return false;
    const interactingTokenDocument = interactingToken ? getActor(interactingToken) : false;
    const pileData = getActorFlagData(targetActor);
    pileData.locked = false;
    hooks.call(CONSTANTS.HOOKS.PILE.PRE_UNLOCK, targetActor, pileData, interactingTokenDocument);
    return this.updateItemPile(targetActor, pileData, { interactingToken: interactingTokenDocument });
  }
  /**
   * Toggles a pile's locked state if it is enabled and a container
   *
   * @param {Token/TokenDocument} target          Target pile to lock or unlock
   * @param {Token/TokenDocument/boolean} [interactingToken=false]
   *
   * @return {Promise/boolean}
   */
  static toggleItemPileLocked(target, interactingToken = false) {
    const targetActor = getActor(target);
    if (!isItemPileContainer(target))
      return false;
    const interactingTokenDocument = interactingToken ? getActor(interactingToken) : false;
    const pileData = getActorFlagData(targetActor);
    if (pileData.locked) {
      return this.unlockItemPile(targetActor, interactingTokenDocument);
    }
    return this.lockItemPile(targetActor, interactingTokenDocument);
  }
  /**
   * Causes the item pile to play a sound as it was attempted to be opened, but was locked
   *
   * @param {Token/TokenDocument} target
   * @param {Token/TokenDocument/boolean} [interactingToken=false]
   *
   * @return {Promise<boolean>}
   */
  static rattleItemPile(target, interactingToken = false) {
    const targetActor = getActor(target);
    if (!isItemPileContainer(target))
      return false;
    const interactingTokenDocument = interactingToken ? getActor(interactingToken) : false;
    const pileData = getActorFlagData(targetActor);
    hooks.call(CONSTANTS.HOOKS.PILE.PRE_RATTLE, targetActor, pileData, interactingTokenDocument);
    if (pileData.lockedSound) {
      let sound = pileData.lockedSound;
      if (pileData.lockedSound.includes("*")) {
        sound = random_array_element(pileData.lockedSounds);
      }
      AudioHelper.play({ src: sound }, true);
    }
    return ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.CALL_HOOK, CONSTANTS.HOOKS.PILE.RATTLE, getUuid(targetActor), pileData, getUuid(interactingTokenDocument));
  }
  /**
   * Whether an item pile is locked. If it is not enabled or not a container, it is always false.
   *
   * @param {Token/TokenDocument} target
   *
   * @return {boolean}
   */
  static isItemPileLocked(target) {
    return isItemPileLocked(target);
  }
  /**
   * Whether an item pile is closed. If it is not enabled or not a container, it is always false.
   *
   * @param {Token/TokenDocument} target
   *
   * @return {boolean}
   */
  static isItemPileClosed(target) {
    return isItemPileClosed(target);
  }
  /**
   * Whether an item pile is a container. If it is not enabled, it is always false.
   *
   * @param {Token/TokenDocument} target
   *
   * @return {boolean}
   */
  static isItemPileContainer(target) {
    return isItemPileContainer(target);
  }
  /**
   * Updates a pile with new data.
   *
   * @param {Actor/TokenDocument} target                                      Target token or actor to update
   * @param {object} newData                                                  New data to update the actor with
   * @param {object} options                                                  Options to pass to the function
   * @param {Token/TokenDocument/boolean} [options.interactingToken=false]    If an actor caused this update, you can pass one here to pass it along to macros that the item pile may run
   * @param {Object/boolean} [options.tokenSettings=false]                    Updates to make to the target token
   *
   * @return {Promise}
   */
  static updateItemPile(target, newData, { interactingToken = false, tokenSettings = false } = {}) {
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`updateItemPile | Could not determine the UUID, please provide a valid target`);
    const interactingTokenUuid = interactingToken ? getUuid(interactingToken) : false;
    if (interactingToken && !interactingTokenUuid)
      throw custom_error(`updateItemPile | Could not determine the UUID, please provide a valid target`);
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.UPDATE_PILE, targetUuid, newData, {
      interactingTokenUuid,
      tokenSettings
    });
  }
  /**
   * Deletes a pile, calling the relevant hooks.
   *
   * @param {Token/TokenDocument} target
   *
   * @return {Promise}
   */
  static deleteItemPile(target) {
    if (!isValidItemPile(target)) {
      throw custom_error(`deleteItemPile | This is not an item pile, please provide a valid target`);
    }
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`deleteItemPile | Could not determine the UUID, please provide a valid target`);
    if (!targetUuid.includes("Token")) {
      throw custom_error(`deleteItemPile | Please provide a Token or TokenDocument`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.DELETE_PILE, targetUuid);
  }
  /**
   * Splits an item pile's content between all players (or a specified set of target actors).
   *
   * @param target {Token/TokenDocument/Actor}                                                  The item pile to split
   * @param {object} options                                                                    Options to pass to the function
   * @param {boolean/TokenDocument/Actor/Array<TokenDocument/Actor>} [options.targets=false]    The targets to receive the split contents
   * @param {boolean/TokenDocument/Actor} [options.instigator=false]                            Whether this was triggered by a specific actor
   *
   * @returns {Promise<object/boolean>}
   */
  static async splitItemPileContents(target, { targets = false, instigator = false } = {}) {
    if (!isItemPileLootable(target))
      return false;
    const itemPileUuid = getUuid(target);
    if (!itemPileUuid)
      throw custom_error(`SplitItemPileContents | Could not determine the UUID, please provide a valid item pile`);
    const itemPileActor = getActor(target);
    if (targets) {
      if (!Array.isArray(targets)) {
        targets = [targets];
      }
      targets.forEach((actor) => {
        if (!(actor instanceof TokenDocument || actor instanceof Actor)) {
          throw custom_error("SplitItemPileContents | Each of the entries in targets must be of type TokenDocument or Actor");
        }
      });
      targets = targets.map((target2) => getActor(target2));
    }
    if (instigator && !(instigator instanceof TokenDocument || instigator instanceof Actor)) {
      throw custom_error("SplitItemPileContents | instigator must be of type TokenDocument or Actor");
    }
    const actorUuids = (targets || getPlayersForItemPile(itemPileActor).map((u) => u.character)).map((actor) => getUuid(actor));
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.SPLIT_PILE, itemPileUuid, actorUuids, game.user.id, instigator);
  }
  /**
   * Retrieves the price modifiers for a given item piles merchant
   *
   * @param {Actor/TokenDocument} target                                      Target token or actor to retrieve the modifiers from
   * @param {object} options                                                  Options to pass to the function
   * @param {Token/TokenDocument/Actor/string/boolean} [options.actor=false]  The actor whose price modifiers to consider
   * @param {boolean} [options.absolute=false]                                Whether to only consider the actor's modifiers (true means not considering the merchant's base modifiers)
   *
   * @return {Object}
   */
  static getMerchantPriceModifiers(target, { actor = false, absolute = false } = {}) {
    const merchantActor = getActor(target);
    if (!(merchantActor instanceof Actor)) {
      throw custom_error(`getMerchantPriceModifiers | target must be of type Actor`);
    }
    if (!isItemPileMerchant(merchantActor)) {
      throw custom_error(`getMerchantPriceModifiers | target is not an item pile merchant`);
    }
    if (actor) {
      if (!(actor instanceof Actor) && typeof actor !== "string") {
        throw custom_error(`getMerchantPriceModifiers | actor must be of type Actor or string (UUID)`);
      }
      if (typeof actor === "string") {
        actor = fromUuidSync(actor) || false;
      }
    }
    if (typeof absolute !== "boolean") {
      throw custom_error(`getMerchantPriceModifiers | absolute must be of type boolean`);
    }
    return getMerchantModifiersForActor(target, { actor, absolute });
  }
  /**
   * Updates the price modifiers for a given item piles merchant
   *
   * @param {Actor/TokenDocument} target                                      Target token or actor to update modifiers on
   * @param {Array<{
   *   actor?: Actor,
   *   actorUuid?: string,
   *   relative?: boolean,
   *   override?: boolean,
   *   buyPriceModifier?: number,
   *   sellPriceModifier?: number
   * }>} priceModifierData                                                    The price modifier data to update on the merchant
   *
   * @return {Promise}
   */
  static updateMerchantPriceModifiers(target, priceModifierData = []) {
    const merchantActor = getActor(target);
    const targetUuid = getUuid(merchantActor);
    if (!targetUuid)
      throw custom_error(`updateMerchantPriceModifiers | Could not determine the UUID, please provide a valid target`);
    if (!isItemPileMerchant(merchantActor)) {
      throw custom_error(`updateMerchantPriceModifiers | Target is not an item pile merchant`);
    }
    const flagData = getActorFlagData(merchantActor);
    const actorPriceModifiers = flagData?.actorPriceModifiers ?? [];
    for (const priceModifier of priceModifierData) {
      if (priceModifier.actor && !(priceModifier.actor instanceof Actor)) {
        throw custom_error(`updateMerchantPriceModifiers | priceModifierData.actor must be of type Actor`);
      }
      if (priceModifier.actor) {
        priceModifier.actorUuid = priceModifier.actor.uuid;
      }
      if (priceModifier.actorUuid && typeof priceModifier.actorUuid !== "string") {
        throw custom_error(`updateMerchantPriceModifiers | if priceModifierData.actor if not provided, priceModifierData.actorUuid must be of type string `);
      }
      if (!priceModifier.actorUuid) {
        throw custom_error(`updateMerchantPriceModifiers | Could not find the UUID for the given actor`);
      }
      if (priceModifier.relative !== void 0 && typeof priceModifier.relative !== "boolean") {
        throw custom_error(`updateMerchantPriceModifiers | priceModifierData.relative must be of type boolean`);
      }
      if (priceModifier.override !== void 0 && typeof priceModifier.override !== "boolean") {
        throw custom_error(`updateMerchantPriceModifiers | priceModifierData.override must be of type boolean`);
      }
      if (priceModifier.buyPriceModifier !== void 0 && typeof priceModifier.buyPriceModifier !== "number") {
        throw custom_error(`updateMerchantPriceModifiers | priceModifierData.buyPriceModifier must be of type number`);
      }
      if (priceModifier.sellPriceModifier !== void 0 && typeof priceModifier.sellPriceModifier !== "number") {
        throw custom_error(`updateMerchantPriceModifiers | priceModifierData.sellPriceModifier must be of type number`);
      }
      let actorPriceModifierIndex = actorPriceModifiers.findIndex((existingPriceModifier) => existingPriceModifier.actorUuid === priceModifier.actorUuid);
      if (actorPriceModifierIndex === -1) {
        actorPriceModifierIndex = actorPriceModifiers.push({}) - 1;
      }
      const oldBuyPriceModifier = actorPriceModifiers[actorPriceModifierIndex]?.buyPriceModifier ?? flagData?.buyPriceModifier ?? 1;
      const newBuyPriceModifier = Math.max(0, priceModifier.relative ? oldBuyPriceModifier + priceModifier.buyPriceModifier : priceModifier.buyPriceModifier ?? oldBuyPriceModifier);
      const oldSellPriceModifier = actorPriceModifiers[actorPriceModifierIndex]?.sellPriceModifier ?? flagData?.sellPriceModifier ?? 0.5;
      const newSellPriceModifier = Math.max(0, priceModifier.relative ? oldSellPriceModifier + priceModifier.sellPriceModifier : priceModifier.sellPriceModifier ?? oldSellPriceModifier);
      actorPriceModifiers[actorPriceModifierIndex] = foundry.utils.mergeObject(actorPriceModifiers[actorPriceModifierIndex], {
        actorUuid: priceModifier.actorUuid,
        buyPriceModifier: newBuyPriceModifier,
        sellPriceModifier: newSellPriceModifier,
        override: priceModifier.override ?? false
      });
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.UPDATE_PILE, targetUuid, { actorPriceModifiers });
  }
  /* ================= ITEM AND ATTRIBUTE METHODS ================= */
  /**
   * Adds item to an actor, increasing item quantities if matches were found
   *
   * @param {Actor/TokenDocument/Token} target                  The target to add an item to
   * @param {Array} items                                       An array of objects, with the key "item" being an item object or an Item class (the foundry class), with an optional key of "quantity" being the amount of the item to add
   * @param {object} options                                    Options to pass to the function
   * @param {boolean} [options.removeExistingActorItems=false]  Whether to remove the actor's existing items before adding the new ones
   * @param {boolean} [options.skipVaultLogging=false]          Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]      The interaction ID of this action
   *
   * @returns {Promise<array>}                                  An array of objects, each containing the item that was added or updated, and the quantity that was added
   */
  static addItems(target, items, {
    removeExistingActorItems = false,
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const targetActor = getActor(target);
    if (!targetActor)
      throw custom_error(`addItems | Could not determine the target actor, please provide a valid target`);
    const targetUuid = getUuid(targetActor);
    const itemsToAdd = [];
    items.forEach((itemData) => {
      let item = itemData;
      if (itemData instanceof Item) {
        item = itemData.toObject();
      } else if (itemData.item) {
        item = itemData.item instanceof Item ? itemData.item.toObject() : itemData.item;
        if (itemData.flags) {
          foundry.utils.setProperty(
            item,
            "flags",
            foundry.utils.mergeObject(
              foundry.utils.getProperty(item, "flags") ?? {},
              foundry.utils.getProperty(itemData, "flags")
            )
          );
        }
      } else if (itemData.id) {
        item = target.items.get(itemData.id);
        if (item) {
          item = item.toObject();
        } else {
          throw custom_error(`addItems | Could not find item with id ${itemData.id} on actor with UUID ${targetUuid}!`);
        }
      }
      if (itemData?.quantity !== void 0) {
        setItemQuantity(item, itemData.quantity, true);
      }
      itemsToAdd.push(item);
    });
    if (isItemPileVault(targetActor)) {
      const canItemsFit = fitItemsIntoVault(itemsToAdd, targetActor);
      if (!canItemsFit)
        throw custom_error(`addItems | The vault actor ${targetActor.name} cannot fit these items`, true);
    }
    if (interactionId && typeof interactionId !== "string")
      throw custom_error(`addItems | interactionId must be of type string`);
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.ADD_ITEMS, targetUuid, itemsToAdd, game.user.id, {
      removeExistingActorItems,
      interactionId,
      skipVaultLogging
    });
  }
  /**
   * Subtracts the quantity of items on an actor. If the quantity of an item reaches 0, the item is removed from the actor.
   *
   * @param {Actor/Token/TokenDocument} target                  The target to remove items from
   * @param {Array} items                                       An array of objects each containing the item id (key "_id") and the quantity to remove (key "quantity"), or Items (the foundry class) or strings of IDs to remove all quantities of
   * @param {object} options                                    Options to pass to the function
   * @param {boolean} [options.skipVaultLogging=false]          Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]      The interaction ID of this action
   *
   * @returns {Promise<array>}                                  An array of objects, each containing the item that was removed or updated, the quantity that was removed, and whether the item was deleted
   */
  static removeItems(target, items, { skipVaultLogging = false, interactionId = false } = {}) {
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`removeItems | Could not determine the UUID, please provide a valid target`);
    const targetActorItems = getActorItems(target, { getItemCurrencies: true });
    items = items.map((itemData) => {
      let item;
      if (typeof itemData === "string" || itemData._id) {
        const itemId = typeof itemData === "string" ? itemData : itemData._id;
        item = targetActorItems.find((actorItem) => actorItem.id === itemId);
        if (!item) {
          throw custom_error(`removeItems | Could not find item with id "${itemId}" on target "${targetUuid}"`);
        }
        item = item.toObject();
      } else {
        if (itemData.item instanceof Item) {
          item = itemData.item.toObject();
        } else if (itemData instanceof Item) {
          item = itemData.toObject();
        } else {
          item = itemData.item;
        }
        let foundActorItem = targetActorItems.find((actorItem) => actorItem.id === item._id);
        if (!foundActorItem) {
          throw custom_error(`removeItems | Could not find item with id "${item._id}" on target "${targetUuid}"`);
        }
      }
      return {
        _id: item._id,
        quantity: itemData?.quantity ?? getItemQuantity(item)
      };
    });
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`removeItems | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.REMOVE_ITEMS, targetUuid, items, game.user.id, {
      interactionId,
      skipVaultLogging
    });
  }
  /**
   * Transfers items from the source to the target, subtracting a number of quantity from the source's item and adding it to the target's item, deleting items from the source if their quantity reaches 0
   *
   * @param {Actor/Token/TokenDocument} source              The source to transfer the items from
   * @param {Actor/Token/TokenDocument} target              The target to transfer the items to
   * @param {Array} items                                   An array of objects each containing the item id (key "_id") and the quantity to transfer (key "quantity"), or Items (the foundry class) or strings of IDs to transfer all quantities of
   * @param {object} options                                Options to pass to the function
   * @param {boolean} [options.skipVaultLogging=false]      Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]  The interaction ID of this action
   *
   * @returns {Promise<object>}                             An array of objects, each containing the item that was added or updated, and the quantity that was transferred
   */
  static transferItems(source, target, items, { skipVaultLogging = false, interactionId = false } = {}) {
    const sourceActor = getActor(source);
    if (!sourceActor)
      throw custom_error(`transferItems | Could not determine the source actor, please provide a valid source`);
    const sourceUuid = getUuid(sourceActor);
    const sourceActorItems = getActorItems(source, { getItemCurrencies: true });
    items = items.map((itemData) => {
      let item;
      if (typeof itemData === "string" || itemData._id) {
        const itemId = typeof itemData === "string" ? itemData : itemData._id;
        item = sourceActorItems.find((actorItem) => actorItem.id === itemId);
        if (!item) {
          throw custom_error(`transferItems | Could not find item with id "${itemId}" on target "${sourceUuid}"`);
        }
        item = item.toObject();
      } else if (itemData instanceof Item) {
        item = itemData.toObject();
      } else if (itemData.item instanceof Item) {
        item = itemData.item.toObject();
      } else {
        item = itemData.item;
      }
      let foundActorItem = sourceActorItems.find((actorItem) => actorItem.id === item._id);
      if (!foundActorItem) {
        throw custom_error(`transferItems | Could not find item with id "${item._id}" on target "${sourceUuid}"`);
      }
      return {
        id: item._id,
        quantity: Math.max(itemData?.quantity ?? getItemQuantity(itemData), 0),
        flags: foundry.utils.getProperty(itemData, "flags")
      };
    });
    const targetActor = getActor(target);
    if (!targetActor)
      throw custom_error(`transferItems | Could not determine the target, please provide a valid target`);
    const targetUuid = getUuid(targetActor);
    if (isItemPileVault(targetActor)) {
      const itemsToFit = items.reduce((acc, data2) => {
        const item = sourceActor.items.get(data2.id);
        if (canItemStack(item, targetActor)) {
          acc.push(item);
        } else {
          for (let i = 0; i < data2.quantity; i++) {
            acc.push(item);
          }
        }
        return acc;
      }, []);
      const canItemsFit = fitItemsIntoVault(itemsToFit, targetActor);
      if (!canItemsFit)
        throw custom_error(`transferItems | The target vault actor ${targetActor.name} cannot fit these items`, true);
    }
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`transferItems | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRANSFER_ITEMS, sourceUuid, targetUuid, items, game.user.id, {
      interactionId,
      skipVaultLogging
    });
  }
  /**
   * Transfers all items between the source and the target.
   *
   * @param {Actor/Token/TokenDocument} source                The actor to transfer all items from
   * @param {Actor/Token/TokenDocument} target                The actor to receive all the items
   * @param {object} options                                  Options to pass to the function
   * @param {Array/boolean} [options.itemFilters=false]       Array of item types disallowed - will default to module settings if none provided
   * @param {boolean} [options.skipVaultLogging=false]        Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]    The interaction ID of this action
   *
   * @returns {Promise<array>}                                An array containing all the items that were transferred to the target
   */
  static transferAllItems(source, target, {
    itemFilters = false,
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(source);
    if (!sourceActor)
      throw custom_error(`transferAllItems | Could not determine the source actor, please provide a valid source`);
    const sourceUuid = getUuid(sourceActor);
    const targetActor = getActor(target);
    if (!targetActor)
      throw custom_error(`transferAllItems | Could not determine the target actor, please provide a valid target`);
    const targetUuid = getUuid(targetActor);
    if (itemFilters) {
      if (!Array.isArray(itemFilters))
        throw custom_error(`transferAllItems | itemFilters must be of type array`);
      itemFilters.forEach((entry) => {
        if (typeof entry?.path !== "string")
          throw custom_error(`transferAllItems | each entry in the itemFilters must have a "path" property that is of type string`);
        if (typeof entry?.filter !== "string")
          throw custom_error(`transferAllItems | each entry in the itemFilters must have a "filter" property that is of type string`);
      });
    }
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`transferAllItems | interactionId must be of type string`);
    }
    if (isItemPileVault(targetActor)) {
      const sourceActorItems = getActorItems(sourceActor, { getItemCurrencies: true });
      const canItemsFit = fitItemsIntoVault(sourceActorItems, targetActor, { itemFilters });
      if (!canItemsFit)
        throw custom_error(`transferAllItems | The target vault actor ${targetActor.name} cannot fit these items`, true);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRANSFER_ALL_ITEMS, sourceUuid, targetUuid, game.user.id, {
      itemFilters,
      skipVaultLogging,
      interactionId
    });
  }
  /**
   * Sets attributes on an actor
   *
   * @param {Actor/Token/TokenDocument} target                  The target whose attribute will have their quantity set
   * @param {object} attributes                                 An object with each key being an attribute path, and its value being the quantity to set
   * @param {object} options                                    Options to pass to the function
   * @param {string/boolean} [options.interactionId=false]      The interaction ID of this action
   *
   * @returns {Promise<object>}                                 An array containing a key value pair of the attribute path and the quantity of that attribute that was set
   *
   */
  static setAttributes(target, attributes, { interactionId = false } = {}) {
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`setAttributes | Could not determine the UUID, please provide a valid target`);
    Object.entries(attributes).forEach((entry) => {
      const [attribute, quantity] = entry;
      if (!isRealNumber(quantity)) {
        throw custom_error(`setAttributes | Attribute "${attribute}" must be of type number`);
      }
    });
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`setAttributes | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.SET_ATTRIBUTES, targetUuid, attributes, game.user.id, {
      interactionId
    });
  }
  /**
   * Adds attributes on an actor
   *
   * @param {Actor/Token/TokenDocument} target                  The target whose attribute will have a set quantity added to it
   * @param {object} attributes                                 An object with each key being an attribute path, and its value being the quantity to add
   * @param {object} options                                    Options to pass to the function
   * @param {boolean} [options.skipVaultLogging=false]          Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]      The interaction ID of this action
   *
   * @returns {Promise<object>}                                 An array containing a key value pair of the attribute path and the quantity of that attribute that was added
   *
   */
  static addAttributes(target, attributes, { skipVaultLogging = false, interactionId = false } = {}) {
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`addAttributes | Could not determine the UUID, please provide a valid target`);
    Object.entries(attributes).forEach((entry) => {
      const [attribute, quantity] = entry;
      if (!isRealNumber(quantity) && quantity > 0) {
        throw custom_error(`addAttributes | Attribute "${attribute}" must be of type number and greater than 0`);
      }
    });
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`addAttributes | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.ADD_ATTRIBUTES, targetUuid, attributes, game.user.id, {
      skipVaultLogging,
      interactionId
    });
  }
  /**
   * Subtracts attributes on the target
   *
   * @param {Token/TokenDocument} target                      The target whose attributes will be subtracted from
   * @param {Array/object} attributes                         This can be either an array of attributes to subtract (to zero out a given attribute), or an object with each key being an attribute path, and its value being the quantity to subtract
   * @param {object} options                                  Options to pass to the function
   * @param {boolean} [options.skipVaultLogging=false]        Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]    The interaction ID of this action
   *
   * @returns {Promise<object>}                               An array containing a key value pair of the attribute path and the quantity of that attribute that was removed
   */
  static removeAttributes(target, attributes, { skipVaultLogging = false, interactionId = false } = {}) {
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`removeAttributes | Could not determine the UUID, please provide a valid target`);
    const targetActor = getActor(target);
    let attributesToSend = {};
    if (Array.isArray(attributes)) {
      attributes.forEach((attribute) => {
        if (typeof attribute !== "string") {
          throw custom_error(`removeAttributes | Each attribute in the array must be of type string`);
        }
        attributesToSend[attribute] = Number(foundry.utils.getProperty(targetActor, attribute));
      });
    } else {
      Object.entries(attributes).forEach((entry) => {
        const [attribute, quantity] = entry;
        if (!foundry.utils.hasProperty(targetActor, attribute)) {
          throw custom_error(`removeAttributes | Could not find attribute ${attribute} on target's actor with UUID "${targetUuid}"`);
        }
        if (!isRealNumber(quantity) && quantity > 0) {
          throw custom_error(`removeAttributes | Attribute "${attribute}" must be of type number and greater than 0`);
        }
      });
      attributesToSend = attributes;
    }
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`removeAttributes | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.REMOVE_ATTRIBUTES, targetUuid, attributesToSend, game.user.id, {
      skipVaultLogging,
      interactionId
    });
  }
  /**
   * Transfers a set quantity of an attribute from a source to a target, removing it or subtracting from the source and adds it the target
   *
   * @param {Actor/Token/TokenDocument} source                The source to transfer the attribute from
   * @param {Actor/Token/TokenDocument} target                The target to transfer the attribute to
   * @param {Array/object} attributes                         This can be either an array of attributes to transfer (to transfer all of a given attribute), or an object with each key being an attribute path, and its value being the quantity to transfer
   * @param {object} options                                  Options to pass to the function
   * @param {boolean} [options.skipVaultLogging=false]        Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]    The interaction ID of this action
   *
   * @returns {Promise<object>}                               An object containing a key value pair of each attribute transferred, the key being the attribute path and its value being the quantity that was transferred
   */
  static transferAttributes(source, target, attributes, { skipVaultLogging = false, interactionId = false } = {}) {
    const sourceUuid = getUuid(source);
    if (!sourceUuid)
      throw custom_error(`transferAttributes | Could not determine the UUID, please provide a valid source`);
    const sourceActor = getActor(source);
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`transferAttributes | Could not determine the UUID, please provide a valid target`);
    getActor(target);
    if (Array.isArray(attributes)) {
      attributes.forEach((attribute) => {
        if (typeof attribute !== "string") {
          throw custom_error(`transferAttributes | Each attribute in the array must be of type string`);
        }
        if (!foundry.utils.hasProperty(sourceActor, attribute)) {
          throw custom_error(`transferAttributes | Could not find attribute ${attribute} on source's actor with UUID "${targetUuid}"`);
        }
      });
    } else {
      Object.entries(attributes).forEach((entry) => {
        const [attribute, quantity] = entry;
        if (!foundry.utils.hasProperty(sourceActor, attribute)) {
          throw custom_error(`transferAttributes | Could not find attribute ${attribute} on source's actor with UUID "${targetUuid}"`);
        }
        if (!isRealNumber(quantity) && quantity > 0) {
          throw custom_error(`transferAttributes | Attribute "${attribute}" must be of type number and greater than 0`);
        }
      });
    }
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`transferAttributes | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRANSFER_ATTRIBUTES, sourceUuid, targetUuid, attributes, game.user.id, {
      skipVaultLogging,
      interactionId
    });
  }
  /**
   * Transfers all dynamic attributes from a source to a target, removing it or subtracting from the source and adding them to the target
   *
   * @param {Actor/Token/TokenDocument} source                The source to transfer the attributes from
   * @param {Actor/Token/TokenDocument} target                The target to transfer the attributes to
   * @param {object} options                                  Options to pass to the function
   * @param {boolean} [options.skipVaultLogging=false]        Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]    The interaction ID of this action
   *
   * @returns {Promise<object>}                               An object containing a key value pair of each attribute transferred, the key being the attribute path and its value being the quantity that was transferred
   */
  static transferAllAttributes(source, target, { skipVaultLogging = false, interactionId = false } = {}) {
    const sourceUuid = getUuid(source);
    if (!sourceUuid)
      throw custom_error(`transferAllAttributes | Could not determine the UUID, please provide a valid source`);
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`transferAllAttributes | Could not determine the UUID, please provide a valid target`);
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`transferAllAttributes | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRANSFER_ALL_ATTRIBUTES, sourceUuid, targetUuid, game.user.id, {
      skipVaultLogging,
      interactionId
    });
  }
  /**
   * Transfers all items and attributes between the source and the target.
   *
   * @param {Actor/Token/TokenDocument} source                The actor to transfer all items and attributes from
   * @param {Actor/Token/TokenDocument} target                The actor to receive all the items and attributes
   * @param {object} options                                  Options to pass to the function
   * @param {Array/boolean} [options.itemFilters=false]       Array of item types disallowed - will default to module settings if none provided
   * @param {boolean} [options.skipVaultLogging=false]        Whether to skip logging this action to the target actor if it is a vault
   * @param {string/boolean} [options.interactionId=false]    The ID of this interaction
   *
   * @returns {Promise<object>}                               An object containing all items and attributes transferred to the target
   */
  static transferEverything(source, target, {
    itemFilters = false,
    skipVaultLogging = false,
    interactionId = false
  } = {}) {
    const sourceActor = getActor(source);
    if (!sourceActor)
      throw custom_error(`transferEverything | Could not determine the source actor, please provide a valid source`);
    const sourceUuid = getUuid(sourceActor);
    const targetActor = getActor(target);
    if (!targetActor)
      throw custom_error(`transferEverything | Could not determine the target actor, please provide a valid target`);
    const targetUuid = getUuid(targetActor);
    if (itemFilters) {
      if (!Array.isArray(itemFilters))
        throw custom_error(`transferEverything | itemFilters must be of type array`);
      itemFilters.forEach((entry) => {
        if (typeof entry?.path !== "string")
          throw custom_error(`transferEverything | each entry in the itemFilters must have a "path" property that is of type string`);
        if (typeof entry?.filter !== "string")
          throw custom_error(`transferEverything | each entry in the itemFilters must have a "filter" property that is of type string`);
      });
    }
    if (isItemPileVault(targetActor)) {
      const sourceActorItems = getActorItems(sourceActor, { getItemCurrencies: true });
      const canItemsFit = fitItemsIntoVault(sourceActorItems, targetActor, { itemFilters });
      if (!canItemsFit)
        throw custom_error(`transferEverything | The target vault actor ${targetActor.name} cannot fit these items`, true);
    }
    if (interactionId) {
      if (typeof interactionId !== "string")
        throw custom_error(`transferEverything | interactionId must be of type string`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRANSFER_EVERYTHING, sourceUuid, targetUuid, game.user.id, {
      itemFilters,
      skipVaultLogging,
      interactionId
    });
  }
  /**
   * Return all th registered currencies abbreviations
   * @returns {Array<string>}                                 An array of string containing the abbreviation for each currency registered
   */
  static getCurrenciesAbbreviations() {
    return getCurrenciesAbbreviations();
  }
  /**
  	 * Turns an array containing the data and quantities for each currency into a string of currencies
  	 *
  	 * @param {Array<object>} currencies                      An array of object containing the data and quantity for each currency
  |    * @param {number} currencies[].cost                      The cost of the currency
  |    * @param {string} currencies[].denom                     The abbreviation of the currency, which are usually {#}GP, which when {#} is replaced with the number it becomes 5GP.  
  	 * @param {string} currencies[].percent                   The cost of  the currency is in percentage (for work the 'abbreviation' property must includes '%' substring)
  	 * @returns {string}                                      An array of object containing the data and quantity for each currency
  	 */
  static getStringFromCurrencies(currencies) {
    if (!currencies) {
      throw custom_error(`getStringFromCurrencies | currencies must be defined`, true);
    }
    if (typeof currencies === "string") {
      throw custom_error(`getStringFromCurrencies | currencies can't be of type string`, true);
    }
    if (!Array.isArray(currencies)) {
      throw custom_error(`getStringFromCurrencies | currencies must be of type array`, true);
    }
    if (currencies.length === 0) {
      throw custom_error(`getStringFromCurrencies | currencies must be a not empty array`, true);
    }
    currencies.forEach((currency) => {
      if (typeof currency !== "object") {
        throw custom_error("setCurrencies | each entry in inCurrencies must be of type object");
      }
      if (typeof currency.cost !== "number") {
        throw custom_error("getStringFromCurrencies | currency.cost must be of type number");
      }
      if (typeof currency.abbreviation !== "string") {
        throw custom_error("getStringFromCurrencies | currency.abbreviation must be of type string");
      }
    });
    return getStringFromCurrencies(currencies);
  }
  /**
   * Turns a string of currencies into an array containing the data and quantities for each currency
   *
   * @param {string} currencies                               A string of currencies to convert (eg, "5gp 25sp")
   *
   * @returns {Array<object>}                                 An array of object containing the data and quantity for each currency
   */
  static getCurrenciesFromString(currencies) {
    if (typeof currencies !== "string") {
      throw custom_error(`getCurrenciesFromString | currencies must be of type string`);
    }
    return getPriceFromString(currencies).currencies;
  }
  /**
   * This method takes a string, and another string or number, an alternatively a boolean, to modify the first string's currencies.Whether to subtract the second currencies from the first; not needed if the second argument is a number
   *
   * @param firstCurrencies {string}                          The starting sum of money as strings
   * @param secondCurrencies {string/number}                  A string of currencies to alter the first with, or a number to multiply it
   * @param subtract {boolean}                                Whether to subtract the second currencies from the first; not needed if the second argument is a number
   *
   * @returns {string}                                        The resulting currency string
   */
  static calculateCurrencies(firstCurrencies, secondCurrencies, subtract = true) {
    if (typeof firstCurrencies !== "string") {
      throw custom_error(`getCurrencyDifference | firstCurrencies must be of type string`);
    }
    if (!(typeof secondCurrencies === "string" || typeof secondCurrencies === "number")) {
      throw custom_error(`getCurrencyDifference | secondCurrencies must be of type string or number`);
    }
    const firstCurrenciesData = getPriceFromString(firstCurrencies);
    const secondCurrenciesData = typeof secondCurrencies === "string" ? getPriceFromString(secondCurrencies) : secondCurrencies;
    const totalCost = typeof secondCurrencies === "string" ? firstCurrenciesData.overallCost + secondCurrenciesData.overallCost * (subtract ? -1 : 1) : firstCurrenciesData.overallCost * secondCurrencies;
    const differenceCost = getPriceArray(totalCost);
    const newBaseCurrencies = differenceCost.filter((currency) => !currency.secondary && currency.cost).reduce((acc, currency) => {
      return acc + currency.abbreviation.replace("{#}", currency.cost) + " ";
    }, "");
    const newSecondaryCurrencies = firstCurrenciesData.currencies.reduce((acc, currency, index2) => {
      if (!currency.secondary)
        return acc;
      const quantity = typeof secondCurrencies === "string" ? currency.quantity + secondCurrenciesData.currencies[index2].quantity * (subtract ? -1 : 1) : Math.round(currency.quantity * secondCurrencies);
      if (quantity <= 0)
        return acc;
      return acc + currency.abbreviation.replace("{#}", quantity) + " ";
    }, "");
    return (newBaseCurrencies + newSecondaryCurrencies).trim();
  }
  /**
   * Turns a string of currencies or a number into an object containing payment data, and the change an optional target would receive back
   *
   * @param {string/number} price                             A string of currencies to convert (eg, "5gp 25sp") or a number
   * @param {object} options                                  Options to pass to the function
   * @param {number/boolean} [options.quantity=1]             The number of this to buy
   * @param {string/boolean} [options.target=false]           The target whose currencies to check against
   *
   * @returns {object}                                        An object containing the price data
   */
  static getPaymentData(price, { quantity = 1, target = false } = {}) {
    let targetActor = false;
    if (target) {
      targetActor = getActor(target);
      if (!targetActor)
        throw custom_error(`getPaymentData | Could not determine target actor`);
    }
    let overallCost;
    let secondaryPrices = false;
    if (typeof price === "string") {
      const priceData = getPriceFromString(price);
      const currenciesToRemove = priceData.currencies.filter((currency) => currency.quantity);
      if (!currenciesToRemove.length) {
        throw custom_error(`getPaymentData | Could not determine currencies to remove with string "${price}"`);
      }
      overallCost = priceData.overallCost;
      secondaryPrices = currenciesToRemove.filter((currency) => currency.secondary);
    } else if (typeof price === "number") {
      overallCost = price;
    } else {
      if (!targetActor)
        throw custom_error(`getPaymentData | price must be of type string or number`);
    }
    return getPaymentData({
      purchaseData: [{ cost: overallCost, quantity, secondaryPrices }],
      buyer: targetActor
    });
  }
  /**
   * TODO: Remove in future update
   * @deprecated
   */
  static getPaymentDataFromString(...args) {
    custom_warning(`game.itempiles.API.getPaymentDataFromString has been deprecated in favor of game.itempiles.API.getPaymentData`, false);
    return this.getPaymentData(...args);
  }
  /**
   * Adds currencies to the target
   *
   * @param {Actor/Token/TokenDocument} target                The actor to add the currencies to
   * @param {string} currencies                               A string of currencies to add (eg, "5gp 25sp")
   * @param {object} options                                  Options to pass to the function
   * @param {string/boolean} [options.interactionId=false]    The ID of this interaction
   *
   * @returns {Promise<object>}                               An object containing the items and attributes added to the target
   */
  static addCurrencies(target, currencies, { interactionId = false } = {}) {
    const targetActor = getActor(target);
    const targetUuid = getUuid(targetActor);
    if (!targetUuid)
      throw custom_error(`addCurrency | Could not determine the UUID, please provide a valid target`);
    if (typeof currencies !== "string") {
      throw custom_error(`addCurrency | currencies must be of type string`);
    }
    const currenciesToAdd = getPriceFromString(currencies).currencies.filter((currency) => currency.quantity);
    if (!currenciesToAdd.length) {
      throw custom_error(`addCurrency | Could not determine currencies to add with string "${currencies}"`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.ADD_CURRENCIES, targetUuid, currencies, game.user.id, { interactionId });
  }
  /**
   * Removes currencies from the target
   *
   * @param {Actor/Token/TokenDocument} target                The actor to remove currencies from
   * @param {string} currencies                               A string of currencies to remove (eg, "5gp 25sp")
   * @param {object} options                                  Options to pass to the function
   * @param {boolean} [options.change=true]                   Whether the actor can get change back
   * @param {string/boolean} [options.interactionId=false]    The ID of this interaction
   *
   * @returns {Promise<object>}                               An object containing the items and attributes removed from the target
   */
  static removeCurrencies(target, currencies, { change = true, interactionId = false } = {}) {
    const targetActor = getActor(target);
    const targetUuid = getUuid(targetActor);
    if (!targetUuid)
      throw custom_error(`removeCurrencies | Could not determine the UUID, please provide a valid target`);
    let overallCost;
    let secondaryPrices = false;
    if (typeof currencies === "string") {
      const priceData = getPriceFromString(currencies);
      const currenciesToRemove = priceData.currencies.filter((currency) => currency.quantity);
      if (!currenciesToRemove.length) {
        throw custom_error(`removeCurrencies | Could not determine currencies to remove with string "${currencies}"`);
      }
      overallCost = priceData.overallCost;
      secondaryPrices = currenciesToRemove.filter((currency) => currency.secondary);
    } else {
      throw custom_error(`removeCurrencies | price must be of type string`);
    }
    const paymentData = getPaymentData({
      purchaseData: [{ cost: overallCost, quantity: 1, secondaryPrices }],
      buyer: targetActor
    });
    if (!paymentData.canBuy) {
      throw custom_error(`removeCurrencies | ${targetActor.name} cannot afford "${currencies}"`);
    }
    if (!change && paymentData.buyerChange.length) {
      throw custom_error(`removeCurrencies | ${targetActor.name} cannot afford "${currencies}" without receiving change!`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.REMOVE_CURRENCIES, targetUuid, currencies, game.user.id, { interactionId });
  }
  /**
   * Transfers currencies between the source and the target.
   *
   * @param {Actor/Token/TokenDocument} source                The actor to transfer currencies from
   * @param {Actor/Token/TokenDocument} target                The actor to receive the currencies
   * @param {string} currencies                               A string of currencies to transfer (eg, "5gp 25sp")
   * @param {object} options                                  Options to pass to the function
   * @param {boolean} [options.change=true]                   Whether the source actor can get change back
   * @param {string/boolean} [options.interactionId=false]    The ID of this interaction
   *
   * @returns {Promise<object>}                               An object containing the items and attributes transferred to the target
   */
  static transferCurrencies(source, target, currencies, { change = true, interactionId = false } = {}) {
    const sourceActor = getActor(source);
    const sourceUuid = getUuid(sourceActor);
    if (!sourceUuid)
      throw custom_error(`transferCurrencies | Could not determine the UUID, please provide a valid source`);
    const targetActor = getActor(target);
    const targetUuid = getUuid(targetActor);
    if (!targetUuid)
      throw custom_error(`transferCurrencies | Could not determine the UUID, please provide a valid target`);
    let overallCost;
    let secondaryPrices = false;
    if (typeof currencies === "string") {
      const priceData = getPriceFromString(currencies);
      const currenciesToRemove = priceData.currencies.filter((currency) => currency.quantity);
      if (!currenciesToRemove.length) {
        throw custom_error(`transferCurrencies | Could not determine currencies to remove with string "${currencies}"`);
      }
      overallCost = priceData.overallCost;
      secondaryPrices = currenciesToRemove.filter((currency) => currency.secondary);
    } else {
      throw custom_error(`transferCurrencies | price must be of type string`);
    }
    const paymentData = getPaymentData({
      purchaseData: [{ cost: overallCost, quantity: 1, secondaryPrices }],
      buyer: sourceActor
    });
    if (!paymentData.canBuy) {
      throw custom_error(`transferCurrencies | ${sourceActor.name} cannot afford to transfer "${currencies}"`);
    }
    if (!change && paymentData.buyerChange.length) {
      throw custom_error(`transferCurrencies | ${sourceActor.name} cannot afford to transfer "${currencies}" without receiving change!`);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRANSFER_CURRENCIES, sourceUuid, targetUuid, currencies, game.user.id, { interactionId });
  }
  /**
   * Transfers all currencies between the source and the target.
   *
   * @param {Actor/Token/TokenDocument} source                The actor to transfer all currencies from
   * @param {Actor/Token/TokenDocument} target                The actor to receive all the currencies
   * @param {object} options                                  Options to pass to the function
   * @param {string/boolean} [options.interactionId=false]    The ID of this interaction
   *
   * @returns {Promise<object>}                               An object containing all items and attributes transferred to the target
   */
  static transferAllCurrencies(source, target, { interactionId = false } = {}) {
    const sourceUuid = getUuid(source);
    if (!sourceUuid)
      throw custom_error(`transferCurrencies | Could not determine the UUID, please provide a valid source`);
    const targetUuid = getUuid(target);
    if (!targetUuid)
      throw custom_error(`transferCurrencies | Could not determine the UUID, please provide a valid target`);
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRANSFER_ALL_CURRENCIES, sourceUuid, targetUuid, game.user.id, { interactionId });
  }
  /**
   * Rolls on a table of items and collates them to be able to be added to actors and such
   *
   * @param {string/RollTable} table                              The name, ID, UUID, or the table itself, or an array of such
   * @param {object} options                                      Options to pass to the function
   * @param {string/number} [options.timesToRoll="1"]             The number of times to roll on the tables, which can be a roll formula
   * @param {boolean} [options.resetTable=true]                   Whether to reset the table before rolling it
   * @param {boolean} [options.normalizeTable=true]               Whether to normalize the table before rolling it
   * @param {boolean} [options.displayChat=false]                 Whether to display the rolls to the chat
   * @param {object} [options.rollData={}]                        Data to inject into the roll formula
   * @param {Actor/string/boolean} [options.targetActor=false]    The target actor to add the items to, or the UUID of an actor
   * @param {boolean} [options.removeExistingActorItems=false]    Whether to clear the target actor's items before adding the ones rolled
   * @param {boolean/string} [options.customCategory=false]       Whether to apply a custom category to the items rolled
   *
   * @returns {Promise<Array<Item>>}                              An array of object containing the item data and their quantity
   */
  static async rollItemTable(table, {
    timesToRoll = "1",
    resetTable = true,
    normalizeTable = false,
    displayChat = false,
    rollData = {},
    targetActor = false,
    removeExistingActorItems = false,
    customCategory = false
  } = {}) {
    let rollTable2 = table;
    if (typeof table === "string") {
      let potentialTable = await fromUuid(table);
      if (!potentialTable) {
        potentialTable = game.tables.get(table);
      }
      if (!potentialTable) {
        potentialTable = game.tables.getName(table);
      }
      if (!potentialTable) {
        throw custom_error(`rollItemTable | could not find table with string "${table}"`);
      }
      if (resetTable && table.startsWith("Compendium")) {
        resetTable = false;
      }
      rollTable2 = potentialTable;
    }
    if (!(rollTable2 instanceof RollTable)) {
      throw custom_error(`rollItemTable | table must be of type RollTable`);
    }
    table = rollTable2.uuid;
    if (!(typeof timesToRoll === "string" || typeof timesToRoll === "number")) {
      throw custom_error(`rollItemTable | timesToRoll must be of type string or number`);
    }
    if (typeof rollData !== "object") {
      throw custom_error(`rollItemTable | rollData must be of type object`);
    }
    if (typeof removeExistingActorItems !== "boolean") {
      throw custom_error(`rollItemTable | removeExistingActorItems of type boolean`);
    }
    if (targetActor) {
      targetActor = getActor(targetActor);
      if (!(targetActor instanceof Actor)) {
        throw custom_error(`rollItemTable | could not find the actor of the target actor`);
      }
    }
    const items = await ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.ROLL_ITEM_TABLE, {
      table,
      timesToRoll,
      resetTable,
      normalizeTable,
      displayChat,
      rollData,
      customCategory,
      targetActor: getUuid(targetActor),
      removeExistingActorItems,
      userId: game.user.id
    });
    if (items) {
      for (const entry of items) {
        entry.item = targetActor ? targetActor.items.get(entry.item._id) : await Item.implementation.create(entry.item, { temporary: true });
      }
    }
    return items;
  }
  /**
   * Refreshes the merchant's inventory, potentially removing existing items and populating it based on its item tables
   *
   * @param {Actor/Token/TokenDocument} target                  The merchant actor to refresh the inventory of
   * @param {object} options                                    Options to pass to the function
   * @param {boolean} [options.removeExistingActorItems=true]   Whether to clear the merchant's existing inventory before adding the new items
   * @returns {Promise<boolean|*>}
   */
  static async refreshMerchantInventory(target, { removeExistingActorItems = true } = {}) {
    if (target) {
      target = getActor(target);
      if (!(target instanceof Actor)) {
        throw custom_error(`refreshMerchantInventory | could not find the actor of the target actor`);
      }
    }
    const targetUuid = getUuid(target);
    if (!isItemPileMerchant(target)) {
      throw custom_error(`refreshMerchantInventory | target of uuid ${targetUuid} is not a merchant`);
    }
    if (typeof removeExistingActorItems !== "boolean") {
      throw custom_error(`refreshMerchantInventory | removeExistingActorItems of type boolean`);
    }
    const items = await ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.REFRESH_MERCHANT_INVENTORY, targetUuid, {
      removeExistingActorItems,
      userId: game.user.id
    });
    if (items) {
      for (const entry of items) {
        entry.item = target.items.get(entry.item._id);
      }
    }
    return items;
  }
  /**
   * Gets all the valid items from a given actor or token, excluding items based on its item type filters
   *
   * @param {Actor/TokenDocument/Token} target      The target to get the items from
   *
   * @returns {Array<Item>}                         Array containing the target's valid items
   */
  static getActorItems(target) {
    return getActorItems(target);
  }
  static findSimilarItem(itemsToSearch, itemToFind, options = {}) {
    return findSimilarItem(itemsToSearch, itemToFind, options);
  }
  /**
   * Gets the valid currencies from a given actor or token
   *
   * @param {Actor/TokenDocument/Token} target      The target to get the currencies from
   * @param {object} [options]                      Object containing optional parameters
   * @param {Boolean} [options.getAll]              Whether to get all the currencies, regardless of quantity
   *
   * @returns {Array<object>}                       An array of objects containing the data about each currency
   */
  static getActorCurrencies(target, { getAll = false, secondary = true } = {}) {
    return getActorCurrencies(target, { getAll, secondary });
  }
  static updateTokenHud() {
    return ItemPileSocket.executeForEveryone(ItemPileSocket.HANDLERS.RERENDER_TOKEN_HUD);
  }
  static requestTrade(user) {
    return TradeAPI._requestTrade(user);
  }
  static spectateTrade(tradeId) {
    return TradeAPI._spectateTrade(tradeId);
  }
  /**
   * Renders the appropriate interface for a given actor
   *
   * @param {Actor/TokenDocument} target                      The actor whose interface to render
   * @param {object} options                                  An object containing the options for this method
   * @param {Array<string/User>} [options.userIds]            An array of users or user ids for each user to render the interface for (defaults to only self)
   * @param {Actor/TokenDocument} [options.inspectingTarget]  Sets what actor should be viewing the interface
   * @param {boolean} [options.useDefaultCharacter]           Whether other users should use their assigned character when rendering the interface
   *
   * @returns {Promise}
   */
  static renderItemPileInterface(target, {
    userIds = null,
    inspectingTarget = null,
    useDefaultCharacter = false
  } = {}) {
    const targetDocument = getDocument(target);
    const targetUuid = getUuid(targetDocument);
    if (!targetUuid)
      throw custom_error(`renderItemPileInterface | Could not determine the UUID, please provide a valid target item pile`);
    if (!isValidItemPile(targetDocument)) {
      throw custom_error("renderItemPileInterface | This target is not a valid item pile");
    }
    if (!inspectingTarget && !useDefaultCharacter) {
      useDefaultCharacter = true;
    }
    if (inspectingTarget && useDefaultCharacter) {
      throw custom_error("renderItemPileInterface | You cannot force users to use both their default character and a specific character to inspect the pile");
    }
    const inspectingTargetUuid = inspectingTarget ? getUuid(inspectingTarget) : false;
    if (inspectingTarget && !inspectingTargetUuid)
      throw custom_error(`renderItemPileInterface | Could not determine the UUID, please provide a valid inspecting target`);
    if (!Array.isArray(userIds)) {
      if (userIds === null) {
        userIds = [game.user.id];
      } else {
        userIds = [userIds];
      }
    } else {
      userIds = userIds.map((user) => {
        return user instanceof User ? user.id : user;
      });
    }
    if (!game.user.isGM) {
      if (userIds.length > 1 || !userIds.includes(game.user.id)) {
        throw custom_error(`renderItemPileInterface | You are not a GM, so you cannot force others to render an item pile's interface`);
      }
      userIds = [game.user.id];
    }
    if (userIds.length === 1 && userIds[0] === game.user.id) {
      return PrivateAPI._renderItemPileInterface(targetUuid, {
        inspectingTargetUuid,
        useDefaultCharacter,
        remote: true
      });
    }
    for (const userId of userIds) {
      const user = game.users.get(userId);
      if (!user)
        throw custom_error(`renderItemPileInterface | No user with ID "${userId}" exists`);
      if (user.isGM)
        continue;
      if (useDefaultCharacter) {
        if (!user.character) {
          custom_warning(`renderItemPileInterface | User "${user.name}" has no default character`, true);
          return;
        }
      }
    }
    return ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.RENDER_INTERFACE, userIds, targetUuid, {
      inspectingTargetUuid,
      useDefaultCharacter,
      remote: true
    });
  }
  /**
   * Closes any open interfaces from a given item pile actor
   *
   * @param {Actor/TokenDocument} target                      The actor whose interface to potentially close
   * @param {object} options                                  An object containing the options for this method
   * @param {Array<string/User>} [options.userIds]            An array of users or user ids for each user to close the interface for (defaults to only self)
   *
   * @returns {Promise}
   */
  static unrenderItemPileInterface(target, { userIds = null } = {}) {
    const targetDocument = getDocument(target);
    const targetUuid = getUuid(targetDocument);
    if (!targetUuid)
      throw custom_error(`unrenderItemPileInterface | Could not determine the UUID, please provide a valid target item pile`);
    if (!isValidItemPile(targetDocument)) {
      throw custom_error("unrenderItemPileInterface | This target is not a valid item pile");
    }
    if (!Array.isArray(userIds)) {
      if (userIds === null) {
        userIds = [game.user.id];
      } else {
        userIds = [userIds];
      }
    } else {
      userIds = userIds.map((user) => {
        return user instanceof User ? user.id : user;
      });
    }
    if (!game.user.isGM) {
      if (userIds.length > 1 || !userIds.includes(game.user.id)) {
        throw custom_error(`unrenderItemPileInterface | You are not a GM, so you cannot force others to close an item pile's interface`);
      }
      userIds = [game.user.id];
    }
    if (userIds.length === 1 && userIds[0] === game.user.id) {
      return PrivateAPI._unrenderItemPileInterface(targetUuid, { remote: true });
    }
    for (const userId of userIds) {
      const user = game.users.get(userId);
      if (!user)
        throw custom_error(`unrenderItemPileInterface | No user with ID "${userId}" exists`);
    }
    return ItemPileSocket.executeForUsers(ItemPileSocket.HANDLERS.UNRENDER_INTERFACE, userIds, targetUuid, { remote: true });
  }
  /**
   * Retrieves the total numerical cost of an item
   *
   * @param item
   * @returns {number}
   */
  static getCostOfItem(item) {
    return getCostOfItem(item);
  }
  /**
   *  Get the prices array for a given item
   *
   * @param {Item} item                             Item to get the price for
   * @param {object} options                        Options to pass to the function
   * @param {Actor/boolean} [options.seller=false]  Actor that is selling the item
   * @param {Actor/boolean} [options.buyer=false]   Actor that is buying the item
   * @param {number} [options.quantity=1]           Quantity of item to buy
   *
   * @returns {Array}                               Array containing all the different purchase options for this item
   */
  static getPricesForItem(item, { seller = false, buyer = false, quantity = 1 } = {}) {
    if (!(item instanceof Item)) {
      throw custom_error("getPricesForItem | The given item must be of type Item");
    }
    if (seller) {
      seller = getActor(seller);
      if (!seller) {
        throw custom_error("getPricesForItem | Could not determine actor for the seller");
      }
    } else {
      if (!item.parent) {
        throw custom_error("getPricesForItem | If no seller was given, the item must belong to an actor");
      }
      seller = getActor(item.parent);
    }
    if (buyer) {
      buyer = getActor(buyer);
      if (!buyer) {
        throw custom_error(`getPricesForItem | Could not determine the actor for the buyer`);
      }
    }
    return getPriceData({ item, seller, buyer, quantity });
  }
  /**
   * Trades multiple items between one actor to another, and currencies and/or change is exchanged between them
   *
   * @param {Actor/Token/TokenDocument} seller                                                    The actor that is selling the item
   * @param {Actor/Token/TokenDocument} buyer                                                     The actor that is buying the item
   * @param {Array<Object<{ item: Item/string, quantity: number, paymentIndex: number }>>} items  An array of objects containing the item or the id of the
   *                                                                                              item to be sold, the quantity to be sold, and the payment
   *                                                                                              index to be used
   * @param {string/boolean} [interactionId=false]                                                The ID of this interaction
   *
   * @returns {Promise<Object>}                       The items that were created and the attributes that were changed
   */
  static tradeItems(seller, buyer, items, { interactionId = false } = {}) {
    const sellerActor = getActor(seller);
    const sellerUuid = getUuid(sellerActor);
    if (!sellerUuid) {
      throw custom_error(`tradeItems | Could not determine the UUID of the seller, please provide a valid actor or token`, true);
    }
    const buyerActor = getActor(buyer);
    const buyerUuid = getUuid(buyer);
    if (!buyerUuid) {
      throw custom_error(`tradeItems | Could not determine the UUID of the buyer, please provide a valid actor or token`, true);
    }
    let itemsToSell = items.map((data2) => {
      data2 = foundry.utils.mergeObject({
        item: "",
        quantity: 1,
        paymentIndex: 0
      }, data2);
      if (!data2.item) {
        throw custom_error(`tradeItems | You must provide an item!`, true);
      }
      let actorItem;
      if (typeof data2.item === "string") {
        actorItem = sellerActor.items.get(data2.item) || sellerActor.items.getName(data2.item);
        if (!actorItem) {
          throw custom_error(`tradeItems | Could not find item on seller with identifier "${data2.item}"`);
        }
      } else {
        actorItem = sellerActor.items.get(data2.item instanceof Item ? data2.item.id : data2.item._id) || sellerActor.items.getName(data2.item.name);
        if (!actorItem) {
          throw custom_error(`tradeItems | Could not find provided item on seller`);
        }
      }
      const itemPrices = getPriceData({
        item: actorItem,
        seller: sellerActor,
        buyer: buyerActor,
        quantity: data2.quantity
      });
      if (itemPrices.length) {
        if (data2.paymentIndex >= itemPrices.length || data2.paymentIndex < 0) {
          throw custom_error(`tradeItems | That payment index does not exist on ${actorItem.name}`, true);
        }
        const selectedPrice = itemPrices[data2.paymentIndex];
        if (data2.quantity > selectedPrice.maxQuantity) {
          throw custom_error(`tradeItems | The buyer actor cannot afford ${data2.quantity} of ${actorItem.name} (max ${selectedPrice.maxQuantity})`, true);
        }
      }
      return {
        id: actorItem.id,
        quantity: data2.quantity,
        paymentIndex: data2.paymentIndex
      };
    });
    if (isItemPileVault(buyerActor)) {
      const items2 = itemsToSell.reduce((acc, data2) => {
        const item = sellerActor.items.get(data2.id);
        if (canItemStack(item, buyerActor)) {
          acc.push(item);
        } else {
          for (let i = 0; i < data2.quantity; i++) {
            acc.push(item);
          }
        }
        return acc;
      }, []);
      const canItemsFit = fitItemsIntoVault(items2, buyerActor);
      if (!canItemsFit)
        throw custom_error(`tradeItems | The vault buyer actor ${buyerActor.name} cannot fit these items`, true);
    }
    return ItemPileSocket.executeAsGM(ItemPileSocket.HANDLERS.TRADE_ITEMS, sellerUuid, buyerUuid, itemsToSell, game.user.id, { interactionId });
  }
  static canItemFitInVault(item, vaultActor) {
    return canItemFitInVault(item, vaultActor);
  }
  static fitItemsIntoVault(items, vaultActor) {
    return fitItemsIntoVault(items, vaultActor);
  }
  static async registerItemPileType(type, label, flags = []) {
    game.i18n.translations["ITEM-PILES"].Types[type] = "Custom: " + label;
    CONSTANTS.CUSTOM_PILE_TYPES[type] = flags;
  }
  static isItemInvalid(item) {
    return isItemInvalid(item.parent, item);
  }
  static canItemStack(item, actor = false) {
    return canItemStack(item, actor);
  }
  static getVaultGridData(vaultActor) {
    return getVaultGridData(vaultActor);
  }
  static getActorFlagData(actor) {
    return getActorFlagData(actor);
  }
  static getItemQuantity(item) {
    return getItemQuantity(item);
  }
  static showItemPileConfig(actor) {
    if (!isValidItemPile(actor))
      return;
    return ItemPileConfig.show(actor);
  }
};
__name(_API, "API");
let API = _API;
async function runMigrations() {
  for (const version of Object.keys(migrations)) {
    try {
      await migrations[version](version);
    } catch (err) {
      console.error(err);
      custom_warning(`Something went wrong when migrating to version ${version}. Please check the console for the error!`, true);
    }
  }
}
__name(runMigrations, "runMigrations");
function getItemPileActorsOfLowerVersion(version) {
  return getItemPileActors((actor) => {
    const actorFlagVersion = getProperty(actor, CONSTANTS.FLAGS.VERSION) || "1.0.0";
    return getProperty(actor, CONSTANTS.FLAGS.PILE)?.enabled && isNewerVersion(version, actorFlagVersion);
  });
}
__name(getItemPileActorsOfLowerVersion, "getItemPileActorsOfLowerVersion");
function getItemPileTokensOfLowerVersion(version) {
  return getItemPileTokens((token) => {
    try {
      const actorFlagVersion = getProperty(token, CONSTANTS.FLAGS.VERSION) || "1.0.0";
      return token.actor && isNewerVersion(version, actorFlagVersion);
    } catch (err) {
      return false;
    }
  });
}
__name(getItemPileTokensOfLowerVersion, "getItemPileTokensOfLowerVersion");
function filterValidItems(items, version) {
  return items.filter((item) => {
    const itemFlagVersion = getProperty(item, CONSTANTS.FLAGS.VERSION);
    return itemFlagVersion && isNewerVersion(version, itemFlagVersion) || !itemFlagVersion && hasProperty(item, CONSTANTS.FLAGS.ITEM);
  });
}
__name(filterValidItems, "filterValidItems");
function getActorValidItems(actor, version) {
  return filterValidItems(actor.items, version);
}
__name(getActorValidItems, "getActorValidItems");
async function updateActors(version, callback) {
  const actorUpdates = getItemPileActorsOfLowerVersion(version).map((actor) => {
    let flags = getProperty(actor, CONSTANTS.FLAGS.PILE);
    const flagData = {
      [CONSTANTS.FLAGS.PILE]: callback(flags, actor),
      [CONSTANTS.FLAGS.VERSION]: version
    };
    if (actor.actorLink) {
      flagData["token"] = foundry.utils.deepClone(flagData);
    }
    return {
      _id: actor.id,
      ...flagData
    };
  });
  if (actorUpdates.length) {
    debug(`Item Piles | Migrating ${actorUpdates.length} actors to version ${version}...`);
    await Actor.updateDocuments(actorUpdates);
  }
}
__name(updateActors, "updateActors");
async function updateTokens(version, callback) {
  const { validTokensOnScenes } = getItemPileTokensOfLowerVersion(version);
  for (const [sceneId, tokens] of validTokensOnScenes) {
    const scene = game.scenes.get(sceneId);
    const updates = tokens.map((token) => ({
      _id: token.id,
      [CONSTANTS.FLAGS.PILE]: callback(getProperty(token, CONSTANTS.FLAGS.PILE)),
      [CONSTANTS.FLAGS.VERSION]: version
    }));
    if (updates.length) {
      debug(`Item Piles | Migrating ${updates.length} tokens on scene "${sceneId}" to version ${version}...`);
      await scene.updateEmbeddedDocuments("Token", updates);
    }
  }
}
__name(updateTokens, "updateTokens");
async function updateItems(version, callback) {
  const gameItems = filterValidItems(game.items, version);
  const gameItemUpdates = gameItems.map((item) => {
    const flags = getProperty(item, CONSTANTS.FLAGS.ITEM);
    if (!flags)
      return false;
    return updateItemData(item, {
      flags: callback(flags)
    }, { version, returnUpdate: true });
  }).filter(Boolean);
  if (gameItemUpdates.length) {
    debug(`Item Piles | Migrating ${gameItemUpdates.length} items to version ${version}...`);
    await Item.updateDocuments(gameItemUpdates);
  }
  const actors = getItemPileActorsOfLowerVersion(version);
  const actorItemUpdates = actors.map((actor) => {
    const itemPileItems = getActorValidItems(actor, version);
    return {
      actor,
      update: {
        _id: actor.id,
        [CONSTANTS.FLAGS.VERSION]: version
      },
      items: itemPileItems.map((item) => {
        const flags = getProperty(item, CONSTANTS.FLAGS.ITEM);
        if (!flags)
          return false;
        return updateItemData(item, {
          flags: callback(flags)
        }, { version, returnUpdate: true });
      }).filter(Boolean)
    };
  });
  if (actorItemUpdates.length) {
    debug(`Item Piles | Migrating ${actorItemUpdates.length} item pile actors' items to version ${version}...`);
  }
  await Actor.updateDocuments(actorItemUpdates.map((data2) => data2.update));
  for (const { actor, items } of actorItemUpdates) {
    await actor.updateEmbeddedDocuments("Item", items);
  }
  const { validTokensOnScenes } = getItemPileTokensOfLowerVersion(version);
  for (const [sceneId, tokens] of validTokensOnScenes) {
    const scene = game.scenes.get(sceneId);
    const updates = tokens.map((token) => {
      const itemPileItems = getActorValidItems(token.actor, version);
      return {
        token,
        update: {
          _id: token.id,
          [CONSTANTS.FLAGS.VERSION]: version
        },
        items: itemPileItems.map((item) => {
          const flags = getProperty(item, CONSTANTS.FLAGS.ITEM);
          if (!flags)
            return false;
          return updateItemData(item, {
            flags: callback(flags)
          }, { version, returnUpdate: true });
        }).filter(Boolean)
      };
    });
    if (updates.length) {
      debug(`Item Piles | Migrating ${updates.length} tokens on scene "${sceneId}" to version ${version}...`);
    }
    await scene.updateEmbeddedDocuments("Token", updates.map((data2) => data2.update));
    for (const { token, itemUpdates } of updates) {
      await token.actor.updateEmbeddedDocuments("Item", itemUpdates);
    }
  }
}
__name(updateItems, "updateItems");
const migrations = {
  "2.4.0": async (version) => {
    await updateActors(version, (flags) => {
      return cleanFlagData(flags);
    });
    await updateTokens(version, (flags) => {
      return cleanFlagData(flags);
    });
    const { invalidTokensOnScenes } = getItemPileTokensOfLowerVersion(version);
    for (const [sceneId, tokens] of invalidTokensOnScenes) {
      const scene = game.scenes.get(sceneId);
      let deletions = [];
      let updates = [];
      for (const token of tokens) {
        const flagData = {
          [CONSTANTS.FLAGS.PILE]: cleanFlagData(migrateFlagData(token)),
          [CONSTANTS.FLAGS.VERSION]: version
        };
        let tokenActor = game.actors.get(token.actorId);
        if (!tokenActor) {
          tokenActor = game.actors.get(getSetting(SETTINGS$1.DEFAULT_ITEM_PILE_ACTOR_ID));
        }
        if (!tokenActor) {
          deletions.push(token.id);
          continue;
        }
        const update2 = {
          _id: token.id,
          actorId: tokenActor.id,
          [CONSTANTS.ACTOR_DELTA_PROPERTY]: {
            items: []
          },
          ...flagData
        };
        for (let itemData of token[CONSTANTS.ACTOR_DELTA_PROPERTY]?.items ?? []) {
          const item = await Item.implementation.create(itemData, { temporary: true });
          update2[CONSTANTS.ACTOR_DELTA_PROPERTY].items.push(item.toObject());
        }
        updates.push(update2);
      }
      await scene.updateEmbeddedDocuments("Token", updates);
      await scene.deleteEmbeddedDocuments("Token", deletions);
      debug(`Item Piles | Fixing ${updates.length} tokens on scene "${sceneId}" to version ${version}...`);
    }
    if (invalidTokensOnScenes.length && invalidTokensOnScenes.some(([sceneId]) => sceneId === game.user.viewedScene)) {
      ui.notifications.notify("Item Piles | Attempted to fix some broken tokens on various scenes. If the current scene fails to load, please refresh.");
    }
  },
  "2.4.17": async (version) => {
    await updateItems(version, (flags) => {
      flags.infiniteQuantity = "default";
      return flags;
    });
  },
  "2.6.1": async (version) => {
    const flagUpdateCallback = /* @__PURE__ */ __name((flags) => {
      if (flags?.itemTypePriceModifiers) {
        flags.itemTypePriceModifiers = flags.itemTypePriceModifiers.map((priceModifier) => {
          const custom = Object.keys(CONFIG.Item.typeLabels).indexOf(priceModifier.type) === -1;
          priceModifier.category = custom ? priceModifier.type : "";
          priceModifier.type = custom ? "custom" : priceModifier.type;
          return priceModifier;
        });
      }
      return flags;
    }, "flagUpdateCallback");
    await updateActors(version, flagUpdateCallback);
    await updateTokens(version, flagUpdateCallback);
  },
  "2.7.18": async (version) => {
    const actors = getItemPileActorsOfLowerVersion(version);
    const recursivelyAddItemsToCompendium = /* @__PURE__ */ __name(async (itemData) => {
      const flagData = getItemFlagData(itemData);
      for (const priceGroup of flagData?.prices ?? []) {
        for (const price of priceGroup) {
          if (price.type !== "item" || !price.data.item)
            continue;
          const compendiumItemUuid = await recursivelyAddItemsToCompendium(price.data.item).uuid;
          price.data = { uuid: compendiumItemUuid };
        }
      }
      setProperty(itemData, CONSTANTS.FLAGS.ITEM, cleanItemFlagData(flagData, { addRemoveFlag: true }));
      return findOrCreateItemInCompendium(itemData);
    }, "recursivelyAddItemsToCompendium");
    const getActorItemUpdates = /* @__PURE__ */ __name(async (actorItems) => {
      const items = actorItems.filter((item) => getItemFlagData(item).prices.length);
      const updates2 = [];
      for (const item of items) {
        const flagData = getItemFlagData(item);
        let update2 = false;
        if (!flagData.prices.length)
          continue;
        for (const priceGroup of flagData.prices) {
          for (const price of priceGroup) {
            if (price.type !== "item" || !price.data.item)
              continue;
            const compendiumItem = await recursivelyAddItemsToCompendium(price.data.item);
            price.data = { uuid: compendiumItem.uuid };
            update2 = true;
          }
        }
        if (update2) {
          updates2.push({
            _id: item.id,
            [CONSTANTS.FLAGS.VERSION]: version,
            [CONSTANTS.FLAGS.ITEM]: cleanItemFlagData(flagData)
          });
        }
      }
      return updates2;
    }, "getActorItemUpdates");
    const updates = await getActorItemUpdates(filterValidItems(game.items, version));
    if (updates.length) {
      debug(`Item Piles | Migrating ${updates.length} items to version ${version}...`);
      await Item.updateDocuments(updates);
    }
    let updatedActors = 0;
    for (const actor of actors) {
      const items = getActorValidItems(actor, version);
      const updates2 = await getActorItemUpdates(items);
      if (updates2.length) {
        await actor.updateEmbeddedDocuments("Item", updates2);
        updatedActors++;
      }
    }
    if (updatedActors) {
      debug(`Item Piles | Migrating ${updatedActors} actors with out of date items to version ${version}...`);
    }
    const { validTokensOnScenes } = getItemPileTokensOfLowerVersion(version);
    for (const [sceneId, tokens] of validTokensOnScenes) {
      let updatedTokens = 0;
      for (const token of tokens) {
        const items = getActorValidItems(token.actor, version);
        const updates2 = await getActorItemUpdates(items);
        if (updates2.length) {
          updatedTokens++;
          await token.actor.updateEmbeddedDocuments("Item", updates2);
        }
      }
      if (updatedTokens) {
        debug(`Item Piles | Migrating ${updatedTokens} tokens on scene "${sceneId}" to version ${version}...`);
      }
    }
  },
  "2.8.2": async (version) => {
    const flagUpdateCallback = /* @__PURE__ */ __name((flags) => {
      if (flags?.canStackItems !== void 0) {
        flags.canStackItems = flags.canStackItems ? "yes" : "no";
      }
      return flags;
    }, "flagUpdateCallback");
    await updateActors(version, flagUpdateCallback);
    await updateTokens(version, flagUpdateCallback);
  }
};
Hooks.once("init", async () => {
  registerSettings();
  registerHotkeysPre();
  registerLibwrappers();
  registerUIOverrides();
  setupCaches();
  applyShims();
  setupPlugins("init");
  game.itempiles = {
    API,
    hooks: CONSTANTS.HOOKS,
    flags: CONSTANTS.FLAGS,
    pile_types: CONSTANTS.PILE_TYPES,
    pile_flag_defaults: CONSTANTS.PILE_DEFAULTS,
    item_flag_defaults: CONSTANTS.ITEM_DEFAULTS,
    Transaction,
    apps: {
      ItemPileConfig,
      ItemEditor
    }
  };
  window.ItemPiles = {
    API
  };
});
Hooks.once("ready", () => {
  setTimeout(() => {
    if (game.user.isGM) {
      if (!game.modules.get("lib-wrapper")?.active) {
        let word = "install and activate";
        if (game.modules.get("lib-wrapper"))
          word = "activate";
        throw custom_error(`Item Piles requires the 'libWrapper' module. Please ${word} it.`);
      }
      if (!game.modules.get("socketlib")?.active) {
        let word = "install and activate";
        if (game.modules.get("socketlib"))
          word = "activate";
        throw custom_error(`Item Piles requires the 'socketlib' module. Please ${word} it.`);
      }
    }
    ItemPileSocket.initialize();
    PrivateAPI.initialize();
    TradeAPI.initialize();
    ChatAPI.initialize();
    registerHotkeysPost();
    initializeCompendiumCache();
    setupPlugins("ready");
    ChatAPI.disablePastTradingButtons();
    Hooks.callAll(CONSTANTS.HOOKS.READY);
  }, 100);
});
Hooks.once(CONSTANTS.HOOKS.READY, async () => {
  setTimeout(async () => {
    if (game.user.isGM) {
      await checkSystem();
      await patchCurrencySettings();
      await runMigrations();
    }
    if (SYSTEMS.DATA.SYSTEM_HOOKS) {
      SYSTEMS.DATA.SYSTEM_HOOKS();
    }
    applySystemSpecificStyles();
  }, 500);
});
Hooks.on(CONSTANTS.HOOKS.RESET_SETTINGS, async () => {
  for (let setting of game.settings.storage.get("world").filter((setting2) => setting2.key.includes("item-piles"))) {
    await setting.delete();
  }
  checkSystem();
});
//# sourceMappingURL=module.js.map
